Capture All DNS Traffic

Question: I have a system that receives many different DNS requests every day from unauthorized users. What I need is a method to accept all DNS requests made to to this system and give back them back the same IP. Think of this as a gateway situation, where regardless of their DNS request, it will hand back the same IP.
Is it possible to do this through BIND? or is there a better more elegant solution?
Answer: My evldns framework could do this trivially and with the minimum of memory overhead, if you've got a Linux box available.
A plugin that always gives out a specific IP would only take a dozen or so lines of code.
If you can wait a day or so I might even write it myself...
EDIT - I've now done this - if you look at the mod_arec.c and fixed.c modules there's a demo of how to always return a specific IP address for any inbound IN A foo query.
Answer: I'd just use iptables to redirect all port 53 traffic to wherever it needs to go.
Comment: Then you might want to rewrite your question not to use the word "redirect"...
Comment: yes, but I am trying to capture this traffic, not redirect it to another DNS server. basically I want anyone who makes a DNS request of my server to get an answer, but it needs to answer the same for ALL requests
Answer: The best answer, in my opinion, is going to be to whip one up in the programming language of your choice.  It's easy enough to do in python using twisted.names.
Comment: so you're suggesting writing my own program that will just accept all and punt back our default answer?
Comment: @Tedd - no need - I've written one for you...
Comment: Yes, I am.  Unless Alnitak's answer works better :)
Answer: It's called a wildcard DNS record, and yes, it's doable with Bind and possibly other servers too.
Google it, or at least see this Wikipedia page. It's pretty trivial after all.
Comment: Google it isn't an acceptable answer here. The point of SF is to have the answers listed here so that it is a static source of information. Linking to external sources as a reference is encouraged, but not as an entire answer.

Capture All DNS Traffic


Formula to get the maximum value in alphabetical order within a subset of a range

Question: I have two columns in my Excel tab. One defines the status of a task and another gives the expected time needed to complete.

I need to calculate, for those rows where Status is not Completed, the longest time frame. In this case 1 - 3 hours. To facilitate this I have added letters to the beginning of the time frames, so that the exercise is to get the maximum value in alphabetical order (for the rows having status <> "Completed").
Comment: what value? time? or another column you are not showing?
Comment: The question is pretty clear... just don't stop at the title.
Comment: It really isn't a clear question.. honestly it looks like you've already alphabetized your sheet for sorting, so what is left to be done exactly?
Comment: Ook guys! I'll edit the questtion
Answer: If you're using Structured Table References then I'll have to leave it to you to translate this solution into the necessary syntax if you so desire (in any case, it will still work as it stands).
Assuming your table is in A1:B10 (with headers in row 1):
=IF(COUNTIF(B2:B10,"<>Completed"),LOOKUP(1,0/FREQUENCY(0,1/(1+(B2:B10<>"Completed")*COUNTIF(A2:A10,"<="&A2:A10))),A2:A10),"No Solution")
Regards
Comment: Thanks a lot. It works except for when the column status is "Completed for every row. In this case it shows just the value in the top row.
Comment: Good spot. Apologies. Have amended with an additional clause.


How to solve a cryptarithm?

Question: Given multiplication is
$$\begin{array}{cccccc}
  &   &   & P & E & N \\
  &   &   & I & N & K \\\hline
  &   & L & K & P & R \\
  & I & R & T & N &   \\
E & A & K & N &   &   \\\hline
L & E & T & T & E & R
\end{array}$$
how to find the values of the letters?
Comment: If you get stuck: http://www.math.ubc.ca/~israel/applet/metic/metic.html
Answer: Start from N*N ends in N, so N must be 5 or 6 (can't be 0 or 1 from the second line in the sum).  Then I*N ends in N (and I !=1) says N is 5 and I is odd.  Then K is even and R is 0.  Continue
Comment: It has in all cryptarithms I have ever solved and matches the way I was taught to do multiplication.
Comment: @Whoever it was that posted a comment: your math didn't render, and was breaking the comment display, so I removed it. Please try to re-post it correctly.
Comment: Can we be sure that the second block represents:
$
\begin{array}{llllll}
 &&K &(P & E & N) \\
 &N &(P & E & N)& \\
 I &(P & E & N)&& \\
\end{array}
$
and not:
$
\begin{array}{llllll}
 &&N &(I & N & K) \\
 &E &(I & N & K)& \\
 P &(I & N & K)&& \\
\end{array}
$
Answer: Rules:
1) If $ A+B=A$ then $B= 0$ or  $9$.
Answer: 6 1 5 * 354
<code> 2 4 6 0
</code>
3 0 7 5
 1 8 4 5
2 1 7 7 1 0
Comment: -1. The OP ask for the way of find the values, no the answer.
Comment: Please state it in a way that's easier to understand. Even saying that $615 \times 354 = \ldots$ is much better than what you have.
Comment: I * N = N and N * N = N implies N=5; ans I is odd ,it may be {1, 3 7,9} since N is 5. and k * N (5) = R ;imples R is 0 ;
Comment: observe column  KTN T ==> K+N=10 ; it cannot be 5+5.. if K cannot greater than 5 since adding 6 or greater will result in value greater than 10 and condition K+T+N= T fails. therefore K must be less than ; also observe 1st partial product P * K = K (+L ->carry) implies K is even and P is 6. so K can be now either 2 or 4. since 0 6 are already consumed. Now observe  N(5)+P= E +(10). We know P=6; therefore E= 1; Now you know P E N K R values, do multiplication and you will get values in first partial product. which gives L=2 and from column L+R+K=T ==> T=L+5;

How to solve a cryptarithm?


Store only voice in PSR keyboard memory bank

Question: I tried to store my voice settings in a PSR i455 keyboard, but the style also got saved along with it.

I want to store only voice so that I can use it while playing in ACMP mode. The problem is that each time I press those bank buttons where my voice is saved , the style that was saved along with the voice get selected. I want to use different voices while playing in ACMP mode but it should come from the memory banks. I don't know about higher PSR series but it should be possible to do this.
How can I store only my voice settings in the memory banks?
Comment: I don't see myself why this is Too Localized, it seems like a reasonable problem that others could have.  Since there is a lack of any other reasoning here I have re-opened.
Comment: Question is about a specific piece of equipment, and not Musical practice or performance.
Comment: I do not have this keyboard and actually right now I am using a midi keyboard without memory. I suggest you to send an email to Yamaha support I am sure they will find a solution for you. I was looking through their faq but I didn't seem to find what you're looking for http://faq.yamaha.com/us/en/category/musical-instruments/keyboards/digitalkeyboards/portable_keyboards/psr400/#/?search_query=Store%20voice%20memory%20bank&current_page_id=1
Comment: @AlexanderTroup I looked through meta, and it looks like the MP&P hasn't dealt with the question of whether electronic music equipment questions are on topic or not. I'm voting to leave open and asking a question on meta: http://meta.music.stackexchange.com/questions/676/are-questions-about-electronic-music-equipment-on-topic
Answer: According to the Manual for this keyboard, there are two ways to do this.
On page 31, it says that if you hold down the Voice button while pressing the Registration Memory button, it will recall your panel settings without changing your Style settings.
If you want this behavior permanently without having to hold down the Voice button every time you switch, there is a parameter called "Freeze Mode."  This is parameter 60, on page 50 of the manual.  It defaults to Off, but if you turn this parameter On, the keyboard will keep your Style settings even after you press a Registration Memory button.
Comment: Thank you for helping. The keyboard is in the church. So, this Sunday when I go to church I will confirm if this setting really works or not, and then I'll accept this answer if it works.
Answer: best mode for storing voices are..... just press songs button... when u are in song file start saving you voices needed by you.... remember not to play that song file... start saving your voices... by pressing bank then 1 button to its right(bank  +  1 regestration button) you one voice is saved ....  repeat the process with other three buttons.... then go to styles button... play any style... select your voice... play it as u lyk.... remember transpose will remain the same... as voice were saved


Make my view the default for content type

Question: I am probably doing this the wrong way, so please correct me if I am wrong!
I have created a new content type, called "Entities". My content type has many fields, and the default view when you visit "/node/123" is ugly, and doesn't permit much customization. So I created a new View with all my fields displayed exactly how I want, and set the path to be "entity/%", so when you visit "/entity/123" you get my new, prettier version.
However, the default view at "/node/123" still exists, and is the default display when you click on a link in the search results, or admin interface, etc.
How can I make it so "/entity/123" (my view) completely replaces "/node/123" (default view) everywhere? Eg. becomes the default view for the "entity" content type?
Comment: I wouldn't use views for something this at all. Better go to `/admin/structure/types/manage/entity/display` and adjust display settings for the default view there. You can hide some of them, and with Field Groups module (contrib) you can also rearrange them pretty easily
Answer: Your main concern is you don't want the /node/123 link to be available publicly or in search results?  You could unpublish the node and then make a Boolean field in your content type and for your view choose to show the piece of content based on your new boolean field INSTEAD Of the stock published/unpublished checkbox.  So your view by default will only show "published" content but you can change that so that it shows "live" content (new boolean field you created for that content type)  or like that and ignores the published/unpublished field.  So node/123 won't show up for anonymous users or in search results but will still be processed by your view.  Assign the view to the path of your choice /contact-page or whatever and you're golden.


GPS Intermediate Driver Slowing down the data from a virtual serial port driver

Question: Follow on from - GPS Intermediate Driver Issues
The above was not successfully answered and feel I have new information over the issue to go for a new question.
The issue I am facing is the speed of which data is being delivered by the GPS Intermediate Driver.
I have successfully used Pocket Putty to read the serial ports and see the exact information been exposed.
COM 1 - GPS Intermediate Driver
COM 6 - Serial port to PC (Input data manually)
COM 8 - Virtual serial port for GPS hardware.
When reading COM 8, I can see about 18 NMEA strings appear every ~3 seconds, this is as fast as we can push it over the limited USB connection. And it appears quickly on the display. When reading COM 6 (send data from PC manually), it is displayed equally as quick. So there is no problem with the data been available.
Enter in the GPS Intermediate Driver. When The GPS Intermediate Driver is set to COM1 (Software) and COM6 (Hardware). The data entered on COM6 is displayed on COM1 just as quickly as it was without the GPS Intermediate Driver. The data is unaltered, so if I send "JON" on COM6, it will appear on COM1, even though its not valid NMEA data, which is fine.
The problem is with COM8. When the GPS Intermediate Driver is set to COM1 (Software) and COM8 (Hardware). The data showing in PocketPutty on COM1 is really slow. The output on the screen is about 5 characters per second, the data is valid but it just been delivered very slowly. This to me points out an issue in the implementation of the virtual serial port, as if the GPS Intermediate Driver is not reading all the data just one character at a time, given I have isolated the issue to my virtual serial port.
Can anyone provide a clear example of a virtual serial port implementation, as im not sure what I could change to improve this, given COM8 directly works with GPS software and the PocketPutty application, which indicates the data is available, being read, and is correct.
Answer: After getting support from the device manufacturer running a debug build, the cause of the problem was client applications were making to many read calls. The serial port could handle them on its own, but via the GPS Intermediate driver the number of calls were too high and the overhead was crippling the communication, this was down to Mutex locks and general threading issues.
Client applications need to read 960 bytes of data per read to the GPS Intermediate driver for them to work ok. This is not an ideal solution so another fix was found.
The resolution was to add in a WaitForSingleObject(IsThereEnoughGPSDATAEvent, COMTotalTimeout) in the read method, so that all reads would only get data if there was a sufficient amount of data available. Originally I requested 960 to be available in the buffer but i've set it down to just 10 bytes and it still works.
Sample Code
<code>DWORD COM_Read( DWORD hOpenContext, LPVOID pBuffer, DWORD Count )
{
    if(gpsThreadEvents[GPS_THREAD_EVENT_DATA_AVAILABLE] != NULL)
    {
        if(WaitForSingleObject(gpsThreadEvents[GPS_THREAD_EVENT_DATA_AVAILABLE], GPSTimeouts.ReadTotalTimeoutConstant) != WAIT_OBJECT_0)
        {
            return 0;
        }
    }

    //read code goes in here

    return dataOut;
}
</code>


How to parse csv file in python?

Question: I need the first column of the table to be written to a variable, and the remaining columns (their number may vary) to be written to the list in order to get the desired value from the list. I'm trying to get email addresses, but the table itself is porridge, so every column needs to be checked.
with open('data.csv', 'r', encoding='utf-8-sig', newline='') as file:
    reader = csv.reader(file)
    name = list(next(reader))

    for items in list(reader):
        for item in items:
            if '@' in item:
                if not item in emails:
                    emails.append(item)

    with open('result.csv', 'a', encoding='utf-8-sig', newline='') as file:
        writer = csv.writer(file, delimiter=';')
        for email in emails:
            writer.writerow(
                (
                    name,
                    email
                )
            )

Input:
Наименование,Описание,Адрес,Комментарий к адресу,Почтовый индекс,Микрорайон,Район,Город,Округ,Регион,Страна,Часы работы,Часовой пояс,Телефон 1,E-mail 1,Веб-сайт 1,Instagram 1,Twitter 1,Facebook 1,ВКонтакте 1,YouTube 1,Skype 1,Широта,Долгота,2GIS URL
Магазин автозапчастей,,"Мира, 007",,655153,,,Черногорск,Черногорск городской округ,Республика Хакасия,Россия,Пн: 09:00-18:00; Вт: 09:00-18:00; Ср: 09:00-18:00; Чт: 09:00-18:00; Пт: 09:00-18:00; Сб: 09:00-18:00,+07:00,89130502009,firstname.lastname@example.com,http://avtomagazin.2gis.biz,,,,,,,53.805192,91.334047,https://2gis.com/firm/9711414977516651
Спектр-Авто,автотехцентр,"Вяткина, 4",1 этаж,655017,,,Абакан,Абакан городской округ,Республика Хакасия,Россия,Пн: 09:00-18:00; Вт: 09:00-18:00; Ср: 09:00-18:00; Чт: 09:00-18:00; Пт: 09:00-18:00; Сб: 09:00-18:00,+07:00,89233931771,+firstname.lastname@example.com,http://spectr-avto.2gis.biz,,,,,,,53.716581,91.45005,https://2gis.com/firm/70000001034136187

The result is:
['Наименование', 'Описание', 'Адрес', 'Комментарий к адресу', 'Почтовый индекс', 'Микрорайон', 'Район', 'Город', 'Округ', 'Регион', 'Страна', 'Часы работы', 'Часовой пояс', 'Телефон 1', 'E-mail 1', 'Веб-сайт 1', 'Instagram 1', 'Twitter 1', 'Facebook 1', 'ВКонтакте 1', 'YouTube 1', 'Skype 1', 'Широта', 'Долгота', '2GIS URL'];firstname.lastname@example.com
['Наименование', 'Описание', 'Адрес', 'Комментарий к адресу', 'Почтовый индекс', 'Микрорайон', 'Район', 'Город', 'Округ', 'Регион', 'Страна', 'Часы работы', 'Часовой пояс', 'Телефон 1', 'E-mail 1', 'Веб-сайт 1', 'Instagram 1', 'Twitter 1', 'Facebook 1', 'ВКонтакте 1', 'YouTube 1', 'Skype 1', 'Широта', 'Долгота', '2GIS URL'];+email@example.com
['Наименование', 'Описание', 'Адрес', 'Комментарий к адресу', 'Почтовый индекс', 'Микрорайон', 'Район', 'Город', 'Округ', 'Регион', 'Страна', 'Часы работы', 'Часовой пояс', 'Телефон 1', 'E-mail 1', 'Веб-сайт 1', 'Instagram 1', 'Twitter 1', 'Facebook 1', 'ВКонтакте 1', 'YouTube 1', 'Skype 1', 'Широта', 'Долгота', '2GIS URL'];email@example.com

Comment: Can you spell out what your desired output would be exactly? Your `name` variable is the whole header row in your files, and then you're printing it along with each e-mail, so the result is what I'd expect from your code. Did you mean to have pairs with the value from the first column plus any e-mail found on the line, instead?
Answer: If I understand the question correctly, what you really want to output is a two-column CSV, with names in the first column, which I assume come from the original CSV's first column, and e-mail in the second column.
If my assumptions are correct, this should work for you:
import csv

with open('data.csv', 'r', encoding='utf-8-sig', newline='') as file:
    reader = csv.reader(file)
    header = list(next(reader))

    emails = []
    for items in reader:
        name = items[0]
        for item in items:
            if '@' in item:
                if not (name, item) in emails:
                    emails.append((name, item))

    with open('result.csv', 'a', encoding='utf-8-sig', newline='') as file:
        writer = csv.writer(file, delimiter=';')
        for email in emails:
            writer.writerow(email)

Output:
Магазин автозапчастей;email@example.com
Спектр-Авто;+email@example.com

Things I have changed in your code:

The input CSV header is now read into header - did you want to do anything with that?
The name is now set from items[0] for each row in the input CSV.
The emails list is now a list of (name, email) pairs.
Optimization detail: you don't need to turn reader into a list to iterate over it. Just say for items in reader:, it'll be more efficient since it will process each row as it reads it instead of storing them all into a list.
Answer: import petl

table = petl.fromcsv('data.csv', encoding='utf-8-sig')
table2 = petl.addfield(table, 'email_address', lambda r: [r[r1] for r1 in petl.header(table) if '@' in r[r1]])
table3 = petl.cut(table2, 'Наименование', 'email_address')
petl.tocsv(table3, 'result.csv', encoding='utf-8-sig', delimiter=';', write_header=True)

Load the CSV into a table
Create a new field(column) that is an aggregate of any field containing an email address
Reduce(cut) the table to only contain the 2 important fields: 'Наименование', 'email_address'
Output the results to a CSV

Output:
Наименование;email_address
Магазин автозапчастей;['email@example.com']
Спектр-Авто;['+firstname.lastname@example.com']

Be sure to install petl:
pip install petl

How to parse csv file in python?


Does uniform integrability plus convergence in measure imply convergence in $L^1$?

Question:
Does uniform integrability plus convergence in measure imply convergence in $L^1$?

I know this holds on a probability space. Does it hold on a general measure space? I have tried googling. It returned very few results on UI on measure spaces, and none of them mentioned a result like the one in the title. This comes from a discussion about another question.
The proof i have seen for a probability space breaks for a general measure space.
By UI, i mean
$\sup_{f}\int_{|f|>h} |f|d\mu $ goes to $0$ as $h$ goes to infinity.
Comment: On $\Bbb R$, $f_n={1\over n}\cdot \chi_{[n,2n]}$ would furnish a counterexample.
Answer: As David Mitra showed, the result does not hold with this definition of uniform integrability. The main reason is that it is not adapted to infinite measure spaces: if $f$ is a bounded function, then $\{f\}$ is a uniformly integrable (UI) family but $f$ may be not integrable it self.
We rather use the definition

The family $\{f_i,i\in I\}$ is uniformly integrable if for each $\varepsilon\gt 0$, there is an integrable function $g$ such that
  $$\sup_{i\in I}\int_X(|f_i|-g)^+\mathrm d\mu\lt\varepsilon.$$

With this definition, we have the result

Let $(X,\mathcal A,\mu)$ be a measure space, $\{f_n,n\geqslant 1\}$ a UI sequence and $f$ such that $f_n\to f$ in measure. Then $f_n\to f\in\mathbb L^1$.

Proof: Considering $B_{n,k}:=\{|f_n|\geqslant k^{-1}\}$, that we rearrange into an increasing sequence $(A_k)_{k\geqslant 1}$, we have by an approximation argument that
$$\lim_{k\to \infty}\sup_n\int_{X\setminus A_k}|f_n|\mathrm d\mu=0.$$
Fix $(f_{n'})$ a subsequence of $(f_n)$. Using a diagonal argument, we can extract a further subsequence $(f_{n''})$ which converges almost everywhere to $f$. We thus have by Fatou's lemma: $\int_{X\setminus A}|f|\mathrm d\mu=0$ where $A:=\bigcup_kA_k$. We then conclude by dominated convergence.
Comment: Is the converse true? I assume so.
Comment: Yes: combine the fact "a finite family of integrable functions is UI", with an approximation argument. Convergence in measure is a consequence of Markov inequality.
Comment: What approximation argument?
Answer: On $\Bbb R$ with Lebesgue measure, the sequence $(f_n)$ defined by $f_n={1\over n}\cdot \chi_{[n,2n]}$ for each $n$ would furnish a counterexample. Here, $\chi_A$ is the indicator function on the set $A$.


Como colocar anuncios da AdMob no Genexus?

Question: Estou tentando colocar anúncios em meu aplicativo feito e Genexus, utilizando a AdMob, segui o tutorial, mas os anúncios não aparecem no aplicativo. Alguém já fez isso?
Answer: Você precisa se cadastrar no site da adMob, e entrar com sua conta do Google de desenvolvedor, depois é só seguir esses passos:
http://www.androidbegin.com/tutorial/integrating-new-google-admob-banner-interstitial-ads/
Espero ter ajudado.
Comment: Já fiz isso, e tbm coloquei o sdk da admob no meu app, mas nenhum anuncio é mostrado no app


Abstract/formal interest of rings

Question: I am about to introduce first year undergrads to the concept of rings, after spending some time looking at groups; and I would like to give them more than a practical motivation (the most usual rings they have been manipulating: real, complex, rational numbers and matrices) so also a more abstract motivation: why is it formally interesting to extend groups to rings, to add a ``denser'' structure?
I have a physics background and I definitely lack examples or intuition to answer that. What can you think of?
Comment: Rings arise naturally as the endomorphism structures of abelian groups.
Comment: Under what general course are those first year undergraduates going to see rings? From what I know, this happens *only* after a hefty one year course in linear algebra is studied, and a good understanding in real analysis and basic foundations (basic set theory) is gotten.
Comment: With linear algebra already studied, perhaps endomorphisms of a vector space, or more specifically, square matrices, are good examples. Polynomial rings are also very widely known, and completely necessary for fields and Galois theory.
Comment: Hrm, thought this was a duplicate, but can't seem to find anything.
Comment: @Timbuc It seems like the OP is ruling out matrices in his parenthetical comment. But yeah, it would be nice for someone to elaborate about polynomial rings and maybe even their connection to linear transformations.
Answer: This sort of thing is usually best done by example, rather than from the top down.
The basic goal is to convince them that rings are a very good level of generalization of integers and real numbers. Those things are very useful, and you want to say that the generalizations can be useful too.
Here are the applications of rings that I find very compelling:

You already mentioned matrices, I know, but I don't want you to write them off. If you can establish the connection of matrices to the ring of linear transformations of a vector space, you have already done a lot. I'm not sure anybody can fully appreciate rings until they realize what linear algebra can do.
polynomial rings: these are essential for doing algebraic geometry and field theory. You might be able to single out a classical result of field theory and steer toward it through polynomial rings.
Representation theory: if you think groups are already motivated, you could try to also motivate how group representations are interesting. (This is especially connected to physics.) Then you can make a little miracle happen: $F$ representations of $G$ naturally become modules of the group ring $F[G]$. Suddenly, linear algebra can be applied to group representations.
Cyclic codes: if you have time to motivate linear codes, the cyclic linear codes are in correspondence with the ideals of $F[x]/(x^n)$. Knowing the ring theory behind this tells you exactly how to build all possible linear codes of length $n$, as well as some properties the code is going to have.
Answer: The nLab describes rings like this:

More abstractly, a ring is a monoid internal to abelian groups (with their tensor product of abelian groups), and this perspective helps to explain the central relevance of the concept, owing to the fundamental nature of the notion of monoid objects.

You won't want to use these words, but you could say something like this: we know addition (abelian groups) is important; multiplication is also important (as when we compose two functions to get another function); multiplication in the context of addition leads naturally to the definition of a ring.

Abstract/formal interest of rings


$fields is undefined - custom theme creation

Question: I'm attempting to create a custom template for a view. The template file I'm creating is being loaded (if I add some static html it renders).
I'm having trouble accessing values from the view. The tutorial I'm using advises using
dpm($fields);

To output the available fields.
This is coming up as an undefined variable.
Googling suggests using $rows instead of fields but this was also undefined in this case.
Comment: what is the file name of the template you started with - ie: are you working with views-view.tpl.php, views-view-field.tpl.php, etc.
Answer: The $fields variable will be available for theming only if you have selected to display fields  instead of content, check under format section of view.
Secondly, the $fields variable is not available if your template file is views-view.tpl.php, you have to use views-view-field.tpl.php or if you want theme only a specific field, you can use views-view-field--fieldname.tpl. php.


django-admin.py startproject asks to chose default program

Question: When trying to start a project with django using : django-admin.py startproject  a pop up window opens asking to choose a default program to use.
The two main programs it shows are : Visual studio and Notepad.
I have already set the python in 'PATH' and same with the pip which i used to install django.
What should I do to fix that?
Thanks.
Answer: run
<code> python <PATH>/django-admin.py startproject
</code>
your system is not  configured to run <code>.py</code> files.  read here
Comment: After using 'python /django-admin.py startproject ' it sais : "The system cannot find the file specified".
Comment:  means the full path to your django-admin.py
Comment: Ain`t that enough to change directory?
Comment: yep but I don't think you want to create your project in the same dir where django-admin.py
Comment: Alright I misunderstood you at first but now I got it and it worked.
Can you explain why I had to add that python  and it doesn`t work without it?
Comment: When you launch python you start another process. It does not known where django-admin is.
Comment: That`s wierd cuz it worked for me witouht the  on another computer.
Comment: see here http://stackoverflow.com/questions/5299241/cant-open-file-django-admin-py-errno-2-no-such-file-or-directory


How to validate a paragraph field?

Question: I have a paragraph type with 2 fields: year and quarter
I have a content type with a paragraph field (field_year_and_quarter) targeting ONLY this paragraph type
I am trying to create a constraint to disallow the encoding of a duplicate (same year/quarter)
I have tried:
1-A constraint at the node level which is looping into field_year_and_quarter with $node->get('field_year_and_quarter')->referencedEntities() to check if any duplicate
=>This is not working as it is not taking into account what is encoded in the widget, only the last saved version is checked
2-A constraint at the paragraph level which is getting its Parent to be able to loop into field_year_and_quarter with $node_parent->get('field_year_and_quarter')->referencedEntities() to check if any duplicate [I replace one item by the paragraph provided in the parameter ]
Here is the code:
  public function validate($certificate_p, Constraint $constraint) {
    /* @var \Drupal\paragraphs\Entity\Paragraph $certificate_p */
    if ($certificate_p->bundle() == 'qoc') {
      $prod_company = $certificate_p->getParentEntity();
      $certificates = $prod_company->get('field_year_and_quarter')
        ->referencedEntities();
      $all_certificates = [];
      foreach ($certificates as $certificate) {
        // use the paragraph provided in the function parameter
        $certif_to_check = ($certificate_p->id() == $certificate->id()) ? $certificate_p : $certificate;
        $year = $certif_to_check->get('field_qoc_year')->value;
        $quarter = $certif_to_check->get('field_qoc_quarter')->value;
        // Year/Quarter are already encoded
        if (isset($all_certificates[$year][$quarter])) {
          $this->context->addViolation($constraint->duplicate_certif, [
            '%quarter' => surround_by_nbsp($quarter),
            '%year' => surround_by_nbsp($year),
          ]);
          break;
        }
        $all_certificates[$year][$quarter] = TRUE;
      }
    }

=>This is not working for the same reason
3- A constraint at the field level... here is the code:
  public function validate($items, Constraint $constraint) {
    $certificates = $items->referencedEntities();
    $all_certificates = [];
    foreach ($certificates as $certificate) {
      $year = $certificate->get('field_qoc_year')->value;
      $quarter = $certificate->get('field_qoc_quarter')->value;
      // Year/Quarter are already encoded
      if (isset($all_certificates[$year][$quarter])) {
        $this->context->addViolation($constraint->duplicate_certif, [
          '%quarter' => surround_by_nbsp($quarter),
          '%year' => surround_by_nbsp($year),
        ]);
        break;
      }
      $all_certificates[$year][$quarter] = TRUE;
    }
  }

=>Not working for the same reason
What should I do? (I have also tried to validate in the form without luck)
Comment: It's no problem to validate multiple paragraphs in a constraint, see https://drupal.stackexchange.com/questions/278067/adding-constraint-to-paragraph-field. Could this be conneced with the IEF issue from the last question? Also why is the variable a core EntityReferenceFieldItemList and not an [ERR](https://www.drupal.org/project/entity_reference_revisions) field?
Comment: 1-I have edited the question to remove the wrong reference. 2-I have removed the IEF. 3-The example you gave will works because it is not checking the internal values... This is a constraint at the field level (like my example 3) but, in my case, it keep saying I have a duplicate even if I edit the form to remove it (or this opposite)
Comment: Related https://drupal.stackexchange.com/questions/294733/adding-constraint-to-entity-referenced-paragraph-field
Answer: OK, looking at the ERR implementations of $items->referencedEntities() and $item->entity it seems like the first function is able to handle new entities, but only the second is able to handle unsaved entities.
So loop over $items and then get the paragraph from the single field item:
foreach ($items as $item) {
  $paragaph = $item->entity;
  $value = $paragraph->field_foo->value;
  // ...
}

Comment: you saved my day!!!! Many thanks!
Comment: Great find by the way! Didn't know this makes a difference. I cross-link it with the linked example.

How to validate a paragraph field?


Writing down income

Question:
Consider a welfare system under which a single cash transfer (a guaranteed income) is given to every citizen. Then for each dollar the person earns, this payment is reduced by $\alpha$ dollars, where $0<\alpha<1$. Let $Y_G\geq0$ be the guaranteed income. Then, if earned income is $Y_E$, the cash transfer is reduced by $\alpha Y_E$ dollars. So the net transfer is $T=Y_G-\alpha Y_E$. If $T>0$, you get a transfer. If $T<0$, you pay taxes. If $T=0$, you don't pay taxes or receive transfers.

$(i)$ Find an expression for an individual's disposable income, $Y_D$ (i.e., his income after transfers) as a function of $Y_G$, $Y_E$, and other parameters.

Please help me to write disposable income.
Thanks a lot.
What I have thought
Disposable income = total income +transfers
So,
$$Y_D = Y +T$$
$$Y_D = Y +Y_G - \alpha Y_E$$
But I cannot decide what is Y ?
But possibly I think that Y is $ Y_E $
So
$$Y_D = Y_E + Y_G - \alpha Y_E$$
So,
$$Y_D =  (1- \alpha )Y_E +Y_G $$
Comment: Yes it is correct
Answer: This is correct. Intuitively, disposable income is earned income $\pm$ transfer or taxes. You have already correctly identified that the transfer or taxes paid is $Y_T = Y_G - \alpha Y_E$, and it is given in the problem that earned income is $Y_E$.
So, $Y_D = Y_E + Y_G - \alpha Y_E=(1-\alpha )Y_E+Y_G$.

Writing down income


inequality regarding norm of linear operator

Question: Let $T$ be a linear operator on a vector space $X$. For $x\in X$, I know there's the inequality that $$||Tx||<||T||||x||$$
Yet I'm wondering what are those norms. Are they arbitrary? especially on the right hand side there's operator norm and vector norm, how do we cooperate that?
Thank you!
Comment: The inequality states that the vector norm of $Tx$ is less than or equal to the operator norm of $T$ multiplied by the vector norm of $x$. What is your question?
Answer: There are a few equivalent definitions of the operator norm. Perhaps the most relevant for this particular question is the following:
Let $T:V \to W$ be a linear map between two normed vector spaces $V$ and $W$. The operator norm $\|T\|_{op}$ of $T$ is defined to be
$$\|T\|_{op} := \sup \left\{\frac{\|Tx\|}{\|x\|} : x \in V \text{ and } x \not = 0 \right\}$$
It then follows immediately that $\|Tx\| \leq \|T\|_{op} \|x\|$ for any $x \in V$.
Check out Wikipedia for more info.
Answer: This inequality does not hold for arbitrary norms, but only for compatible operator and vector norms.
Let $X$ and $Y$ be normed linear spaces with norms $\|\cdot\|_X$, $\|\cdot\|_Y$, $T:X\to Y$ be linear and continuous.
Then the inequality above is true for the induced operator norm
$$
\|T\|_{L(X,Y)}:= \sup_{x\ne0} \frac{\|Tx\|_Y}{\|x\|_X}.
$$
Due to the supremum property it follows
$$
\|Tx\|_Y \le \|T\|_{L(X,Y)} \|x\|_X.
$$

Here is an example, that the inequality does not hold for arbitrary norms:
Take $X=Y=\mathbb R^2$, $\|x\|_X =\sqrt{ |x_1|^2 + |x_2|^2}$, $\|y\|_Y =  |y_1| + |y_2|$, $\|T\|=\|T\|_2$ (spectral norm):
$$
x=y = \pmatrix{1 \\1} ,  T=I_2
$$
implying
$$
2 = \|Tx\|_Y \not\le \|T\|_2 \|x\|_X = 1\cdot \sqrt2.
$$
Comment: Thank you for your answer, and I have an additional question that it seems that the operator norm is dependent on the norm of the vector space so it has different values? Inequalities like $||T||_{op}<||T||2$ where $||T||_2$ is the Hilbert–Schmidt norm, does it apply for any operator norm?
Comment: The operator norm depends on the vector norm. In general there is no realtion to the Hilbert-Schmidt norm.


Refreshing line reading operator Perl

Question: what happens after the eof is reached with <> operator in perl?
I'm reading INP1 line by line with
while(<INP1>) {
}

but I need to do this reading multiple times and I need to start from the beginning of the file each time. How can I do that? Is there something like refreshing the stream in perl?
Thanks in advance.
Answer: If INP1 is connected to a regular filehandle (not a socket handle or pipe handle), you can also seek back to the beginning of the file.
while(<INP1>) {
   ...
}
seek INP1, 0, 0;

# do it again
while (<INP1>) {
   ...
}

Another option is to load the entire file into an array one time, and then loop through that array as often as you wish. This is a good idea if the whole file fits comfortably in memory and if the contents of the file won't change between traversals.
open INP1, '<', $the_file;
@INP1 = <INP1>;
close INP1;

foreach (@INP1) {
   ...
}

# do it again
foreach (@INP1) {
   ...
}

Comment: use lexically scoped filehandles
Answer: In addition to using seek to go back to the start of the file, you could use Tie::File to treat the file as an array of lines. Depending on your access pattern, this might be more efficient than re-reading the file from the start each and every time.
Answer: You can seek back to the beginning:
use Fcntl;
open INP1, ...
while (<INP1>) {
}
seek INP1, 0, SEEK_SET;
while (<INP1>) {
}

This will only work properly if INP1 is a real file (not a pipe or socket).
Comment: I sure hope this program start with `use strict`, `use warnings qw`, `use autodie`, one or another flavor of `use open qw< :std IO :utf8 >`, `END{close STDOUT}`, and an explicit `close INP1`. Like, you know? :(
Comment: @Adrian: Making syscalls without checking their success is acceptable under what circumstances?
Comment: @tchrist => I think part of the problem might be that most of the perldocs never explicitly check for errors, which probably keeps that from sticking as well as it could.  I just spent a minute googling the docs, and the only example of seek with an error check that I saw was in one of your tutorials :)
Comment: @tchrist: Good suggestions, but they don't address the question the OP asked so I consider them off-topic and won't include them in my answer.
Comment: @Eric: Agreed, but I'm not convinced that's a bad thing. Examples are provided to illustrate a point; error checking creates a distraction. If an example is about using a filehandle any appearance of `open` is secondary; error checking is tertiary noise. Additionally, the appropriate error response is application-dependent, so cargo-culting error checking isn't right, either (though it could lead to better code on average). Finally, "best practice" changes. e.g. even if the docs had `open or die` some would want it changed to `use autodie`.
Comment: @Adrian - tell all the haters to `autodie and goto &hell`

Refreshing line reading operator Perl


Real reverb vs virtual reverb

Question: Times have changed and studios more and more often start using virtual reverb. Yet, some musicians and bands still prefer real reverb: they find places with interesting reverb and record there.
My question is: How good is the quality of a virtual reverb compared to a real one?
Comment: I think the premise of your question is flawed. Unless you consider plates and chambers to be "real", then non-"real" reverb has been used on the majority of recordings since the late 60s. Even if you consider plates and chambers "real", then digital reverbs dominated the 1980s, and today you are certainly hearing a large number of convolution reverbs (a digital modeling process). Some people go old school with a plate reverb. Only rarely are natural spaces used, although actually more often now than in the period of the 70s through the 90s, I would say.
Comment: One of the ways that acoustic spaces are used more often today is via the Internet. There's the famous [Silophone](http://www.npr.org/programs/atc/features/2001/feb/010222.silo.html) and the less famous [Tank-FX](http://cdm.link/2005/03/online-reverb-feed-your-audio-through-a-real-tank/) online acoustic space reverb processing services.
Comment: Why do you consider those to be non-real?
Comment: I didn't say whether I consider them to be real or not. I don't know what you consider to be real or not. Even if you consider plates and chambers "real", they are not currently very popular reverb sources. Digital reverbs from Lexicon and Eventide and convolution reverbs from... pretty much everyone, currently dominate reverb processing. Some genres might have more acoustic space or plate/chamber/spring/hose reverbs used, but I wouldn't say those are the norm.
Answer: You hear virtual digital and convolution reverbs all the time. They sound good enough that tracks and albums that use them go multi-platinum and win Grammy awards every year. Modern sound design for film and TV relies on convolution reverbs to create convincing spaces, especially when dialog is replaced. That's why ADR sounds so much better now than it did in the 70s and 80s. I myself have re-created the interior of an SUV using a convolution reverb for a short film.
You probably hardly ever hear reverb that is not created digitally in major studio releases. So you know very well what it sounds like - you're hearing digital reverb almost every time you listen to music or watch a movie or a TV show.
Answer: In my book, 'real' reverb is when musicians are recorded, almost certainly all at once, in a concert hall or other space.  They aren't close-miced, a stereo pair is placed so as to capture the whole thing, instruments and room.  (In modern practice, there will probably be some spot-micing as well as the main stereo pair.  But the reverb comes from the room, not from any contrived devcice.)  I doubt many 'bands' record in this way.  Orchestras and other acoustic ensembles, yes.
Then there's 'artificial' reverb.  Originally a room containing loudspeaker and microphone.  Then perhaps a plate or spring with transducers at each end.  Or the plate/spring could be replaced by an electronic delay line.  Now more likely to be a computer simulation.   All these methods have their own sound.  I don't really put the 'room containing loudspeaker and microphone' method in any special category.
What's best?  Best at what?  Sounding like it's recorded at Carnegie Hall?  Or best at enhancing today's style of ultra-seperated multi-tracked and processed recording?   Not better, just different.
It's a pity, though, how rarely we hear real stereo - as distinct from pan-potted mono - these days, especially in popular music recordings.  There's a special magic in a three-dimensional 'stereo image' which is worth experiencing.
Comment: "… a stereo pair is placed so as to capture the whole thing, instruments and room." This is how I casually record in my jam space, and it's amazing how well it captures everything, even the drums have separation between pieces on either side of the kit.
Answer: Maybe "natural reverb" vs "digitally added reverb" is a better way of formulating it, to avoid people digressing over "what's real" ?
I suppose one of the advantages of using natural reverb is simply logistics: it's simply practical for a situation like a choir where the choir master for example can try out different dispositions of people in the room until they like the result. Same to any other situation where you have an ensemble of musicians/singers and an artist director that knows what they want. It's instant feedback!
Of course you'd still need someone to figure out how to record it, but compare that to recording one instrument at the time, then spending hours editing it in a computer later, trying things and re-listening, until you get something your ears appreciate.
Both have pros and cons, one could think of it as a different "user interface" for obtaining essentially the same goal.

Real reverb vs virtual reverb


Handle PUT like GET on Apache2

Question: When I request with PUT, I'm getting 405 Method Not Allowed.
I've seen on Internet that PUT is for using with DAV. But I don't want to use DAV and I want to make PUT working like GET.
I tried with Limit, LimitExcept, Rewrite, on Linux and Windows.
I got PHP5 (i think it's not the filtered one), APACHE 2.2 and Ubuntu Server 12.04.
Thanks for help.
Comment: maybe this will help you?
http://stackoverflow.com/questions/2934554/how-to-enable-and-use-http-put-and-delete-with-apache2-and-php
Comment: not working, 405 Method not allowed.
Answer: You need to run a plugin or script that will actually handle PUT. The core of the server isn't willing to do that.
Comment: Yes, I understand you don't want to have to do anything but that's not how it works
Comment: yes but, wich one?
Comment: Pick your language of choice and search the web. There's no popular third party module for this
Comment: actually I just want to make apache run PUT like GET

Handle PUT like GET on Apache2


How to get from a file.txt the array that I need? (in Xcode)

Question: I don't know if it's possible.
In my app I am saving a list of arrays in a file.txt. (e.g.:

2012-09-02 16:27:15.010 SMAccelerometerDataLogger[1950:707] -0.818863 0.286575 0.206177
2012-09-02 16:27:15.017 SMAccelerometerDataLogger[1950:707] -1.024597 0.380875 0.456131
2012-09-02 16:27:15.023 SMAccelerometerDataLogger[1950:707] -0.754196 0.417053 1.165237
...

and I need (the first numbers array):
     -0.818863

     -1.024597

     0.754196

e.g in Gnuplot it is possible
plot "file.txt"using 2:7

I need this array to filter it by FFT, here is my code:
int SIZE = 97;

fftw_complex    *data, *fft_result, *ifft_result;
fftw_plan       plan_forward, plan_backward;
int             i;

data        = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * SIZE);
fft_result  = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * SIZE);
ifft_result = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * SIZE);

plan_forward  = fftw_plan_dft_1d(SIZE, data, fft_result,
                                 FFTW_FORWARD, FFTW_ESTIMATE);
plan_backward = fftw_plan_dft_1d(SIZE, fft_result, ifft_result,
                                 FFTW_BACKWARD, FFTW_ESTIMATE);

for( i = 0 ; i < SIZE ; i++ ) {
    data[i][0] = array[i][0];//>>>> here i should use the array that i need

    data[i][1] = 0.0;
}

for( i = 0 ; i < SIZE ; i++ ) {
    fprintf( stdout, "data[%d] = { %2.2f, %2.2f }\n",
            i, data[i][0], data[i][1] );
}

fftw_execute( plan_forward );

for( i = 0 ; i < SIZE ; i++ ) {
    fprintf( stdout, "fft_result[%d] = { %2.2f, %2.2f }\n",
            i, fft_result[i][0], fft_result[i][1] );
}

fftw_execute( plan_backward );

for( i = 0 ; i < SIZE ; i++ ) {
    fprintf( stdout, "ifft_result[%d] = { %2.2f, %2.2f }\n",
            i, ifft_result[i][0] / SIZE, ifft_result[i][1] / SIZE );
}

fftw_destroy_plan( plan_forward );
fftw_destroy_plan( plan_backward );

fftw_free( data );
fftw_free( fft_result );
fftw_free( ifft_result );

is it possible?  how?
Answer: If the format is always the same then you could split the string by the known delimiter in this case you could get that column of data using something like:
NSArray *components = [line componentsSeparatedByString:@" "];
if (components.count > 3) {
  NSLog(@"%@", components[3]);
}

Comment: thank you for helping.
where should i write the path of the file that i have (file.txt)?
and its showing me an error for `[line componentsSeparatedByString:@" "];`  > use of undeclared identifier "line"; did you mean "link"?
Comment: For efficiently reading a file line by line check out this great answer http://stackoverflow.com/questions/3707427/how-to-read-data-from-nsfilehandle-line-by-line
Comment: thank you, i read it, even that it is for reading lines , i could complete my code from there. :)

but i am getting now null
please take a look on my new Question :
[link](http://stackoverflow.com/questions/23766925/how-to-chose-an-array-from-a-given-file-txt-stringbyappendingpathcomponent-x)


Navbar Bootstrap 4 collapse já automatico

Question: Estou copiando EXATAMENTE qualquer modelo de navbar que encontrei na nova documentação do bootstrap 4 que estou a utilizar nos meus projetos.
Só que, ele já vem "collapsado" digamos assim.
Existe alguma função em javascript que eu possa colocar para que ele não "collaspse" automaticamente.
Segue o menu que copiei do bootstrap 4: https://jsfiddle.net/7pq9zoaL/
Esse é o layout que estou fazendo: https://jsfiddle.net/yxwzwq7e/ (uma dashboard simples)
Comment: Rafael, edita a pergunta com o código  de exemplo? você pode usar o Bootstrap CND(https://v4-alpha.getbootstrap.com/getting-started/download/#bootstrap-cdn) para o fiddle.
Comment: Atualizei, obrigado!
Answer: Simples, na div
 consta a classe collapse que justamente "colide" a sua nav. Basta remover, ficando assim
, segue exemplo:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#nav-content" aria-controls="nav-content" aria-expanded="false" aria-label="Toggle navigation">

   </button>
  Logo

        Link 1

        Link 2

        Link 3

Ou você pode manter a classe collapse e executar a função toggle() do Jquery após o load da sua página com o seguinte código do Jquery $("#nav-content").toggle();, segue exemplo:

$("#nav-content").toggle();

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#nav-content" aria-controls="nav-content" aria-expanded="false" aria-label="Toggle navigation">

   </button>
  Logo

        Link 1

        Link 2

        Link 3


Submitting a Pyspark job with multiple files in AWS EMR

Question: I have a pyspark job that is distributed in multiple code files in this structure:
flexible_clendar
   - Cache
       - redis_main.py
   - Helpers
       - helpers.py
   - Spark
       - spark_main.py
   - main.py

In the 'main.py' I'm using the functions from 'helpers.py', 'redis_main.py', etc...
The 'flexible_calendar' folder is uploaded in S3 bucket, so that the EMR could run the code from it.
Iv'e created an EMR cluster that is bootstraped with all the needed packages and it is working if I'm running a simple-one file code (from s3) with all the functions in it:

The problem is when I'm trying to use the distributed file structure the code fails, because it doesn't recognize the files from 'helpers.py', 'spark_main', etc... like so:

I've tried multiple configurations in the 'Step Arguments' field which none of them worked, such as:
Arguments: spark-submit --deploy-mode cluster s3://flexible-calendar/flexible-calendar-emr
Arguments: spark-submit --deploy-mode cluster s3://flexible-calendar/flexible-calendar-emr/Cache/redis_main.py s3://flexible-calendar/flexible-calendar-emr/Helpers/helpers.py s3://flexible-calendar/flexible-calendar-emr/Spark/spark_main.py s3://flexible-calendar/flexible-calendar-emr/main.py
Arguments: spark-submit --deploy-mode cluster --class s3://flexible-calendar/flexible-calendar-emr s3://flexible-calendar/flexible-calendar-emr/main.py
Arguments: spark-submit --deploy-mode cluster --class s3://flexible-calendar/main_one.py

Also:

Arguments: spark-submit --py-files s3://flexible-calendar/flexible-calendar-emr.zip
Arguments: spark-submit --deploy-mode --py-files s3://flexible-calendar/flexible-calendar-emr.zip
Arguments: spark-submit --py-files s3://flexible-calendar/flexible-calendar-emr.zip --deploy-mode cluster s3://flexible-calendar/flexible-calendar-emr/Spark/spark_main.py
Arguments: spark-submit --deploy-mode cluster s3://flexible-calendar/flexible-calendar-emr/Spark/spark_main.py --py-files s3://flexible-calendar/flexible-calendar-emr.zip

and more...
Hope someone could help,
Thanks.
Answer: Quoting from Spark Documentation:

For Python, you can use the --py-files argument of spark-submit to add .py, .zip or .egg files to be distributed with your application. If you depend on multiple Python files we recommend packaging them into a .zip or .egg.
Comment: I've tried 'spark-submit --py-files s3://flexible-calendar/flexible-calendar-emr.zip' and 'spark-submit --deploy-mode cluster s3://flexible-calendar/flexible-calendar-emr/Spark/spark_main.py --py-files s3://flexible-calendar/flexible-calendar-emr.zip' and it didn't work..
Answer: So the zip file you have created needs to be added to the sys path inside the main.py.
if os.path.exists('flexible-calendar-emr.zip'):
    sys.path.insert(0, 'flexible-calendar-emr.zip')

Let me know of this helps!
Comment: I added this to the 'main.py' file and tried all the steps above and nothing worked...


Oracle: SELECT statement GROUP BY clause

Question: I'm working with a table with structure like the following: (not my design, can't be changed)
Columns:    foreign_key    job_type    job_code
            1              1           AA
            1              2           BB
            2              1
            2              2           CC

Values in job_type can only be 1 or 2. Values in job_code can be any varchar.
I'm trying to get rows from this table in the following order:
            foreign_key    job_type_1_code    job_type_2_code

My search query is like this:
select foreign_key
from my_table
    where
    ( job_type = 1 and job_code like 'D%'
      or
      job_type = 2 and job_code like 'in_job_2_code%'
    )
group by foreign_key

The problem I have is that this returns job_code BB and CC when I'm expecting no results at all.
How can I group these together so that the query will not return any result?
Comment: You need to use a [Pivot](http://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php)
Answer: Below query works if you always have records for both job types:
SELECT a.foreign_key, a.job_code as job_type_1_code, b.job_code as job_type_2_code,
FROM table_name a INNER JOIN table_name b ON a.foreign_key = b.foreign_key
    AND a.job_type = 1 AND b.job_type = 2

Answer: you need to use CASE statement not Group by
select foreign_key,
 case job_type when 1 then job_code else null end as job_type_1_code,
 case job_type when 2 then job_code else null end as job_type_2_code
from your_table


Swift - Como pego uma imagem da internet e mando para uma ImageView?

Question: Possuo uma ImageView, quero pegar uma imagem da internet (através de um link) e jogar pra ImageView na tela.
Exemplo de imagem a ser capturada:
   http://likefotos.com/wp-content/uploads/2015/01/paisagem-tailandia1.jpg
Como quero que apareça
Answer: Vc. está usando Mac ou a versao free no Linux ?Porque no Linux ainda nao tem as foundations liberadas. Ainda assim a versao free da usar com lib chamada Zewo que é só procurar no github.
para Mac vc. já viu aqui ?  ->
https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift
Comment: Era em Mac. Funcionou aqui da forma mostrada neste link. Obrigado.


How can I parse the localStorage object and get values

Question: I have below localStorageData object with following items. Depending upon the need I might pass any object like recordId, autoId, simId, sessionId into the  localData.saveLocalStorageData({recordId});
So in the main.js file how can I call the localStorageData object and parse the recordId or autoId or simId and assign the value to data ?
localStorage.js
    let localStorageData = {};

    function saveLocalStorageData ({recordId, autoId, simId, sessionId}) {
        localStorageData = {
            recordId:recordId,
            autoId: autoId,
            simId: simId,
            sessionId : sessionId
        }
        return localStorageData
    }

    export { saveLocalStorageData };

record.js
        let localData = require("../../support/localStorage");

        let text =  $('#someId > span').text();
        let ele = text.split("#");
        let recordId = {};
        recordId = ele;
        const localStorageData =   localData.saveLocalStorageData({recordId});
        window.localStorage.setItem('localStorageData', JSON.stringify(localStorageData));

main.js
    const moment = require('moment');
    let data;
    const today = moment().format('DD/MM/YYYY');

    /* Below code snippet will find the columnPosition of the desired column in a table */
    const columnPosition = $(`#RecordIdMain`)
        .find(`th:has(a:contains("Record"))`)
        .index();

    if (value === 'localStorage') {
    // how can I call the localStorageData object and parse the recordId or autoId or simId and assign the value to data ?
      data = ???
    } else if (value === 'date') {
        data = today;
    } else {
        data = value;
    }

Comment: keep in mind, localStorage is just saving a string. you are just saving a string to localStorage, and then reading a string back. whatever you do with that string beyond that, has nothing to do with localStorage.
Answer: Using a localStorage object requires you to JSON.parse() it first.
console.log({'loginStatus': JSON.parse(window.localStorage.getItem('loginStatus')).isAuthenticated})

You need a variable that contains the item key you want to retrieve, and it has to be a string:
const key = 'someId' || 'autoId' ... // (some logic to determine the item key)

let data

fakeLocalStorageItem = {
  "autoId": "123",
  "simId": "aaa111",
  "someId": "2bb2bcQQQ",
  "recordId": "44342asd33423-234234"
}

// Convert fake json to imitate localStorage string format:
const stringJson = JSON.stringify(fakeLocalStorageItem)

// Convert it back to a js object
storedItem = JSON.parse(localStorage.getItem(stringJson))

if ((1 + 1) === 2) {
  data = storedItem.key
} else if (value === 'date') {
  data = today;
} else {
  data = value;
}

Comment: value is a variable that has "localStorage" string ...in my situation I have to add an if case like that....
Comment: No, I have stored the localtorage is as an object and the object have recordId or autoId, or simId or sessionId...so I would like to have way to get any one of the items to be retreived and assign into the data varaible.. so .i can't just say ```window.localStorage.getItem('recordId ')``` ...so this will always get recordId only ..so if    the value stored simId or autoId the above will not work right ?


Blocks are invisible after hosting drupal7

Question: I am facing with a problem in drupal7, I am new to drupal7 too. When I run my website in localhost everything fine, blocks and menu are visible. But after I host my website in GoDaddy, that blocks and menu are invisible, where they gone. I am also hoping someone can help me to solve this problem. Thanks.
This is the image when I call this website in localhost. We can see block and menu.

This is the image when I call after hosting this website.
Comment: It might help if you could explain how you transfered the site.
Comment: I doubt, that would be paths problem. Checkout the paths you have given in blocks.
Answer: Sometime the issue occurs when we migrate the site. Just follow through these steps:-
1) Check the block section of the local and live site
2) Check all blocks from the local and live
3) Now assign the blocks to the same regions in live as it is in the local setup
4) Check blocks are visible on the given region on the page or not.
Edit the blocks to set their display settings.
Answer: You configured the block in your localsite so the data is stored in your local database.
Please take dump from your local site the import the dump into your server database.


Script (window.innerHeight) not working in IE

Question: Hi all the following script was working fine on chrome and firefox but not in IE11. Any solutions please
window.onscroll = function (i)
 {
   window.innerHeight + window.scrollY >= document.body.offsetHeight ?
   $("#str").removeClass("str_one") : $("#str").addClass("str_one")
  };

Comment: window.scrollY not supported in IE https://developer.mozilla.org/ru/docs/Web/API/Window/scrollY you can use
document.documentElement.scrollTop
and check this https://stackoverflow.com/questions/16618785/ie8-alternative-to-window-scrolly
Comment: Did you try debugging it, e.g. logging the values of `window.innerHeight`, `window.scrollY`, and `document.body.offsetHeight`?
Answer:

window.getWindowSize= function(){
    if(window.innerWidth!= undefined){
        return [window.innerWidth, window.innerHeight];
    }
    else{
        var docBody= document.body,
        docEle= document.documentElement;
        return [Math.max(docEle.clientWidth, docBody.clientWidth),
        Math.max(docEle.clientHeight, docBody.clientHeight)];
    }
}


How to know which file to delete in a submit function?

Question: I've got a managed file field in a form like this:
$form['source_file'] = array(
  '#type' => 'managed_file',
  '#title' => t('Source File'),
  '#default_value' => isset($data['source_file']) ? $data['source_file'] : 0,
  '#upload_validators' => array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ),
  '#upload_location' => 'public://imagemerge/merge/',
  '#required' => FALSE,
);

My submit function looks like this so far:
function imagemerge_merge_submit($form, &$form_state) {
  $source_file_fid = $form_state['values']['data']['source_file'];
    if ($source_file_fid != 0) {
      $source_file = file_load($source_file_fid);
      $source_file->status = FILE_STATUS_PERMANENT;
      file_save($source_file);
    } else {
      //some logic to determine previous fid?
      //and then a call to file_delete()
    }
  }

The docs for Forms API under managed_file say that it is up to the module to call file_delete. How do I know when and which file to delete?
Answer: Ok I solved this but it will be different for each type of form.  The form I was adding this managed_file upload to is actually the image effect form. (image_effect_form(), I had to do some form_altering to add my submit function.) My goal was to add a new image effect that allows placing a source file onto the destination image.
What I finally did was compare the $form_state variables in the submit function for the following actions:

uploading a file when none was previously there
removing a file and submitting no file
removing a file and uploading a new file

For this particular form I came up with the following variables:
$new_fid = $form_state['values']['data']['myformfile'];
$old_fid = $form_state['image_effect']['data']['myformfile'];

Once I got what the new FID is and what the old FID was It was trivial to put together some logic that deletes the file at the appropriate place. The problem is that this isn't universal logic that works for every type of form that has a managed_file in it. There didn't seem to be a standard way to get what the old file FID was. I found it for this specific form but for the next time I do a managed_file I'll have to examine $form_state again and find out if/where the old file FID is stored.
My code for the submit function is below. I also added some logic for the file_usage table.
$source_file_new_fid = $form_state['values']['data']['source_file'];
$source_file_old_fid = $form_state['image_effect']['data']['source_file'];

if ($source_file_new_fid != 0) {
  $source_file = file_load($source_file_new_fid);
  $source_file->status = FILE_STATUS_PERMANENT;
  file_save($source_file);
  file_usage_add($source_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
}

if ($source_file_old_fid != 0) {
  $del_file = file_load($source_file_old_fid);
  file_usage_delete($del_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
  file_delete($del_file);
}

Answer: Looking at the description given in the "Form API Reference" page for the "#managed_file" form field, I read the following sentence:

The #managed_file element is expanded into a set of FAPI elements including two '#submit' buttons one for Upload one for Remove, a '#file' element and a handful of '#hidden' and '#markup' elements to handle progress indication and displaying of already uploaded files.

Looking then at the process function for that form field (file_managed_file_process()), which is the one set from file_element_info(), I notice that it defines a form submission handler for the "Remove" button, and that function (file_managed_file_submit()) calls file_delete().
  if ($button_key == 'remove_button') {
    // If it's a temporary file we can safely remove it immediately, otherwise
    // it's up to the implementing module to clean up files that are in use.
    if ($element['#file'] && $element['#file']->status == 0) {
      file_delete($element['#file']);
    }
    // …
  }

I would say there isn't the need for the module using that form field to call file_delete().
Comment: Ahh so the only thing I need to do is mark the file FILE_STATUS_PERMANENT and call file_save. I guess I should do that if the fid is 0 though, right?
Comment: Hmm I'm testing this and it seems like the file never get's deleted and it stays in the file_managed table as well. Apparently I do need to delete the file somehow.
Comment: To notice that the code checks `$element['#file']->status`; the "Remove" button deletes the file that has been previously uploaded. If you select a file, but you don't upload it, then that button doesn't delete the file.
Comment: I checked on my test server, and the file is deleted when I click on "Remove," and then on "Save" to save the node. (The file is actually an image that is added to the node.)
Comment: On my form the file is NOT deleted when I click remove and then submit. See my answer for details.
Answer: It's definitely so that you will have to delete the file yourself if the file was made permanent. My guess that could be when the module get's uninstalled? Or if the node get's deleted?


Fully qualified name with dollar sign in SSDT project

Question: I was working on a tsql project, and I have noticed that the existing code used a syntax that I have not seen before. They have put a dollar sign in front of the database name for fully qualified address.
Here is one example :
SELECT  c.AccountCode, FROM **[$(SmartAdmin)]**.dbo.Customers c

If I rename the database name as SmartAdmin.dbo.Customers, Visual Studio throws error says "contains an unresolved reference to an object".
It appears to be a Visual Studio related thing, can anyone explain what is this and
whether I can remove it.
Please see the attached screenshots, the last one comes from project solution file.
Comment: go to sql server and execute `Select * From sys.databases` and see if your database is actually called `$(SmartAdmin)`.
Comment: @GSerg - SSDT (visual studio) uses this for cross database references. It ought to resolve them itself if all set up correctly.
Comment: Seems [pretty boring](http://stackoverflow.com/q/3551284/11683) to me.
Comment: Well, if I don't solve this issue, my database project will not build and I can't check in. So, it is not boring to me. Thanks
Comment: Hi M.Ali thank you very much for your comments. The database is called SmartAdmin, and in Visual Studio, I have always be able to call it using fully qualified name as [SmartAdmin].[dbo].[TableName] without any issue.
Comment: looks like the usual format for a parameter placeholder that would be substituted by code.
Comment: Hi Mitch, thank you very much for your comments. I think it is to do with Visual Studio settings. Please see the attached screenshot. Regards.
Comment: so you have your answer.
Comment: Not yet, modified solution file, still not working.
Comment: The `[$(SmartAdmin)]` is not the problem. The rest of the error message is the problem. Read what it says about ambiguous references.
Comment: This appears to be an SQL script with parameters intended for the [sqlcmd utility](http://dba.stackexchange.com/a/46258/5203), not to be directly executed from the studio.
Answer: The [$(SmartAdmin)] syntax is used in an SSDT project to reference objects in other databases. To be precise, it is SQLCMD syntax.
If you have a database reference to SmartAdmin, and if the reference is set up so that [$(SmartAdmin)] properly references it, then that is not the problem. It looks like the problem is the other two references to [SmartAdmin]. Change them to look like [$(SmartAdmin)].dbo.whatever.

Example of why these references are useful: I just edited a stored procedure I had in SSDT to misspell a column name. Within seconds, the column name was underlined in red. I then deleted the database reference the column name depended on. The red underline went away. I added the database reference back, and the column was once again underlined in red. I corrected the column name, and the red underline went away.
Without the database reference, I would have had to wait until the stored procedure was deployed, or possibly executed, to see the error. With the database reference, I found out about the problem in the editor. Just like code.
Comment: Hi John, thank you very much for the solution ! Do you know where I should go in Visual Studio to change that reference. I would like to just call it as [SmartAdmin] instead of [$(SmartAdmin)]. Thank you.
Comment: You can't change it that way. The `[$()]` is syntax, not naming. If you don't switch those external references to the `[$(x)]` syntax, you will lose some of the best features in SSDT. For instance, SSDT won't know the data types of `sp.[PerSms]` and `spo.[PerSms]`, so it won't be able to warn you about inconsistent use of the `PerSms` column of the view. It's ugly, but once you get used to it, you'll see the benefits. Once you get the projects building, start turning on code analysis and you'll see problems you never imagined were there.
Comment: You can also change your database reference to NOT reference through a variable name. Edit the properties of your database reference to do that and then reference the way your normally would.
Comment: @PeterSchott: how would you do this (edit the properties)? I don't see a way to accomplish that. And I just verified that if you don't use a DB reference, then SSDT will not notice errors in referencing the other DB.
Comment: See if this helps: http://schottsql.blogspot.com/2012/10/ssdt-external-database-references.html
Comment: @PeterSchott that was interesting, but it didn't "work". Meaning with a blank variable name and referencing db as "SmartAdmin.", I can still use invalid column names. Please try this "negative test" and see what you see. I am using SQL Server 2008 and VS2013 Ultimate.
Comment: It sounds like you might have turned off that warning in your project - suppress warnings in the main project properties can do that. I don't think you'll get an error in those cases, but you should get a warning unless they've been suppressed. If you get warnings, you can set the project to treat warnings as errors for the purpose of builds. That may help a bit. --- I'd also recommend using DB References rather than counting on SSDT not seeing errors.
Comment: @PeterSchott: which warning? I suppress warnings from unreferenced objects in the referenced project, but that shouldn't prevent SSDT from showing me warnings in the referencing project. In fact, I see those warnings when I use the database reference with the variable. This is why I use such references - I want to see the warnings. Your technique prevents warnings about the referencing project. In fact, I think your technique causes SSDT to not use the reference at all, at least, not in the editor.
Comment: Strange - when I use that method and try to reference a column that was added to a later version of the dacpac (i.e., not in the current dacpac), I get a warning about it. I'll most often get the warnings on build, but have seen them pop up in the editor as well. I'll do some more digging into what we're doing to see if I can repro or give better examples.
Comment: Also, I have been using references to database projects in the same solution, if that matters at all.
Answer: It appears to me that your database is actually called $(SmartAdmin)
As the error suggests "contains an unresolved reference to an object". which means when you change the database name to SmartAdmin, it cannot find a database with this name on server.
If you want to change the database name you will need to execute the following statement and then you will be able to use that name in your statements.
USE master;
GO

EXEC sp_renamedb '$(SmartAdmin)', 'SmartAdmin';
GO

USE SmartAdmin;  --<-- Now you will be able to connect to this database
GO                 -- without the dollar ($) sign.

Comment: Hi M.Ali. Thank you very much for your answer. However, the database is named SmartAdmin without $(). Regards,
Answer: This issue relates to Database Project External Database References. When you add another solution to a database project, you can specify the "Database Variable Name", in my case, it is $(SmartAdmin).
Please see this link for more information.
Thanks everybody for answering my question.


Multiple AJAX Requests Without Refresh

Question: I have a form that contains lines for company name address post code etc.
I have an option where if you don't know the full details you can enter the name and click search. This will get a list of all companies with a similar name via AJAX and return them to a modal window (not sure if this is the best method)
Each of the companies in the list has a button next to them to enable the user to select that company.
After click the company they want the form closes and I want the address details on the original page to be completed.
The problem is that the button on the modal after being clicked is refreshing the original page as i am use the method="post" command and this is removing any other data that is already in original form.
Is there a way to close the modal and update the original form without refreshing?
Thanks
This is my original page:
<input type="text" id="text1"><button id="button"> Search </button>
<input type="text" id="Address1">
<input type="text" id="Address2">
<input type="text" id="Country">
<input type="text" id="PostCode">

      <button type="button" class="close" data-dismiss="modal">×</button>

Companies Found

      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

And this is the page i call via AJAX:
$company_name= $_POST['text1'] ;
$api_key = 'xxx'; // Get your API key from here:     https://developer.companieshouse.gov.uk

$api = new companiesHouseApi($api_key);
$response = $api->send('/search/companies', ['q' => $company_name]); //  Process API request

echo'';

echo'
';

foreach($response['items'] as $key){
echo' <form action="search.php" method="post">';
echo'
';
echo'    '.$key['title'] . "
".'	';
echo'     <input type="submit" value="Submit">	';
echo'
';

echo'
';
echo'    '.$key['description'] . "
".'	';
echo'
';

echo'
';
echo'    '.$key['address_snippet'] . "
".'	';
echo'
';
echo' </form>';
}

echo'
';

Answer: Set the forms action to the page your on and change your javascript into a function like this:

Process the form in php and check to see if the fields are blank (do your form processing here).
If they are blank, call the javascript function from php like this:
echo ''
;

If the form has the required fields, process the data and then use this to redirect to another page if desired:
header('Location: destination.php')

This is important, the statement above MUST be called before any html code (including echo from php)
On your ajax php page, I would recommend making 1 string of the data using a variable and then echo once the variable for example:
$str = '';
$str .= '
';
$str .= '    '.$key['address_snippet'] . "
".'	';
$str .= '
';
echo $str;

Comment: I'm still confused sorry. The modal displays the results of the Ajax call. I then need to close the modal and populate the original fields without refreshing.
Comment: as the modal is in the first pages code, you could run a javascript function when the ok button in the modal is clicked. the code would take the values from the modal fields and then set the values of the fields in the main page, finally close the modal. (the fields would need unique id's to ensure you put the data in the correct fields). this would run without refreshing the page as anything with get or post will need a page refresh.
Comment: thanks that worked I'm nearly there. I have managed to populate the fields however for some reason no matter what button i lick it only passes the value of the first button even though the values in each form are differet?
Comment: Could you edit your question to show the modal form processing code please
Answer: The reason why it is reloading your page is because you have used submit buttons inside table rows wrapped in forms.
For one thing, that is bad HTML as

 tags should not be immediately wrapped in <form></form> tags. But more importantly, if you have a submit button within a form, it will submit the form upon click (unless of course you do something to prevent it using JavaScript).
Here's what I propose you do:
PHP
Remove <form/> tag that is wrapped around the table rows.
Change the type attribute of your button to button. Most browsers will treat this as a non-submit button.
Attach a class to the table cells that you will need to copy into the form. For demonstration, we have given the last table cell an address class. We are attaching a class to reference it later.
foreach ($response['items'] as $key) {
    echo '
';
        echo ''. $key['title'] . '
	';
        echo '<input type="button" value="Submit">	';
    echo '
';

    echo '
';
        echo ''. $key['description'] . '
	';
    echo '
';

    echo '
';
        echo ''. $key['address_snippet'] . '
	';
    echo '
';
}

JS
Make use of event delegation to attach event handler to dynamically created elements. We will attach an onclick event handler to your table buttons.
Now, you know what you need to do when you click a button: (1) close the modal (2) populate form with company information using the button's table row as starting point of reference. I have no idea what address snippet is, but below should show you how you can copy content from your table row into the form.
$('#button').click(function() {
    $.ajax({
        type: 'POST',
        url: 'api.php',
        data: {
            text1: $('#text1').val()
        },
        success: function (response) {
            $("#myModal").modal('show');
            $('#result').html(response);
        }
    });
});

$('#myModal').on('click', 'table.tg input[type=button]', function () {
    // get table row containing the button
    var $tr = $(this).closest('tr');
    // close modal
    $('#myModal').modal('hide');
    // populate form
    $('#Address1').val($tr.find('.address').text());
});

Extra
You may find HTML5 data attributes useful here. You could store the company information in the
.
echo '
';

And instead reference them in your JavaScript code using
$('#Address1').val($tr.data('address1'));
$('#Address2').val($tr.data('address2'));

Multiple AJAX Requests Without Refresh


Programmatically created content type module title not working

Question: I created a module with a .info, .module and .install file that can be installed by customers. This module file to create content types from node consists basically atm of:
<code>/**
* Implements hook_node_info()
*/
function mycontent_node_info() {
  return array(
    'mycontent' => array(
        'name' => t('My content'),
        'base' => 'mycontent',
        'description' => t('You can define your objects here'),
        'has_title' => TRUE,
        'title_label' => t('Object title')
       )
    );
}

/**
* Implement hook_form()
*/
function mycontent_form($node, $form_state) {
   return node_content_form($node, $form_state);
}
</code>
The problem is as follows:
I want to use entity translation. This works fine but the title module. It ist automatically installed, so the standard title of nodes can be replaced by clicking 'replace', but the default language is not filled.
E.g. if default language is German, the title is not saved. When I translate in English, the English title is saved. When I debug I can see that the complete (German or English) form is taken, the value of the form state are identical except the content itself and the language values 'de' and 'en'.
If I change en as default language then english title is not saved.
Because i can not see anything in the issue tracker of the title module I hope that I have to add anything to my code.
Thx in advance
maen
Answer: Ok, I BELIEVE that this is a drupal core issue:
I thought I can create a module with another name as the node bundle I made.
<code>/**
* Implements hook_node_info()
*/
function mycontent_node_info() {
  return array(
    'mycontent' => array(
      'name' => t('My content'),
      'base' => 'mycontent',
      'description' => t('You can define your objects here'),
      'has_title' => TRUE,
      'title_label' => t('Object title')
     )
  );
 }

 /**
  * Implement hook_form()
 */
   function mycontent_form($node, $form_state) {
     return node_content_form($node, $form_state);
   }
</code>
This is correct! But my module and hence my hook_node_info function had another name than my bundle.
So admin/strucure/types didn't show the bundle and the module title didn't recognize the bundle property.
So this is solved!


Criar conta de email com PHP através do CPANEL

Question: Gostaria de saber se é possivel criar uma conta de e-mail usando o CPANEL, mas não de forma manual, e sim de forma programática?
Preciso automatizar a criação, pois manualmente não seria possivel dar conta da demanda.
Comment: Só depende de como seu sistema de emails funciona. Muitos sistemas tem APIs para isso, mas cada um tem o seu modo de trabalhar. Da forma como está a pergunta, tem um numero infinito de respostas. Precisa [edit] e ser bem mais específico quanto à infraestrutura de emails que usa atualmente (e o quanto conhece dela).
Comment: O problema nada tem a ver com PHP. Email não usa um sistema padrão de criação de contas. Cada sistema de email (que não tem absolutamente relação nenhuma com a hospedagem do site) tem seu próprio meio de criar contas. Um email Google funciona de determinada maneira, um email da Microsoft funciona de outra, o meu sistema de emails local usa uma terceira maneira, e assim vai. Com certeza o CPanel não conseguiria criar um email na minha hospedagem, por exemplo. O fato é que por acaso, quem instala CPanel e libera o recurso de criação nele, optou por um sistema de email compativel.
Comment: Agora, depois do edit, o que vc procura é isto: https://documentation.cpanel.net/display/SDK/Guide+to+cPanel+API+2 - Mas ainda continua dependendo do CPanel, no caso.
Comment: @Bacco, primeiro obrigado pelo feedback, estava recebendo varios fechar() e ninguem havia comentado, não saberia o motivo.. Por segundo: Não consigo pensar que haja infinitas respostas, na minha mente parece Claro. Veja só: Tenho um site, xxx.com, e quero criar uma conta de e-mail nele, pro exemplo: firstname.lastname@example.com, o PHP não tem métodos ou bibliotecas conhecidas para isso? pois penso: Cpanel faz isso, porque nao posso fazer? Pensei que era algo mais simples, como sou leigo nisso, talvez exista uma linha de pensamento mais complexa que não estou dando conta de acompanhar.
Comment: @Bacco Obrigado, editei para tentar não colocar o tópico no lixo e aproveitar para tirar a dúvida que talvez alguém passa ou passará.
Answer: A documentação do CPanel orienta a utilizar a UAPI: https://documentation.cpanel.net/display/SDK/Guide+to+UAPI
Versão suportada: 11.42 ou superior
Para criar uma conta de email, mostrarei um exemplo com a LiveAPI (PHP Class)
// Inclua a library principal do CPANEL
// O local do arquivo varia de acordo com o ambiente. Verifique em qual local está o arquivo no seu ambiente.
require_once '/usr/local/cpanel/php/cpanel.php';

// Instancia o objeto CPANEL. (Faça apenas uma instância)
$cpanel = new CPANEL();

// Aqui invocamos o método uapi informando os parâmetros para criação de conta de email
// Criaremos o email email@example.com com 50mb de quota (espaço limite em disco)
$new_email = $cpanel->uapi(
    'Email', 'add_pop',
    array(
        'email'           => 'sample',
        'password'        => '123456',
        'quota'           => '50', // Caso queira ilimitado, coloque 0 (ZERO)
        'domain'          => 'foo.bar', // domínio
        'skip_update_db'  => '1'
    )
);

Quando bem sucedido retorna uma string no formato user+domain. No caso do exemplo acima, sample+foo.bar.
Documentação: https://documentation.cpanel.net/display/SDK/UAPI+Functions+-+Email%3A%3Aadd_pop
Para a versão 11 até a versão atual (legacy): https://documentation.cpanel.net/display/SDK/cPanel+API+2+Functions+-+Email%3A%3Aaddpop
// Create the firstname.lastname@example.com email address.
$add_email_address = $cpanel->api2(
    'Email', 'addpop',
    array(
        'domain'          => 'foo.bar',
        'email'           => 'sample',
        'password'        => '123456',
        'quota'           => '50',
    )
);


Is there a way to get C++ source compiled into a binary so gdb can see it?

Question: Say I have a build machine and test machine and the source code is only on the build machine. (Linux)
I have a debug build C/C++ executable and I want to run it with gdb on the test machine.
In the debugger running on the test machine it is still looking for the actual source files which are not there.
Is there a way to have g++ actual include the source in the executable itself with the other debug information so files are not needed?
Answer: There is no way to have the source compiled into the binary to allow gdb debugging in this manner.
Probably the best mechanism in this case is to use gdbserver - which allows you to run the application remotely and debug it on the build machine.
If you can't use remote debugging, then an alternative is to mount the directory containing the source on the test machine, and then use the set substitute-path to map the directory that the test machine has vs. the build machine.
Answer: No, but the good news is that is no necessary. You should set your source path. It should accept a network path.


Is there some pattern behind the many VIM commands?

Question: I have to add a VIM personality to an IDE. I never used VIM for more than the most basic edits and i'm now overwhelmed by the complexity of the command structure.
Is there any overall structure for the combination of counts moves and insert/delete commands?
I just can't see the wood for the trees.
Answer: Well, there is obviously a finger position pattern behind h, j, k, l.
The fact that ^ goes to the beginning of a line and $ goes to the end is patterned on common regular expression syntax.
Ctrl-F and Ctrl-B page forward and back, and that's fairly intuitive.
i inserts (before) and a appends (after the cursor). Similarly,
I inserts at the beginning of the line, and A appends at the very end.
> and < indent and outdent, respectively. That's also kind of intuitive.
But on the whole, many of the other commands are on whatever keys were left – it's hard to find an intuitive mapping between the letters of the alphabet and an editor's commands.
Repeat counts are always entered before a command, and mostly repeat the command that many times, but in some cases do something clever but analogous.
I think the secret to not going crazy over vi is to start out with only a small handful of commands. I have a lot of colleagues who don't know to do anything other than

move the cursor around using the arrow keys (you don't have to use h, j, k, l);
insert with i, delete with Del (you don't have to use x);
delete a line with dd
get out of input mode with Esc
get out of vi with :x (exit) or q! (quit, and throw away my changes!)

Because I'm much smarter, the additional commands I know and use are:

go to the top of the file with gg, the bottom with G.
I can go to a specified line number with (line-number)G.
copy a line with y (yank), paste it with p
change a word with cw, the rest of the line with C
delete a word with dw, the rest of the line with D
I sometimes use . to repeat the last command, or u (undo) if I messed up.

When you have occasion to use other commands, you can teach them to yourself one by one as needed.
Answer: This is a good article for explaining the VIM philosophy.
Answer: I think the characteristic that better defines VIM in respect to other editors is its wide array of motion commands. The first thing to learn to fully use VIM is hitting the arrow keys as little as possible, and think at the text in terms of "blocks" like "a sentence" "a tag" "a word" "a group of brackets".
Say you have function foo($bar, $fooz) you can change the parameters by simply positioning your cursor anywhere inside the brackets and pressing ci) (mnemonic: change inner bracket). The same pattern applies to other commands: yank (y), delete (d) and so on.
I know this doesn't explain the whole "VIM philosophy" but combining normal mode commands with the vast amount of motion modifiers is what really made me see the light.
Answer: There are plenty of nice and interesting tutorials. One example is
http://blog.interlinked.org/tutorials/vim_tutorial.html
But the broad structure that most of them would give you is

There are two main modes for editing - Command mode and insert mode. You can move from insert mode to command mode using the  key.
You can execute commands in the command mode by typing a single key or a sequence of keys.
Commands can help you achieve a wide variety of things
deletion of lines - dd
yanking (copying of lines ) - yy
pasting lines below the current line - p
pasting lines above the current line - P ( and so on)
Most commands in the command mode can be pre-fixed by a "count" to indicate the number of times the command has to be executed. For example, 3dd would delete three lines.
One set of commands in the command mode lets you move to the insert mode. That is explained below.
There are different ways of entering the insert mode from the command mode. Prominent among them are (i-insert at cursor, I-insert at beginning of line, o-insert a line below, O-insert a line above, a-append, A-append at end of line.

The quick reference at
http://www.andy-roberts.net/misc/vim/vim.pdf
Will help you understand the relevance of "count"


Is it possible to use search api indexs together?

Question: I'm trying to create a search page for forum topics. Forum topics however are both posts and the comments attached to them, unlike other content the comments and actually posts are just as important to search.
I have an index of all forum posts and one of all forum comments. I'd like to be able to have both searchable from one page. Maybe even if it's possible then I'd like to have one index that handles all of them. But if that is not possible then is it possible to combine two index's in search api into one page search?
I'm not finding anything on this so far, but will keep looking. If I find something before I get an answer I'll post it here.
Answer: Yes, you need to used the Search API multi-index searches module.

This module is an addition to the Search API module which allows users
  to search on several indexes at once.
When the module is enabled, you'll get a new Views base table where
  you can search all enabled Search API indexes at once. Performance
  might suffer, though, if not all indexes lie on the same Solr server
  (or other backend server that supports this feature).
Please note that, since multi-index searches aren't supported
  explicitly by the Search API, most other Search API add-on
  functionality (facets, autocomplete, saved searches, search pages,
  etc.) won't work with searches created with this module.

There is also a sanbox project that allows you to combine Search Multi Index and Facets.
Comment: Thanks, I just found that module and was about to update this question with that as an answer. Forums are just one of those use cases where it's not just the node you need indexed but the comments as well.


codeigniter 301 redirect with router for old url and remaning no redirect

Question: I have a codeigniter site, for which i am doing SEO, so the issue is most of the urls are cached in search engines, what my old url is
<code>/product/details/productname/productid
</code>
My new urls will be
<code>/tours/cityname/productname
</code>
I want for my old urls to be redirected to new with 301, and new product url not to be redirected with 301 as they are new and will have the same url structure, as I search on codeigniter site about url routing in router.php, which gives an example for redirection as
<code>$route['product/(:num)'] = "catalog/product_lookup_by_id/$1";
</code>
I think that this where i can make the change but how can i do a 301 in this pattern, by using header or is there a better way of doing this ?
Answer: I was faced with a very similar situation recently.
To save the 404 from all the results at Google & linked sites, I kept the old route but pointed it at a new controller/function. Theis function manages the the 301 redirection.
<code>    public function oldurl_to_newurl()
    {
          $newURL = LogicToGetNewURL
          redirect($newURL,'location',301);
    }
</code>
Using the segments from the old URL, I query the database(if needed) and create the new URL. It then redirects the users accordingly. This was I am also able to track the some metrics for my analytic.


What are the odds of losing a bet 20 times in a row when I have a 49.95% chance of winning?

Question: I have been trying to figure this out, and I can't find anything online that will help me.
What I have to do, is figure out the odds of losing a bet 20 times in a row when I have a 49.95% chance of winning.
I did 2 x 2 20 times, and came out with just over 1,050,000.
Is that the correct amount?
Thanks
Comment: Rounding errors, rounding errors everywhere.
Answer: $49.95\%$, assuming no ties are allowed, means your chance of losing is $50.05\%$.
That means in standard probability notation $p=0.5005$.
Losing $20$ times in a row therefore is $p^{20} = 0.5005^{20} = 9.72930093 \cdot 10^{-7}$ (pretty low)
Answer: If each bet is assumed to be an independent and identically distributed Bernoulli trial with probability of winning equal to $p = 0.4995$, then the probability of losing all $20$ bets out of $n = 20$ trials is $$(1-p)^{20} = (1-0.4995)^{20} \approx 9.7293 \times 10^{-7}.$$ or slightly more rare than $1$ in $1027823$.
Comment: Thanks... I'm not really good at p = x and y = z, so thanks for giving me the odds. I'll accept when I can
Answer: If you have a 49.95% chance of winning, then you have a 50.05% chance of losing. Given independent events, which non-rigorously means that losing bet #1 has no bearing on bet #2, the probability of both events happening is the product of their individual probabilities. In this case, to lose 20 times in a row, you need to calculate $.5005^{20}$.
More precisely, this is a binomial distribution with $n = 20$ trials, $k = 20$ successes (where a success is losing the bet), and $p = 0.5005$ is the probability of a success (lost bet). The formula for a specific binomial probability is:
$$
\textrm{Binomial}(n, k, p) = {n \choose k}p^k\left(1 - p\right)^{n-k}
$$
Substitute the numbers and you see you get $.5005^{20}$
Answer: There's nothing really special about winning or losing here. Because the probabilities of winning or losing are very nearly identical (very close to $\frac12$), the probability of ANY specific sequence of twenty outcomes is extremely close to $(\frac12)^{20} \approx 0.00000095367431640625$.
This is simply because there are a huge number of possible outcomes ($2^{20}=1,048,576$ to be exact) so they are all individually equally very unlikely.