Azure Compute Vision Service skips a letter

Question: I am using link https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/csharp-hand-text to read a hand written image.
My Issue

Some of the letters it skips reading.

Some values in boxes are read as one value\word.
Is there a way I can address it?

Image above for #1 issue: The red circled doesn't get read.
Image above for #2 issue:  The yellow highlighted is read as one word (like 13.71/89.8/47.5/31.8/7.6|72),
The below image shows the numbers read as one value.

while the first row is read separately as expected  (i.e 5,1,3.4,129, 72 are read as separate words)
Any help will be greatly appreciated. Thanks.
Answer: You can try using the Custom Vision service.  This service allows you to upload and train the model for better accuracy.  Once trained, the service is exposed via an API URL that you can replace in your code.
https://learn.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/home
Comment: The image I would be processing will need to identify handwritten data from clients. Can you please give me some pointers on  how to train this kind?
Comment: Sure, we have a tutorial here: https://learn.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/getting-started-build-a-classifier
Comment: The tutorial speaks about objects image to be trained. In my case I need to process the image that will have data (numbers with precision and words). I  need to 100% correctly detect  those values with precision. Will this help for my case?
Comment: Statistically, you will never get to 100%, that is why it is called a model.  The best you can get is a model that gets you close enough to 100% to solve your problem.  If you need 100% accuracy, you will most likely need human validation after the model run.
Comment: Its OK on not being always 100%. I'm curios if the Custom Vision Service would support to train\identify the handwritten numbers that would be in the target image. `Note : The expected image will be a snapshot of a application FORM to be filled by the applicants`.
Comment: I don't see why you can't train Custom Vision service with handwritten numbers.  The issue will be accuracy since not all handwriting is legible.  As you can see 3's and 8's are difficult for the vision service to accurately id as will 7's and 1's.
Comment: @jAntoni just give it a try and if the performance is good enough for you, then you can use it.
Comment: @PingJin actually I couldn't get the way how to train the numbers or characters in the image to be processed. With the link mentioned above I couldn't get more further. Any help will be greatly appreciated.
Comment: Something like draw a box around the text "7" and label it as a tag "7". Then the trained model can detect positions of "7" in other pics.
Comment: Can you please give me a sample code.Need to deliver it asap. THanks in advance.


solution for XMPP in iOS swift 3.0

Question: I would like to add the chatting feature in my app by connect to my openfire server. I have gotten the openfire account and password for each user. I am looking for a direction, including frameworks or libs, to implement this.
First, I found XMPP Framework for ios, which is a well-done framework for XMPP, but built in ObjectiveC and probably hasn't supported swift 3. So I'm not sure whether there is any other better choice. This is the main problem for me.
Second, if I find a way to connect with openfire server (in step one), I could send and receive message via openfire server. I can use some chat frameworks, such as Chatto, to implement a chat feature by inputing data resource.
Would you give me suggestion about chatting feature in swift 3? Thanks
Comment: I have transferred the XMPPFramework to swift 3.0. The second problem is still under survey
Comment: I am searching the same Do you find any solution for it ?
Comment: Do you get any solution for that
Comment: Any Solution found ??
Answer: You can use bridging feature for XMPP Framework to use Objective C classes in Swift.
for using bridging you can follow bridging in project
And you can also follow swift chat project https://github.com/processone/xmpp-messenger-ios

solution for XMPP in iOS swift 3.0


Adding and preserving i18n basepath on Routify

Question: I want to use an i18n basepath on Routify.
In other words, my URL is like this: www.example.com/about-us/
And I want to change it to this: www.example.com/[CURRENT_LANGUAGE]/about-us/
I've followed the example provided on the official website but it didn't work for me. When I add the /ru/ or /en/ prefix it works. But when I change the URL by clicking href it removes the prefix but goes to the desired URL. I need to have the prefix in the new URL as well.
I think I need to change my hrefs to adopt the new basepath logic. But not sure how to do it. How can I solve this issue? Any help is very much appreciated.
My build info: Svelte, Snowpack, Routify, Svelte-i18n.
GitHub repo: Click here
Answer: I tried copy pasting your App.svelte to the starter template, but it works as expected. The language was retained when navigating.
If you're trying to change the active language, you have to

A) update the lang value in your App.svelte or
B) use window.location.href = '/en/some/page'

If you're using plain href, you need to include $url. Ie. about or about. Otherwise, your URLs won't be rewritten. https://routify.dev/docs/helpers#url
Comment: Hi Ulvi. I just checked and it says your invite is pending. Could you check your email?
Comment: JakeDK, thank you very much for your help! I didn't know how to change the hrefs. I think it would be better to include it in 'i18n basepath' example. I tried $goto($page.path); to change the basepath when changing the language from dropdown but it didn't work for me. Isn't it for changing basepath? I followed your script from https://github.com/roxiness/routify/issues/332#issuecomment-780500138
Comment: I see that  $goto($page.path) changes the URL but it changes it to the exact same without trailing slash.
Comment: I can't see how you've implemented the script you link to. If you're interested I can send you an invite to our new auto generated templates repo. Then you can generate a template with the features you need.
Comment: Sorry, I forgot to include that. I updated index.svelte and about-us.svelte and included the script I am talking about. Yes, sure it would be awesome, my email is firstname.lastname@example.com if you prefer to not disclose it in a comment. I'm using Snowpack, I hope it is compatible with it.
Comment: I'll need your github name to share the repo. Github couldn't find you by email.
Comment: My GitHub username is ulvidamirli
Comment: Hey Jake, I didn't get any invitation. Just wanted to let you know.


How to condense a single dataframe based on the index

Question: I have the following dataframe:
                    label scoreCTBIN004v1  scoreCTBIN003v1  scoreCTBIN001v1
    Overall Stress Score              54              NaN              NaN
            Stress Score              50              NaN              NaN
  Short-Term Stress Risk              50              NaN              NaN
      Future Stress Risk              59              NaN              NaN
     Chronic Stress Risk              55              NaN              NaN
    Overall Stress Score             NaN             57.0              NaN
            Stress Score             NaN             52.0              NaN
  Short-Term Stress Risk             NaN             52.0              NaN
      Future Stress Risk             NaN             65.0              NaN
     Chronic Stress Risk             NaN             59.0              NaN
    Overall Stress Score             NaN              NaN             57.0
            Stress Score             NaN              NaN             49.0
  Short-Term Stress Risk             NaN              NaN             54.0
      Future Stress Risk             NaN              NaN             66.0
     Chronic Stress Risk             NaN              NaN             60.0

I simply want to condense the label column so that they are all on the same row, but it is not combining the labels even though they are the same name?
Something simple like this:
                    label scoreCTBIN004v1  scoreCTBIN003v1  scoreCTBIN001v1
    Overall Stress Score              54              57              57
            Stress Score              50              52              49
  Short-Term Stress Risk              50              52              54
      Future Stress Risk              59              65              66
     Chronic Stress Risk              55              59              60

Answer: You can use pd.pivot_table in this case.
data = {'label':['Overall Stress Score','Stress Score','Short-Term Stress Risk','Future Stress Risk','Chronic Stress Risk']*3,'scoreCTBIN004v1':[1,2,3,4,5]+[np.nan]*10,'scoreCTBIN003v1':[np.nan]*5+[6,7,8,9,10]+[np.nan]*5,'scoreCTBIN001v1':[np.nan]*10+[1,2,3,4,5]}
df=pd.DataFrame(data)

pd.pivot_table(df,index='label')
Out[21]:
                        scoreCTBIN001v1  scoreCTBIN003v1  scoreCTBIN004v1
label
Chronic Stress Risk                 5.0             10.0              5.0
Future Stress Risk                  4.0              9.0              4.0
Overall Stress Score                1.0              6.0              1.0
Short-Term Stress Risk              3.0              8.0              3.0
Stress Score                        2.0              7.0              2.0

Comment: As you can see, the 'label' column becomes indexes. I'm not sure if you are  ok with this.
Comment: Actually, you can ignore the values parameter and you will get the same thing. See the updated code. However, you can always do `df.columns[1:]` for the values parameter
Comment: Is there a way to not hard code the column value names? They will be constantly changing so that won't be possible for me. Also, the label column is already indexes which i think may be part of the problem
Answer: If that is an accurate representation of your whole dataset, you could groupby your 'label' column, and keep 'first' values:
df.groupby('label',as_index=False).first()

prints:
                   label  scoreCTBIN004v1  scoreCTBIN003v1  scoreCTBIN001v1
0     Chronic Stress Risk             55.0             59.0             60.0
1      Future Stress Risk             59.0             65.0             66.0
2    Overall Stress Score             54.0             57.0             57.0
3  Short-Term Stress Risk             50.0             52.0             54.0
4            Stress Score             50.0             52.0             49.0

Comment: I truly thought this would work as well, but my dataframe is still producing the same result as above.  The dataframe I gave is the result of appending other dataframes onto it, but for all intents and purposes that is the end result DF that I'd like to make the change to.
Answer: clean and simple if you really have this format:
if label is the index:
df.stack().unstack()

output:
                        scoreCTBIN004v1  scoreCTBIN003v1  scoreCTBIN001v1
label
Chronic Stress Risk                55.0             59.0             60.0
Future Stress Risk                 59.0             65.0             66.0
Overall Stress Score               54.0             57.0             57.0
Short-Term Stress Risk             50.0             52.0             54.0
Stress Score                       50.0             52.0             49.0

if it is a column:
df.set_index('label').stack().unstack().reset_index()

output:
                    label  scoreCTBIN004v1  scoreCTBIN003v1  scoreCTBIN001v1
0     Chronic Stress Risk             55.0             59.0             60.0
1      Future Stress Risk             59.0             65.0             66.0
2    Overall Stress Score             54.0             57.0             57.0
3  Short-Term Stress Risk             50.0             52.0             54.0
4            Stress Score             50.0             52.0             49.0


Como printar na mesma linha em python?

Question: A função print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) possui o argumento end e por padrão end='\n', eu sei que se trocar para end=' ' vai printar na mesma linha.
Porém estou avançando meus conhecimentos em Python e pensei numa atividade que preciso 'printar' na mesma linha uma formula matemática lado a lado, exemplo:
 1       2       3
+1      +2      +3
--      --      --

Possui alguma forma de 'printar' desta formula acima usando um for mais ou menos nesse exemplo "1\n+1\n--" ou para conseguir esse efeito preciso criar uma matriz e usar dois for (rows,columns) para 'printar' o resultado que eu quero?
Realizei um código de teste. Veja aqui:
my_list=(["1 + 1","2 + 2","3 + 3"])
for i in my_list:
  print(i, end=" | ")

print("\n\n\n")
for j in my_list:
  print(f" {j.split()[0]}\n{j.split()[1]}{j.split()[2]}\n--", end="")

print("\n\n\n")
print("""
------Espectativa-----
 1     2    3
+1    +2   +3
--    --   --
""")

Quero entender se é possível fazer como o exemplo.
Comment: Para esse caso específico poderia ser algo assim: https://ideone.com/S12uj7 - claro que se as expressões puderem variar de tamanho, ter números com mais de 1 dígito, etc, aí teria que adaptar
Comment: Funcionou como estava esperando. Vou procurar entender o que acontece e em cada parte do código para aprimorar meu conhecimento. Obrigado!
Answer: O terminal visto pelo Python e outras linguagens sempre é um conjunto de linhas de cima pra baixo - então, se você tem informação que vai ser distribuida em multiplas linhas, em paralelo com informação que deveria ir em outras colunas, sempre vai ter que criar primeiro na memória uma estrutura com todas as informações que você quer,
e em seguida imprimir essa estrutura linha a linha.
Algo do tipo:
my_list=(["1 + 1","2 + 2","3 + 3"])

saida = []

for elemento in my_list:
    linhas_por_elemento = elemento.split(" ", 1) # separa os elementos de exemplo - com a parte esperada em cada linha
    for j, linha_do_elemento in enumerate(linhas_por_elemento):
        if len(saida) <= j:
            # a linha onde essa informação vai entrar ainda não foi criada:
            saida.append([])
        saida[j].append(linha_do_elemento)
# nesse ponto, a variável saída é uma lista de listas - onde cada elemento da mesma é uma lista com as strings que vão em cada coluna

# O print abaixo concatena com "|" os elementos de uma mesma linha, e concatena cada linha de texto com "\n":

print("\n".join("|".join(f"{elemento:>8s}" for elemento in linha) for linha in saida))

Alternativamente, você pode usar uma biblioteca que te deixe usar o terminal como uma "saida 2D" - eu desenvolvo a lib "terminedia" que permite isso:
import terminedia as TM
sc = TM.Screen()

for coluna, elemento in enumerate(my_list):
    for linha, parte in enumerate(elemento.split(" ", 1)):
        sc.print_at((coluna * 8, linha), parte)

sc.update()

(é só instalar o terminedia com "pip install terminedia" )
O objeto "sc" permite tratar o terminal como uma matriz 2D -e
o print_at requer como primeiro parâmetro uma tupla
com as coordenadas de linha, coluna onde você quer
fazer a impressão)
Comment: O "print" é uma função normalizinha. O que é possível é usar um `for` dentro de uma expressão. (O print recebe como parâmetro o resultado da expressão). No caso aí, a expressão com `for` é passada para o método `join` - o que o `join` retorna é que vai para o print. E aí, por fim, esses `for` dentro de expressões criam as `generator expressions`
Comment: Muito interessante, vi que é possível usar um for dentro do print, eu não sabia que era possível. Pode me indicar algum livro que ensine funções mais complexas? Os cursos que fiz nunca mostra funções mais complexas. Vou pesquisar sobre essa lib que você está desenvolvendo
Comment: Acho que essa resposta aqui pode explicar bem as generator expressions: https://pt.stackoverflow.com/questions/193622/como-funciona-o-any-e-o-all-em-python/193625#193625

Como printar na mesma linha em python?


Matching and DiD - understanding of the control group

Question: Im trying to understand the methodology of matching and how to matches are used in this article.
Specifically, are treated firms compared the WHOLE group of matched firms (ie all firms that got assigned to a treated firm as a match), or are the treated firms only compared to the one specific assigned match in the regression?
Article, section 6.1.2 = matching & 6.1.3 = difference in difference regression
Comment: @thomas.diridondo would you mind re-posting the article you asked the question about? The link you provided doesn't work anymore.
Comment: I have updated the link to a persistent DOI.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stats.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://stats.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/331009)
Comment: As an aside, if the matching excluded any valid data, watch out for inefficiency and non-reproducibility.
Comment: @FrankHarrell what do you mean?
Comment: Most matching algorithms do not go to the work of n:m matching for variable n and m with reuse of controls that happen to be good matches to multiple cases.  The result is that perfectly good controls are not used, resulting in inefficiency from the reduction in sample size. Any method that discards perfectly good data is suspect and creates inefficiencies.
Answer: The first sentence of section 6.1.3 says

To examine how firm-level outcomes evolve following the issuance of
corporate green bonds, I estimate a difference-in-differences
specification using all firm-year observations of the treated and
matched control firms from 2010-2018.

This implies that they performed a difference-in-difference analysis in the matched set, i.e., discarding all control units that were not matched to a treated unit. It looks like they ignored pair membership in the analysis and treated the matched groups as independent samples, i.e., as if the treated and the matched controls were the only units in the study but had been sampled without a matched pair structure.
Note that retaining the matched structure would not have changed the effect estimate, in the same way a matched pairs t-test and an independent samples t-test test the same hypothesis and use the same sufficient statistic (i.e., the difference in means). So interpreting the results of the study doesn't depend on the answer to your question; the effect would be the same regardless.
Comment: Alright, I will try to rephrase to see if I understand your feedback.

(1) the author creates a pool of matched control firms that do not get treatment. And discard all potential controls that were not assigned as a match to any treated firm.
(2) the author ignores the matched pairs, i.e: rather than comparing the treated company A to its specific match A*, Treated company B to matched company B* etc, she compares A,B,C to A*,B*,C*. In other words run a DiD comparing treated vs matched control group
(3)using the approach mentioned above would give same results as matched pairs
Comment: Yes, that is a good rephrasing of my answer and what I believe to be true based on my reading of the paper.


Number of notes in a tune such that it is metrically sensible

Question: I am computationally generating short tunes (aiming for around 10-15 notes, 0.5 seconds per note) for a psychology experiment. I am wondering exactly how many notes I should have per tune, so that the tunes, though artificial (random pitches), will at least still sound complete and well-rounded to the ear from a metrical point of view.
To that end, and having the common time (4/4) in mind, I thought that integer multiples of this number of beats, for instance 12 or 16, would be a good number of notes to aim for. However, while playing a few samples to myself, it seems to me that tunes made up of an integer number of time-signature beats plus one is the more sensible length, which would give me, say, 13 or 17 notes instead of 12 or 16. This is probably because this length means that the final note in the tune is metrically strong (the first note in a bar), as opposed to weak (the last note in a bar).
Does anyone know any references to perception studies that may help answer this question, or otherwise share their opinion from a purely music-theoretic point of view?
Comment: Does your first sentence imply that *all the notes are the same length?* If so, that is probably why the tunes sound "incomplete" - from a music-theory point of view they are ending on the last beat of a bar, which is the weakest beat in 4/4 time. In "real music" the last note of a tune is often longer than the average - for example a whole bar (4 beats). Another issue is that bars are perceived in the context of *longer* rhythmic units which are often derived from the underlying harmony (so-called "harmonic rhythm"). With random note pitches, that cue to interpreting the rhythm won't exist.
Comment: Also, random pitches will not create any impression of the music being in "a key" (in the sense of the common-practice-harmony meaning of "key") and therefore will not have any alternation of increasing and relaxing "tension" as the pitches move further from or near to the important notes of the key - hence you lose another audible cue as to when the tune has "ended".
Comment: Definitely one more note would help than 12 or 16 and do not just use beats of the same value especially for a psychology experiment. Variations  and different notes would sound nice. What is the aim of this experiment? Please respond. I am sure there are quite a few studies out there o music perception. If I come across any of them, I will post it.
Comment: So many songs and parts of songs and symphonies and movements and generally bits of music end "on the one", and you have observed yourself that it sounds more like an ending to stop on the first beat of a subsequent measure. Given that, and the fact that the sharing of opinions is not what Stack Exchange is for, what exactly are you looking for here? A scientific basis for an artistic convention?
Comment: Hello all, thanks for answering. The experiment has to do with perception and memory for note sequences, therefore the harmonic element is irrelevant here. You are right that having a longer final note would help with the completeness, particularly if that final note is metrically strong ("ends on the one" as you say). @ToddWilcox: What I am looking for is to simply see whether in people's opinions, there is any sense (given current/past musical practice) to a end a melody on the last (as opp to the first) note of a bar; my piloting suggests that sounds very unnatural.
Comment: "Off on 4" vs "off on 1" is a good research point to start at.
Answer: There is way too much missing to provide a complete answer but I will try and add some guidance from experience.  You state that you want random groups of notes to be "meaningful" but can you define a criterion for meaningful (or is that what you want from us).  What makes music meaningful in many cultures is rhythm not melody (though both are important).
From a melodic perspective we tend to like simple melodic phrases that move around within a key signature, e.g. on the major scale (or relative minor).  There is a simpler unit of musical expression called a tetrachord (Do, Re, Mi, Fa).  The major scale is just 2 tetra chords separated by a step.  The reason I feel that this is important is that there is "repetition" built into the ascending scale, and repetition is what many people crave (whether they know it or not).  So even simple melodic phrases (say three or four notes long) tend to (1) have a repeated or well defined rhythm or pulse (2) either have or hint at melodic repetition and (3) tend to stay within a key.  Of course there are exceptions to every rule.  And you cannot really repeat yourself with 3 notes unless it's the same note 3 time.  But, longer phrases like the ones you are trying to make are usually built from simpler 3 and 4 note phrases repeated at the same or different places within the key.  So a better algorithm might be to randomly move the phrase (Do, Mi, Re) around varying the starting pitch (with or without constraints to stay in key).  Perhaps a library of small phrases.
I would ask why you want to do this at random.  Why?  What are you testing?  If you can share this it might help.  Unless it's proprietary (I'd understand).  Music is filled with patterns and IMO there is nothing random about it.  If you are trying to see what it takes for subjects to tell the difference between human generated music and computer generated music that won't take much.  If you are trying to create AI that mimics human creativity that might take more.  We are pattern recognition machines and we crave pattern.  If you wan to generate short melodies to make life easy you will need more than a random tone generator.  You will need some constraints that create rhythm and melodic structure consistent with western tastes.  That would essentially mean coding up a text on music theory.
A couple other constraints might help.  One is that moving small patterns around we usually come back where we started, in other words we cycle rather that just move endlessly in one direction.  A small chunk of music light have a scale going up but will eventually come back around.  This is critical to creating the feeling of completeness.  Phases can begin and end on different notes but usually notes that are part of the Tonic chord of the key (Do, Mi, Sol).  So this is a second thing to consider.  Third, you didn't state how many octaves you were restricted to (unless I missed it).  For a 16 note phrase it is possible, but highly unlikely, to generate a 2 octave scale.  This is not very musical even though it is a musical element.  You need to either restrict your "random" choices to be within an octave or octave and a 5th or require that they turn around somewhere.
There are a lot of degrees of freedom to play with.  It is possible to encapsulate some of our decision making process in the constraints and try randomizing the rest but you have a lot to think about.  And there is also the possibility of chromaticism.  Are you trying to emulate real musical phrases at random?
Comment: Also a helpful comment thank you. I hope to be able to respond more fully in a few days.
Answer: As this is an old question, I don't know if OP is still looking for this information.  But there is significant literature (both theoretical and empirical) on metric grouping and perception.  Perhaps the first to create a detailed theoretical model based on Gestalt principles was Lerdahl and Jackendoff's A Generative Theory of Tonal Music (1983), which proposed a set of rules for hierarchies of larger-scale metric structure.
For a very basic summary, meter tends to be perceived with a primary tactus ("beat"), which is generally felt with subdivisions of 2 or 3.  This tactus beat is generally grouped into 2s or 3s.  Rhythmic entrainment due to regularity of these metric patterns often results in higher-level groupings (usually in 2s), sometimes referred to as hypermeter.  Even in relatively undifferentiated stimuli (e.g., monotone pulses with no accents), these groupings tend to emerge in perception.
So, a pattern that ends after 12 notes or 16 notes with the same rhythm is often felt as "incomplete," as it lacks a final hypermetric or phrasal "downbeat."  Note that most standard Western pop songs, folk songs, and many types of classical music tend to be built around "4-bar phrases" that frequently end on the downbeat of the fourth or fifth bar, rather than on a weaker beat (and very rarely an offbeat).  Even phrases that do end on weak beats generally have their primary harmonic and rhythmic resolution on a strong downbeat, with the weaker beat feeling like a sort of "afterthought" or delayed release of some tension (e.g., in a suspension at a cadence).
Anyhow, there's a lot more to all of this, but searching the empirical literature that validated some of Lerdahl and Jackendoff's ideas of large-scale metric structure, as well as other discussions of hypermetric groupings will provide further details.
Comment: Very helpful answer, thank you, I think what you reference confirms my intuitions about why the downbeat of the following bar could not go missing.


Launch VLC from Terminal and set default renderer to ChromeCast from start (NO GUI)

Question: I am on Mac, and tried basically:
 vlc --sout '#R5 TV (Chromecast)' --sout-chromecast-ip=192.168.0.8 --demux-filter=demux_chromecast

Vlc opens, but it does not seem to select the renderer to the chrome cast in my menu.

How can I make this choice automatic? I believe most things are possible from Terminal for VLC.
I looked at
vlc --longhelp --advanced

Which is quite long but could not find it.
Answer: This
path/to/vlc '/nothing.mp4' --sout '#chromecast' --sout-chromecast-ip=192.168.0.8 --demux-filter=demux_chromecast"

seems to work on MacOS at least. It won't play nothing.mp4 but allows you to start playing anything, like with a VLC remote application from phone.


How to write a Join query in AWS DocumentDB

Question: AWS DoucmentDB is not supporting the $lookup operator, how to write a Join Query in DocumentDB, is there any alternative of $lookup operator in DocumentDB?
Answer: Left-outer joins (or correlated subqueries) are written in MongoDB using the $lookup operator.
[Updated 10/16] Amazon DocumentDB now supports $lookup: https://aws.amazon.com/about-aws/whats-new/2019/10/amazon-documentdb-add-additional-aggregation-pipeline-capabilities/
You can find the most up-to-date list of supported API/stages/operators here:https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html
Also, please check the following for recent launches: https://aws.amazon.com/documentdb/resources/


Can BCEL generate LocalVariableTable?

Question: I came across a boring error:
Exception in thread "main" java.lang.VerifyError: Bad type on operand stack in method
         net.madz.lifecycle.demo.standalone.ServiceOrder.allocateResources(JJJ)V at offset 27

I don't quite understand the error mean.
I have wrote a class and generate a class, and they look pretty similar:
Wrote:
    public void allocateResources(long arg0, long truckResourceId, long arg2) {
    /* L23 */
    0 new 2;
    3 dup;
    4 invokespecial 3;        /* net.madz.lifecycle.solutionOne.InterceptorController() */
    7 astore 7;               /* controller */
    /* L24 */
    9 new 4;
    12 dup;
    13 aload_0;               /* this */
    14 invokevirtual 5;       /* java.lang.Class getClass() */
    17 aload_0;               /* this */
    18 ldc 6;                 /* "allocateResources" */
    20 iconst_3;
    21 anewarray 7;           /* new java.lang.Class[] */
    24 dup;
    25 iconst_0;
    26 getstatic 8;           /* java.lang.Long.TYPE */
    29 aastore;
    30 dup;
    31 iconst_1;
    32 getstatic 8;           /* java.lang.Long.TYPE */
    35 aastore;
    36 dup;
    37 iconst_2;
    38 getstatic 8;           /* java.lang.Long.TYPE */
    41 aastore;
    42 invokespecial 9;       /* net.madz.lifecycle.solutionOne.InterceptContext(java.lang.Class summaryPlanId, java.lang.Object arg1, java.lang.String truckResourceId, java.lang.Class[] arg3) */
    45 astore 8;              /* context */
    /* L26 */
    47 aload 7;               /* controller */
    49 aload 8;               /* context */
    51 new 10;
    54 dup;
    55 aload_0;               /* this */
    56 lload_1;               /* summaryPlanId */
    57 lload_3;               /* truckResourceId */
    58 lload 5;               /* plangResourceId */
    60 invokespecial 11;      /* net.madz.lifecycle.solutionOne.ServiceOrder$1(net.madz.lifecycle.solutionOne.ServiceOrder summaryPlanId, long arg1, long truckResourceId, long arg3) */
    63 invokevirtual 12;      /* java.lang.Object exec(net.madz.lifecycle.solutionOne.InterceptContext arg0, java.util.concurrent.Callable truckResourceId) */
    66 pop;
    /* L34 */
    67 return;
}

Generated:
    public void allocateResources(long arg0, long arg1, long arg2) {
    0 new 77;
    3 dup;
    4 invokespecial 78;       /* net.madz.lifecycle.solutionOne.InterceptorController() */
    7 astore 7;
    9 new 80;
    12 dup;
    13 ldc 7;
    15 aload_0;
    16 ldc 81;                /* "allocateResources" */
    18 iconst_3;
    19 anewarray 83;          /* new java.lang.Class[] */
    22 dup;
    23 iconst_0;
    24 getstatic 88;          /* java.lang.Long.TYPE */
    27 aastore;
    28 dup;
    29 iconst_1;
    30 getstatic 88;          /* java.lang.Long.TYPE */
    33 aastore;
    34 dup;
    35 iconst_2;
    36 getstatic 88;          /* java.lang.Long.TYPE */
    39 aastore;
    40 invokespecial 91;      /* net.madz.lifecycle.solutionOne.InterceptContext(java.lang.Class arg0, java.lang.Object arg1, java.lang.String arg2, java.lang.Class[] arg3) */
    43 astore 8;
    45 aload 7;
    47 aload 8;
    49 new 93;
    52 dup;
    53 aload_0;
    54 lload_1;
    55 lload_3;
    56 lload 5;
    58 invokespecial 96;      /* net.madz.lifecycle.demo.standalone.ServiceOrder$5(net.madz.lifecycle.demo.standalone.ServiceOrder arg0, long arg1, long arg2, long arg3) */
    61 invokevirtual 100;     /* java.lang.Object exec(net.madz.lifecycle.solutionOne.InterceptContext arg0, java.util.concurrent.Callable arg1) */
    64 pop;
    65 return;
}

Since it says "Bad type on operand stack in method net.madz.lifecycle.demo.standalone.ServiceOrder.allocateResources(JJJ)V at offset 27"
is it the "27 aastore;" which caused this exception? At the wrote version class, I mean I wrote a java file and compile it into class file. I use this.getClass() to load the class reference, so in wrote version, "offset" 13 and 14 are "aload_0;" and "invokevirtual 5;" But in generated version I use "ldc" at offset 13 to reference the class directly, so the two versions cannot align precisely.
Usually how to diagnose these problems and how to monitoring operand stack at runtime, can BCEL generate LocalVariableTable into class files?
Answer: Finally I try to utilize BCELifier to generate Java codes from both generated and wrote class files, and I found the differences between them.
    public static void main(String[] args) throws Throwable {
    final JavaClass outerClass = Repository.lookupClass(ServiceOrder.class.getName());
    StringRepresentation s = new StringRepresentation(outerClass);
    System.out.println(s);
    BCELifier fier = new BCELifier(outerClass, System.out);
    fier.start();

    final JavaClass outer2Class = Repository.lookupClass(net.madz.lifecycle.solutionOne.ServiceOrder.class.getName());
    BCELifier fier2 = new BCELifier(outer2Class, System.out);
    fier2.start();

And then found the difference part:
CORRECT:
il.append(_factory.createFieldAccess("java.lang.Long", "TYPE", new ObjectType("java.lang.Class"), Constants.GETSTATIC));

WRONG:
il.append(_factory.createFieldAccess("java.lang.Long", "TYPE", Type.LONG, Constants.GETSTATIC));

In my code, actually I am using:
ilist.append(ifact.createGetStatic(convertType2ClassName(type), "TYPE", Type.LONG));

Obviously it should be:
ilist.append(ifact.createGetStatic(convertType2ClassName(type), "TYPE", new ObjectType("java.lang.Class")));

In summary, there are two mistakes I made:

I did not use InstructionFactory.createFieldAccess method, but I choose InstructionFactory.createGetStatic, although they can produce same results, but createFieldAccess has documents and createGetStatic does not.
I should use new ObjectType(Class.class.getName()) other than Type.LONG, since it should be the field type, which should match Class[].

Can BCEL generate LocalVariableTable?


Is there a function to cast string tokenizer to array

Question: I am working over an hour to find a way to explode a string into a string array.
This method have failed for me:
lineFields = str.split("|");
System.out.print(lineFields.length);

because it gives back an array of equal length to the string it self.
Then I read here that string tokenizer can explode a string, but unfortunately I cannot find a way to access the element randomly like lineFields[1].
I come from php and doing the simpliest things here looks so unusual, and of course I have searched the relative post on this forum, but still nothing close to my needs.
Answer:
Don't try to use StringTokenizer where split(...) should be used.
Just because your attempt to use split(...) isn't working doesn't mean that it's the wrong tool for the job.
You're using split wrong. Don't forget to escape your pipe, | String: "\\|"
Comment: +1. But I think an explanation is needed on why the pipe must be escaped this way. String.split takes a regex as argument. And the pipe is a logical operator in the regex syntax. To be treated as a literal pipe character, it must be escaped with a backslash. Since the backslash must itself be escaped with another backslash in a String literal, we end up with `\\|`
Comment: Thank you very, much! how do I escape it, isn't double quote enough?
Comment: It worked right away, I was so sceptical to ask, being afraid of down voting. Thank you very much again!
Comment: @JBNizet: thanks for your lucid explanation! Sorry for not adding something like it in my initial post.


Dataframe converting to Option[DataFrame] after it's mapped

Question: I'm trying to make a function that maps table names to Dataframes, my code is:
  def tableGen(tables: Array[Any], df: DataFrame, sqlContext: SQLContext): Map[String,DataFrame]={
    df.registerTempTable("TempTable")
    var myMap: Map[String,DataFrame] = Map()
    for(i <- tables){
      val queryRows = sqlContext.sql(s"SELECT * FROM TempTable WHERE table = '$i'")
      queryRows.cache()
      myMap += (i.toString -> queryRows.toDF())
    }
    for((k,v) <- myMap){
      printf("Key: %s , Value: %s\n",k,v)
    }
    myMap
  }

Although I explicitly state I want my return type to be Map[String,DataFrame] when I go outside of the function and do these:
val test: DataFrame = TableMap.get("Company")
test.show()

I get a type mismatch error:
Error:(41, 39) type mismatch;
 found   : Option[org.apache.spark.sql.DataFrame]
 required: org.apache.spark.sql.DataFrame
    val test: DataFrame = TableMap.get("Company")

I don't even know what Option[org.apache.spark.sql.DataFrame] is, and I don't know why it converts.
Comment: What is this code really used for? Is it a big table which one column table?
Comment: It's used with maxwell, I have a giant json file filled with bin log info so it's a separation step.
Comment: I had similar case. just the column is different. Please check my answer if it works.
Answer:
Although I explicitly state I want my return type to be Map[String,DataFrame] when I go outside of the function and do these:

Below I link to the docs of these classes.
Map[String,DataFrame]#get(String) returns an Option[DataFrame]. An Option[T] is a type that can contain one of two values Some[T] or None, None indicates the absence of a value.
You can either do
TableMap.get("Company") map { test.show() }

To properly deal with Option or you just
val test: DataFrame = TableMap("Company")
test.show()

To bypass the Option (Map#apply method). This second one is not recommended because it will just throw a Exception.
Comment: Thanks! I got the second one to work, and then realized I could do tableMap.get("Company").get, I hope that's an okay option.
Comment: it's just like the second
Answer: Based on certain category column, create a map based on this column. In this case the category column is table.
val categoryCol = col("table")

// category can be type String, Int, ...
val categories = df.select(categoryCol).distinct.collect.map(row => row.get(0))

// result is Map[String, DataFrame]
val dfs = categories.map {
    category =>
        (category.toString, df.filter(categoryCol === category).cache)
    }
    .toMap

val companyDF = dfs("Company")

Comment: This wasn't the problem I had, but you really cleaned up my code, thanks!


Do I need to have a company so that I can buy an SSL certificate that will display green at the address bar?

Question: I have a non-comercial website in which the users store some sensitive information so I feel the need to have a SSL certificate, but it seems that if I don't have a registered company I can't buy a green certificate.
I have some related questions:

Is it true that if I don't have a company, I can't have a green certificate?
If I issue a standard (non-business) certificate that won't go green (from GoDadday, for instance), will it go red? Or will it have a less ugly display.. something more neutral that won't scary the user.
Comment: Ref: https://en.wikipedia.org/wiki/Extended_Validation_Certificate
Answer: 1: yes, you need to have a company
btw: What you mean is an extended validation (EV) certificate (I think its also called "class 3").
2: no, it will be displayed "normally" - depending of the browser. If the CA is accepted and your certificate chain is installed correctly the browser will correctly display the encryption informations.
Comment: Most major browsers will display an error or block access entirely to self-signed certificate sites, correct. If your site's users are willing and able to import your CA they would then automatically trust your certificates.
Comment: additional thanks for the EV concept. So, as I understand, the "green" displayed in the address bar is actually an EV. Certificates can be considered safe without an EV. Do you mind answering another question? Is there any chance major browsers will not show a red sign if I self generate a certificate? Or they will tend to display red if the issuing company isn't well known?
Comment: adric is absolutely correct. Since adverts are not welcome here I won´t post an URL but there are more or less accepted ssl-cert distibutors which are quite cheap and whose certificates are working in all major browsers. You´ll have to pay ~60$/year for a class 2 certificate.


image carousel for following requirement using jQuery,javascript

Question: I am trying to create a slider that allows users to move through reviews by clicking arrows. Which will go from review1 to review2 etc etc. This is what I have so far, I have set up my HTML with my reviews, and my CSS with hidden values for the time being. Any help would be greatly greatly appreciated

“THIS PLACE IS AMAZING”

- The Georgia Straight

“A TASTE OF ITALY IN VANCOUVER”

- The Vancouver Sun

“THIS IS THE REAL DEAL”

- Yelp.ca

“SIMPLY DELICIOUS”

- VanCity Buzz

and my CSS

.review1{
font-family: Clarendon;
letter-spacing: .2em;
font-size: 22pt;
text-align: center;
padding-top: 200px;
width: 1024px;
}

.review2{
display: none;
font-family: Clarendon;
letter-spacing: .2em;
font-size: 22pt;
text-align: center;
padding-top: 200px;

}

.review3{
display: none;
font-family: Clarendon;
letter-spacing: .2em;
font-size: 22pt;
text-align: center;
padding-top: 200px;

}

.review4{
display: none;
font-family: Clarendon;
letter-spacing: .2em;
font-size: 22pt;
text-align: center;
padding-top: 200px;
}

Answer: This is answer

UPDATED FOR PREV,NEXT => http://jsfiddle.net/Su3pG/2/
Paste above HTML as it is in your machine(in New html file)


Problem adding Windows 7 64-bit print drivers to a 32-bit Windows 2003 print server

Question: I have installed the final RTM version of Windows 7 Professional 64-bit on a test system before we begin the rollout in our company.
I'm having problems connecting to several HP printers that we have on the network. These printers are being shared from a Windows 2003 server host.
I have downloaded the lastest HP Universal Printer driver, however I'm unable to add the 64-bit driver onto the 2003 server system (it's 32 bit).
How can I get connected to these printers from the Windows 7 system?
Comment: I think it would be more appropriate to change your title to something along the lines of "Problem Adding 64-bit print drivers to 32-bit Windows 2003 Print Server"
Comment: Richard, I'm having the same issue as you and none of these answer resolve it (probably why this one is marked unanswered).  Typically, any of the following three answers would do fine, but HP really mucked things up with their "Universal Print Driver".  I've installed it on my x64 workstation, located the .inf, pointed the server to that file and it claimed that "The specified location does not contains the driver HP LaserJet P2015 Series PS for the requested processor architecture."  Has anyone found a way to do this?
Comment: I found this post while searching for a solution to the error mentioned above - (..."when trying to download the drivers (0x0000007e)"). Just saying that JohnnyD's solution worked for me. I hadn't thought of entering the network path to a shared printer as a port. Thanks!
Answer: Push the 64-bit driver across the network

Go to a 64-bit machine on the network and copy the 64-bit driver files to the machine
From the 64-bit machine, open Windows Explorer and browse to the 32-bit server
Open the Printers dialog seen via Windows Explorer.
From the Menu bar, select File > Server Properties, select the Drivers tab and click the Add button.
In the Add Driver Wizard, tick the x64 Processor checkbox, and untick the x86 checkbox.
Click Next, then click Have Disk and browse to the 64-bit driver on the local 64-bit machine.
Complete the Add Driver Wizard.

Upon completion the Server Properties dialog should show the x64 drivers installed for that device type
Answer: I used the RSAT tools to get Windows 2003 to serve up drivers to Windows 7 x64.  But, first, I had to update the driver list.  Procedure I used:
-Update Windows Driver Database

Go to Control Panel -> Devices and Printers.
Add a new printer, choose local.
Choose LPT1.
In the "Install printer driver" dialogue, click the Windows Update button.  This will download the rest of the drivers you expect to see listed.
Cancel the printer installation, the drivers will not be deleted.

-Install drivers to the server with RSAT

Download and install the RSAT tools.
Open the Print Management tool.
Right-click on Print Servers, choose Add/Remove Server, and add your target print server.
Under the new server object, click Add Drivers.
In my case, since I'm on Windows x64, I selected x64, and deselected x86.
This will bring up the list of drivers installed on your workstation.  Choose the driver to install on the server.
Answer: Dom's answer got me pretty close.
I needed to modify it as follows.
My printer manufacture had re-designated the name of the printer within the driver.  You can only add addition drivers with the same name to one you already have setup.
I had to download both of the new drivers (x86 and x64) and change my orginal printer over to the new x86 driver, then the system automatically added the x64 to it's list.  Then I was able to install the printer on my Win 7 machine with no problems.
Thanks for this help!!
Comment: Thanks. That was the last part of the puzzle I needed to unravel. +1
Answer: I know this is an old question but I just figured out how to do it so I thought I'd post my method for connecting to and printing from Windows 7 64-bit to a 32-bit Windows print server (should be the same for 64-bit Vista):

ensure you have the proper printer driver installed on your Windows 7 box
goto printers and devices, add new printer
select local printer
use existing port (LPT1)
select proper print driver
click next throughout rest of process
name the printer how you'd like it to be displayed.
let it install...
select "do not share"
when finished, right click and select "Printer Properties"
goto ports tab, click "Add port..."
select "Local Port" and then click "New Port..."
type in the exact network address for the printer. ie: \printserver01\hplaserj
click OK, then click close
ensure the new port is selected and click Apply, then close
test printer. If it doesn't work than you may have an incorrect or incompatible print driver installed

Also, if you're trying to connect to HP printers I have found the HP Universal PCL6 driver to work remarkably well: download here
Comment: The only problem with JohnnyD's response, is it is only for a single machine. Any additional X64 machines will have to do the same process to have them set up to the printer. Modifying thre server to allow X64 clients to connect and print becomes much more important the larger your organization becomes.
Answer: The easiest way is to download the x64 drivers for that device then rdp to print server and select printers the properties on the printer you want to install then sharing tab and click on additional drivers.
Tick the checkbox for x64 Windows XP and widows server 2003
then point to the inf file from the folder of the drivers you just downloaded.
The when a user clicks on that printer it will ask if they want to install a driver.
Answer: Download XP64 bit driver. Go to the server and add 'additional drivers' under Sharing. Click on the x64 and point it to the XP64 bit driver. That should install X64 driver and you should be able to add the printer on any MS 64 bit OS. This works for our Win7 64 Bit OS users (HP P3005X printer).
P.S. I did unzip the driver on the 64 bit PC but that might not matter. It might work as well on the 32 bit hosting  printer server.
Comment: The HP P3005 has been by far our biggest problem. Using the HP "Universal Driver" failed completely until I renamed it as per Dash's answer. We are now able to use that printer on Win 7 64 bit machines, albeit with less than perfect results.
Answer: I have run into this issue before.  It comes down to the printer name inside the .inf.  The x32 and x64 printer names have to be "EXACTLY" the same. So, "HP LaserJet P2015 Series PS" is different from "HP LaserJetP2015 Series PS".  This drove me nuts for a little while until I learned that and went into the x64 .inf and copied and pasted the x32 .inf's printer name into it.  After they are exactly the same then it should work.


assign value to a text box from jQuery

Question: In the form, I have put a textbox and a button as:
<input type="text" class="form-control" id="txtCustomerId" placeholder="Customer ID">

    <button class="btn btn-secondary" type="button" data-toggle="modal" data-target="#LovCustomer"></button>

when this button is pressed, a modal form (bootstrap) is popped up. I have placed a button on the modal form as:
<button id="LSSL" value="LSSL" class="btn btn-info btn-xs"></button>

I have below jQuery in :
$(function(){
    $('#LSSL').click(function(){
        $('#txtCustomerId').val($(this).val());
    });
});

My requirement is to obtain the value of the button being pressed (in the modal form) and assign it to the txtCustomerId of the parent form. But when I press the button, page gets refreshed and the text filed is blank (since it is refreshed).
I think the value is assigned but since the page is refreshed, assigned value vanishes.
I would like to know either to stop the page refresh or any other way of getting this achieved.
Thanks in advance.
Below is my  section for your reference:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="http://tarruda.github.com/bootstrap-datetimepicker/assets/css/bootstrap-datetimepicker.min.css">

Answer: Your button should be like this,
<button type="button" id="LSSL" value="LSSL" class="btn btn-info btn-xs"></button>

And in Js part, you can do preventDefault(),
$(function(){
   $('#LSSL').click(function(e){
       e.preventDefault();
       var value = $(this).attr('value');
       $('#txtCustomerId').val(value);
   });
});

//You can also use $(document).ready(function(){}) as well.
$(document).ready(function(){
    $('#LSSL').click(function(e){
       e.preventDefault();
       var value = $(this).attr('value');
       $('#txtCustomerId').val(value);
   });
});

Comment: with `e.preventDefault();` the page doesn't get refreshed. (Y)

But the value doesn't get assigned to the textbox.
Comment: Updated my answer @LakmalPremaratne
Comment: If the top method will not work, try using the same with `$(document).ready(function()`. @LakmalPremaratne
Answer: Use
preventDefault() to stop the default behavior of button
$(function(){
   $('#LSSL').click(function(e){
       e.preventDefault();
       alert($(this).val());
   });
});

or use
<input id="LSSL" type="button" value="Click" onclick="doSomething(this)">

function doSomething(obj) {
alert(obj.value);
}

assign value to a text box from jQuery


How does randomized search cv algorithm work?

Question: I am building a DNN, and I used Randomizedsearchcv from Scikit learn to optimise the hyper-parameters.
Hence, I have one question about this:
As I understood, the basic of random search is to try out bunch of different random choices. Is that why the results of randomizedsearchcv are different every time I run it again? Is there any ways that I can reach an optimum in the bounded search space?
Answer:
Correct, the method is randomized, so you can get different results on each run. For reproducibility, you can fix the random seed.
If there is single global minimum, you would reach it if you try long enough. How long it is depends on how big the search space is. With continuous parameters the space is infinite, what would make it infinitely long. There were experiments showing that random search can give equally good results as "smarter" algorithms if you use twice as many iterations.
With hyperparameter tuning we usually don't aim at finding the global minimum, but at finding better hyperparameters. The machine learning algorithms are usually pretty robust to the choice of hyperparameters, so you don't really need to find the "best" ones. Tuning is designed for being efficient in exploring the space, not for being the most precise.


Collect id's of ALL inserted records as result set

Question: I need a stored procedure which returns resultset of IDs for created records. I've already read that SCOPE_IDENTITY gives only last ID. but my SQL skill is not enough to solve this particular case and get all IDs as the output.
here's what I have for now - this only gets the last record's id
USE AdventureWorks2008;
DELETE FROM [HumanResources].[Shift] where [HumanResources].[Shift].Name='c' or [HumanResources].[Shift].Name='d'
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'ShiftUpdateXml')
DROP PROCEDURE ShiftUpdateXml
GO

CREATE PROCEDURE ShiftUpdateXml
 @strXML XML, @ShiftID [tinyint] = NULL OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT [HumanResources].[Shift](Name,StartTime,EndTime) SELECT
    TEMP.Name,TEMP.StartTime,TEMP.EndTime
        FROM (SELECT
    assignreassignro.value('Name[1]','nvarchar(50)') AS Name,
    assignreassignro.value('StartTime[1]','time(7)') AS StartTime,
    assignreassignro.value('EndTime[1]','time(7)') AS EndTime

    FROM @strXML.nodes('documentelement/assignreassignro')Documentelement(assignreassignro)) AS TEMP

    SET @ShiftID = SCOPE_IDENTITY();
END
GO

DECLARE @ShiftID INT;
DECLARE @XmlVal XML= '<?xml version="1.0"?>
<documentelement>
  <assignreassignro>
    <Name>c</Name>
    <StartTime>10:30:00.0000000</StartTime>
    <EndTime>17:30:00.0000000</EndTime>
  </assignreassignro>
  <assignreassignro>
     <Name>d</Name>
    <StartTime>11:00:00.0000000</StartTime>
    <EndTime>18:00:00.0000000</EndTime>
  </assignreassignro>
</documentelement>'

EXEC  ShiftUpdateXml @XmlVal,@ShiftID = @ShiftID OUTPUT;
PRINT @ShiftID;

Answer: You are looking for the output clause.  If you just want the ids, you can do:
DECLARE @ids TABLE (id int);

INSERT [HumanResources].[Shift](Name,StartTime,EndTime)
    OUTPUT inserted.Id INTO @ids
    SELECT assignreassignro.value('Name[1]', 'nvarchar(50)') AS Name,
           assignreassignro.value('StartTime[1]', 'time(7)') AS StartTime,
           assignreassignro.value('EndTime[1]', 'time(7)') AS EndTime
    FROM @strXML.nodes('documentelement/assignreassignro') Documentelement(assignreassignro);

If you want additional values, you can add them to the table and the INSERT statement.
Also, note that you do not need a subquery for the SELECT.
Answer: To get multiple rows you'll need to use output from the table inserted with something like this:
CREATE PROCEDURE ShiftUpdateXml
 @strXML XML
AS
BEGIN
    INSERT [Shift](Name,StartTime,EndTime)
    output inserted.id
    SELECT
    TEMP.Name,TEMP.StartTime,TEMP.EndTime
        FROM (SELECT
    assignreassignro.value('Name[1]','nvarchar(50)') AS Name,
    assignreassignro.value('StartTime[1]','time(7)') AS StartTime,
    assignreassignro.value('EndTime[1]','time(7)') AS EndTime

    FROM @strXML.nodes('documentelement/assignreassignro')Documentelement(assignreassignro)) AS TEMP
END

That way the procedure will return the list of IDs. I made an example into SQL Fiddle


Jquery como selecionar um elemento especifico pelo index

Question: Gostaria de saber como selecionar um elemento especifico pela posição do index, pois consigo percorrer a estrutura com as funções next e prev, mas não estou encontrando uma forma de selecionar um elemento diretamente pela posição dele.
Estou utilizando Jquery
function proximo()
{
    if($(".elemento").next().size())
    {
       $(".elemento").fadeOut().removeClass("elemento").next().
           fadeIn(1000).addClass("elemento");

      var texto = $(".elemento").attr("alt");
      $("#slide p").hide().html(texto).delay(500).fadeIn();
    }
}

Comment: `$(".ativo")[i]`?
Answer: Existem duas possibilidades:

O pseudo selector :eq(numero) (mais info em Inglês)
O método .eq(numero) (mais info em Inglês)

Exemplo:
$('li:eq(1)').css('color', 'blue');
$('li').eq(2).css('color', 'red');

http://jsfiddle.net/Sfdpq/

Se já tiver uma coleção de elementos e quiser escolher um deles atravé do index pode usar .index(numero)
Por exemplo:
$('li').click(function(){
   this.innerHTML = $(this).index(); // vai mudar o texto para o numero do index
});

http://jsfiddle.net/Sfdpq/1/

Pode sempre usar javascript simples, tendo em conta que uma coleção é tipo array, usando $(variosElementos)[numero]. Mas atênção que desta maneira retorna-lhe um objeto raw (apetece-me traduzir para "crú"...), mas no fundo um objeto sem os metodos jQuery adicionados.
Comment: perfeito funcionou corretamente, muito obrigado pela ajuda.  $("#slide img:eq("+numero+")").fadeIn(1000).addClass("elemento");


Alternatives to Google's weighted sort for binomial experiments with n=1

Question: An interesting data scientist interview question:
"We are looking at the failure rate for opening files on websites for many clients. We want to rank the files by failure rate; but, with our current method, the files that have been only opened once (and failed) rise to the top of the rank. What statistical method would you use to get around this?
What statistical methods would you use to rank the file load failure rate so that files with only one open do not rise to the top?"
They really liked Google's weighted sort that is described here https://moz.com/blog/build-your-own-weighted-sort
I have my own thoughts on this question; but, I would like to hear what the community thinks.
Comment: I'm really interested in your thoughts on this. This is a really exciting problem! What are your thoughts on this question?
Comment: Thank you so much for your help! I was thinking of a Bayes approach (also mentioned in your link).
Answer: Wouldn't a standard solution to this problem just be some kind of credibility factor? For example say $f(n)$ with your weighted average being $f(n) \bar{x}_i + (1-f(n)) \bar{x}$. Where $\bar{x}_i$ is the mean of the observations and $\bar{x}$ is the mean of the population.
The google example is one. There is also the Buhlmann Model. In order to make this work I believe $f(n)$ should be bounded between 0 and 1 and should not be decreasing with $n$
Comment: Thank you so much for your help. I ended up using your formula with f(n) = (number of file dls for site x)/(number of file dls for all sites) for its simplicity.


Convert normal pdf into lognormal pdf

Question: I have fitted a mixture of 3 normal distributions to my log-transformed data Y, as the package I'm using cannot fit a mixture of lognormal distributions.
My questions is: how I can convert pdf from 3 normal distributions into lognormal pdf?
Thank you.
Answer: It is just the same mixture of the associated log-normal PDFs. Your mixture model says that $\log Y|\mu \sim N(\mu,\sigma^2)$, so $Y|\mu$ has a log normal distribution. The distribution of $\mu$ (a discrete distribution on 3 values) is the same.

Convert normal pdf into lognormal pdf


Can I have notifications/alerts sent by IM to a Skype account from a headless machine?

Question: I want to make my network monitoring system send IM alerts, and the IM client of choice at my workplace is Skype.
Is there a command-line driven API, that doesn't require the GUI Skype client, so I can run it on the Linux machines that run my monitoring?
Alternatively, is there a Jabber-to-Skype gateway that would solve this problem?
Answer: http://code.google.com/p/skype-command-line/
Comment: This calls the GUI Skype client, so doesn't fit the requirements.  Thanks for the suggestion though and welcome to ServerFault.
Comment: @crb: If your only objection to the GUI client is that it requires a GUI, run it on a headless X server such as `Xvfb` or `Xvnc`.
Comment: I object more to the fact I need to have Qt and X on a tiny machine, vs. an open protocol like Jabber where this would be trivial :)  I was under the impression that Skype had been reverse engineered, just a little.
Answer: According to common wisdom, including this SuperUser post, Skype has not been reverse engineered, and they do not offer a command-line only client.
There are a number of options for controlling a GUI client from the command line, including Skype4py and skype-command-line (Java).
Answer: I know I am totally late, but there is a simple service to send server alerts to Skype and other IM platforms: https://ezalert.me
It also has an email gateway that can forward alert emails via IM.


How to view php pages in my mvc application

Question: I'm new to php. I have made some php code and I would like to run it within my mvc application together with razor. How is it possible for me to do so? I basically want to implement my steamlogin php script into the autogenerated homepage on mvc.
This is a school project!
Thanks!
Answer: You can run PHP in the project (ASP.NET MVC) as html page (dynamic files) but you can't return a .php file from Controller.
How can I execute PHP code from ASP.NET MVC
As it's school project, it's look like you have write some functionality in PHP. You can send POST request to .php file handle the code in the .php file and show the response.


warning undefined reference to arduino due in multiwii

Question: I try to compile multiwii code on DUE https://github.com/HefnySco/MultiWii_DUE
I keep getting
C:\Users\MCA9A~1.HEF\AppData\Local\Temp\build4616066844745192383.tmp\EEPROM.cpp.o: In function eeprom_write_block(void*, void*, unsigned int)
C:\Users\MCA9A~1.HEF\AppData\Local\Temp\build4616066844745192383.tmp/Sensors.cpp:307: warning: undefined reference toWire'

I made a separate project to simulate the case and created file called class1.cpp and included Wire_DUE.h and then called it from the main project class Sample1.cpp and it worked using the very same Wire_DUE code.
Kindly advise
Answer: At last after 4 days I found the answer.
I used this in def.h
#if defined (__CM3_REV)
    #define ARDUINO_DUE
#endif

and when I updated to this
#if defined (ARDUINO_ARCH_SAM)
    #define ARDUINO_DUE
#endif

it works .... pls not that in both cases ARDUINO_DUE is defined .... but not sure what is the difference exactly as in both ways ARDUINO_DUE is active.... seems that in some .cpp files it is not active due to other declarations that conflict with __CM3_REV


Explode Function not working

Question: I want to add the username that select an item to my db . for example if three users selected that item i want it to be like user1,user2,user3 .. im getting the different users to go into db but i cant get the comma to separate .. im using explode but still not working properly
<?php

session_start();
$date = date("Y-m-d H:i:s");

include("php/connect.php");

if (isset($_SESSION['username'])){

           $query1 = mysql_query("SELECT * FROM user WHERE username='$username'");

    $username = $_SESSION['username'];

    $submit = $_POST["submit"];
    $tests = $_POST["test"];

    // If the user submitted the form.
    // Do the updating on the database.
    if (!empty($submit))
    {
        if (count($tests) > 0)
        {
            foreach ($tests as $test_id => $test_value)
            {
                switch ($test_value)
                {

                    case 1:
                        mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
                        mysql_query("UPDATE test SET date = '$date'  WHERE id = '$test_id'");
                        $username = explode(",", $username);
                        $cnt = count($username);
                        $slice = array_slice($username, 0,10);
                        mysql_query("UPDATE test SET users = CONCAT(users, '$username')  WHERE id = '$test_id'");
                    break;

                    case 'X':
                        mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
                        mysql_query("UPDATE test SET date = '$date'  WHERE id = '$test_id'");
                    break;

                    case 2:
                        mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
                        mysql_query("UPDATE test SET date = '$date'  WHERE id = '$test_id'");
                    break;

                    default:
                        // DO NO THING.
                }
            }
        }

    }

    // Whenever this wiil be fetched it will be updated.
    $query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
    $result = mysql_query($query);

    echo "
Seria A

Welcome, ".$username."! LogOut
";

    while($row = mysql_fetch_array($result)){

        $id = $row['id'];
        $home = $row['home'];
        $away = $row['away'];
        $win = $row['win'];
        $draw = $row['draw'];
        $lose = $row['lose'];

        echo "
",$id,") " ,$home, " - ", $away;

        echo "

        <form action='seria.php' method='post'>

        <select name='test[$id]'>
            <option value=\"\">Parashiko</option>
            <option value='1'>1</option>
            <option value='X'>X</option>
            <option value='2'>2</option>
       </select>

       <input type='submit' name='submit' value='Submit'/>

        </form>
";

        echo "Totali ", $sum = $win+$lose+$draw, "

";

    }

    }else{

        $error = "
Duhet te besh Log In qe te vendosesh parashikime ndeshjesh
Kycu Ketu
";

    }

 ?>

Answer: EDIT
Ok, this should work for you....Iv also cleaned up some of your multiple executing queries...
This retrieves the test row, gets the usernames, attaches the current username to the list, and re-inserts....
case 1:
   $sql = mysql_query("SELECT * FROM test WHERE id = '$test_id'");
   $users = mysql_fetch_row($sql);
   $usernames = $users['users'].",".$username;
   mysql_query("UPDATE test SET users = '$usernames', win = win + 1, date = '$date' WHERE id = '$test_id'");
   break;

case 'X':
mysql_query("UPDATE test SET date = '$date', draw = draw + 1 WHERE id = '$test_id'");
break;

case 2:
mysql_query("UPDATE test SET date = '$date', lose = lose + 1 WHERE id = '$test_id'");
break;

default:

Just insert this into your switch statement
Also...for security purposes you will wanna escape the user entered data...
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = mysql_real_escape_string($_POST["test"]);

Or better yet, switch to using mysqli_* or PDO, as mysql is deprecated and will soon be removed from PHP altogether.
Comment: Also it doesn't look like youre doing anything with $query1, what is its purpose?
Comment: I figured you were checking against database for user....if thats the case...then that needs to change as well
Comment: ___sql injection___ ___sql injection___
Comment: @NullPointer Im not here to completely revamp his system to mysqli or PDO....Im just helping him on a problem, the $username comes from SESSION anyways, and Im assuming he sanitized the user data when it was entered into the database in the first place....
Comment: even why not mysql_real_escape_String ? i am not telling that about api :)
Answer: I am not sure what username is when you get it.
If $username is an ARRAY before you do this line: $username = explode(",", $username); then you should do $username = implode(",",$username);
so if it is somthing like this:
INPUT: $username = array('fred','frank','jill');

$username = implode(",",$username);

OUTPUT: fred,frank,jill

Comment: what would be the point imploding to explode??
Comment: ___sql injection___ ___sql injection___

Explode Function not working


Evaluate $\lim_{n \to \infty} \int_{0}^1 [x^n + (1-x)^n ]^{1/n} \ \mathrm{d}x$

Question:
Evaluate
$$\lim_{n \to \infty} \int_{0}^1 [x^n + (1-x)^n ]^{1/n} \ \mathrm{d}x$$

I simplified the limit to
$$\dfrac{1}{2}\lim_{n \to \infty} \int_{0}^{1/2} \left[\left(\frac{1}{2}+x\right)^n + \left(\frac{1}{2}-x\right)^n \right]^{1/n} \ \mathrm{d}x$$
using properties of definite integrals, but I can't solve further.
Any help will be appreciated.
Thanks.
Comment: 1 Fractional part is redundant here. 2 Apply dominated convergence theorem 3 Note that $\lim_{n\to\infty}(a^n+b^n)^{1/n}=\max(a,b)$ for positive $a$ and $b$.
Comment: @Norbert Sorry Sir, but I haven't read about Dominated convergence theorem yet.
Comment: Then you have the DCT to look forward to, since it makes your problem easy.  Perhaps the integrand converges uniformly to $\max(a,b)$, so the Riemann theory of integration will work.
Comment: @GEdgar This was 5 years ago. I have since read about DCT and much more :)
Answer: Hint: It looks like there may be a mistake in your proposed simplification step, but at any rate, you can break the limit up into $\lim_{n \to \infty} \int_0^{1/2} f_n dx + \int_{1/2}^1 f_n dx$ where $f_n = (x^n + (1 - x)^n)^{1/n}$. You should be able to show that in each piece of the broken up integral, either $x^n$ is hugely dominating or $(1-x)^n$ is hugely dominating (before you take the root). Since then you are taking the $n$th root before integrating, this will hopefully allow you to see what the limit should be.
Comment: @Samurai Sorry, my hint was not necessarily directly appealing to any classical theorems that can simply be applied directly. However, if you understand the proof outline, filling in the details shouldn't be too hard hopefully, even if you make minimal use of theorems. I'm not sure what theorems are available to you now so it would be hard to put it in terms of theorems you are allowed to use (plus I would have to look up analysis/calculus theorems to know the easiest way to phrase this argument in terms of those most common theorems).
Comment: If either is dominating, does that mean we can ignore the other term? Which theorem is that?
Comment: I edited my simplification step. Now it's correct.
Answer: Note that for $1\ge x>1/2$,
$$xe^{\frac1n \left(\left(\frac{1-x}{x}\right)^n-\frac12\left(\frac{1-x}{x}\right)^{2n}\right)}<\left(x^n+(1-x)^n\right)^{1/n}=x\left(1+\left(\frac{1-x}{x}\right)^n\right)^{1/n}<xe^{\frac1n \left(\frac{1-x}{x}\right)^n}$$
where we used the estimates $x-\frac12 x^2<\log (1+x)<x$.  Thus, by the Squeeze Theorem
$$\lim_{n\to \infty}\left(x^n+(1-x)^n\right)^{1/n}=x \tag 1$$
for $1\ge x>1/2$.  Exploiting symmetry, we have for $0\le x<1/2$
$$\lim_{n\to \infty}\left(x^n+(1-x)^n\right)^{1/n}=1-x \tag 2$$
Therefore, putting $(1)$ and $(2)$ together reveals
$$\lim_{n\to \infty}\left(x^n+(1-x)^n\right)^{1/n}=\frac12 +\left|x-\frac12\right|$$
And since $1/2<\left(x^n+(1-x)^n\right)^{1/n}\le 1$, we can use the Dominated Convergence Theorem to obtain
$$\begin{align}
\lim_{n\to \infty}\int_0^1 \left(x^n+(1-x)^n\right)^{1/n}\,dx&=\int_0^1 \lim_{n\to \infty}\left(x^n+(1-x)^n\right)^{1/n}\,dx\\\\
&=\int_0^1 \left( \frac12 +\left| x-\frac12 \right| \right) \,dx\\\\
&=\frac34
\end{align}$$
as expected!
Comment: @robjohn First of all, thank you!  Second, the development before validating the interchange of limit and integral was to establish that the limit of the integrand was $1/2+|x-1/2|$.  Then, the estimate $1/2<(x^n+(1-x)^n)^{1/n}\le 1$ alone permitted use of the DCT.  Did I misunderstand your note?  Or was my answer unclear?
Comment: (+1) However, on $\left[\frac12,1\right]$, note that $\left[1+\left(\frac{1-x}x\right)^n\right]^{1/n}\le2$ and easily $\lim\limits_{n\to\infty}\left[1+\left(\frac{1-x}x\right)^n\right]^{1/n}=1$. From these observations alone, we can apply Dominated Convergence.
Answer: It's a little easier to let $x=(1+u)/2$ with $-1\le u\le1$. We have
$$\int_0^1(x^n+(1-x)^n)^{1/n}dx={1\over2}\int_{-1}^1\left(\left(1+u\over2\right)^n+\left(1-u\over2\right)^n \right)^{1/n}du=\int_0^1\left(1+u\over2\right)\left(1+\left(1-u\over1+u\right)^n \right)^{1/n}du$$
where we did two things in the second step: we used the symmetry between $1+u$ and $1-u$ to replace ${1\over2}\int_{-1}^1$ with $\int_0^1$, and we factored out the $\left(1+u\over2\right)^n$.  What you do from here on out depends in part on how finicky you need to be about moving the limit across the integral sign. But since for $0\le u\le1$ we have
$$1\le\left(1+\left(1-u\over1+u\right)^n \right)^{1/n}\le\left(1+\left(1-0\over1+0\right)^n \right)^{1/n}=2^{1/n}$$
we see that
$$\int_0^1\left(1+u\over2\right)du\le\int_0^1\left(1+u\over2\right)\left(1+\left(1-u\over1+u\right)^n \right)^{1/n}du\le2^{1/n}\int_0^1\left(1+u\over2\right)du\to\int_0^1\left(1+u\over2\right)du$$
so the Squeeze Theorem tell us
$$\lim_{n\to\infty}\int_0^1(x^n+(1-x)^n)^{1/n}dx=\int_0^1\left(1+u\over2\right)du={(1+u)^2\over4}\big|_0^1=1-{1\over4}={3\over4}$$
Answer: $I=\lim_{n\to\infty}\int_0^1(x^n+(1-x)^n)^{1/n}\ dx=\lim_{n\to\infty}\int_0^1x(1+((1-x)/x)^n)^{1/n}dx$. Now $\lim_{n\to\infty}(1+(1-x)/x)ⁿ)^{1/n}=1$. This can be verified by taking log. Assuming uniform convergence we get the result as $\int_0^1xdx=1/2.$
Comment: That is not the correct answer unfortunately.


How to run Openedge explorer?

Question: I am new to Progress and have the Progress OE 12.2 developer Kit classroom version. Try to create an OpenEdge explorer connection using the studio and get the following error message.
"The version of OpenEdge Explorer service running at localhost:9090 does not support this request"
Is it the issue from the software version or else?
Error Image
Comment: This looks like it might be the same question as asked at https://community.progress.com/s/question/0D54Q0000ACUMYjSQP/how-to-run-openedge-explorer . If so, someone from Progress will ahve to answer.
Answer: Do you have multiple versions of OpenEdge running? If so please disable autostart of all the other OpenEdge Admin Servers, restart and try again.

How to run Openedge explorer?


How to sort a list of tuples based on the keys in a list?

Question: I want to sort a list of tuples based on a number of keys. For example, I have this list of tuples:
list_t = [(1, 3, 5, 6, 9, 10), (1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 12, 43)]

One time I want to sort it by the first, second, third, and fifth element of the tuples:
keys = [0, 1, 2, 4]
list_t_sorted = [(1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 9, 10), (1, 3, 5, 6, 12, 43)]

And another time I need to sort it just by the third element of the tuples:
keys = [2]
list_t_sorted = [(1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 3, 5, 6, 9, 10), (1, 3, 5, 6, 12, 43), (1, 2, 6, 7, 9, 54)]

So far I tried this code but it does not return the expected results:
def sort_list(keys, list_t):
    return sorted(list_t, key=lambda l: (l[x] for x in keys))

For example, for keys = [0, 1, 2, 4] it returns [(1, 3, 5, 6, 9, 10), (1, 2, 3, 4, 5, 61), (1, 3, 5, 6, 12, 43), (1, 2, 6, 7, 9, 54), (1, 2, 3, 0, 9, 81)] which is not sorted based on the keys.
Can anybody help me? Thanks!
Comment: You say it doesn't return the expected results. What _does_ it return?
Comment: A not sorted list of tuples based on the keys. For example, for keys = [0, 1, 2, 4], it returns [(1, 3, 5, 6, 9, 10), (1, 2, 3, 4, 5, 61), (1, 3, 5, 6, 12, 43), (1, 2, 6, 7, 9, 54), (1, 2, 3, 0, 9, 81)], which is not sorted on keys!
Answer: Here you go. You can read more about operator.itemgetter here in the docs.
import operator
list_t = [(1, 3, 5, 6, 9, 10), (1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 12, 43)]
keys = [0, 1, 2, 4]
sorted(list_t, key=operator.itemgetter(*keys))

Outputs:
[(1, 2, 3, 4, 5, 61),
 (1, 2, 3, 0, 9, 81),
 (1, 2, 6, 7, 9, 54),
 (1, 3, 5, 6, 9, 10),
 (1, 3, 5, 6, 12, 43)]

Comment: Thanks a lot for your quick answer!
Answer: michael_j_ward's answer is a much cleaner solution to your question, but if you want to know what went wrong with your original idea:
You are attempting to sort generator objects, which I am guessing has a different way of equating. A way to show this is by showing what you are actually attempting to sort with a for loop:
>>> def sort_list(keys, list_t):
...     for l in list_t:
...             print (l[x] for x in keys)
...     return sorted(list_t, key = lambda l: (l[x] for x in keys))
...
>>> sort_list(keys, list_t)
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
[(1, 3, 5, 6, 12, 43), (1, 2, 6, 7, 9, 54), (1, 2, 3, 0, 9, 81), (1, 2, 3, 4, 5, 61), (1, 3, 5, 6, 9, 10)]

This is obviously not your intended output, and it has to do with how those generators are being compared. If you want to do it with your original idea (without itemgetter), explicitly create tuples instead of generators:
>>> def sort_list(keys, list_t):
...     return sorted(list_t, key = lambda l: tuple(l[x] for x in keys))
...
>>> sort_list(keys, list_t)
[(1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 9, 10), (1, 3, 5, 6, 12, 43)]

Comment: Thanks for your great clarification!


Loop in a loop, can I do this better?

Question: I use Python 2.7 and Beautiful Soup 3.2 and I got the following scraper to get the stream URLs:
# Import the classes that are needed
import urllib2
from BeautifulSoup import BeautifulSoup

# URL to scrape and open it with the urllib2
url = 'http://www.wiziwig.tv/broadcast.php?matchid=219751&part=sports'
source = urllib2.urlopen(url)

# Turn the saved source into a BeautifulSoup object
soup = BeautifulSoup(source)

for tr in soup.findAll('tr', {'class': ['broadcast']}):
    stationName = tr.findAll('td')[1].text

    for trBelow in tr.findAllNext('tr'):
        curClass = trBelow['class']
        if curClass == 'broadcast':
            break

        kindStream = trBelow.findAll('td')[0].text
        streamUrl = trBelow.find('a', {'class': 'broadcast go'})['href']
        streamQuality = trBelow.findAll('td')[2].text
        streamRating = trBelow.find('div', {'class': 'rating'})['rel']

        print stationName, kindStream, streamQuality, streamRating, streamUrl

This is working perfectly and gives the following output:
BWIN Flash 650 Kbps 100 http://forum.wiziwig.eu/threads/1847-BWIN-Info
BWIN Flash 675 Kbps 100 https://sports.bwin.com/en/sports?wm=3448325&zoneId=1068792
Bet365 Flash 650 Kbps 100 http://forum.wiziwig.eu/threads/6258-Bet365
Bet365 Flash 675 Kbps 100 http://www.bet365.com/?affiliate=365_014110
TRK Ukraine+ AceStream 1250 Kbps 100 acestream://94879770520f2e9db2146d0eca59204bfbd72cbe
TRK Ukraine+ AceStream 1251 Kbps 75 http://aviatortv.org/football_ua_plus/
Arenavision1 Sopcast 2000 Kbps 75 sop://broker.sopcast.com:3912/143876
Arenavision3 AceStream 2000 Kbps 75 acestream://a53a380706846bfc6667e21a1485dedb78b9674b
Arenavision3 AceStream 2001 Kbps 75 http://avod.me/play/a53a380706846bfc6667e21a1485dedb78b9674b
Dazsports Ace2 AceStream 850 Kbps 100 acestream://d293c82146aa6c2904e45ff305ae0f38dc5b329d
Dazsports Ace2 AceStream 851 Kbps 75 http://dazsports.org/ace2.html
Digi Sport1 [RO] Sopcast 1500 Kbps 100 sop://broker.sopcast.com:3912/146141
Digi Sport1 [RO] Sopcast 1500 Kbps 100 sop://broker.sopcast.com:3912/124992
Digi Sport1 [RO] Sopcast 1501 Kbps 100 sop://broker.sopcast.com:3912/139777
Digi Sport1 [RO] Sopcast 1501 Kbps 100 sop://broker.sopcast.com:3912/110152
Pole Position1 [NL] AceStream 1000 Kbps 100 acestream://86fd521d30e9319198b75121761eccf260fef0cb
Pole Position1 [NL] AceStream 1001 Kbps 75 http://polepositionweb.org/?page_id=6 popup
Solodeportes Veetle Veetle 850 Kbps 100 http://veetle.com/index.php/widget/index/E47CFF6CB6A770852515B8B30C2E30F6/0/true/default/false
Livesports4u4 Flash 225 Kbps 75 http://livesport4u.com/stream4.html
Cricfree Flash2 Flash 175 Kbps 75 http://cricfree.tv/live-golf-streaming-ch2.php
Njtvx9 Flash 175 Kbps 75 http://nutjob.eu/njtvx9.html
Igoal C+ Liga Flash 175 Kbps 75 http://ana1.me/liga+.html
Soccertoall2 [PT] Flash 175 Kbps 75 http://soccertoall.net/index.php?channel=2
Tugalive1 Flash 175 Kbps 75 http://www.tugalive.eu/p/live-1.html
Diresport1 Flash 175 Kbps 75 http://diresportt.blogspot.com.es/
Footstream11 Flash 175 Kbps 75 http://www.footstream.tv/channel11.html
Lag10 (8) Flash 150 Kbps 50 http://lag10.com/channel8
ANA STV2 Flash 400 Kbps 75 http://ana1.me/STV2.html
ANA STV2 Flash 400 Kbps 75 http://bliner.tv/sporttv2pt.html
Livesoccerhd4 Flash 225 Kbps 75 http://livesoccerhd.tv/l4.html
Stvstreams Ace HD1 AceStream 1500 Kbps 100 acestream://750acfc788e12220dbd57188505eae08f566281e
Stvstreams Ace HD1 AceStream 1500 Kbps 100 http://stvstreams.com/acestreams/stv-hd/
Btsportshd12 Flash 200 Kbps 75 http://www.btsportshd.com/stream12.php
Ana Stream1 Flash 175 Kbps 75 http://ana3.me/STREAM1.html
Onlinesoccer2all (13) Flash 175 Kbps 75 http://online--soccer.eu/channel13.html
Hdfoots6 Flash 175 Kbps 75 http://hdfoots.com/stream6.html

But I was wondering if I did this like it should or is there a better way without doing the next loop for trBelow in tr.findAllNext('tr'): and then break out of it when it hits the specific class?
Answer: I'd probably just iterate over the
 items:
station_name = ''
for tr in soup.findAll('tr'):
    if tr['class'] == 'broadcast':
        station_name = tr.findAll('td')[1].text
    else:
        # Your current extraction code
        print stationName, kindStream, ....

This way the code is a little bit clearer, I guess.
On the other hand... looks like you have a quick script that works. It'll break quicker through changes in the html output of the actual page than though bugs in your code. So if it works, it works, I'd say.
Answer: I think your implementation is great already.
Just a quick question, what if I wanted to reuse some of the contents I received?
I assert "Soup" is not using a built in cache for this and if I wanted to re run through
this loop It'd re traverse the nodes.
Here's my take:
with soup:
  tr_elements, tr_belows, collection = findAll('tr', {'class': ['broadcast']}) \
                                       [tr.findAllNext('tr') for tr in tr_elements], {}
  collection['station_names'] = [tr.findAll('td').text[1] for tr in tr_elements]
  collection['kind_streams'] = [trb.findAll('td').text[0] for trb in tr_belows]
  ## and so fourth.
  print dict(collection)

this will still need some work as it can't scan a 'broadcast' node inside the others. In addition, the complexity on my approach can use some work.

Loop in a loop, can I do this better?


Provisioning by stand alone with customization to embedded users

Question: Is it natural to provision stand alone GoodData service with necessary individual customization toward embedded GoodData dashboard users (indirect GoodData users) additionally? Isn't there any worry in such manner to be regarded as duplicated provisioning?
Answer: I'm not sure what do you mean by duplicated provisioning and stand alone GoodData service. But, since GoodData Platform is provided as a service, all users are synchronized across all data centers. Let me know if you mean anything else.
JT
Comment: I thought uniqueness in data correlation brings apps variations and differentiations.


Does Anyone knows a NAT/PT free software?

Question: I was wondering if someone knows a NAT64 software, preferably for windows.
This is because i need to communicate a only IPv6 service with a only IPv4 network without going to the Internet. The service cannot have IPv4 and on the network IPv6 cannot be implemented. That's why I need a translator, a NAT64 / DNS64.
Forefront UAG from Microsoft has a NAT64, it works for me. But i want to know if some of you know a free alternative.
Thank you.
Comment: Teredo (built into Windows) doesn't do what you need?
Comment: Not. Teredo is a transition technologie for get a public IPv6 address when you are behind a NAT Device. This is not what I need in this case. I need a software that I put on a computer in the middle of a IPv4 network and IPv6 network and it translates. Thank you Brian.
Comment: @Steve I'm telling my problem. "I need to communicate a only IPv6 service with a only IPv4 network. The service cannot have IPv4 and on the network IPv6 cannot be implemented. That's why I need a translator, a NAT64 / DNS64.". For being exactly i would like to implement Microsoft Direct Access in a network with not IPv6 capabilities, not even ISATAP. Thank you.
Answer: I only know of Linux or BSD based implementations. This is one with source and pre-built binaries for different Linux distributions: http://ecdysis.viagenie.ca/download.html
It also offers a live CD, so maybe it's a solution for you if you run it in VirtualBox or VMware.
Answer: Let's list out some options and try to get your feedback for each.
1)  Teredo.
Provides connectivity to IPv6 hosts to IPv4 hosts.  Built into Windows and hence very easy to deploy.
2)  IPv6 SOCKS proxy
Sit the proxy on the IPv6 Internet and have one side sitting on your IPv4 intranet.
3)  IPv6 HTTP proxy
You do not specify which protocols you require, if it is only HTTP then a HTTP proxy would be a valid solution.
4)  SSH tunnel
You can implement an IPv6 SOCKS proxy simply with say PuTTY and a regular SSH server.
Comment: Thank you for your answer. I know about the transitions technologies that you mention but none of them works for my everyroment. I'm looking for a NAT64 software.
Comment: @Ricardo you still haven't answered why?  I can only read between the lines and guess you have an IPv4-only application that you are trying to force into communicating with IPv6-only hosts.
Comment: I'm waiting for someone to knows a NAT64 implementation for Windows different to Microsoft UAG. If not my solution will be the one from Sander Steffan.

Yes It's something like that but just the opossitive way. I have an only IPv6 application (Microsoft Direct Access) and i need it to communicate with an IPv4 network by an ethernet cable.
The problems is that for some concerns of the IT area they cannot make the network IPv6 capable.
I need to put something in the middle what makes the translations, even in the DNS queries. That is what NAT64/DNS64 does. Thank you.
Answer: If you go to http://www.sixxs.net you can sign up for their IPv6 tunneling service which allows you to use AICCU to get a routable IPv6 address even if you're behind an IPv4 NAT.
This will let you access IPv6-only services from anywhere.
Comment: Hello @MikeyB. Thanks for your answer. That it's not what I'm looking for. For that I have as example Teredo or the tunnel service that you mention. But it's not what I need. I need to communicate as example, two LANS, one which only can have IPv4 and one which only can have IPv6 and without going to the Internet. That's why I need use the protocol NAT64.
Comment: @Ricardo, aha new information, add that to the question:  "without going to the Internet".
Comment: @Steve Doing that. :)
Comment: Then set up a proxy server (Squid) that has access to both networks.
Answer: Your question confuses me a bit, because you mention a IPv6-only service to be reached from IPv4-only clients, and then call it NAT64. But looking up NAT64 on wikipedia gives me the answer I expect: NAT64 is for IPv6-only clients to reach IPv4-only services.
The 'easy' answer I can think of for your question is setting up a dual-stack device on your network which translates a dedicated v4 address to the v6 destination and advertising the v4 address on your v4-only network for the service. I am not aware of a Windows approach to this (a windows server version may be able to do this). Linux/BSD can be configured to do this.
Comment: Windows have native IPv6/IPv4 dual stack. But that is not what I need.

For be clear I need to connect a Microsoft Direct Access Server (IPv6 only service) with a Network that only supports IPv4 and cannot install dual stack on that network.  In the Microsoft world what a i need is a UAG Server, it has NAT64/DNS64. I put it in the middle of the server and the network and everything works. I was wondering if somenone knows a free alternative.


$\dim\{f:(-1,1)\to \mathbb{R}\mid f^{(n)}(0)=0 ~\forall~ n~\geq0\}=\infty$ if $f\in C^\infty[-1,1]$

Question:
Claim: $$V=\{f:(-1,1)\to \mathbb{R}\mid f^{(n)}(0)=0 ~\forall~ n~\geq0\}$$
is infinite dimensional over $\mathbb{R}$ where $f$ is infinitely differentiable on $(-1,1)$.

Attempt:
Before handling the dimension I'm wondering what functions does $V$ contain.
If we remove the property $f^{(n)}(0)=0 ~\forall~ n~\geq0$ of the functions of $V$ we get that $V$ contains polynomials, exponential functions, trigonometric functions but non of these have $f^{(n)}(0)=0 ~\forall~ n~\geq0$. So, all these types of functions that I mentioned won't work except for the zero function but that makes the dimension of $V$ $1$ if I consider that $0$ is the only possible function in $V$ which is not the case. What are those functions that I'm missing?
Any hints?
Comment: What about $g(0)=0$ and $g(x) = e^{-\frac{1}{x^2}}$ otherwise for example?
Comment: @mathcounterexamples.net would you please name the book where you found this example ? I want to explore this example more.
Answer: Hint: $e^{-n/x^{2}}, n=1,2,...$ are linearly independent elements of $V$. (These functions are given the value $0$ at $x=0$).
It helps to make the change of variable $y=\frac 1 x$ in the proof of independence.
Comment: Thank you that was helpful
Comment: How we confirm that there is no more such function! !!


Trigonometric limit without L'Hospital rule

Question: I am having some problems for solving the following limit without L'Hospital rule or series:
$$\lim_{x\rightarrow 0}\frac{\arctan{2x}}{\sin{3x}}$$
Thank you very much for your help!
Comment: Try a Taylor expansion at $0$. See what you get.
Answer: $$\lim_{x\rightarrow 0}\frac{\arctan{2x}}{\sin{3x}} = \lim_{x\rightarrow 0}\frac{\frac{\arctan{2x}}{2x}}{\frac{\sin{3x}}{3x}}\times \frac{2x}{3x} = \frac{2}{3}$$
Answer: First you want to show that
$$
    \lim_{y\to 0} \frac{\arctan y}{y} = 1
$$
To do this, I would let $\theta = \arctan y$.  Then $\theta \to 0$ as $y \to 0$, so
$$
    \lim_{y\to 0} \frac{\arctan y}{y}
    = \lim_{\theta\to 0} \frac{\theta}{\tan \theta}
    = \lim_{\theta\to 0} \frac{\theta}{\sin \theta}\cdot \cos\theta
    = 1 \cdot 1 = 1
$$
(the limit $\lim_{\theta \to 0} \frac{\sin\theta}{\theta} = 1$ is one of the basic limits you can usually invoke without proof).
Now
$$
    \frac{\arctan 2x}{\sin 3x} = \frac{\dfrac{\arctan 2x}{2x}}{\dfrac{\sin 3x}{3x}}\cdot \frac{2}{3}
$$
Can you take it from there?
Comment: Yes, thank you very much. I was not aware of the limit of  arctan(x)/x.
Comment: @user369151: You're welcome.  $\arctan$ is just $\tan$ after reflecting the plane through the line $y=x$.


How would I, in jQuery remove the extra parts of this string?

Question: So I'm trying to change this string :
9 days from now Write about "go to market strategy" - 0.03 - 8100

To this :
Write about "go to market strategy"

How could I do it in javascript or jQuery without the use of regular expressions ?
Any answers here appreciated.
Comment: @Tapha please start making your questions more complete. When you post incomplete questions you keep creating a deluge of bad answers based on guesses. Define the criteria more precisely for this string. As it stands right now your question can be interpreted different ways
Comment: That's not really what jquery does
Comment: Also show what you tried. This just looks like no effort was attempted to solve this problem yourself and you expect others to do your work for you
Comment: Just to clarify, you have something like `var str = '9 days from now Write about "go to market strategy" - 0.03 - 8100';` and you want `str = 'Write about "go to market strategy"` ?
Comment: `var input = '9 days from now Write about "go to market strategy" - 0.03 - 8100'; var output = input.split("now")[1].split(" - ")[0].trim();`
Answer: Apparently you want to get the title which is between double quotes and insert it in another phrase.
function answer(yourString) {
    // Get the first double quote position
    var start = yourString.indexOf('"')+1;
    // Get the second double quote position
    var end = yourString.indexOf('"',start);
    // Get the subject
    var subject=yourString.substr(start,end-start);

    //result
    return 'Write about "'+subject+'"';
}

Comment: They need the text after `from now` and before the ` - `. :)
Comment: @JamesPederson this is an ambiguous point of the question, maybe **Tapha** would be kind to provide more examples of what is needed. Nevertheless you bring a valid concern, but the answer provide a solution that fit the question.
Answer: Give this a shot:
var str = '9 days from now Write about "go to market strategy" - 0.03 - 8100',
    separator1 = "from now",
    separator2 = ' - ';
str = str.substring( str.indexOf( separator1 )+separator1.length+1 );
str = str.substring(0, str.indexOf(" - "));
console.log( str );

It uses the .indexOf() method to find the strings and .substring() to shorten the main string.
Hope this helps.
Comment: Absolutely, that's the main idea of it :) Mine just lets him store whatever strings he wants to read the content between, and calculates the lengths of them to accommodate.
Comment: I agree that this solution  also fit the question, additionaly I hope @Tapha would get the gist of the solution, which is using the `indexOf` method
Answer: I have a feeling you are going to want to parse out other strings within the larger string that something other than 'go to market strategy'. With that being said, you're going to want to think about what the 'red flag' will be (delimeters). However, for what you're asking, this will do the trick:
$(document).ready(function () {
    var theString = "9 days from now write about 'Go to market strategy' - 0.03 - 8100";
    var regEx = /Go to market strategy/;
    result = regEx.exec(theString);
    alert(result);

});

If you didn't want to use a regular expression, you need to update your question with more specifications on what you're actually trying to accomplish so we can provide more specific code. For right now, this solution utilizes a static regex.
Comment: They don't want to use regular expressions. Also, they need more of the string than just the specific text that's in the quotes - and this regex will only match this one reminder message, that message changes, so it's not going to match the next reminder message.
Comment: Yes, but the OP's question was unclear and not specific. Therefore, the most general 'catch all' answer if provided with the hope it will help guide the OP solve their problem. Oh, and the reasoning for using a regular expression is mentioned in the answer.


Phalcon view not rendering right from other actions

Question: I was reading the documentation on Phalcon about Hierarchical Rendering("http://docs.phalconphp.com/en/latest/reference/views.html#hierarchical-rendering"). And I can't seem to figure it out. I have the following file setup just like the documentation but the only difference is that i am using volt.
--views
  --vacancy
      --index.volt// action
      --new.volt//action
  --layouts
    --vacancy.volt//controller

And this is my Vacancy controller. It's just an empty controller
class VacancyController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {

    }
    public function newAction()
    {

    }
}

Problem
When i go to "mysite.com/vacancy" everything seems to be rendering just fine. But when i use the "new" action "mysite.com/vacancy/new"  i get the content of the file new.volt but it doesn't render the way i think it's supposed too.
In the chrome console i get this error:
Resource interpreted as Script but transferred with MIME type text/html:
If i remove the action "new " it will just renders fine!
I hope it's clear enough.
Comment: Put the code of `new.volt` in the question please.
Comment: Can you post the contents of your `new.volt` file?
Comment: It doesn't have anything relevant i think.. "new vacancy" it's just that string
Answer: I resolve it just by putting a / before every file that i was including into the html document..
Example

instead of