Q: How does google chrome launch desktop apps? i don't really know the terminology so im going to start with an example.
If I click a magnet link, Google chrome asks if i want to launch a torrent client. I click ok and chrome launches that app and the app does some stuff based on the link.
now is there anyway to see how the app gets the info from chrome? and how chrome starts the app?

A: It depends exactly on the OS, but in general, another desktop program can register a specific protocol, or URI scheme, to open up a program. Then, when Chrome doesn't know how to deal with a protocol, it'll just hand it over to the OS to deal with.
In Windows for example, they're configured by putting something into the system registry under a specific key (https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx).
Most applications will setup themselves as a default for the particular protocol when installed.

A: Chrome is a "desktop" program. It can open any program exposed from the operating system.
A link can contain a specific protocol instead of http://, the OS can have a map that ties protocols directly to installed programs. Chrome is not communicating with the app at any point. It only tells the os to open a resource at a given url with a given program.


Q: Is there a word that means both frustrating and enticing? I'm writing a story for which I'm trying to find a descriptive, yet attractive title. The protagonists are total opposites and they're always bickering and throwing sarcastic comments at each other, the story is basically about how they constantly get under each other's skin, but at the same time they feel attraction and excitement toward one another, they just won't admit it. I looked up names for similar feelings and I came across these: Skinny love / despire (despise+desire) / ambivalent / bittersweet
I just want a word (or more than one) that explains how things are between them: like how a puzzle is so exciting to solve but at some points, when the pieces won't fit, it gets too frustrating. I feel like the suggestions I mentioned above are so blunt and plain, I don't know it's just my opinion. I was thinking of oxymorons, maybe something along "Sweetly/enticingly Provoking", but I am not sure, maybe there's a more adequate word or oxymoron you can come up with.
Thanks in advance!

A: It sounds like a love-hate relationship:

strong feelings of both love and hatred for someone (Merriam-Webster)

But I'm not sure if this would work as a title.

A: The following words mean both frustrating and enticing to different degrees. First choice words may be

*

*Knotty

*Koan (in Zen Buddhism) a problem or riddle that admits no logical solution.

*Challenging

*Riddle

*Beguiling

*Bewitching

*Baffling

*Perplexing

*Gordian, Gordian knot

*Convoluted

*Enigma, Enigmatic

*Intricate
Examples of some other words that can also be used are

*

*Impossible

*Addictive

*Sirenic, Siren/s

*Riveting

*Outrageous

*Maddening

*Vexed, Vexatious

*Intrigue, Intriguing

*Cryptic

*Labyrinthine

*Byzantine

*Greek (example sentence, "Greek to me")

*Risque (may not be appropriate as it has a strong sexual connotation)

*Orphic (mystic, oracular, fascinating, entrancing).

*Recondite (Difficult to grasp or understand; abstruse, profound. Little known; esoteric, secret).

*Arcane

*Esoteric
Love-hate had already been mentioned by @Dan

A: In the context of a title, I'm not sure if the following will help (haha), but I hope it provides some ideas:
First off, the word that immediately came to mind was 'ambivalent', which you provided. 'Temperamental' is related to this, in the emotional sense.
The term I've noticed people use to describe a 'morbid curiousity', is 'fascinating'. For example, if you were to ask a friend "why do you like serial killers so much?", they may respond with: "I don't like them! But I do find them fascinating".
I hear this a lot in debates, myself. Typically in the context of someone hearing an opinion they strongly disagree with (and may be offended by), they may interrupt with: "I find that/you fascinating". I have also (less commonly) heard morbid fascination, and morbidly fascinating before.
The phrase 'opposites attract' was also one of the first things that came to mind, which is somewhat similar to the idea of a "love-hate relationship", as previously mentioned. The latter is more fitting, in my opinion.
Finally, words like 'perplex' and 'allure' may fit. E.g. "She was perplexed by him".
Again, I hope this helps!... Now I'm interested in what a singlar fitting word may be too. -- I feel 'fascinating' is probably the one (at least for me, at the time of writing this), but that requires one to have heard its use in such a context previously (i.e. the implication might not be obvious to all people).
I guess what I'm saying is: people typically think fascinating implies a positive interest, but it's infact a neutral word.
Cheers!


Q: Podio: "Item has been deleted" on PUT, but can retrieve item via GET For some items I have the following problem:
I can retrieve them via GET https://api.podio.com/item/$itemId (meaning the item is not deleted). But when I want to update the item via PUT https://api.podio.com/item/$itemId, it results in a HTTP 410 with the following body:
{
    "error_parameters": {},
    "error_detail": null,
    "error_propagate": false,
    "request": {
        "url": "http://api.podio.com/item/$itemId",
        "query_string": "",
        "method": "PUT"
    },
    "error_description": "Item has been deleted",
    "error": "gone"
}

Is there any wrong assumption on my side, or why do I get this error?


Q: insert table with onclick JS function I want a onclick button that when you press it, it shows up a pre-compilated table.
I've tried to use the table as a text or a paragraph in teh script and obviusly it did'nt work. I can't figure out how to do it. can you help me?

A: The easy way is to add the table with a 'hide' class, like:
<button id='toggleTable'>
  show/hide table
</button>
<table class='hide' id='tableTarget'>
...
</table>

The js:

document.addEventListener('DOMContentLoaded', () => {
  document
    .querySelector('#toggleTable')
    .addEventListener(
      'click',
      () => {
        document
          .querySelector('#tableTarget')
          .classList
          .toggle('hide')
      },
      false
    )
  },
  false
)

the css:
.hide {
  display: none !important;
}

if you use any frontend framework should be easier. But this is with plain html/js/css. And IE9 is not supported with this solution. If you need it, you have to change a little bit the js code.
Good Luck!


Q: My django objects get affected when I commit changes in heroku with git My django admin panel objects get affected when I commit changes in git for my heroku website.
I commit changes to my heroku website from following command in terminal -
git add .
git commit -am "make it better"
git push heroku master
enter code here

before committing when I add new model:

after committing changes it disappeared:

Is there any solution for that committing changes does not affect these objects in django admin panel ?


Q: reverse geocoding to find exact organization/building/landmark name that location When I search  about an  organization in google maps,along with map location, there is side  pop up where  other  details like adress,ph no etc show  up.
I  know  the python coding to find cordinates  for an address.
but  I  am notable to find  the a way to extract name of  the  organization from the  address.
Is there a way to program( python preferred) to  find the organization/building/landmark name for  which I only have the address ?
Note : Through web scraping I can find the address of the organization from its web-site but  how do  I find the name of organization if I  have only its address or cordinates
Eg : search 'Ajanta Chemical Industries' on google map and you get below address
Office & Factory 812/ E-9, 10 11 & 12, Samtel Zone, Phase- III, RIICO Industrial Area, Bhiwadi, Rajasthan 301019
Question - If I  have above address , is  there a programmable  way to  find that its for 'Ajanta Chemical Industries'  ?


Q: how to convert unsigned char array to QByteArray in Qt? unsigned char x[] = {0x7E,0x00,0x00,0x0F };
I want to push it to QByteArray but the QByteArray when finds '\0' stops copying.

A: Which Qt version are you using? 4.7 has QByteArray(const char*, size) which should work and QByteArray::fromRawData(const char*, int size) which also should work.

A: QByteArray test("\xa4\x00\x00", 3);


Q: Case insensitive matching python I want to match items from one list in another without worrying about case sensitivity.
mylist1 = ['fbH_q1ba8', 'fHh_Q1ba9', 'fbh_q1bA10','hoot']
mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic']

I was doing this before:
for item in mylist2:
    if item in mylist1:
        print "true"
    else:
        print "false"

But this fails because it is not case sensitive.
I am aware of re.match("TeSt", "Test", re.IGNORECASE) but how can I apply that to my example?

A: Normalize the case with str.lower():
for item in mylist2:
    print item.lower() in mylist1

The in containment operator already returns True or False, easiest just to print that:
>>> mylist1 = ['fbh_q1ba8', 'fhh_q1ba9', 'fbh_q1ba10','hoot']
>>> mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic']
>>> for item in mylist2:
...     print item.lower() in mylist1
...
True
False
False
True
False
False
False

If mylist1 contains mixed case values, you'll need to make the loop explicit; use a generator expression to produce lowercased values; testing against this ensures only as many elements are lowercased as needed to find a match:
for item in mylist2:
    print item.lower() in (element.lower() for element in mylist1)

Demo
>>> mylist1 = ['fbH_q1ba8', 'fHh_Q1ba9', 'fbh_q1bA10','hoot']
>>> for item in mylist2:
...     print item.lower() in (element.lower() for element in mylist1)
...
True
False
False
True
False
False
False

Another approach is to use any():
for item in mylist2:
    print any(item.lower() == element.lower() for element in mylist1)

any() also short-circuits; as soon as a True value has been found (a matching element is found), the generator expression iteration is stopped early. This does have to lowercase item each iteration, so is slightly less efficient.
Another demo:
>>> for item in mylist2:
...     print any(item.lower() == element.lower() for element in mylist1)
...
True
False
False
True
False
False
False

A: Why not just do:
for item in mylist2:
    if item.lower() in [j.lower() for j in mylist1]:
        print "true"
    else:
        print "false"

This uses .lower() to make the comparison which gives the desired result.

A: The other answers are correct. But they dont account for mixed cases in both lists. Just in case you need that:
mylist1 = ['fbh_q1ba8', 'fbh_q1ba9', 'fbh_q1ba10','hoot']
mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic']

for item in mylist2:
    found = "false"
    for item2 in mylist1:
        if item.lower() == item2.lower():
            found = "true"
    print found


Q: Reading and using data from user files in Javascript (web application), without uploading them I'd like to have a way for a webpage -which is generated dynamically by my server- to read all the files in a specific user folder, manipulate them using javascript, within the web browser, and using them to show to the user some results (specific correlations between the data, dependent on the context and sometimes some graphs, drawn using these correlations).
Communication with the server about these data is neither required nor desired. Actually, since all the manipulations needed can be done via javascript and the files can be huge, for now I absolutely don't want that their content is uploaded to the server. Therefore there are no security risks (at least none that I can see).
Server side, I'm only interested to save the name of the folder, so that the user (who is registered) doesn't need to select the files one by one or to select them again every time a new page is dynamically created.
For now, the only hopes to find a solution that I have been able to gather are about using the Chrome FileSystem API (but I'd prefer a general solution, not dependent on a specific browser) or creating an extension that the user should install to use this feature when visiting the website (which, for me, is maybe even worse than relying on a specific browser).
So I wonder if there is a way to implement this feature using only pure javascript and HTML5 and using neither extensions nor browser dependent solutions.

A: Due to security reasons, JavaScript running in the browser should not be used to access the filesystem directly. But definitely you can access it using Node's fs module (but that's on the server side).
Another way is, if you let the user pick files using the <input type="file"> tag then you can use the File API to fetch the contents. But I think that is not what you are looking for.
Recommended reading: https://en.wikipedia.org/wiki/JavaScript#Security


Q: How to set the Priority for feature file inside include tag How to set the priority for feature file(s) to run in the TestNG.xml file with include tag.
I have added the "priority" attribute inside the include tag as follows:
<test name="DESKTOP Chrome" enabled="true">
<parameter name="platform" value="desktop" />
<parameter name="driver.name" value="chromeDriver" />
<parameter name="webdriver.chrome.driver" value="driver/chromedriver.exe" />
<parameter name="chrome.additional.capabilities" value="{'chromeOptions':{'useAutomationExtension':false}}"/>
    <groups>
        <run>
            <include name="@aLoginMenuDesktop" priority="1"/>
            <include name="@ViewPrimaryNavigationMenuDesktop" priority="2"/>
            <include name="@PortfolioOverview" priority="3"/>
            <include name="@FooterDesktop" priority="4"/>
            <include name="@zSignOutMenuDesktop" priority="5"/>
        </run>
    </groups>

    <classes>
        <class name="com.qmetry.qaf.automation.step.client.gherkin.GherkinScenarioFactory" />
    </classes>
</test>

But during the execution it throws the below error.

Caused by: org.xml.sax.SAXParseException; lineNumber: 17;
  columnNumber: 54; Attribute "priority" must be declared for element
  type "include".   at
  com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown
  Source)

A: I removed the priority inside the tag and make it run by default instead,
I just found out that the priority by default (alphabetical) is not based on the tag name of the feature file (@faturefile) that is being called
But, it is based from the filename of the feature file (teststep.feature)


Q: How to set a breakpoint on clicking a 3rd party button? I'm trying to debug a 3rd party widget (+1 button to be exact). Specifically, I'd like to set a breakpoint in Chrome that stops when a button in the widget is clicked.
I would like to break on the 3rd party code that handles to click event. Is there a Chrome extension (or something else I haven't thought of) to help me find the right place in the code to break on?

A: You can make use of Chrome's Developer Tools; no extension is required.
I made a +1 button example here: http://jsfiddle.net/rPnAe/.
If you go to that fiddle and then open Developer Tools (F12), then go to Scripts and expand Event Listener Breakpoints and lastly expand 'Mouse' and tick the 'click' checkbox, then whenever you click somewhere (which includes an event listener), the debugger will now break at the line of code which contains the listener function.


Q: JS Script not loading on Firefox and Safari My web page does not seem to load a JS file into it on Firefox, Safari and most mobile browsers, but it works on Chrome (and other chromium based browsers).
https://paxco.in/wallet.html Is the page
I have the script tage <script type="text/javascript" scr="./js/web3.min.js"></script> But it does not show in the sources when I use dev tools, and I get errors when I reference functions from the file as according to the browser it is non-existent.
EDIT: Fixed Linking script,
Now I can't reference the /js/web3.min.js file in my other scripts

A: You have an unclosed tag somewhere on your page.
This results in the browser not being able to parse the DOM properly, resulting in your script tag not being "rendered".
Chrome has some better error handling for cases like that, which makes it work in that browser.

Also, there's a typo:
scr="./js/web3.min.js"
Should be
src="./js/web3.min.js"


Q: How to configure Ubuntu's Calendar event to open Thunderbird I am trying to configure the Add event... option in the Calendar offered by Ubuntu to open Thunderbird. I am already using the latest Thunderbird and have updated Ubuntu but still when trying to add an event it will try to open the even in Evolution.
How can I open the events in Thunderbird.

A: Sounds like you are probably using Ubuntu 11.10 LTS... As far as I can tell the monthly calendar displayed in Unity's control panel (or whatever that bar at the top is called) is only integrated for Evolution. The mail on the other hand is integrated to Thunderbird. Thunderbird has an extension called Lightning which adds calendar capabilities to the program. I haven't been able to find any packages to install that will integrate lightning to the calendar in Unity.
There have been workarounds mentioned where both Thunderbird and Evolution are installed to allow events to be viewed in the Unity Calendar. However, it seems Thuderbird will not integrate with this calendar. I am currently looking into a way to change the default calendar app... unfortunately I am unable to when in: System Settings > Details > Default Applications. Maybe I'm doing something wrong but this is where I would expect to see it.


Q: RegEx para duas hipóteses de string simultaneamente Possuo a seguinte entrada, e faço uma interação linha por linha em todas.
D      b1308 pspE; thiosulfate sulfurtransferase PspE   K03972 pspE; phage shock protein E
B  09193 Unclassified: signaling and cellular processes-6
C    99977 Transport
D      b2347 yfdC; inner membrane protein YfdC  K21990 yfdC; formate-nitrite transporter family protein
D      b3657 yicJ; putative xyloside transporter YicJ   K03292 TC.GPH; glycoside/pentoside/hexuronide:cation symporter, GPH family
D      b3876 yihO; putative sulfoquinovose transporter  K03292 TC.GPH; glycoside/pentoside/hexuronide:cation symporter, GPH family
D      b0361 insD-1; IS2 element protein    K07497 K07497; putative transposase
D      b1402 insD-2; IS2 insertion element protein InsB K07497 K07497; putative transposase

Entretanto usando o seguinte RegEx para cada linha extrair o nome do gene (por exemplo b2347 yfdC):
[b]\d{4}\s[a-zA-z]{3,4}

Mas este RegEx não extrai o nome inteiro em casos como b1402 insD-2.
Existe um único RegEx para que se extraia ambos os casos?

A: Você pode usar esta regex:
b\d{4}\s[a-zA-Z]{3,4}(-\d)?

Detalhe: os colchetes definem uma classe de caracteres. Por exemplo, [ab] significa "a letra a ou a letra b" (qualquer uma delas). Mas quando você quer somente uma única letra, não precisa dos colchetes. Sendo assim, [b] é o mesmo que b, por isso removi os colchetes em torno do b.
Outro detalhe é que você estava usando [a-zA-z] (com o z minúsculo duas vezes). Isso funciona por coincidência, já que A-z é o intervalo entre A e z, e se você olhar na tabela ASCII verá que este intervalo pega todas as letras maiúsculas e minúsculas. O problema é que neste intervalo também existem outros caracteres, como o [, \ e ]. Então é melhor deixá-los de fora e usar o intervalo correto: [a-zA-Z] (com Z maiúsculo no final).
Por fim, se você quer pegar tanto yihO quanto insD-1, use:

*

*[a-zA-Z]{3,4}: para pegar de 3 a 4 letras

*(-\d)?: um hífen seguido de um dígito (\d). Eu envolvo tudo entre parênteses e coloco um ?, que torna todo esse grupo opcional

Veja esta regex funcionando no regex101.com.

Só lembrando que \s geralmente (na maioria das linguagens/engines) corresponde não só aos espaços em branco, mas também a outros caracteres, como o TAB e quebras de linha (a lista exata de caracteres varia). Se quiser que a regex considere apenas o espaço em branco, basta trocar para:
b\d{4} [a-zA-Z]{3,4}(-\d)?

Repare que agora há um espaço entre o \d{4} e o [.


Q: Hide buttons when printing I have a page which contains at the bottom 3 buttons with the following coding:

    function printpage() {
        //Get the print button and put it into a variable
        var printButton = document.getElementById("printpagebutton");
        //Set the print button visibility to 'hidden'
        printButton.style.visibility = 'hidden';
        //Print the page content
        window.print()
        printButton.style.visibility = 'visible';
    }
#options {
 align-content:center;
 align-items:center;
    text-align: center;
}

<input type="submit" value="post news" >
<input id="printpagebutton" type="button" value="print news" onclick="printpage()"/>
<input type="button" value="re-enter the news">

I managed to hide the print button while printing but i couldn't with the others.
I've searched the internet for the solution, and most questions were answered by adding the display:none; in css, but i end up with 3 hidden buttons on the screen.
I only want the buttons hidden while printing
Answer might be simple, my knowledge in web developing is acient.
Thank you in advance.

A: You can use a css media query to target print:
@media print {
  .hide-print {
    display: none;
  }
}

A: You can use CSS @media queries. For instance:

@media print {
  #printPageButton {
    display: none;
  }
}
<button id="printPageButton" onClick="window.print();">Print</button>

The styles defined within the @media print block will only be applied when printing the page. You can test it by clicking the print button in the snippet; you'll get a blank page.

A: Assign an id to the other 2 buttons. For the POST NEWS button you can set id to postnews and RE-ENTER THE NEWS to reenterthenews; Then do this
function printpage() {

    //Get the print button and put it into a variable
    var printButton = document.getElementById("printpagebutton");
    var postButton = document.getElementById("postnews");
    var reenterButton = document.getElementById("reenterthenews");

    //Set the button visibility to 'hidden'
    printButton.style.visibility = 'hidden';
    postButton.style.visibility = 'hidden';
    reenterButton.style.visibility = 'hidden';

    //Print the page content
    window.print()

    //Restore button visibility
    printButton.style.visibility = 'visible';
    postButton.style.visibility = 'visible';
    reenterButton.style.visibility = 'visible';

}

HTML

<input type="submit" id="postnews" value="post news" >
<input id="printpagebutton" type="button" value="print news" onclick="printpage()"/>
<input type="button" id="reenterthenews" value="re-enter the news">


Q: Using Teradata macros from Entity Framework? Is it possible to use Teradata Macros directly from Entity Framework? I tried the model designer and guessed they would show up under stored procedures which they don't. Does the Teradata .Net provider support macros at all?
Or, do I have to manually write the SQL sentences to execute the macros?


Q: SQL query to update all subpages of a specific uid in TYPO3 I'm looking to find an SQL query to update my TYPO3 table (pages) to add a specific fe_group for all pages under a specific uid in the page tree.
Example: UPDATE pages SET fe_group = 16 WHERE pid = 84;
This will add my fe_group to all pages under my specific uid in the page tree but only for the first level under. I need to reach the infinite levels.
TYPO3 v6.2 and above
Thanks!

A: If you want to apply usergroup access rights to all subpages of a page, there is a built in function the page properties already: Extend to Subpages.
This works in all TYPO3 versions you mentioned:

If you really want to do it with an SQL query, you need to create a small PHP script to recursively change the access rights.


Q: MySQL crash. Unknown cause. Signal 11 This is a database that I installed ~6 months ago and had been running fine.  This is currently running in Ubuntu 12.04.  Attempting to connect to MySQL causes this error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)
Then theres:
$ sudo mysqld

which returns:
130702 15:38:54 [Note] Plugin 'FEDERATED' is disabled.
130702 15:38:54 InnoDB: The InnoDB memory heap is disabled
130702 15:38:54 InnoDB: Mutexes and rw_locks use GCC atomic builtins
130702 15:38:54 InnoDB: Compressed tables use zlib 1.2.3.4
130702 15:38:54 InnoDB: Initializing buffer pool, size = 128.0M
130702 15:38:54 InnoDB: Completed initialization of buffer pool
130702 15:38:54 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
130702 15:38:54  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
130702 15:38:55  InnoDB: Waiting for the background threads to start
130702 15:38:56 InnoDB: 1.1.8 started; log sequence number 5201901917
130702 15:38:56 [Note] Server hostname (bind-address): '127.0.0.1'; port: 3306
130702 15:38:56 [Note]   - '127.0.0.1' resolves to '127.0.0.1';
130702 15:38:56 [Note] Server socket created on IP: '127.0.0.1'.
130702 15:38:56 [Note] Event Scheduler: Loaded 0 events
130702 15:38:56 [Note] mysqld: ready for connections.
Version: '5.5.28-0ubuntu0.12.04.3'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  (Ubuntu)
19:39:02 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

key_buffer_size=16777216
read_buffer_size=131072
max_used_connections=1
max_threads=151
thread_count=1
connection_count=1
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 346681 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x7f9509e51530
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 7f94f1d3de60 thread_stack 0x30000
mysqld(my_print_stacktrace+0x29)[0x7f95083427b9]
mysqld(handle_fatal_signal+0x483)[0x7f9508209b43]
/lib/x86_64-linux-gnu/libpthread.so.0(+0xfcb0)[0x7f9506f5bcb0]
mysqld(+0x320e1c)[0x7f9508113e1c]
mysqld(_ZN4JOIN15alloc_func_listEv+0x9c)[0x7f950812391c]
mysqld(_ZN4JOIN7prepareEPPP4ItemP10TABLE_LISTjS1_jP8st_orderS7_S1_S7_P13st_select_lexP18st_select_lex_unit+0x918)[0x7f9508124658]
mysqld(_Z12mysql_selectP3THDPPP4ItemP10TABLE_LISTjR4ListIS1_ES2_jP8st_orderSB_S2_SB_yP13select_resultP18st_select_lex_unitP13st_select_lex+0x130)[0x7f950812d060]
mysqld(_Z13handle_selectP3THDP3LEXP13select_resultm+0x17c)[0x7f9508132fbc]
mysqld(+0x2f6714)[0x7f95080e9714]
mysqld(_Z21mysql_execute_commandP3THD+0x16d8)[0x7f95080f1178]
mysqld(_Z11mysql_parseP3THDPcjP12Parser_state+0x10f)[0x7f95080f5e0f]
mysqld(_Z16dispatch_command19enum_server_commandP3THDPcj+0x1380)[0x7f95080f7260]
mysqld(_Z24do_handle_one_connectionP3THD+0x1bd)[0x7f950819b80d]
mysqld(handle_one_connection+0x50)[0x7f950819b870]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x7e9a)[0x7f9506f53e9a]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7f9506684cbd]

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (7f94e0004b80): is an invalid pointer
Connection ID (thread ID): 1
Status: NOT_KILLED

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.

I'm at a loss.  What other reports would be useful in diagnosing this?  /var/log/mysql.err & /var/log/mysql.log are empty.

A: It appears you have been victimized by an on-going bug.
For some unknown reason, the mysql.sock file tends to disappear without warning:

*

*http://www.unix.com/unix-advanced-expert-users/7581-mysql-problem-missing-mysql-sock.html

*http://forums.freebsd.org/showthread.php?t=6805

*http://lists.mysql.com/mysql/223277

*https://kb.hivelocity.net/what-to-do-if-mysql-sock-file-is-missing/
I have dealt with this situation many times, Here are my past posts addressing this:

*

*Dec 14, 2012 : Percona-server time out on /etc/init.d/mysql start

*May 08, 2012 : How to properly stop MySQL server on Mac OS X?

*Feb 06, 2012 : MySQL Database and Table Loss
The way around this is to login to mysql using the TCP/IP protocol. As long as you have:

*

*You have a MySQL user called root@127.0.0.1

*You use the --protocol=tcp option with mysql client

*You are not using skip-networking
You can login to mysql like this:
mysql -uroot -h127.0.0.1 --protocol=tcp -p

If you can do this, then shutting down mysql and starting it will fix it like this:
mysqladmin -uroot -h127.0.0.1 --protocol=tcp -p shutdown
service mysql start

That will bring back the file mysql.sock. This explains why rebooting the OS also solved it.
Going back to the question, you typed
sudo mysqld

MySQL was already running and you were attempting to start mysqld again, thus the weird message.


Q: Convert websites into mobile website format I would like to display other we pages in my mobile webapp, but some web pages will be too cumbersome for use on a tiny mobile device screen. So implement some kind of google mobilizer feature. Is there any API available in PHP so that i can use that to convert these pages into mobile compatible

A: No. You'll have to do it manually. You should look into responsive CSS layouts. These will adjust the content of the page as the width of the browser changes. So same page will work in a full browser window and mobile.
Look at

*

*http://www.columnal.com/

*http://lessframework.com/

*http://speckyboy.com/2011/11/17/15-responsive-css-frameworks-worth-considering/

A: I got it, we can use skweezer API for this. If you want to see your website in mobile compatible format try this
http://www.skweezer.com/s.aspx?q=www.example.com

Replace www.example.com with your website URL.
For more details, visit http://company.skweezer.com/


Q: Wrong rendering (character set?) for the profile name in the Android app First of all: the profile page is a very nice addition to the Android app. Thumbs up!
I want to report a very minor bug: my name contains an accent (Lorenzo Dematté). It is rendered correctly on the site, and also inside Q and A in the app, but it looks like Lorenzo Demattß on the left-side menu.

A: Fixed in version 0.1.76 coming out in tonight (UTC).


Q: Estimation time to read an article In ASP MVC How can I estimate time to read an article  like docs.asp.net website
docs.asp.net
At the top of all articles, it says you need xxx minutes to read. I think they are using an algorithm to estimate time
How can I do that!
Thanks in advance

A: The words read per minute average is about 250-300, once you know this you just need to:

*

*Get the article word count.

*Divide this number by 275 (more or less).

*Round the result to get a integer number of minutes.

A: According to a study conducted in 2012, the average reading speed of an adult for text in English is: 228±30 words, 313±38 syllables, and  987±118 characters per minute.
You can therefore calculate an average time to read a particular article by counting one of these factors and dividing by that average speed. Syllables per minute is probably the most accurate, but for computers, words and characters are easier to count.
Study Citation:
Standardized Assessment of Reading Performance: The New International Reading Speed Texts IReST by
Susanne Trauzettel-Klosinski; Klaus Dietz; the IReST Study Group, published in Investigative Ophthalmology & Visual Science August 2012, Vol.53, 5452-5461

A: A nice solution here, on how
to get an estimated read time of any article or blog post  https://stackoverflow.com/a/63820743/12490386
here's an easy one

*

*Divide your total word count by 200.

*You’ll get a decimal number, in this case, 4.69. The first part of your decimal number is your minute. In this case, it’s 4.

*Take the second part — the decimal points — and multiply that by 0.60. Those are your seconds. Round up or down as necessary to get a whole second. In this case, 0.69 x 0.60 = 0.414. We’ll round that to 41 seconds.

*The result? 938 words = a 4 minute, 41 second read.


Q: How to make vs2010 auto generate method stubs at the end of file I try to auto generate method stub using visual studio's View.ShowSmartTag functionality

When I choose this option, Method8 will be placed right after Method2 but I want to place it after all methods, Method7 in this case.
Is there any settings for this?

A: After researching I found that I couldn't do that


Q: How to extract the hidden value in imacros I want to extract the verification code in attribute value, what the code? i dont understand in this problem
Look this

A: I hope it helps, And not too late.
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=NAME:_RequestVerificationToken* EXTRACT=TXT


Q: Error JAVAC0000: error: package com.google.android.gms... does not exist So I just got a new MAC, and I have so many errors when running my project. I haven't worked on the project for about a year now, and this happens:
Image here
I have tried cleaning, rebuilding etc.. nothing seems to work. Tips?
I am using Visual Studio Community 2019 for Mac Version 8.3.3 (build 8)


Q: How to create a value in enum with '&' I need to create a enum value something like this' DESIGN & BUILD'. I am writing an importer service and that imports the types like above. I need to compare it with ones in the Db.
Is it possible to create enum values like above? Moreover, I think we could also do it by taking a regex expression that yields only text but not any sort of symbols, I mean we only get 'DESIGNBUILD'.

A: You can't. Enum value names have to be valid C# identifiers, and that excludes &. I suggest you use DescriptionAttribute or something similar to provide more flexible metadata for the enum values.
While you could use a regular expression to perform the mapping, I believe you'll end up with a more flexible result if you use metadata. You can then easily build a Dictionary<string, YourAttributeType> and vice versa.


Q: ajax unpload image and showing img thumb I am trying to work on an application form that fill information and submit to server, but in the images part i am having a problem. i want to show the user a thumb of the selected img. and that can just happen with uploading the img to the server and give it the path and refresh the control when getting back the url of the img.
I am not using the ajaxupload toolkit or anything, all whtat i am using is a input type file, and c# for the code behind and ajax functions.
i am calling the ajax function with javascript but what should i pass as parameter so i can catch it from the server side, save it and how to return back the url of the saved img . i red lots of articles, most of them uses PHP, or ajaxupload packages, nd i think i can be done without that..surely i dont need a post back at all
regards

A: I don't think you can send file on server using AJAX, 'cause you don't have access to file system via JavaScript. I don't believe what you're trying to do is possible without Flash or Silverlight. Try SWFUpload, for instance. I was using it on my previous project, and it worked fine for me.
EDIT:
And about returning the URL. SWFUpload lets you to send some parameters along with file. So you could generate GUID (on the server side, then just insert it in JavaScript for SWFUpload as an additonal post parameter) and once SWFUpload finished with uploading image, save it on the server using posted GUID as a name of file. After that you can make AJAX request from JavaScript using the same GUID and ask for uploaded image. Hope this helps.


Q: job for zabbix-server.service failed because the control process exited with error code I would like to install zabbix-server on Ubuntu 20.04. When I run the following command, I receive an error:
sudo systemctl restart zabbiz-server zabbix-agent apache2

Error:

How can I solve this problem?


Q: A sequence with Supremeum at least 1
Problem: Let $a_1, a_2, \cdots$ be an infinite sequence of positive reals such that
$$
|a_i - a_j| > \frac{1}{i+j}, \quad \forall i \ne j.
$$
Show that $\sup_i a_i \ge 1$.

I am able to do this problem if the sequence is increasing...because then I get something like,
$$a_i > \frac{1}{3}+ \frac{1}{5} + \cdots \frac{1}{2i-1}.$$
However, when the sequence might oscillate I don't know how to show that a subsequence goes close to something at least $1$.


Q: java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet in Liferay? hai iam new to json web services in liferay i got the following error! i have added JSONWebServiceServlet in web.xml. do i have to add any jar file to classpath?
05:51:36,250 ERROR [PortalClassLoaderServlet:76] java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet
java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    at com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.portalInit(PortalClassLoaderServlet.java:70)
    at com.liferay.portal.kernel.util.PortalLifecycleUtil.register(PortalLifecycleUtil.java:52)
    at com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.init(PortalClassLoaderServlet.java:44)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4350)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4659)
    at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1244)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1342)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:303)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1337)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1601)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1590)
    at java.lang.Thread.run(Unknown Source)

in web.xml i have written like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>pdfportlet-portlet</display-name>

    <jsp-config>
        <taglib>
            <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
            <taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location>
        </taglib>
    </jsp-config>
    <servlet>
           <servlet-name>JSON Web Service Servlet</servlet-name>
           <servlet-class>com.liferay.portal.kernel.servlet.PortalClassLoaderServlet</servlet-class>
           <init-param>
               <param-name>servlet-class</param-name>
               <param-value>com.liferay.portal.jsonwebservice.JSONWebServiceServlet</param-value>
           </init-param>
           <load-on-startup>0</load-on-startup>
       </servlet>
      <servlet-mapping>
          <servlet-name>JSON Web Service Servlet</servlet-name>
          <url-pattern>/api/jsonws/*</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
          <servlet-name>JSON Web Service Servlet</servlet-name>
          <url-pattern>/api/secure/jsonws/*</url-pattern>
      </servlet-mapping>

</web-app>

A:  configure the servlet like this: some sysntax error i think. its working fine now.
   <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>student-portlet</display-name>
    <servlet>
    <servlet-name>JSON Web Service Servlet</servlet-name>
    <servlet-class>
    com.liferay.portal.kernel.servlet.PortalClassLoaderServlet
    </servlet-class>
    <init-param>
    <param-name>servlet-class</param-name>
    <param-value>com.liferay.portal.servlet.JSONServlet</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>JSON Web Service Servlet</servlet-name>
    <url-pattern>/api/jsonws/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>JSON Web Service Servlet</servlet-name>
    <url-pattern>/api/secure/jsonws/*</url-pattern>
    </servlet-mapping>
        <jsp-config>
        <taglib>
          <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
          <taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location>
        </taglib>
        </jsp-config>
    </web-app>


Q: USB type C dual data role and Sink power role My knowledge with USB type C is very limited. For my new project I am planning to use USB type C port. I want my device to work as a power sink e.g. it will be powered by the source or host device. As well as it will have that capabilities of data data swapping (it can transfer data in both direction). What protocol do I need to use to achieve this? Do I have to use any IC? Or, is there any simple connection diagram for the CC using pull down resistors would do the work. I went through a lot of docs. But I am still confuse. I don't have the proper understanding yet.

A: If you want to have a device that takes power while being a USB host, then you have to master the entire PowerDelivery protocol to implement Power_swap function (and all the Discover_ID etc. functions). There are ICs from Texas Instruments, Cypress, Renesas etc, all are based on a serious embedded microcontroller that requires properly loaded firmware. But to engage them (to configure the PD IC to the set of modes supported by your device) you will need a really proper understanding.

A: USB-C can support being a power source or sink, and can support 'dual role' operation (upstream or downstream).
Sounds like what you want is to make a downstream device that accepts power. Easy-peasy, don't need much more than USB3.2 and a bit of stuff to support flip-over. If you only need USB2 speed then it’s strictly wiring, no ICs needed.
Here's a quick intro to USB-C here: https://www.reclaimerlabs.com/blog/2016/12/31/usb-c-for-engineers-part-1
And here: https://www.reclaimerlabs.com/blog/2017/1/12/usb-c-for-engineers-part-2
Here's a related answer about 'dual role' support in USB-C: Connecting two "USB C" hosts, what happens?


Q: How get get the entered values from input box and not the content of Value attribute I have some input fields with pre-populated values. After editing the values of this field if the save button is pressed in my script tag I want to take the edited value in the field and send it to my controller using ajax. The problem I faced is when I am picking the value of my input field using

var name = document.getElementById('iusername').value;

I am getting the value in value attribute and not the one resulted after edit.


Q: Truncated If Statement C++ (Turning letters to numbers) I am trying to change a series of letters into numbers with C++ and have started by making this code.
However, it appears that the math that calculates the digit1 variable is never getting executed.
Any thoughts?
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int qtyofnumbers, num, digit1, counter;
    char letters, upperlower;

    cout << "Enter a letter: ";
    cin >> letters;

    for (counter = 0; counter < 8; counter++)
    {
        if (counter == 3)
            cout << "-";

        num = static_cast<int>(letters) - static_cast<int>('A');

        if (0 <= num && num < 26)
            digit1 = (num / 3) + 2;

        if (((num / 3 == 6 ) || (num / 3 == 7)) && (num % 3 == 0))
            digit1 = digit1-1;

        if (digit1 > 9)
            digit1 = 9;

        cin >> letters;
    }

    cout << digit1;

    return 0;
}

A: My guess is that the problem is in your input. Are you entering capital letters or lowercase letters? Their ASCII codes are different. So, you probably want to change the code from
num= static_cast<int>(letters)-static_cast<int>('A');

to something like
if (num >= 'a')
    num = letters - 'a';
else
    num = letters - 'A';

Also, as mentioned by @jtbandes, use the curly braces { and }. Whitespace does not determine scope in C++. Even if it's for only one line of code after your if-statement, it'll save you headaches in the future.

A: Is the static cast necessary? I recommend using a string stream or just traversing the string character by character using .at() and relying on the ascii values for conversion. http://web.cs.mun.ca/~michael/c/ascii-table.html.


Q: Where can I set path to make.exe on Windows? When I try run make from cmd-console on Windows, it runs Turbo Delphi's make.exe but I need MSYS's make.exe. There is no mention about Turbo Delphi in %path% variable, maybe I can change it to MSYS in registry?

A: The path is in the registry but usually you edit through this interface:

*

*Go to Control Panel -> System -> System settings -> Environment Variables.

*Scroll down in system variables until you find PATH.

*Click edit and change accordingly.

*BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2

*Launch a new console for the settings to take effect.

A: Or you can just run this PowerShell command to append extra folder to the existing path:
$env:Path += ";C:\temp\terraform"

A: To add a PERSISTENT path (eg one that's permanent), you can do this one-liner in PowerShell (adjust the last c:\apps\terraform part)
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value  (((Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path) + ";c:\apps\terraform" )

Alternatively, you can jump directly to the Environment Variables dialog by RUNning/CMD/PowerShell this:
rundll32.exe sysdm.cpl,EditEnvironmentVariables

A: Here I'm providing solution to setup Terraform environment variable in windows for beginners.

*

*Download the terraform ZIP file from Terraform site.

*Extract the .exe from the ZIP file to a folder eg C:\Apps\Terraform
copy this path location like C:\Apps\terraform\

*Add the folder location to your PATH variable, eg: Control Panel -> System -> System settings -> Environment Variables
In System Variables, select Path > edit > new > Enter the location of the Terraform .exe, eg C:\Apps\Terraform then click OK

*Open a new CMD/PowerShell and the Terraform command should work

A: I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.
For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

A: Why don't you create a bat file makedos.bat containing the following line?
c:\DOS\make.exe %1 %2 %5

and put it in C:\DOS (or C:\Windowsè or make sure that it is in your %path%)
You can run from cmd, SET and it displays all environment variables, including PATH.
In registry you can find environment variables under:

*

*HKEY_CURRENT_USER\Environment

*HKEY_CURRENT_USER\Volatile Environment

*HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment

A: just copy it to system32 call make1 or whatever if the name conflicts.


Q: How to catch ajax error response? when i have an ajax error response with jquery i have the following log:
jquery.js:8630 OPTIONS http://10.0.1.108:8000/api/v1.0/auth/ net::ERR_CONNECTION_REFUSED
Object {readyState: 0, status: 0, statusText: "error"}

In my object i have a property statusText: 'error', but no properties with 'net::ERR_CONNECTION_REFUSED'.
I tried to log the responseText as see here Get server response with AJAX error? but my object didn't have this property;
Do you know how i can get it in javascript please? Thank.

A: You can't.
Many errors, including most (if not all) status: 0 errors, are not exposed to JavaScript.
They indicate network or same origin policy errors and exposing the details to JavaScript could leak information. For example, if it was possible to distinguish between "Connection Refused", "Post doesn't speak HTTP" and "No Access-Control-Allow-Origin header", then it would be trivial to write a page that would quietly map out all the webservers on the visitor's corporate network. That information could then be used for phishing attacks.


Q: sum of specific key for multiple similar keys in array of object - JavaScript I have an array of objects like the following:
[
    {
        'Product': 'P1',
        'Price': 150,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 100,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2,
    },
    {
        'Product': 'P2',
        'Price': 10,
        'Location': 1,
    },
    {
        'Product': 'P2',
        'Price': 130,
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    }
]

I need to add up all the prices for objects with the same product and same location.  For the example above the result would be:
[
   {
        'Product': 'P1',
        'Price': 250, // price is the sum of both similar in location and product
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2, // same product but different location
    },
    {
        'Product': 'P2',
        'Price': 140, //sum of same
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    },
]

I have searched several similar issues, but those were dealing with only one key to check for, I have different keys (product and location - may be more than 2 in the future) to identify as different.

A:

const input = [
    {
        'Product': 'P1',
        'Price': 150,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 100,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2,
    },
    {
        'Product': 'P2',
        'Price': 10,
        'Location': 1,
    },
    {
        'Product': 'P2',
        'Price': 130,
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    }
]

const output = []
input.forEach(item => {
  const index = output.findIndex(o => o.Product === item.Product && o.Location === item.Location);
  if (index === -1) {
    output.push(item);
  } else {
    output[index].Price += item.Price;
  }
});
console.log(output);

Without arrow function
input.forEach(function(item) {
  const index = output.findIndex(function(o) { return o.Product === item.Product && o.Location === item.Location});
  if (index === -1) {
    output.push(item);
  } else {
    output[index].Price += item.Price;
  }
});

A: You can use reduce() to do that,

obj = [
   {
        'Product': 'P1',
        'Price': 250, // price is the sum of both similar in location and product
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2, // same product but different location
    },
    {
        'Product': 'P2',
        'Price': 140, //sum of same
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    },
]

res = obj.reduce((prev, curr) => {
  index = prev.findIndex(item => item.Product=== curr.Product && item.Location === curr.Location);
  if(index > -1) {
    prev[index].Price += curr.Price;
  } else {
    prev.push(curr);
  }
  return prev;
}, []);

console.log(res);

A: Modifying @William's answer (Accepted) for my use case as it was to be run on the platform which was not supporting ES6 features (findIndex and arrow function), this can be done without findIndex as below;

var input = [{
    'Product': 'P1',
    'Price': 150,
    'Location': 1,
  },
  {
    'Product': 'P1',
    'Price': 100,
    'Location': 1,
  },
  {
    'Product': 'P1',
    'Price': 200,
    'Location': 2,
  },
  {
    'Product': 'P2',
    'Price': 10,
    'Location': 1,
  },
  {
    'Product': 'P2',
    'Price': 130,
    'Location': 1,
  },
  {
    'Product': 'P3',
    'Price': 40,
    'Location': 1,
  }
]

var output = []
input.forEach(function(item) {
  var index = output.indexOf(output.filter(function(o) {
    return o.Product === item.Product && o.Location === item.Location
  })[0]); // note the [0] index here
  if (index === -1) {
    output.push(item);
  } else {
    output[index].Price += item.Price;
  }
});
console.log(output);


Q: Why is gmailr not working in docker build process? I'm using the gmailr package for sending emails from a r script.
Locally it's all working fine, but when I try to run this during a docker build step in google cloud I'm getting an error.
I implemented it in the following way described here.
So basically, locally the part of my code for sending emails looks like this:
gm_auth_configure(path  = "credentials.json")
gm_auth(email = TRUE, cache = "secret")
gm_send_message(buy_email)

Please note, that I renamed the .secret folder to secret, because I want to deploy my script with docker in gcloud and didn't want to get any unexpected errors due to the dot in the folder name.
This is the code, which I'm now trying to run in the cloud:
setwd("/home/rstudio/")
gm_auth_configure(path  = "credentials.json")
options(
  gargle_oauth_cache = "secret",
  gargle_oauth_email = "email.which.was.used.to.get.secret@gmail.com"
)
gm_auth(email = "email.which.was.used.to.get.secret@gmail.com")

When running this code in a docker build process, I'm receiving the following error:
Error in gmailr_POST(c("messages", "send"), user_id, class = "gmail_message",  :
  Gmail API error: 403
  Request had insufficient authentication scopes.
Calls: gm_send_message -> gmailr_POST -> gmailr_query

I can reproduce the error locally, when I do not check the
following box.
Therefore my first assumption is, that the secret folder is not beeing pushed correctly in the docker build process and that the authentication tries to authenticate again, but in a non interactive-session the box can't be checked and the error is thrown.
This is the part of the Dockerfile.txt, where I'm pushing the files and running the script:
#2 ADD FILES TO LOCAL
COPY . /home/rstudio/

WORKDIR /home/rstudio

#3 RUN R SCRIPT
CMD Rscript /home/rstudio/run_script.R

and this is the folder, which contains all files / folders beeing pushed to the cloud.
My second assumption is, that I have to somehow specify the scope to use google platform for my docker image, but unfortunately I'm no sure where to do that.
I'd really appreciate any help! Thanks in advance!

A: For anyone experiencing the same problem, I was finally able to find a solution.
The problem is that GCE auth is set by the "gargle" package, instead of using the "normal user OAuth flow".
To temporarily disable GCE auth, I'm using the following piece of code now:
library(gargle)
cred_funs_clear()

cred_funs_add(credentials_user_oauth2 = credentials_user_oauth2)

gm_auth_configure(path  = "credentials.json")
options(
  gargle_oauth_cache = "secret",
  gargle_oauth_email = "sp500tr.cloud@gmail.com"
)
gm_auth(email = "email.which.was.used.for.credentials.com")

cred_funs_set_default()

For further references see also here.


Q: Asking for name again if the first name input doesn't match the second name input I would like to make a program that asks the user his name two times. If the two names are the same regardless of the case, it will print success. If the two names are not the same, it will ask the user again to input another set of names (2 names) and if it is now the same it will also print success.
public static void main(String args[]) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter name: ");
    String one = input.readLine();
    System.out.println("Enter name: ");
    String two = input.readLine();

    if (one.equalsIgnoreCase(two)) {
        System.out.print("Success");
    }
    else {
        System.out.println("Enter name: ");
        input.readLine();
        System.out.println("Eneter name: ");
        input.readLine();
    }
}

The part that checks if the two names are the same is fine. The part that I am confused is the code where it will ask for another set of 2 names
else {
    System.out.println("Enter name: ");
    input.readLine();
    System.out.println("Eneter name: ");
    input.readLine();
}

Example output:
Enter name:
Mark Andrew
Enter name:
Mark Andrew
Success

Enter name:
Mark Andrew
Enter name:
John Paul
Enter name:
Mark Andrew
Enter name:
Mark Andrew
//this is the part that I am confused. It doesn't print success//

I am open to opinions and suggestions.
Thanks

A: In the else part, you are not checking again if the names are the same or not. That's why it's not showing Success the next time when you gave the same names. Using a loop would be better if we want to take inputs until the same names are entered.
public static void main(String args[]) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    boolean areNamesEqual = false;
    while(!areNamesEqual) {
        System.out.println("Enter name: ");
        String one = input.readLine();
        System.out.println("Re-enter name: ");
        String two = input.readLine();
        if (one.equalsIgnoreCase(two)) {
            areNamesEqual = true;
        }
    }
    System.out.print("Success");
}


Q: Doubt in kernel based method - unit hypercube(Parzan window estimate) I recently started studying pattern recognition on my own. Please clarify me the following.
https://books.google.co.in/books?id=T0S0BgAAQBAJ&pg=PA53&lpg=PA53&dq=hypercube+of+side+h&source=bl&ots=jMaXtIbzki&sig=ACfU3U3gWUMyzkjZ7V1lEUIdy6W4F9180g&hl=en&sa=X&ved=2ahUKEwiZ55ivxqHoAhW5zjgGHWQzBe8Q6AEwEXoECAoQAQ#v=onepage&q=hypercube%20of%20side%20h&f=false
In kernel based method, if $ \phi(u)$ is hypercube of side 1 in d-dimension, then $\phi(\frac{u-u_0}{h})$ must be hypercube centered at $u_0$ and side decreased by factor (1/h) right?(ie., side of hypercube now = 1/h right?) But the book says side of hypercube = h. (In fact such function defination is assumed to show that it is a kernel function in later part). Kindly explain.
Again he writes as $\forall u_n, \phi(\frac{u-u_n}{h})$ is 1 if $u_n$ falls inside that hypercube and 0 otherwise(how is he concluding that? I know $\phi(\frac{u-u_0}{h})$ is hypercube of dimension 1/h centered at $u_0$). Please explain.


Q: PHP foreach() loop $string = "The complete archive of The New York Times can now be searched from NYTimes.com " //the actual input is unknown, it would be read from textarea

$size = the longest word length from the string

I assigned and initialized array in for loop, for example array1, array2 ....arrayN, here is how i did
for ($i = 1; $i <= $size; $i++) {
    ${"array" . $i} = array();
}

so the $string would be divided in the length of the word
$array1 = [""];
$array2 = ["of", "be", ...]
$array3 = ["the", "can", "now", ...] and so on

So, my question is how to assign in simple for loop or foreach loop $string value to $array1, $array2, $array3 ....., since the input text or the size of the longest word is unknown

A: I'd probably start with $words = explode(' ', $string)
then sort the string by word length
usort($words, function($word1, $word2) {
    if (strlen($word1) == strlen($word2)) {
        return 0;
    }
    return (strlen($word1) < strlen($word2)) ? -1 : 1;
});

$longestWordSize = strlen(last($words));

Loop over the words and place in their respective buckets.
Rather than separate variables for each length array, you should consider something like
$sortedWords = array(
    1 => array('a', 'I'),
    2 => array('to', 'be', 'or', 'is'),
    3 => array('not', 'the'),
);

by looping over the words you don't need to know the maximum word length.
The final solution is as simple as
foreach ($words as $word) {
    $wordLength = strlen($word);
    $sortedWords[ $wordLength ][] = $word;
}

A: You could use something like this:
$words = explode(" ", $string);
foreach ($words as $w) {
    array_push(${"array" . strlen($w)}, $w);
}

This splits up $string into an array of $words and then evaluates each word for length and pushes that word to the appropriate array.

A: you can use explode().

$string = "The complete archive of The New York Times can now be searched           from NYTimes.com " ;

$arr=explode(" ",$string);
$count=count($arr);

$big=0;
 for ($i = 0; $i < $count; $i++) {
     $p=strlen($arr[$i]);
if($big<$p){ $big_val=$arr[$i]; $big=$p;}

     }
echo $big_val;

A: Just use the word length as the index and append [] each word:
foreach(explode(' ', $string) as $word) {
    $array[strlen($word)][] = $word;
}

To remove duplicates $array = array_map('array_unique', $array);.
Yields:
Array
(
    [3] => Array
        (
            [0] => The
            [2] => New
            [3] => can
            [4] => now
        )

    [8] => Array
        (
            [0] => complete
            [1] => searched
        )

    [7] => Array
        (
            [0] => archive
        )

    [2] => Array
        (
            [0] => of
            [1] => be
        )

    [4] => Array
        (
            [0] => York
        )

    [5] => Array
        (
            [0] => Times
        )
)

If you want to re-index the main array use array_values() and to re-index the subarrays use array_map() with array_values().


Q: Getting the size of single document in Mongodb? I am new to MongoDB and am trying to retrieve the size of a single document from a database.
The database is named "enron"
The collection is named "email"
I tried:
Object.bsonsize(db.email.findOne())

I also tried:
Object.bsonsize(db.enron.findOne())

But it only returns 0.
How can I get the size of a document?
Thank you!

A: Here is the related question How to get the size of a single document in MongoDB?


Q: Can I run an MVC app and WCF Web Api on the same AppHarbor site? We have a solution with this structure.

*

*OurApp.Web (mvc 3 project with controllers, views)

*OurApp.Api (mvc 3 project with wcf web api service classes)

*OurApp.Domain (entities, repositories, unit of work, etc)

*OurApp.Tests (tests)

We want to use a dns structured like this:
http://www.ourapp.com points to OurApp.Web
http://api.ourapp.com points to OurApp.Api
We want to host on AppHarbor.
How can we do this?

A: AppHarbor currently only supports deploying one application from any given repository. One option might be to fold the API into the web project. I did this for a non-web API WCF service here.
Another option is to maintain two AppHarbor applications, and use solution files named according to what application you want deployed for that application. That is, OurApp.Web.sln contains the Web project and any supporting projects and, OurApp.Api.sln references the API project and any supporting projects. Read more about AppHarbor solution file convention.
(disclaimer, I'm co-founder of AppHarbor)


Q: Locally compact allows shrinking compact neighborhood without hausdorff property? Let $X,Y$ be topological space and $Y$ locally compact. Define $\alpha$ relation on $X$. Consider identity relation on $Y$.(i.e. $Y/1=Y$.)
Let $T\subset X\times Y/(\alpha\times 1)$ be open. Then $T'$ preimage of $T$ in $X\times Y$ is product of open sets $U\times V$ with open sets $U\subset X,V\subset Y$. Then the book claims we can assume $V$ to be compact set.
$\textbf{Q:}$ How can one assume $V$ to be compact? Normally, I knew there is a $V'$ smaller neighborhood of $V$ contained in $K$ with $K$ compact by $Y$ locally compact. However, I need to trim down this $\bar{V'}\subset V$ to reduce $K$ to $\bar{V'}$. This is achieved by $Y$ hausdorff property.
Ref. Pg 2 Algebraic Topology Switzer

A: It suffices to demonstrate 2 definitions of local compactness are equivalent under assumption of hausdorff property.
(a) Every open neighbourhood has a compact neighborhood(i.e. $\forall U,\exists K\subset U$ with $U$ open and $K$ compact.)
(b) For every point there is a compact set containing an open set.
Clearly $a)\implies b)$. It suffices to deal with converse implication.
Take $U\subset K$. It suffices to produce $\bar{W}\subset U$ with $\bar{W}$ compact. Now consider $\partial U\subset K$ is compact by $K$ compact. Use hausdorff property to find a open set $V$ disjoint from $\partial U$'s covering and containing a point $x\in U$. Here we need to use compactness of $\partial U$ to ensure finite intersection. Now $W=U\cap V$ is an open set containing $x$. Note that $\bar{W}\neq K$ for sure as we have removed $\partial U$. So we have found $\bar{W}$ compact neighborhood contained in $U$.
The general case can be handled similarly.


Q: magento 2 logo image cant upload Hi I'm facing trouble in uploading the logo image in the transaction email section using admin back-end, it is still showing the previous one but with some block and the resolution showed "x". May I know the cause of this and how can I solve it?

A: Methods:
1) Try to upload through Admin panel.
2) Try to upload through magento root folder.
Use Command:
php bin/magento c:c
php bin/magento setup:static-content:deploy -f


Q: bind is not validating dnssec Strange. My bind is not validating dnssec even though I configured it to.  Version according to named -V is BIND 9.8.2rc1-RedHat-9.8.2-0.10.rc1.el6_3.2 which has a built-in DLV key.
Under options in named.conf
dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;

But when I query a known bad zone, like doing dig www.dnssec-failed.org @localhost I get IP addresses- not a failure like I was expecting. Any thoughts?

A: don't ask why, but I had the same issue and setting dnssec-validation option to auto instead of yes fixed the issue

A: According to the reference manual,

"dnssec-validation"
[...]
If set to "auto", DNSSEC validation is enabled, and a default trust-anchor for the DNS root zone is used.
If set to "yes", DNSSEC validation is enabled, but a trust anchor must be manually configured using a "trusted-keys" or "managed-keys" statement.

Therefore, you must either set it to auto mode, or explicitly include "/etc/bind.keys".

A: If set to "auto", DNSSEC validation is enabled, and a default trust-anchor for the DNS root zone is used.
the default trust-anchor used is from bind.keys, a default is preloaded out of the box


Q: Python variable not defined error I thought it would be cool to make a text-based adventure game. I am having a problem with a naming error in this block of code:
 elif room1_choice1=='Search the room':
        print('You have chosen to search the room')
        print("As you walk around the room you find a chest that you couldn't see from the doorway")
        print('You see only two choices, to attempt to open it or to search the rest of the room')
        print("Type 'Attempt to open' to try to open the chest or type 'Keep searching' to continue your search")
        room1_chestChoice=input(':')
 if room1_chestChoice=='Attempt to open':
        print('You heave at the lid with all your strength but fail to open it.')
        print('It looks like it is locked and you need a key')
        print("Type 'Keep searching' to try and find the key")
        room1_chestChoice=input(':')

I get an error at the if in the middle:
Traceback (most recent call last):
  File "C:/Users/maxim/PycharmProjects/APCSP project/Prototype 1.py", line 41, in <module>
    if room1_chestChoice=='Attempt to open':
NameError: name 'room1_chestChoice' is not defined

Can anyone help?

A: room1_chestChoice is defined only if the previous choice, room1_choice1, was "search the room".  Checking room1_chestChoice makes sense only in that case.  Change your indentation to reflect your decision tree:
elif room1_choice1=='Search the room':
    print('You have chosen to search the room')
    ...
    room1_chestChoice=input(':')
    if room1_chestChoice=='Attempt to open':
         print('You heave at the lid
               ...
         room1_chestChoice=input(':')

That second if has to be entirely within the code dependent on the elif.


Q: Set difference in probability Do any of these rules apply in probability? Let A and B be events.
$$
P((A \cup B) \backslash B)=P(A\cup B) - P(B)
$$
and
$$
P(A\backslash B) = P(A)-P(B)
$$
I am aware that there seems to be a contradiction since
  $$  (A \cup B) \backslash B   $$ and
$$ A\backslash B
$$
refer to the same set but the probabilities on the RHS might not be equal.

A: The first is true. $A\cup B\setminus B$ and $B$ are disjoint sets with union $$ (A\cup B \setminus B) \cup B = A\cup B$$ so the probabilities add up $$ P(A\cup B \setminus B) + P(B) = P(A\cup B).$$
The second is false. For instance, let $A$ and $B$ be disjoint events with $P(A) = P(B) = 1/2$ (like for instance $A$ is the event that a coin is flipped heads and $B$ is the event that it is flipped tails). Then $A\setminus B = A$ So the LHS is $1/2$ but the RHS is $0.$

A: The first one is true, but the second is not true. Let $A\subseteq B$ with $P(B)>P(A)$. In the second equality the l.h. side is nonnegative and the r.h.s. is negative:
$$P(A\backslash B)\geq 0 \text{ whereas } P(A)-P(B)<0.$$
The following equality is true: if $C\subseteq D$ then $P(D\setminus C)=P(D)-P(C)$. Apply it:
$$
P((A\cup B)\setminus B)=P(A\cup B)-P(B)
$$
since $B\subseteq A\cup B$.


Q: "Getting devices ready" on Windows 10 while booting VM/iSCSI on another machine than initially set up TL;DR version:
virtual Windows instance reinstalls GPU drivers while switching to other hosts despite the fact it's getting the same hardware all the time. I'm trying to avoid it / shorten its time
Full version:
I've got an iSCSI server (Windows Server 2016) and a few diskless targets. Those targets are physically the same machines and contain a few Nvidia GTX 1080Ti graphic cards each. A few targets have 1080Ti from Asus (let's say machines A and B), other ones have 1080Ti from Gigabyte (machines C and D).
I use a single VHDX (with Windows 10) mounted as iSCSI initiator and the machine A is network booting the image. everything is OK, so I shut down Windows and remap the image for booting on machine B. Everything is OK again, so I shut down Windows and remap the image for booting on machine C. Then, "Getting devices ready" and spinning wheel appear for quite a time until desktop finally shows up (it takes up to 1 hour, so you understand it may be irritating).
It turned out that the operating system is reinstalling Nvidia drivers because it detects them as different cards, which isn't completely true (only subvendor differs, everything else is the same). Booting the image on D is normal, but going back again to A or B makes drivers reinstall again. All drivers and versions are up-to-date.
I have done a quick'n'dirty workaround for that which shortens the driver reinstall time by 4 times, but I'm searching for more elegant solution. The quick'n'dirty solution is to kill drvinst.exe after first card shows up, then reboot. All cards are intact then and working, hence my assumption the reinstall is NOT neccesary, or at least not to its full extent on all cards.
I have similar issue when working on Hyper-V virtual machines (Windows 10) with Tesla cards virtualized with DDA (Hyper-V Server 2019), but then the reinstall happens always after I remove the VM and set it up again, even on the same host.
The question is: can I somehow block Windows from trying to discover changes in hardware to prevent drivers reinstall? I tried disabling drvinst.exe facility but that yields exclamation marks near each card after machine change.


Q: Story about a group of programmers detecting the emergence of AI I read this story a couple of years ago but can't seem to find it since.It's a short story.
The story starts with a programmer debugging a program and not being able to find the bug. Frustrated, he decides to disassemble the program and look at the assembly and found instructions that can't possibly come from the original source code. He then looks at the compiler for the source of the bug and even recompiles the compiler but the alien code still managed to make it into the program.
Then he decides to actually see what the alien code does and finds that it's trying to do something simple like adding two numbers but doing it in a completely non-intuitive way. He concludes that no human would do it that way and starts suspecting a virus.
Later he finds alien code everywhere from the compiler (not in the source of the compiler) to the assembler to the OS down even to the router in his office at which point he begins to suspect that the alien code may even be part or the CPU itself (modern CPUs after all are designed on computers).
The story ends with the programming team receiving a letter from another engineering team (I forget if it's Geneva or Tokyo or somewhere else) stating that they've found the same thing but every effort they've tried to publish their findings got censored by the emerging AI (hence the handwritten letter).

A: It's "Coding Machines", by Lawrence Kesteloot, one of my favorite AI stories.


Q: OneSignal Push Notifications Landing Page for manual subscribe and unsubscribe i would like to know if its possible to have a manual subscribe/unsubscribe page for the onesignal web push service next to a existing wordpress setup.
Currently i have created one app id working for the blog on
https://example.com and https://www.example.com
Now is there a way to build a landing page for e.g at
https://www.example.com/push-landing
where users subscribe/unscribe for the same App ID ? So all notifications sent through the blog keeps getting recieved by users manual subscribed on the landing page?
The code below seems to work only for Safari yet, any idea why its not working on chrome/firefox?
<!DOCTYPE html>

Push Notifications

<button id="subscribe" class="button" onclick="subscribeOneSignal()">Subscribe </button>
<button id="unsubscribe" class="button" onclick="unSubscribeOneSignal()">Unsubscribe </button>


Q: Concatenate strings for variable identifier in PHP I know this is not the proper way to do this, however I am trying to put a quick fix on a form that was done by another developer.  Basically I want to add an incremental number to a variable inside a while statement:
$count = 1;
while ($r = mysql_fetch_array($query)) {
    $variable . $count = $r['somefield'];
        $count++
}

So that makes the variables:
$variable1
$variable2
$variable3
....etc

A: $varname = 'variable' . $count;
$$varname = $r['somefield'];

http://www.php.net/manual/en/language.variables.variable.php

A: You'd be better off with an array...
$variable[] = $r['somefield'];

You can use variable variables, however it is probably not a good idea, especially for a trivial case like this one.


Q: Replace conditional with polymorphism refactoring or similar? I have tried to ask a variant of this question before. I got some helpful answers, but still nothing that felt quite right to me. It seems to me this shouldn't really be that hard a nut to crack, but I'm not able to find an elegant simple solution. (Here's my previous post, but please try to look at the problem stated here as procedural code first so as not to be influenced by the earlier explanation which seemed to lead to very complicated solutions: Design pattern for cost calculator app? )
Basically, the problem is to create a calculator for hours needed for projects that can contain a number of services. In this case "writing" and "analysis". The hours are calculated differently for the different services: writing is calculated by multiplying a "per product" hour rate with the number of products, and the more products are included in the project, the lower the hour rate is, but the total number of hours is accumulated progressively (i.e. for a medium-sized project you take both the small range pricing and then add the medium range pricing up to the number of actual products). Whereas for analysis it's much simpler, it is just a bulk rate for each size range.
How would you be able to refactor this into an elegant and preferably simple object-oriented version (please note that I would never write it like this in a purely procedural manner, this is just to show the problem in another way succinctly).
I have been thinking in terms of factory, strategy and decorator patterns, but can't get any to work well. (I read Head First Design Patterns a while back, and both the decorator and factory patterns described have some similarities to this problem, but I have trouble seeing them as good solutions as stated there. The decorator example seemed very complicated there for just adding condiments, but maybe it could work better here, I don't know. At least the fact that the calculation of hours accumulates progressively made me think of the decorator pattern... And the factory pattern example from the book with the pizza factory...well it just seems to create such a ridiculous explosion of classes, at least in their example. I have found good use for factory patterns before, but I can't see how I could use it here without getting a really complicated set of classes)
The main goal would be to only have to change in one place (loose coupling etc) if I were to add a new parameter (say another size, like XSMALL, and/or another service, like "Administration"). Here's the procedural code example:
public class Conditional
{
    private int _numberOfManuals;
    private string _serviceType;
    private const int SMALL = 2;
    private const int MEDIUM = 8;

    public int GetHours()
    {
        if (_numberOfManuals <= SMALL)
        {
            if (_serviceType == "writing")
                return 30 * _numberOfManuals;
            if (_serviceType == "analysis")
                return 10;
        }
        else if (_numberOfManuals <= MEDIUM)
        {
            if (_serviceType == "writing")
                return (SMALL * 30) + (20 * _numberOfManuals - SMALL);
            if (_serviceType == "analysis")
                return 20;
        }
        else //i.e. LARGE
        {
            if (_serviceType == "writing")
                return (SMALL * 30) + (20 * (MEDIUM - SMALL)) + (10 * _numberOfManuals - MEDIUM);
            if (_serviceType == "analysis")
                return 30;
        }
        return 0; //Just a default fallback for this contrived example
    }
}

All replies are appreciated! (But as I stated in my previous posts I would appreciate actual code examples rather than just "Try this pattern", because as I mentioned, that is what I'm having trouble with...) I hope someone has a really elegant solution to this problem that I actually thought from the beginning would be really simple...
========================================================
NEW ADDITION:
I appreciate all the answers so far, but I'm still not seeing a really simple and flexible solution to the problem (one I thought wouldn't be very complex at first, but apparently is). It may also be that I haven't quite understood each answer correctly yet. But I thought I'd post my current attempt at working it out (with some help from reading all the different angles in answers here). Please tell me if I'm on the right track or not. But at least now it feels like it's starting to get more flexible... I can quite easily add new parameters without having to change in lots of places (I think!), and the conditional logic is all in one place. I have some of it in xml to get the basic data, which simplifies part of the problem, and part of it is an attempt at a strategy type solution.
Here's the code:
 public class Service
{
    protected HourCalculatingStrategy _calculatingStrategy;
    public int NumberOfProducts { get; set; }
    public const int SMALL = 3;
    public const int MEDIUM = 9;
    public const int LARGE = 20;
    protected string _serviceType;
    protected Dictionary<string, decimal> _reuseLevels;

    protected Service(int numberOfProducts)
    {
        NumberOfProducts = numberOfProducts;
    }

    public virtual decimal GetHours()
    {
        decimal hours = _calculatingStrategy.GetHours(NumberOfProducts, _serviceType);
        return hours;
    }
}

public class WritingService : Service
{
    public WritingService(int numberOfProducts)
        : base(numberOfProducts)
    {
        _calculatingStrategy = new VariableCalculatingStrategy();
        _serviceType = "writing";
    }
}

class AnalysisService : Service
{
    public AnalysisService(int numberOfProducts)
        : base(numberOfProducts)
    {
        _calculatingStrategy = new FixedCalculatingStrategy();
        _serviceType = "analysis";
    }
}

public abstract class HourCalculatingStrategy
{
    public abstract int GetHours(int numberOfProducts, string serviceType);

    protected int GetHourRate(string serviceType, Size size)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("calculatorData.xml");
        string result = doc.SelectSingleNode(string.Format("//*[@type='{0}']/{1}", serviceType, size)).InnerText;
        return int.Parse(result);
    }
    protected Size GetSize(int index)
    {
        if (index < Service.SMALL)
            return Size.small;
        if (index < Service.MEDIUM)
            return Size.medium;
        if (index < Service.LARGE)
            return Size.large;
        return Size.xlarge;
    }
}

public class VariableCalculatingStrategy : HourCalculatingStrategy
{
    public override int GetHours(int numberOfProducts, string serviceType)
    {
        int hours = 0;
        for (int i = 0; i < numberOfProducts; i++)
        {
            hours += GetHourRate(serviceType, GetSize(i + 1));
        }
        return hours;
    }
}

public class FixedCalculatingStrategy : HourCalculatingStrategy
{
    public override int GetHours(int numberOfProducts, string serviceType)
    {
        return GetHourRate(serviceType, GetSize(numberOfProducts));
    }
}

And a simple example form that calls it (I guess I could also have a wrapper Project class with a Dictionary containing the Service objects, but I haven't gotten to that):
    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        List<int> quantities = new List<int>();

        for (int i = 0; i < 100; i++)
        {
            quantities.Add(i);
        }
        comboBoxNumberOfProducts.DataSource = quantities;
    }

    private void CreateProject()
    {
        int numberOfProducts = (int)comboBoxNumberOfProducts.SelectedItem;
        Service writing = new WritingService(numberOfProducts);
        Service analysis = new AnalysisService(numberOfProducts);

        labelWriterHours.Text = writing.GetHours().ToString();
        labelAnalysisHours.Text = analysis.GetHours().ToString();
    }
    private void comboBoxNumberOfProducts_SelectedIndexChanged(object sender, EventArgs e)
    {
        CreateProject();
    }

}

(I wasn't able to include the xml because it got automatically formatted on this page, but it's basically just a bunch of elements with each service type, and each service type containing the sizes with the hour rates as values.)
I'm not sure if I'm just pushing the problem over to the xml file (I'd still have to add new elements for each new servicetype, and add elements for any new size in each servicetype if that changed.) But maybe it's impossible to achieve what I am trying to do and not having to do at least that type of change. Using a database rather than xml the change would be as simple as adding a field and a row:
ServiceType Small Medium Large
Writing     125   100    60
Analysis    56    104    200
(Simply formatted as a "table" here, although the columns aren't quite aligned... I'm not the best at database design though, and maybe it should be done differently, but you get the idea...)
Please tell me what you think!

A: I would tend to start with an enumeration ProjectSize {Small, Medium, Large} and a simple function to return the appropriate enum given a numberOfManuals.  From there, I would write different ServiceHourCalculators, the WritingServiceHourCalculator and the AnalysisServiceHourCalculator (because their logic is sufficiently different).  Each would take a numberOfManuals, a ProjectSize, and return the number of hours.  I'd probably create a map from string to ServiceHourCalculator, so I could say:
ProjectSize projectSize = getProjectSize(_numberOfManuals);
int hours = serviceMap.getService(_serviceType).getHours(projectSize, _numberOfManuals);

This way, when I added a new project size, the compiler would balk at some unhandled cases for each service.  It's not all handled in one place, but it is all handled before it will compile again, and that's all I need.
Update
I know Java, not C# (very well), so this may not be 100% right, but creating the map would be something like this:
Map<String, ServiceHourCalculator> serviceMap = new HashMap<String, ServiceHourCalculator>();
serviceMap.put("writing", new WritingServiceHourCalculator());
serviceMap.put("analysis", new AnalysisServiceHourCalculator());

A: A good start would be to extract the conditional statement into a method(although only a small method) and give it a really explicit name.  Then extract the logic within the if statement into their own methods - again with really explicit names.  (Don't worry if the method names are long - as long as they do what they're called)
I would write this out in code but it would be better for you to pick names.
I would then move onto more complicated refactoring methods and patterns.  Its only when your looking at a series of method calls will it seem appropriate to start applying patterns etc..
Make your first goal to write clean, easy to read and comprehend code.  It is easy to get excited about patterns (speaking from experience) but they are very hard to apply if you can't describe your existing code in abstractions.
EDIT:
So to clarify - you should aim to get your if statement looking like this
if( isBox() )
{
    doBoxAction();
}
else if( isSquirrel() )
{
    doSquirrelAction();
}

Once you do this, in my opinion, then it is easier to apply some of the patterns mentioned here.  But once you still have calculatios etc... in your if statement, then it is harder to see the wood from the trees as you are at too low of an abstraction.

A: You don't need the Factory if your subclasses filter themselves on what they want to charge for. That requires a Project class to hold the data, if nothing else:
class Project {
    TaskType Type { get; set; }
    int? NumberOfHours { get; set; }
}

Since you want to add new calculations easily, you need an interface:
IProjectHours {
    public void SetHours(IEnumerable<Project> projects);
}

And, some classes to implement the interface:
class AnalysisProjectHours : IProjectHours {
    public void SetHours(IEnumerable<Project> projects) {
       projects.Where(p => p.Type == TaskType.Analysis)
               .Each(p => p.NumberOfHours += 30);
    }
}

// Non-LINQ equivalent
class AnalysisProjectHours : IProjectHours {
    public void SetHours(IEnumerable<Project> projects) {
       foreach (Project p in projects) {
          if (p.Type == TaskType.Analysis) {
             p.NumberOfHours += 30;
          }
       }
    }
}

class WritingProjectHours : IProjectHours {
    public void SetHours(IEnumerable<Project> projects) {
       projects.Where(p => p.Type == TaskType.Writing)
               .Skip(0).Take(2).Each(p => p.NumberOfHours += 30);
       projects.Where(p => p.Type == TaskType.Writing)
               .Skip(2).Take(6).Each(p => p.NumberOfHours += 20);
       projects.Where(p => p.Type == TaskType.Writing)
               .Skip(8).Each(p => p.NumberOfHours += 10);
    }
}

// Non-LINQ equivalent
class WritingProjectHours : IProjectHours {
    public void SetHours(IEnumerable<Project> projects) {
       int writingProjectsCount = 0;
       foreach (Project p in projects) {
          if (p.Type != TaskType.Writing) {
             continue;
          }
          writingProjectsCount++;
          switch (writingProjectsCount) {
              case 1: case 2:
                p.NumberOfHours += 30;
                break;
              case 3: case 4: case 5: case 6: case 7: case 8:
                p.NumberOfHours += 20;
                break;
              default:
                p.NumberOfHours += 10;
                break;
          }
       }
    }
}

class NewProjectHours : IProjectHours {
    public void SetHours(IEnumerable<Project> projects) {
       projects.Where(p => p.Id == null).Each(p => p.NumberOfHours += 5);
    }
}

// Non-LINQ equivalent
class NewProjectHours : IProjectHours {
    public void SetHours(IEnumerable<Project> projects) {
       foreach (Project p in projects) {
          if (p.Id == null) {
            // Add 5 additional hours to each new project
            p.NumberOfHours += 5;
          }
       }
    }
}

The calling code can either dynamically load IProjectHours implementors (or static them) and then just walk the list of Projects through them:
foreach (var h in AssemblyHelper.GetImplementors<IProjectHours>()) {
   h.SetHours(projects);
}
Console.WriteLine(projects.Sum(p => p.NumberOfHours));
// Non-LINQ equivalent
int totalNumberHours = 0;
foreach (Project p in projects) {
   totalNumberOfHours += p.NumberOfHours;
}
Console.WriteLine(totalNumberOfHours);

A: this is a common problem, there are a few options that i can think of.  There are two design pattern that come to mind, firstly the Strategy Pattern and secondly the Factory Pattern.  With the strategy pattern it is possible to encapsulate the calculation into an object, for example you could encapsulate your GetHours method into individual classes, each one would represent a calculation based on size. Once we have defined the different calculation strategies we wrap then in a factory.  The factory would be responsible for selecting the strategy to perform the calculation just like your if statement in the GetHours method. Any way have a look at the code below and see what you think
At any point you could create a new strategy to perform a different calculation.  The strategy can be shared between different objects allowing the same calculation to be used in multiple places.  Also the factory could dynamically work out which strategy to use based on configuration, for example
class Program
{
    static void Main(string[] args)
    {
        var factory = new HourCalculationStrategyFactory();
        var strategy = factory.CreateStrategy(1, "writing");

        Console.WriteLine(strategy.Calculate());
    }
}

public class HourCalculationStrategy
{
    public const int Small = 2;
    public const int Medium = 8;

    private readonly string _serviceType;
    private readonly int _numberOfManuals;

    public HourCalculationStrategy(int numberOfManuals, string serviceType)
    {
        _serviceType = serviceType;
        _numberOfManuals = numberOfManuals;
    }

    public int Calculate()
    {
        return this.CalculateImplementation(_numberOfManuals, _serviceType);
    }

    protected virtual int CalculateImplementation(int numberOfManuals, string serviceType)
    {
        if (serviceType == "writing")
            return (Small * 30) + (20 * (Medium - Small)) + (10 * numberOfManuals - Medium);
        if (serviceType == "analysis")
            return 30;

        return 0;
    }
}

public class SmallHourCalculationStrategy : HourCalculationStrategy
{
    public SmallHourCalculationStrategy(int numberOfManuals, string serviceType) : base(numberOfManuals, serviceType)
    {
    }

    protected override int CalculateImplementation(int numberOfManuals, string serviceType)
    {
        if (serviceType == "writing")
            return 30 * numberOfManuals;
        if (serviceType == "analysis")
            return 10;

        return 0;
    }
}

public class MediumHourCalculationStrategy : HourCalculationStrategy
{
    public MediumHourCalculationStrategy(int numberOfManuals, string serviceType) : base(numberOfManuals, serviceType)
    {
    }

    protected override int CalculateImplementation(int numberOfManuals, string serviceType)
    {
        if (serviceType == "writing")
            return (Small * 30) + (20 * numberOfManuals - Small);
        if (serviceType == "analysis")
            return 20;

        return 0;
    }
}

public class HourCalculationStrategyFactory
{
    public HourCalculationStrategy CreateStrategy(int numberOfManuals, string serviceType)
    {
        if (numberOfManuals <= HourCalculationStrategy.Small)
        {
            return new SmallHourCalculationStrategy(numberOfManuals, serviceType);
        }

        if (numberOfManuals <= HourCalculationStrategy.Medium)
        {
            return new MediumHourCalculationStrategy(numberOfManuals, serviceType);
        }

        return new HourCalculationStrategy(numberOfManuals, serviceType);
    }
}

A: I would go with a strategy pattern derivative. This adds additional classes, but is more maintainable over the long haul.  Also, keep in mind that there are still opporunities for refactoring here:
public class Conditional
{
    private int _numberOfManuals;
    private string _serviceType;
    public const int SMALL = 2;
    public const int MEDIUM = 8;
    public int NumberOfManuals { get { return _numberOfManuals; } }
    public string ServiceType { get { return _serviceType; } }
    private Dictionary<int, IResult> resultStrategy;

    public Conditional(int numberOfManuals, string serviceType)
    {
        _numberOfManuals = numberOfManuals;
        _serviceType = serviceType;
        resultStrategy = new Dictionary<int, IResult>
        {
              { SMALL, new SmallResult() },
              { MEDIUM, new MediumResult() },
              { MEDIUM + 1, new LargeResult() }
        };
    }

    public int GetHours()
    {
        return resultStrategy.Where(k => _numberOfManuals <= k.Key).First().Value.GetResult(this);
    }
}

public interface IResult
{
    int GetResult(Conditional conditional);
}

public class SmallResult : IResult
{
    public int GetResult(Conditional conditional)
    {
        return conditional.ServiceType.IsWriting() ? WritingResult(conditional) : AnalysisResult(conditional); ;
    }

    private int WritingResult(Conditional conditional)
    {
        return 30 * conditional.NumberOfManuals;
    }

    private int AnalysisResult(Conditional conditional)
    {
        return 10;
    }
}

public class MediumResult : IResult
{
    public int GetResult(Conditional conditional)
    {
        return conditional.ServiceType.IsWriting() ? WritingResult(conditional) : AnalysisResult(conditional); ;
    }

    private int WritingResult(Conditional conditional)
    {
        return (Conditional.SMALL * 30) + (20 * conditional.NumberOfManuals - Conditional.SMALL);

    }

    private int AnalysisResult(Conditional conditional)
    {
        return 20;
    }
}

public class LargeResult : IResult
{
    public int GetResult(Conditional conditional)
    {
        return conditional.ServiceType.IsWriting() ? WritingResult(conditional) : AnalysisResult(conditional); ;
    }

    private int WritingResult(Conditional conditional)
    {
        return (Conditional.SMALL * 30) + (20 * (Conditional.MEDIUM - Conditional.SMALL)) + (10 * conditional.NumberOfManuals - Conditional.MEDIUM);

    }

    private int AnalysisResult(Conditional conditional)
    {
        return 30;
    }
}

public static class ExtensionMethods
{
    public static bool IsWriting(this string value)
    {
        return value == "writing";
    }
}