Fatal error using `RWeka::NGramTokenizer` with `tm` to build a term document matrix?

Question: I installed the tm library and want to build n-grams of a corpus using the NGramTokenizer from the RWeka library.
The tm paper p. 11 lists the following call:
> TermDocMatrix(col, control=list(tokenize = NGramTokenizer))

I know I need to use TermDocumentMatrix in the version of tm I'm using. I get the following return:
> col
A corpus with 3 text documents
>
> TermDocumentMatrix(col, control=list(tokenize=NGramTokenizer))
#  fatal error: mach_msg (send) failed: 0x10000003

#  fatal error: mach_msg (send) failed: 0x10000003

A term-document matrix (0 terms, 3 documents)

Non-/sparse entries: 0/0
Sparsity           : NaN%
Maximal term length: 0
Weighting          : term frequency (tf)
Warnmeldung:
In is.na(x) :
  is.na() auf nicht-(Liste oder Vektor) des Typs 'NULL' angewendet

What could be the problem here? The corpus is not that large (truncated for testing).
> print(object.size("col"))
96 bytes

Comment: I'd be happy to answer by explaining how to do this in the **quanteda** package (see http://stackoverflow.com/questions/31281534/generating-all-word-unigrams-through-trigrams-in-r), but you did ask specifically how to do it in **tm**. Let me know if you would find such an answer helpful.
Comment: I would find it useful.
Comment: OK done, see my answer below.
Answer: I cannot quickly see what would generate your error without having a sample data set. But if you run the following code you can see that the RWeka tokonizer works.
  library(tm)
  library(RWeka)

  data("crude")
  crude <- as.VCorpus(crude)
  crude <- tm_map(crude, stripWhitespace)
  crude <- tm_map(crude, content_transformer(tolower))
  crude <- tm_map(crude, removeWords, stopwords("english"))
  crude <- tm_map(crude, stemDocument)
  # Sets the default number of threads to use
  options(mc.cores=1)

  tdm <- TermDocumentMatrix(crude, control=list(tokenize = NGramTokenizer))

  findFreqTerms(tdm, lowfreq = 10)

[1] "accord"      "barrel"      "bpd"         "crude"       "crude oil"   "dlrs"        "dlrs barrel" "futur"       "govern"      "kuwait"      "last"
[12] "market"      "meet"        "mln"         "mln bpd"     "month"       "new"         "offici"      "oil"         "oil price"   "one"         "opec"
[23] "pct"         "price"       "prices"      "product"     "reuter"      "said"        "saudi"       "say"         "sheikh"      "u s"         "will"
[34] "world"       "year"

Comment: I tried to reproduce your example:
>   crude <- tm_map(crude, stripWhitespace)
>   crude <- tm_map(crude, content_transformer(tolower))
Warnmeldung:
In parallel::mclapply(x, FUN, ...) :
  all scheduled cores encountered errors in user code
Comment: Ah, I have seen that mentioned before. RWeka and parallel apparently have some errors working together. See also this post on SO: http://stackoverflow.com/questions/17703553/bigrams-instead-of-single-words-in-termdocument-matrix-using-r-and-rweka.
I have adjusted a line of code that should help.
Answer: OK, here is the method for tokenizing grams in quanteda.  Our view is that there is no such thing as n-grams without tokenization, since the notion implies sequences of tokens defined by some kind of adjacency.  So we built in an ngrams option into our tokenize() function.  ngrams takes a vector of integers, where each integer represents a size of ngram (the default is 1).
It works like this:
> # or: devtools::install_github("kbenoit/quanteda")
> require(quanteda)
> mytext <- c("The quick brown fox, jumped over the lazy dog.",
+             "Here is a second sentence to tokenize.")
> tokenize(toLower(mytext), removePunct = TRUE, ngrams = 2)
[[1]]
[1] "the_quick"   "quick_brown" "brown_fox"   "fox_jumped"  "jumped_over" "over_the"    "the_lazy"
[8] "lazy_dog"

[[2]]
[1] "here_is"         "is_a"            "a_second"        "second_sentence" "sentence_to"     "to_tokenize"

attr(,"class")
[1] "tokenizedTexts" "list"
> tokenize(toLower(mytext), removePunct = TRUE, ngrams = 3)
[[1]]
[1] "the_quick_brown"  "quick_brown_fox"  "brown_fox_jumped" "fox_jumped_over"  "jumped_over_the"
[6] "over_the_lazy"    "the_lazy_dog"

[[2]]
[1] "here_is_a"            "is_a_second"          "a_second_sentence"    "second_sentence_to"
[5] "sentence_to_tokenize"

attr(,"class")
[1] "tokenizedTexts" "list"
> tokenize(toLower(mytext), removePunct = TRUE, ngrams = 1:3)
[[1]]
 [1] "the"              "quick"            "brown"            "fox"              "jumped"
 [6] "over"             "the"              "lazy"             "dog"              "the_quick"
[11] "quick_brown"      "brown_fox"        "fox_jumped"       "jumped_over"      "over_the"
[16] "the_lazy"         "lazy_dog"         "the_quick_brown"  "quick_brown_fox"  "brown_fox_jumped"
[21] "fox_jumped_over"  "jumped_over_the"  "over_the_lazy"    "the_lazy_dog"

[[2]]
 [1] "here"                 "is"                   "a"                    "second"
 [5] "sentence"             "to"                   "tokenize"             "here_is"
 [9] "is_a"                 "a_second"             "second_sentence"      "sentence_to"
[13] "to_tokenize"          "here_is_a"            "is_a_second"          "a_second_sentence"
[17] "second_sentence_to"   "sentence_to_tokenize"

attr(,"class")
[1] "tokenizedTexts" "list"
>
> # to create a dfm from one of these
> mytokTxts <- tokenize(toLower(mytext), removePunct = TRUE, ngrams = 3)
> dfm(mytokTxts)
Creating a dfm from a tokenizedTexts object ...
   ... indexing 2 documents
   ... shaping tokens into data.table, found 12 total tokens
   ... summing tokens by document
   ... indexing 12 feature types
   ... building sparse matrix
   ... created a 2 x 12 sparse dfm
   ... complete. Elapsed time: 0.023 seconds.
Document-feature matrix of: 2 documents, 12 features.
2 x 12 sparse Matrix of class "dfmSparse"
       features
docs    a_second_sentence brown_fox_jumped fox_jumped_over here_is_a is_a_second jumped_over_the over_the_lazy
  text1                 0                1               1         0           0               1             1
  text2                 1                0               0         1           1               0             0
       features
docs    quick_brown_fox second_sentence_to sentence_to_tokenize the_lazy_dog the_quick_brown
  text1               1                  0                    0            1               1
  text2               0                  1                    1            0               0

Happy to help further if you have more questions.
UPDATED 2021 w/quanteda v3
Here's how to do it with a less ancient version of quanteda:
library("quanteda")
## Package version: 3.0.
## Unicode version: 13.0
## ICU version: 69.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.

mytext <- c(
  "The quick brown fox, jumped over the lazy dog.",
  "Here is a second sentence to tokenize."
)

tokens(mytext, remove_punct = TRUE) %>%
  tokens_tolower() %>%
  tokens_ngrams(n = 2) %>%
  dfm()
## Document-feature matrix of: 2 documents, 14 features (50.00% sparse) and 0 docvars.
##        features
## docs    the_quick quick_brown brown_fox fox_jumped jumped_over over_the
##   text1         1           1         1          1           1        1
##   text2         0           0         0          0           0        0
##        features
## docs    the_lazy lazy_dog here_is is_a
##   text1        1        1       0    0
##   text2        0        0       1    1
## [ reached max_nfeat ... 4 more features ]
```


win32set time return error in win 8.1

Question: I want to change system time Programatically in C# (in Windows 8.1) and
I used Win32SetSystemTime and setSystemTime:
 static extern bool Win32SetSystemTime([InAttribute()] ref SYSTEMTIME sysTime)   static extern bool SetSystemTime(ref SYSTEMTIME time);

I set privileges before I call these functions and set privileges return true but when I call Win32SetSystemTime or setSystemTime, I get error 1300 and 1314 and system time doesn't change at all.
These errors are about  privileges!!
And whenever I run app as an administrator, they work correctly!
I use below code to set privilege:
        string privilege = "SE_SYSTEMTIME_NAME";

        try
        {
            bool retVal;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            retVal = OpenProcessToken(hproc,TOKEN_ALL_ACCESS , ref htok);
          //  retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
            retVal = AdjustTokenPrivileges(htok, false, ref tp, 0,         IntPtr.Zero, IntPtr.Zero);
            return retVal;
        }
        catch (Exception ex)
        {
            throw ex;
        }

Comment: Elevating privilege is not that simple, you have to [ask nicely](http://stackoverflow.com/a/2818776/17034)..
Answer: Setting the system time requires administrator privileges. That means running the process as an administrator.
Under UAC processes run as standard user by default. You will need to use one of the variety of ways to run your process as administrator. For instance by specifying the requireAdministrator option in the manifest. Best practice is to elevate only for the operations that require elevation. That involves creating a separate process for these admin tasks.
You'll also be able to get rid of all the code in the question because when running as administrator your token will by default already contain the necessary privilege to change the time.
I'm not sure what Win32SetSystemTime is. The function you need to call is SetSystemTime. This example on MSDN shows how to do it, although the author rather lazily omitted error checking: https://msdn.microsoft.com/en-us/library/ms172517(v=vs.90).aspx
Comment: thank you for your answer but i add a manifest file to my project and set  and set the manifest refrence in My project properties but still when i want to  set tSystem time i get previous error again !!
Comment: You need to remove all the code in the question and just call SetSystemTime. Also, what you say doesn't tally with "whenever I run app as an administrator, they work correctly"
Comment: i think maybe the manifest file doesn't work property in the project!?
Comment: When you start your application, are you presented with the UAC consent dialog?
Comment: no ,UAC Dialog doesn't show .when i Right click on Myproject .exe file or run VisualStudio 2013 as admin i see UAC .but when i use manifest or don't use manifest i don't show any uac, is it possible that my project does't recognize manifest?
Comment: what is the problem? i right click on myproject and select new item --> manifest  then i change the level to requireAdministrator !i use visual studio 2013 and windows 8.1 ,

win32set time return error in win 8.1


Jquey - Como tomar ações com elementos dinâmicos de uma tabela?

Question: Estou fazendo uma tabela que é alimentada dinamicamente com valores do banco de dados. Nessa tabela criada coloquei um campo para inserir a "quantidade" e um botão desabilitado por uma classe. Eu quero habilitar o botão assim que o usuário inserir um valor no input "quantidade", mas da forma que eu tentei fazer com jquery não deu certo, só funciona nos elementos da primeira linha (produto), nos restantes não desabilita o botão.

    @foreach ($produtos as $produto)

            {{ $produto->codigo }}
            {{ $produto->produto }}
            {{ $produto->unidade_medida_peso }}

                <input type="text" id="inputQuantidade">

    @endforeach

E o que eu tentei fazer no jquery:
    $( "#inputQuantidade" ).keyup(function() {
    $(this).closest('tr').find('#addproduto').removeClass("disabled");
    });

Answer: O atributo global id define um identificador exclusivo (ID) que deve ser único por todo o documento. Como você está dentro de um foreach vai acontecer de existir 2 ID's e isso não pode ocorrer. No seu caso, você pode estar fazendo o uso de classes.
Segue um exemplo de como você poderia fazer a implementação:

    @foreach ($produtos as $produto)

            {{ $produto->codigo }}
            {{ $produto->produto }}
            {{ $produto->unidade_medida_peso }}

                <input type="text" class="inputQuantidade">

    @endforeach

Outra coisa é que você precisa garantir que as tag's já estão no documento no momento em que você faz a execução do jQuery. Modifique seu script para seguir as instruções abaixo:
$(function() {
    $( ".inputQuantidade" ).keyup(function() {
          $(this).closest('tr').find('.addproduto').removeClass("disabled");
    });
});

Comment: Perfeito! Agora funcionou. Muito obrigado, cara!


What is the best way to get an integer into an enum?

Question: Criteria: Performance, Performance, Performance.
I need a way to convert a uint, int, etc into it's enum equivalent.  What's the fastest way I can do that using C#?
Answer: Why can't you just do a direct cast?
<code>MyEnum enumVar = (MyEnum)intVar;
</code>
Comment: Argg, was just gonna say that :)
Comment: I know.  That happens to me all the time. ;)
Comment: Thanks!  Wow, that was much easier then some other weird solutions I saw out there.
Comment: Enums to and from ints is trivial.  In fact, I'm pretty sure that the compiler handles 99% of any optimizations that you would need to worry about.  Now when you go back and forth from strings is where it can get funky.
Comment: The only problem with this is that you can cast values that are invalid and you won't get an exception. Enum.Parse() is much safer, but it does involve overhead from a performance perspective.


Permutation of coefficients of polynomials

Question: Are there any known results relating to permutation of coefficients of polynomials?
for example given a polynomial, if the coefficients are permuted, then are there any results relating the two?
related question, given set of all polynomials that are permutations of coefficients, are there any known results?
The only possible example that I can think of is that if roots of a polynomial are not rational, then all polynomials permutations of it's coefficients also have no rational roots. Not sure if this is correct or incorrect.
Answer: AS an example where your assertion is false: $x^2+x+2$ has non rational roots but $x^2 + 2x + 1 = (x+1)^2$. Permuting the coefficients of a polynomial can change the properties of a polynomial drastically: irreducibility, dicriminant, etc. An exception can be made for polynomials that satisfy the Eisenstein criterium for irreducibility on the condition that the first and last coefficients remain unchanged.
Answer: Suppose $\;w\neq0\;$ is a root of $\;a_nx^n+a_{n-1}x^{n-1}+\ldots+a_1x+a_0\;$ (All this over some field), then:
$$a_nw^n+a_{n-1}w^{n-1}+\ldots+a_1w+a_0=0\stackrel{\cdot\,w^{-n}}\implies $$
$$a_0(w^{-1})^n+a_1(w^{-1})^{n-1}+\ldots+a_{n-1}w^{-1}+a_n=0\implies w^{-1}\;\;\text{root of}\;\;$$
$$a_0x^n+a_1x^{n-1}+\ldots+a_{n-1}x+a_n$$
But for the above, I don't know any other more or less significant general relation, though of course there are the polynomials in $\;n\;$ unknowns which remain fixed when a permutation is applied on their coefficients. These are known as symmetric polynomials, but it is not perhaps what you want.


Is it possible to link images to different URLs?

Question: Using View's module it is possible to create a page to display some content horizontally. I have done this using carousel feature.
The content type that these contents belong to have an image_field and a body_field.
What I want from Drupal 8 is that when these images are clicked they should redirect visitors to a specific page (not to the node's / content's page).
Is it possible to do so or using html on body_field to place the images with a and img tags is the only way?
UPDATE:
At first I understood nothing from the answer below but a day later it just made sense like in the movie "Phenomenon"; I was struck by a mysterious light in the sky. Here is what I did:

Created a new link_field inside the content type that I am using on this View.

Went back to the content / node (under Content) where I wanted to add the link to the image and filled the link_field

Added this newly created link_field to the View and made it hidden by checking the box titled "Exclude from display".

Clicked on the image_field on View settings (under the FEILDS) and REWRITE RESULTS > check the box "Output this field as a custom link" (An empty area shows up to be filled here).

Went down and expanded the drop down list titled "REPLACEMENT PATTERNS" and found the link_field's name (The name you gave to your link field you have created it) and copied the string (something like {{ the_name_of_my_link_field }}).

Pasted this string into the empty area above then Saved, Saved, Saved to exit.

That's all!
Answer: You can do this using the Rewrite feature of Views.
These instructions assume that the view is set to show Fields (instead of Content or something else).  If you are not using fields, you can switch to fields under FORMAT in the Views UI.

Click the image field in your view and select the checkbox Exclude from display.
Add a new field to the view of type Custom text.
On the custom text configuration screen, check the Replacement patterns. This will include some twig tokens that you can use, including the image file. You can then use this token to add HTML to the Text field to get the link you want.  For example, {{ image }}.

Note that when using Views twig replacement tokens in a custom text field, order matters!  If your custom text field is above another field, it won't be able to get the tokens from the field(s) below.  In that case, you will need to click the flippy triangle to the right of Fields in the Views UI and choose rearrange, and then move the field that uses tokens below the field(s) that supply the tokens.
Another option is to open up the settings for your image field in Views and, under Rewrite results, click Output this field as a custom link and set the link options there.
Comment: Thanks, it took me a while to understand it.


Listview item not deleting

Question: in my application i add name, address and phone no of person, when i click on view button it will show name, address and phone no. in listview, in my list view each record contain one check box in front of them, if in my list view there are 15 records, out of them only 10 are visible on list view, when i check the 15th record and press delete button it will give me null pointer exception on check box, means the non visible items in the listview are not deleting from list when i check them and press delete, following is my code,
for(int i = 0;i<simpleCursorAdapter.getCount();i++){
            View view = listData.getChildAt(i);
            CheckBox deleteSelectes = (CheckBox) view.findViewById(R.id.checkDelete);

            if(deleteSelectes.isChecked()){
                cursor.moveToPosition(i);
                int delete_id = cursor.getInt(0);
                myDbhelper.deleteSelected(delete_id);
                 Intent intent = new Intent(getApplicationContext(), ListTableData.class);
                 startActivity(intent);
            }

        }
        break;

Answer: int i = 0;i<simpleCursorAdapter.getCount();i++

This doesn't prevent i from increamenting to 15. So the listData.getChildAt(i); is actually saying listData.getChildAt(15); which is Null. Try with i-1.
Comment: done this but still getting the same problem, i think check box view is not getting for the last item,
Comment: Did you try deleting from the top 10. And see if that works first.

Listview item not deleting


is it safe to change the RDP port?

Question: My web server is in the U.S. and it is accessed from my home in Canada using Remote Desktop Connection, standard port.
Unauthorized persons have tried to log in from many different countries, some trying 10000+ times per day until they eventually give up.
if the RDP port is changed to a non-standard port, it is very likely that these people will simply iterate ports until they locate the re-assigned RDP port and then continue to try to brute force the password?
My fear of the unknown is that to change the port it would be done by me via Remote Desktop Connection; is it safe?
What is the risk of locking myself out?
Also, instead of telling RDC to go to "my server ip address", would future access have to be expressed as "my server ip address:new RDP port"?
Comment: i very much appreciate the replies to date and am reviewing them.  thnx
Answer: if the RDP port is changed to a non-standard port, it is very likely that these people will simply iterate ports until they locate the re-assigned RDP port and then continue to try to brute force the password? - Yes, that's likely to happen.
My fear of the unknown is that to change the port it would be done by me via Remote Desktop Connection; is it safe? - It's safe for the current session. Changing the default listening port requires a server reboot, so you'll be OK until you reboot the server after making this change.
What is the risk of locking myself out? - Pretty low for the existing session. The risk is that after making the change and rebooting the server you could be prevented from accessing the server if there's a network firewall in front of the server that only allows connections to the default port to the server.
Also, instead of telling RDC to go to "my server ip address", would future access have to be expressed as "my server ip address:new RDP port"? - Yes.
Answer: There is little risk in losing access to the server by changing the RDP port, but there is still some.
Before changing the RDP port, check any firewalls the server is behind and make sure the new port is not blocked.
Also, make sure you can get console access if needed (remote hands, a friend that has access to the server, a remote IP KVM, whatever). This is probably good for any server anyways.
To answer your last question, yes, you will have to specify the port number in the RDP connection each time.
One last word of advice, even though you're changing the port number RDP listens on, it is still possible for an evil-doer to make connections. Ensure all accounts have strong passwords and disable the Administrator account if possible.
Answer: Don't try to change the RDP port on the server.
Don't expect changing the port number to automatically make RDP safe.
Do have a firewall in front of your server that can control RDP traffic to and from your server.
Do set your firewall to forward traffic on a non-standard port to the RDP standard port 3389. I explain why below. To my knowledge, the built-in Windows Firewall will not do this, but other firewalls will.
Do set your firewall to allow traffic on your RDP port from your home system, and disallow RDP from everything else. Depending on the firewall and other options, this could mean getting a static IP for your home system or setting up a dynamic dns service, or it could mean writing firewall rules based on known mac addresses you use.
To avoid just kicking this issue up to your firewall interface, you want to set this up so your firewall can only be configured over RDP. Even so, this should reduce the risk of locking yourself out. You accomplish by configuring a non-standard port-forward rule on your firewall in addition to the standard RDP port, so you can test the new rule in safe way. Write your firewall rule for what port you want, test that it blocks access from a random location (like a library), but still allows access from home. Then block access on the normal port after you've successfully testing the rule (or vice versa: use the non-standard port as a safeguard until you've tested the rule on the standard port).
And of course, what you should really be doing here is setting up a VPN connection to your server... but even with a VPN connection, you'll want a firewall controlling access.
Answer: IMHO it is not safe to expose RDP directly to internet. I recommend to consider use of VPN as already mentioned. If there is some reason for not using VPN. Change the port on NAT rule of your firewall and setup rules that blocks people scanning ports.

is it safe to change the RDP port?


Can I remove the "Item successfully added to your cart" popup?

Question: Can I removed the Item successfully added to your cart popup in Drupal Commerce?
Answer: Goto: /admin/config/workflow/rules
and disable 'Display an Add to Cart message' Rule.

Thank You.
Comment: disable it as discribed by @AddWeb Solution Pvt Ltd. To customize it you could you can clone it. Remove the action that comes with it and use the "Show a message on the site" action instead. Then enable.


Menu Block change depth

Question: I'm converting an HTML template to a Drupal theme. The HTML template has a 2-level submenu:
ul (main) > ul (first-level) > ul (second level).
In my block--system--main-menu.tpl.php I do only have: <?php print $content ?>
When I check the structure of the Main menu in Drupal (list links) levels are correct.
Now on my frontpage Drupal shows only the first level of the menu. How can I make Drupal show more levels? I'd love to do this without a (non-core) module.
Thanks in advance!
Answer: I think you just have the primary navigation enabled in your theme. To see the second level, enable the secondary navigation in your theme settings. But this will split you're navigation. A probably better solution is, to use the "Menu Block" module. This allows you to build different kind of navigations in a block.

Menu Block change depth


Flexmojo compiledLocal failed for italian or serbian language

Question: I discover flex world and maven by adding some new feature in an existing flex app, I may certainly doing something wrong but i don't know what.
I'm using flexmojo to manage flex compilation and I got some error when I try to activate another languages (spanich, italian or serbian). It work like a charm for french german and english language
Here is my pom.xml :
<configuration>
    <targetPlayer>10.0.0</targetPlayer>
    <incremental>true</incremental>
    <verboseStacktraces>false</verboseStacktraces>
    <optimize>true</optimize>
    <showWarnings>false</showWarnings>
    <debug>false</debug>
    <strict>true</strict>
    <compiledLocales>
        <locale>fr_FR</locale>
        <locale>es_ES</locale>
        <locale>de_DE</locale>
        <locale>it_IT</locale>
        <locale>en_US</locale>
        <locale>rs_SR</locale>
    </compiledLocales>
    <themes>
        <theme>${project.build.directory}/generated-resources/flex/themes/spark-theme.css</theme>
        <theme>${project.build.directory}/generated-resources/flex/themes/halo-theme.swc</theme>
    </themes>

    <services>${project.build.directory}/generated-resources/flex/services-config.xml</services>

    <contextRoot>idApp</contextRoot>
    <useNetwork>true</useNetwork>
    <allowSourcePathOverlap>true</allowSourcePathOverlap>
    <sourcePaths>
        <path>${basedir}/src/main/resources/locale/{locale}</path>
        <path>${basedir}/src/main/flex/</path>
        <path>${basedir}/src/test/</path>
    </sourcePaths>
    <sourceFile>idApp.mxml</sourceFile>
    <skipTests>true</skipTests>
</configuration>

In my config.xml file I have the same language :
<?xml version="1.0" encoding="UTF-8"?>
<IDTRELConfig>
    <service endpoint="http://localhost:8080/idApp/messagebroker/amf" />
    <languages>
        <fr enable="true" />
        <en enable="true" />
        <es enable="true" />
        <de enable="true" />
        <it enable="true" />
        <sr enable="true" />
    </languages>
</IDTRELConfig>

When I execute within eclispe the following command :
clean install -Dmaven.test.skip -Dmaven.javadoc.skip

I got the following error :
    ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.200 s
[INFO] Finished at: 2015-03-11T18:24:45+01:00
[INFO] Final Memory: 15M/220M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:3.8:compile-swf (default-compile-swf) on project idApp: Failure to find com.adobe.flex.framework:datavisualization:rb.swc:rs_SR:126.96.36.19976 in http://download.java.net/maven/2 was cached in the local repository, resolution will not be reattempted until the update interval of java.net2 has elapsed or updates are forced
[ERROR]
[ERROR] Try downloading the file manually from the project website.

Comment: I found a bad solution for the moment, I use the German language (not use for the moment), but I put all the Serbian translation inside and put the Serbian flag instead the German. But I'm going to be block If we got a German customer :/
Answer: Please use a locale chain. The problem is that you are defining a language the flex-framework doesn't have locales for per default. So the compiler complains as soon as it wants to include the serbian locales for the flex resource-bundes. The simplest solution would be to set english as a fallback for any resources not avaialbe in serbian.
<compiledLocales>
    <locale>fr_FR</locale>
    <locale>es_ES</locale>
    <locale>de_DE</locale>
    <locale>it_IT</locale>
    <locale>en_US</locale>
    <locale>rs_SR,en_US</locale>
</compiledLocales>

This way the compiler will use Serbian where you have provided it, and use US-English wherever you are missing a Serbian resource.
See here for details: https://cwiki.apache.org/confluence/display/FLEX/Adding+I18N+support+to+your+application for details


getting error cx-storefront is not known element Spartacus Angular storefront in SAP Hybris

Question: <code>ERROR in 'cx-storefront' is not a known element:
</code>

If 'cx-storefront' is an Angular component, then verify that it is part of this module.
If 'cx-storefront' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]
")
Comment: The `CUSTOM_ELEMENTS_SCHEMA` warning normally indicates that component (`cx-storefront` in this case) hasn't been imported.
Comment: https://stackoverflow.com/questions/77838084/cx-media-cx-carousel-not-emitting-data
Answer: The problem was resolved by below two things in Angular >^9.0

disable Ivy compiler option in tsconfig.app.json
"angularCompilerOptions": {
"enableIvy": false
}

adding below configuration in the src/app/app.module.ts
B2cStorefrontModule.withConfig({
backend: {
occ: {
baseUrl: environment.occBaseUrl,
prefix: '/occ/v2/'
},
},
context: {
baseSite: ['electronics-spa'],
},
})

Where occBaseUrl: 'https://localhost:9002' is the property defined in the environment configuration.
Comment: What helped you was actually *importing `B2cStorefrontModule`*. It exports the `StorefrontComponent` so it's accessible in your `AppComponent`. Ivy is the recommended render engine. Thus *IVY shouldn't be disabled* if not having good enough arguments to do it.
Answer: Just go to your tsconfig.json file and mark strictTemplates as false. This worked for me.
"angularCompilerOptions": {
"strictTemplates": false
}


Can not pass value from Ajax to controller

Question: My AJAX:
<code>   $.ajax({
        url: '{{ URL::to('dashboard') }}',
        type: 'GET',
        data: { cid: val },
        dataType:'JSON',
        success: function(result) {
        },
        error: function(){
            $('#status-msg').addClass('alert alert-danger');
            $('#status-msg').text('Fejl!!');
        }
    });
</code>
My Route:
My Controller:
<code>    public function dashboard(){
        if (Request::ajax()){
            $cid = Input::get('cid');
            var_dump(json_encode($cid));
        } else {
            echo "XX";
        }
    }
</code>
The cid is not passing to controller, the request AJAX is not working.
Comment: If you look in the network console of your browser do you see something like this: `/dashboard?cid=val` ?
Answer: have you try change your ajax type to POST ?
<code>$.ajax({
        url: '{{ URL::to("yourURL") }}',
        type:'POST',
        data:"cid="+$(this).val()+"&_token=" + $("input[name=_token]").val(),
        dataType:'JSON',
        success:function(result){
        },
        error: function() {

        }

  });
</code>
Edit:

try to pass _token if you use {{Form::open}}.

hope this will help.
Comment: have you try to change how to pass data like `data:"cid="+$(this).val()&_token=" + $("input[name=_token]").val(),`. You can fetch the data in controller use `Input::all()` to fetch all the value like `$input = Input::all();`
Answer: Try this:
<code>$.ajax({
   url: '<?php echo base_url() ?>index.php/contorller_name/method_name',
   type: 'POST',
   data: { cid: val },
   dataType:'JSON',
   success: function(result) {},
   error: function() {
      $('#status-msg').addClass('alert alert-danger');
      $('#status-msg').text('Fejl!!');
   }
});
</code>
Comment: I have not tried this, but could be but how is it different the other way?
Comment: Do you have latest jquery library inserted. Because you are using jquery.


Are all modes/scales in a given key signature perceived as equally bright/dark?

Question: Many people experience certain keys to be "brighter" or "sharper" relative to other keys. Keys with more sharps than flats are reported as being "brighter" and keys with more flats than sharps as being "darker." This question cites a book that mentions this, and additional citations are below. To give one example, many find a song written in AMaj to sound brighter than a song written in E♭Maj.
My question is: has any trend been found that correlates this same quality of brightness/darkness (which is normally associated with particular keys) with the particular mode? For example, among people who have a consensus that AMaj is brighter than E♭Maj, would a song written in AMaj sound brighter than a song written in F♯min? Or do both songs elicit the same experience of "brightness" because they both have the same number of sharps?
I'm not wondering about whether one song would sound happier (as this question asks). Rather, I'm asking about a different phenomenon that has less to do with an emotional response and more to do with an associated perception of brightness in the sense of color/contrast.
Note 1: this might be interpreted as a personal poll, which I'm hoping to avoid in the answers. Just as a consensus exists that many people find, e.g., AMaj to be "brighter" than E♭Maj, I'm wondering if a similar consensus exists about whether or not the particular mode impacts this same perceived brightness.
Note 2: the phrasing "keys with more sharps [than flats] are brighter" might be an imperfect description of the phenomenon I'm referring to. I don't want to imply that anyone hears D♭Maj as being brighter than C♯Maj. For more detail on the phenomenon, see below.

Here are a few descriptions of the phenomenon I'm referring to.
The Harvard Dictionary of Music

Keys with sharps in the signature are often said to be bright and keys with flats dark.

https://musiccog.ohio-state.edu/Music838/exam_questions_answers.html:

What is meant by a "key characteristic?" The association of certain musical key signatures with a specific subjective quality or emotion. e.g. E major as "bright & piercing."

http://biteyourownelbow.com/keychar.htm:

Key Characteristics
Today many musicians claim to hear the different characteristics very clearly, and associate them with the emotional quality of the music. They will tell us that music played in the "open" key of C major---with neither flats nor sharps in the key signature---sounds strong and virile; played in the key of G, with one sharp, it sounds brighter and lighter; in D, with two sharps, even more so; and so on. Every additional sharp in the key signature is supposed to add to the brightness and sparkle of the music, while every flat contributes softness, pensiveness, and even melancholy.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/71649/discussion-on-question-by-jdjazz-are-all-modes-scales-in-a-given-key-signature-p).
Answer: When you write a piece in a certain key you're really writing with a tonic note in mind. That is, one note is considered the note on which the piece rests and which all other notes are compared to. Different notes are either higher or lower than each other depending on the instrument's range, the composer's intentions, and the limitations of the player.
For instance, on a guitar the lowest note is (usually) E natural below the bass clef. Technically this would make E major the darkest key on a standard tuned guitar while Eb major would be the brightest (since it's the highest note on the lowest octave).
The human voice is also a big determining factor of what keys people consider brighter or darker. Sopranos and tenors have the highest voices of women and men while Altos and basses have the lowest. I consider the keys of C and F major to have a 180 degree relationship; that is, they are as far apart as can be and are considered the lowest comfortable keys for the 4 singing ranges. Also, unlike most people, I consider C major to be a "flat" key because most flat keys have a C natural in the scale while only one sharp key has it (G major). It's also the 5 of F major.
There's also a psychological factor to consider. When you see the note Eb you immediately compare it to E natural and assume that it must be darker if it's lower. In reality, they're only a half step apart and both are played in a similar range. F major is a half step higher, so wouldn't it be considered brighter? I think the biggest factor is that all keys are based on modifying C major, so most people will practice C major constantly and ingrain in their heads the natural notes. Thus when they play G major and raise the F up it feels brighter. Moreso when playing D major since its tonic is a whole step above C along with raising C itself.
It really depends on where you put the tonic in relation to the other notes and what range the tonic is played within. You can put your 4 voices on their lowest notes (like Eb2 on bass and Eb4 on soprano) but if you raise those up and octave it suddenly sounds much brighter. What makes A major feel brighter is that it's easily reachable on top of the treble staff while still sounding good to our ears (eg A5) while a note like Eb6 is quite shrill. It's a comfortable high. A is also a high note for a bass, since A below the bass clef is inccedible difficult to sing. For a bass singer Eb would be a quite bright key, while for a soprano it would be fairly mellow.
In short, timbre in different ranges is a big determining factor of brightness and the physical location of notes in comparison to that range shapes our expectations of its brightness.
Comment: C to F#/Gb is 180degrees. C to F is no different from C to G. True about C major - most seem to learn that first - even on guitar, where it's *not* the 'most natural' - in a couple of ways!
Comment: The lowest F note a bass singer can sing is a whole tone below the lowest G, so no, they aren't the same. While F to C is a fifth and C to G is also a fifth, but they aren't the same notes! I meant 180 degrees in that they are both the standard keys to which the 4 voices are based around. You're getting too caught up in theoreticals, my friend.
Comment: Regardless of anything else, I'm not convinced that any key will necessarily sound better or shriller, whatever. You mention key A major as feeling brighter, but what if the range of the song stops at E before that top A. It really won't matter what the song's key is - thja more important factor is the *range* of the song. You seem to assume in your answer that any key will use notes up to the root at the top, but it ain't necessarily so. Using that information, that's no basis for determining or even supposing that any key is 'brighter' than another. Tessitura or range may be.
Comment: And - one person's voice isn't like another's, so whatever high note that is sung may sound shrill with one voice, but not another. Key of piece can't be a factor in this case.
Answer: In equal temperament, the mode impacts the brightness or darkness of the music far more than the key, from lydian on the bright side (it's the cartoon mode, after all!) to phrygian on the dark side.
In addition to Tama's excellent answer above on timbres and how they affect brightness, it's also worth considering that before equal temperament, each key did in fact have a unique set of mathematical ratios between pitches. The major third C-E was different from the major third Ab-C or G-B. So, Bach's C major is not quite the same C major we have today. Equal temperament should render all keys equally bright or dark, save for the timbre issue.
Answer:
Many people experience keys with more sharps to be "brighter" and keys with more flats to be "darker," as this question discusses.

The accepted answer doesn't actually agree with the premise that a key with more sharps is brighter in and of itself - and while you may well be able to find a number of people who perceive things like that, I've not heard of any study that has found that any significant proportion of people do so (at least in an equal temperament context, which is normally what is assumed these days.)
Key signatures arrange themselves in a circle - so, for example, we can write a key signature that has the same actual pitches in (and the same octave-repeating pitches of tonic note) with 6 flats (G♭), or 6 sharps (F#). Could the very same piece, played on same set of note pitches, be simultaneously much brighter and much darker than itself? Simplistically speaking, no*.
Of course on a given instrument, there are many reasons why a given piece played in a different key may sound different - you'll have different resonances of the instrument (relative to the key), open strings and other 'unevenesses' in an instrument's topography will be in a different place(again, relatively), and we hear timbre differently at different pitches. But that shouldn't lead us to deduce that there's a general relationship between key signature and perceived level of brightness.
It's also possible that a given individual might perceive some keys as bright or dark relative to a key that they themselves are very familiar with (e.g. perhaps a pianist might see C major as neutral, and A major as brighter). But someone who has grown up with different pitch references would be expected to hear things differently; you wouldn't be able to deduce that people in general hear like our example pianist.

But does this quality of brightness/darkness also depend on the mode?

Again, simplistically speaking*, and for most people, I would say the perception of the feel of a piece only depends on the mode - and not on the given key signature, which is basically an accident of terminology that holds C major as special for historical, and not psychoacoustic, reasons.

*I say simplistically because mood of a piece is affected by timbre, timing, pitch inflections, intonation and temperament, and many other factors. And of course there are lots of other scales beyond the diatonic world of modes.
Comment: @jdjazz *"If we hear the difference immediately after a modulation, doesn't that imply that there's an underlying difference in brightness between the two keys?"* - well, it *could* do.  However, it couldn't plausibly mean that the rule is "keys with more sharps are brighter", because of the facts that A) key signatures go in a circle, so if you keep adding sharps, you get back where you came from - and B) C major is entirely arbitrary as a 'neutral' starting point.
Comment: I was referring to the original question (and the book it cites) more than the accepted answer. I'm not so sure that the accepted answer disagrees with the premise of my question. If we hear the difference immediately after a modulation, doesn't that imply that there's an underlying difference in brightness between the two keys, which the modulation calls attention to? When someone with good pitch memory hears an A# major scale, don't they immediately hear it as brighter because they make the same mental comparison that modulations force the rest of us to make?
Comment: The idea that a difference in brightness exists but only immediately after a song modulates seems like a problematic suggestion. It feels like the modulation proposition is saying that two scales are different *only when we compare them*, but they're not different when we're not comparing them. This doesn't make sense to me because I don't think the language surrounding "comparison" adds anything to the original proposition. The original idea is that some keys are innately brighter or darker [relative to each other].
Comment: The comparison is implied by the original idea, and the original idea only makes any sense in the context of comparison. Stating that a modulation is required to hear the comparison seems silly because some people have great pitch memory, perfect pitch, etc.
Comment: I completely agree that DbMaj doesn't sound brighter to anyone than C#Maj. But this fact doesn't bear on whether AMaj sounds brighter than EbMaj. The issue is finding the right way to describe the phenomenon so that our phrasing (a) includes the difference between AMaj and EbMaj and (b) excludes the identical-ness between DbMaj and C#Maj. I completely grant your point that saying "keys with more sharps are brighter" is imperfect, is shorthand, and might incorrectly imply that people hear DbMaj differently from C#Maj. (Also, I accidentally said "A#" in my first comment but meant to say "A.")
Comment: jdjazz: mind that we may be used to have Cmajor in the ear and then we compare not Amaj with Eb but each of them  with C.
Answer: You ask about the brightness/darkness of modes from a particular key - all using exactly the same notes, but not in the right order (Eric Morecombe-ish).
For starters, bright and dark are somewhat subjective terms in themselves, so it's a difficult question made harder. Taking the Ionian as the basic mode, as is recognised today as the basic major, would generally be accepted as the brightest, as it's the major, and the one we hear most every day. Familiarity is a safe feeling, thus brighter rather than darker. Followed by the Mixolydian and Lydian, both of which contain the major third interval based on the root note.
A lot of people, in my experience, associate dark with serious, sombre, sad, staid, (and probably other words that begin with s...) so, the 'minor' modes will come over in that fashion - giving Dorian, Phrygian and Aeolian.
That leaves Locrian - one of the most difficult to play in, or listen to, so maybe that's the darkest of all.
Given that equal temperament is now de rigeur, I can't see how anything else  factors in. Going back in time to earlier tuning systems, where an instrument such as harpsichord would be tuned to sound good in one key, I wonder if using modes from that key only would have the same darkness/brightness attributed to them. Somehow, I think nothing would be different. However, let's say that harpsichord is tuned to be good in D, then playing in D Dorian, D Phrygian, etc., would have a bigger difference, due to the tuning.
Or - have I missed the point entirely?


Minimum possible sum of weights of the heaviest and the $2^{nd}$ heaviest kid

Question: Question:

The average weight of any $2$ kids in a group of $6$ kids is a distinct natural number. The minimum weight of any kid is $11$ kg. Find the minimum possible sum of the weights of the heaviest and the $2^{nd}$ heaviest kid in the group.

Solution:

By hit and try we get the values as $11,13,15,19,25,35$ kgs.
As after taking $11,13,15$ we can't take $17$, so next take $19$ and so on.

Is there any other (better, that is, more logical) way to do this question (without hit and try)?
Because the hit and try approach is too time taking.
Comment: My first impression is that there is no efficient solution. Maybe, it is related somehow to the subsetsum problem.
Comment: The weights obviously all have the same parity, so they are all odd. That's about all you can get without trial and error.
Comment: @TheBestMagician yeah, figured that much, that's why went from 17 to 19 but inspite of it, it's time taking. I thought/expected a more... maybe insightful/procedural way to do it. Like if there's some series/pattern followed by such numbers or whether we may first jot down the natural numbers for various distinct averages and then work towards solution. Or none of the above but something completely different and wonderful.
Comment: OEIS search result for the given numbers [was this](https://oeis.org/search?q=11%2C13%2C15%2C19%2C25%2C35&language=english&go=Search). Though this is not it (the answer I'm looking for).
Answer: A relevant OEIS sequence is http://oeis.org/A080430.
"a(n) = least odd number such that all pairwise sums a(i) + a(j), i < j <= n, are distinct."
That sequence starts $1,3,5,9,15,25$, ... We can add $10$ to each value there to get values for the given problem here. Adding a constant to every term does not affect the uniqueness of the pairwise sums.
Beyond the $6$th term, that sequence does not give us the correct answer. By using only the next lowest possible number at each step we are only considering the lowest possible weight for the heaviest kid, but we want the lowest possible sum of weights for the two heaviest kids
$\{11, 13, 15, 19, 27, 37, 47\}$ is the best solution for $7$ kids.
$\{11, 13, 15, 19, 27, 39, 49, 59\}$ is the best solution for $8$ kids.
These were found using a brute force program.
Comment: Thank you for the answer. +1. Didn't see that there's optimization issue for the lowest possible sum of weights for 2 heaviest kids. Though still, this makes the question even more time consuming and complicated.
Answer: Partial Answer:
Start with $11,13,15$ obviously and let them belong to the set $S$ (arranged in ascending order). Then all we need to be concerned with is $3$ numbers: $S_1, S_{n-1}, S_n$ (where last 2 terms represent the last 2 elements from set $S$).
Then the next term to be included in the set $S$ is given by:
$$\bf S_{n+1}=S_n+S_{n-1}-S_1+2$$
So, the next term after $15$ is: $=15+13-11+2=19$
Similarly the next term is given by: $=19+15-11+2=25$
And finally the last term is given by: $=25+19-11+2=35$

The logic:
The term $S_{n+1}$ should be such:
$$\frac{S_n+S_{n-1}}{2}+1=\frac{S_{n+1}+S_1}{2}$$

If anybody's interested in knowing the $1^{st}$ $25$ such numbers, they are as follows:

 (Click to enlarge the image.)
Comment: Above is a "partial answer" as it is not "efficient" in a way that, as user @nickgard points out, it won't give the lowest possible sum of weights for the 2 heaviest kids.
Comment: Some similar sequences: [A080430](http://oeis.org/A080430); [A001595](https://oeis.org/A001595); [A005282](https://oeis.org/A005282)


htaccess 404 include page

Question: I know I can redirect to a 404 page with htaccess, but can I just include the custom 404 page I have into the URL that is causing the 404? For example, someone types in blahwat.php, which is not on the server, can I keep them on that page but instead of the apache 404 can I have it include my custom 404 page?
Answer: Using ErrorDocument does not redirect, so I don't know why you're bringing redirection up.
In any case, if there was a page at the URL then you wouldn't be getting a 404 in the first place.

htaccess 404 include page


Como capturar pacotes de uma conexão TCP usando um proxy?

Question: Estou escrevendo um Proxy TCP para capturar pacotes enviados do meu computador para um servidor remoto e vice-versa. Eu liguei um servidor falso de testes em localhost e o Proxy funciona bem, interceptando e direcionando os pacotes recebidos por um client, usando telnet, para o servidor de teste (no meu pc). O problema é que quando eu inicio o Proxy e conecto com o servidor remoto real, o Proxy não captura os pacotes dessa conexão. Como eu posso arrumar isso?
proxy.dart:
class Proxy {
  Proxy(String host, int port) {
    ServerSocket.bind(localhost, port).then((server) {
      print('Listening on $localhost:$port');
      server.listen((socket) async {
        print('Client connected to proxy');
        final clientConn = await Socket.connect(host /* localhost*/, port);

        final client2proxy = ClientToProxy(socket, clientConn);
        final proxy2server = ProxyToServer(clientConn, socket);
      });
    });
  }
}

client_to_proxy.dart:
class ClientToProxy {
  Socket socket;
  Socket remote;
  String address;
  int port;

  ClientToProxy(Socket sock, Socket rem) {
    socket = sock;
    remote = rem;
    address = socket.remoteAddress.address;
    port = socket.remotePort;
    msgPattern = '[client] ($address:$port) ->';

    socket.listen(onDataHandler,
        onError: onErrorHandler, onDone: onDoneHandler);
  }

  void onDataHandler(List<int> data) {
    if (debug) print('$msgPattern Data: ${String.fromCharCodes(data)}');
    pipeSocket(remote, data);
  }

  void pipeSocket(Socket sock, dynamic data) => sock.add(data);
}

proxy_to_server.dart:
class ProxyToServer {
  Socket socket;
  Socket remote;
  String address;
  int port;

  ProxyToServer(Socket sock, Socket rem) {
    socket = sock;
    remote = rem;
    address = socket.remoteAddress.address;
    port = socket.remotePort;
    msgPattern = '[server] ($address:$port) ->';

    socket.listen(onDataHandler,
        onError: onErrorHandler, onDone: onDoneHandler);
  }

  void onDataHandler(List<int> data) {
    if (debug) print('$msgPattern Data: ${String.fromCharCodes(data)}');
    pipeSocket(remote, data);
  }

  void pipeSocket(Socket sock, dynamic data) => sock.add(data);
}

Como eu deveria interceptar esses pacotes?
Comment: não conheço Dart, mas me parece que nesta linha "final clientConn = await Socket.connect(host /* localhost*/, port);" você precisa passar o ip do servidor remoto, onde está "/*localhost*/"
Comment: Na verdade eu já passo o IP do servidor remoto em "host", no caso o "localhost" está comentado.
Comment: verdade...será que não tem um firewalll em sua máquina ou na máquina remota bloqueando conexões ?
Comment: Acredito que não, acho que se bloqueasse a conexão, o socket lançaria uma exceção e terminaria a execução do programa. Talvez eu esteja esquecendo de alguma coisa relacionada ao protocolo TCP?
Answer: Você está fazendo o bind apenas na interface localhost, tem que fazer o bind em todas as interfaces. Para isso usa-se o endereço ip 0.0.0.0.
class Proxy {
  Proxy(String host, int port) {
    // ServerSocket.bind(localhost, port).then((server) { // <-----------------
    ServerSocket.bind("0.0.0.0", port).then((server) {
      print('Listening on $localhost:$port');
      server.listen((socket) async {
        print('Client connected to proxy');
        final clientConn = await Socket.connect(host /* localhost*/, port);

        final client2proxy = ClientToProxy(socket, clientConn);
        final proxy2server = ProxyToServer(clientConn, socket);
      });
    });
  }
}

Obs. não testado, mas se houver erro provavelmente será na sintaxe do Dart.
Comment: Eu não mostrei no código, mas a variável ```localhost``` é definida como: ```final localhost = InternetAddress.anyIPv4.address; //isso retorna '0.0.0.0'```, o que já escuta conexões em todas as interfaces: ```Listening on 0.0.0.0:30009```
Comment: hmm...ok...mas vou deixar a resposta assim mesmo, por ser informativa
Comment: faça um teste com telnet da máquina client para seu programa rodando na máquina server...isso vai dirimir a dúvida se é o seu ambiente (no client ou mais provavelmente no server) que está barrando a conexão
Comment: ```Listening on 0.0.0.0:30000

Client connected to proxy

[client] (127.0.0.1:58930) -> Data: teste

[server] (220.127.116.11:30000) -> Disconnected / shut down
```

Tá meio difiicil de ler pelo comentário, mas basicamente: o socket do cliente (telnet) foi capturado no proxy, mas o servidor rejeita.
Comment: tá com jeito de ser firewall na máquina onde você roda o server (ou algum firewall intermediário, se for uma empresa)
Comment: faça um teste direto da máquina client para a máquina remota server, sem passar pelo proxy...se funcionar, então o erro é no proxy...se não funcionar, então o erro *não* é no proxy
Comment: Obrigado pela ajuda, o que faltava era redirecionar o host para o meu proxy no arquivo ```/etc/hosts``` do Linux.


How do I make smoother rotation for my objects in my game?

Question: I am making a game where insects from the top of the screen come down. The object of the game is to kill these insects. I have made a code for these insects on how they move, but what seems to be the problem is that they seem to rotate in a non smooth pattern. They twitch!
This is the code:
 else // Enemy is still alive and moving across the screen
    {
        //rotate the enemy between 10-5 degrees
        tempEnemy.rotation += (Math.round(Math.random()*10-5));
        //Find the rotation and move the x position that direction
        tempEnemy.x -=  (Math.sin((Math.PI/180)*tempEnemy.rotation))*tempEnemy.speed;
        tempEnemy.y +=  (Math.cos((Math.PI/180)*tempEnemy.rotation))*tempEnemy.speed;
        if (tempEnemy.x < 0)
        {
            tempEnemy.x = 0;
        }
        if (tempEnemy.x > stage.stageWidth)
        {
            tempEnemy.x = stage.stageWidth;
        }
        if (tempEnemy.y > stage.stageHeight)
        {
            removeEnemy(i);

            lives--;
            roachLevel.lives_txt.text = String(lives);
        }
    }
}

}
Another problem that I am experiencing is that some of the insects are going along the edge of the screen. The user can barely kill them because half of their bodies are on the screen, and the other half are off. Can I make them move a bit away from the edge, like an offset? Thank you!
Comment: Are you doing this on every frame?
Comment: I am doing this on each object in the array. There is no animation, all of it is powered by action script
Comment: Animation can also happen by actionscript, if you change something (x,y,rotation) at every frame. You are mistaken to think animation only happens when using keyframes and such in the timeline. Here's a great book dedicated only to animating things by code in AS3. http://www.amazon.com/Foundation-Actionscript-3-0-Animation-Making/dp/1590597915
Answer: From your code, it looks like they are twitching because you're changing the rotation by a large amount right away:
tempEnemy.rotation += (Math.round(Math.random()*10-5));

Instead you should interpolate/animate to your desired rotation instead of just jumping right to it. There are a few ways to do this, but not sure how your animation is set up.
To keep insects from going right to the screen edges you could put in an offset and limit the x/y positions.
Such as going:
var offset:int = 100; // limits the max x to be 100 pixels from the right edge of the stage

if (tempEnemy.x > (stage.stageWidth - offset)){
    tempEnemy.x = stage.stageWidth - offset;
}

Comment: I'd suggest using a different method to produce smooth random behaviour. A bit more complex, but maybe take a look flocking algorithms (namely the steering/wandering part).
Comment: The only animation I have is the insect's legs moving. Rotation and movement is powered by actionscript. I don't want a big rotation, just some rotation where the insect can change direction when it's moving downwards. The rotation and movement should all be random as well
Comment: I'll take a guess and assume your above code is being run every frame. Applying a small bit of random rotation directly every frame is going to result in twitchy behaviour just by its nature. You can see this exactly if you plotted out the values of: Math.round(Math.random()*10-5); You'll see a series of random jumps resulting in a jagged line as opposed to the smooth motion you want.
Comment: Is there a way to give each insect a random define pathway? Like one insect will zip from one point, to another point. Then a different insect in the array may go straight down?
Comment: Sure, that can be doable. You could implement this in a variety of ways. One method that comes to mind is just generate some random waypoints for each insect when spawned and have the insect move/steer towards them (part of this can actually be found in a flocking algorithm, which is why I suggested it).


Does weak* convergence together with convergence of norms implies strong convergence in l1 as dual of c0?

Question: Let $x^{*}_{n}$ is weak$^*$ convergent to $x^*$ in weak$^*$ topology on $l_{1}$ induced by $c_{0}$ and $\|x^{*}_{n}\|\rightarrow \|x^{*}\|.$ It is true that then we have $\|x^{*}_{n}-x^{*}\|\rightarrow 0$?
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Answer: The answer is yes.  In order to prove it, let me make a change in your notation, denoting the given sequence  by
$\{x^n\}_n$, the limit by $x$, where each $x^n = (x^n_i)_i$, and  $x = (x_i)_i$.
Given  $\varepsilon >0$, choose an integer $p>0$ such that
$$
  \sum_{i=p+1}^\infty  |x_i| <\varepsilon ,
  $$
and observe that, for every $n$
$$
  \sum_{i=p+1}^\infty  |x^n_i| =   \|x^n\| - \sum_{i=1}^p |x^n_i|
  \ \buildrel n\to \infty  \over {\longrightarrow} \
  \|x\| - \sum_{i=1}^p |x_i| =   \sum_{i=p+1}^\infty  |x_i| <\varepsilon ,
  $$
so there is an $n_0$ such that
$$
  \sum_{i=p+1}^\infty  |x^n_i| <\varepsilon ,
  $$
for all $n\geq n_0$.  By increasing $n_0$ we may assume that also
$$
  \sum_{i=1}^p |x_i-x^n_i|<\varepsilon .
  $$
For $n\geq n_0$,   we than have that,
$$
  \|x-x^n\| =
  \sum_{i=1}^\infty  |x_i-x^n_i| = $$$$ =
  \sum_{i=1}^p |x_i-x^n_i| +   \sum_{i=p+1}^\infty  |x_i-x^n_i| \leq  $$$$ \leq
  \sum_{i=1}^p |x_i-x^n_i| +   \sum_{i=p+1}^\infty  |x_i| +   \sum_{i=1}^p |x^n_i|  < 3\varepsilon ,
  $$
so   $\|x-x^n\| \to  0$, as desired.


Series of the form $|L - S_N|$

Question: I'm interested in series of the form $\lim_{n\to\infty}$$\sum_{N=1}^n |L-S_N|$ where $\lim_{N\to\infty}S_N = \lim_{N\to\infty}\sum_{k=1}^N a_k = L $ and L is not equal to $0$.
I've tried everything at hand to determine whether or not it always converges.
By way of D'Alembert's test I arrive at $$\lim_{N\to\infty}\frac{|L-S_{N+1}|}{|L-S_N|}$$ then making use of the fact that $S_{N+1}=S_N+a_{N+1}$, I get $$\lim_{N\to\infty}|\frac{L-S_N-a_{N+1}}{L-S_N}|$$ $$\lim_{N\to\infty}|1-\frac {a_{N+1}}{L-S_N}|$$ It is the case that $0<S_N<S_{N+1}<L$ then $0<S_{N+1}-S_N<L-S_N$ therefore $0<\frac {a_{N+1}}{L-S_N}<1$ Applying the limit operator on both sides of the inequality $0\leq\lim_{N\to\infty} \frac {a_{N+1}}{L-S_N}\leq 1$ So if the general term divided by the difference between the series and the limit is bigger than $0$ the series will converge, otherwise I don't know.
Another way of writting it down would be: $$\lim_{N\to\infty}|1-\frac {a_{N+1}}{a_{N+1} + \sum_{k=N+2}^\infty a_k}|$$ The further the series go, the closer $a_{N+1}$ and $\sum_{k=N+2}^\infty a_k$ they get. Maybe it's $0.5$
Comment: You mean $a_{N+1}$ not $a_k$
Comment: Yes. My bad. I'm correcting it.
Answer: I don't know  a general result. Here there are some thoughts.
If $a_n>0$ for all $n\geq 1$ then $S_N$ is increasing and
$$\sum_{N=1}^{\infty} |L-S_N|=\sum_{N=1}^{\infty} \sum_{k=N+1}^{\infty}a_k=a_2+2a_3+3a_4+\dots=\sum_{k=1}^{\infty}ka_{k+1}.$$
So, for example, if $a_k=1/k^a$, your series is convergent if and only if $a>2$.
This is an example where the sign of $a_k$ is alternating. Let
$$S_N=\sum_{k=1}^{N}\frac{(-1)^{k+1}}{k}\to \ln(2)$$
then
$$\sum_{N=1}^{2n} |L-S_N|=\sum_{N=1}^{2n}\sum_{k=N+1}^{\infty}\frac{(-1)^{k+N+1}}{k}=\frac{1}{2}\sum_{k=1}^n\frac{1}{k}\to +\infty$$
and your series is divergent.

Series of the form $|L - S_N|$


Homotopic maps which aren't relative homotopic

Question:
Can anyone give an example of two continuous maps, let say $f,g \colon X \to Y$, such that the set $A =\{ x \in X \mid f(x) = g(x) \}$ is not empty, the two maps are homotopic but there's no homotopy between these function relative to any non empty subspace of $A$?
Comment: Did you mean "relative to every non empty subspace of $A$"?
Comment: @OlivierBégassat I've slightly changed the question, I hope now the question is more clear.
Comment: @LVK No I mean $X$, but if you want you can consider $A$ to be the set $\{x \in X \mid f(x) = g(x)\}$.
Comment: I don't understand the question as it stands. Could you please clarify what you want? I gather $f$ and $g$ should be freely homotopic, agree on some non-empty subset, but I don't understand what follows.
Comment: If $f,g$ are homotopic, they are also homotopic relative to $\emptyset$. I assume you want $f,g$ homotopic, $A$ not empty and for all $p\in A$, $f,g$ are *not* homotopic relative to $\{p\}$?
Answer: Let $X = S^1$, let $p \in S^1$, and let $Y = S^1 \times [0;1]$ with $(p,0)$ and $(p,1)$ identified.
Then let $f(x) = (x,0)$ and $g(x) = (x,1)$. Clearly, $h(x,t) = (x,t)$ is an homotopy from $f$ to $g$, but there is no homotopy relative to $p$.
Suppose $h : S^1 \times [0;1] \to Y$ is an homotopy from $f$ to $g$ such that $h(p,t) = (p,0)$ forall $t$.
Let $q$ be a point of $S^1$ distinct from $p$, and $A$ be the arc-connected component of $(q,0)$ in $(S^1 \times [0;1]) \setminus h^{-1}(\{(p,0)\})$ (this set contains $(q,0)$ because $h(q,0) = f(q) = (q,0) \neq (p,0)$) and define $\tilde h : S^1 \times [0;1] \to Y$ by $\tilde h(x,t) = h(x,t)$ for $(x,t) \in A$, and $\tilde h(x,t) = (p,0)$ for $(x,t) \notin A$.
$\tilde h$ is still continuous : The arc-connected components of an open set are all open, so if $h(x,t) \neq (p,0)$, there is an open neighbourhood of $(x,t)$ in its arc-connected component, and in both cases (wether it is the one of $(q,0)$ or not), $\tilde h$ is continuous there.
If $h(x,t) = (p,0)$, since $h$ is continuous, for every neighbourhood $U$ of $(p,0)$ there is a neighbourhood $V$ of $(p,0)$ such that $h(V) \subset U$. Since $\tilde h(V) \subset h(V) \cup \{(p,0)\} = h(V) \subset U$, that same neighbourhood works to show $\tilde h$ is continuous at $(x,t)$.
If $(q,1) \notin A$, then $(x,1) \notin A$ forall $x \in S^1$, so $\tilde h$ is an homotopy between $f$ and the constant map $(p,0)$, which is impossible because $f$ does one loop around the cylinder and the constant map doesn't.
Thus $(q,1) \in A$. We have a path $\gamma : [0;1] \to S^1 \times [0;1] = (\gamma_1,\gamma_2)$ such that $\gamma(0) = (q,0), \gamma(1) = (q,1)$, and $h \circ \gamma$ doesn't touch $(p,0)$. In particular, $\gamma$ doesn't touch any $(p,t)$, so its first coordinate, $\gamma_1$, has values in $S^1 \setminus \{p\}$.
If we further identify $S^1 \times \{0\}$ with $S^1 \times \{1\}$ (in $Y$) to get a torus, $h \circ \gamma$ is a loop from $(q,0)$ to $(q,1)$, which loops exactly once around the second coordinate. But in fact, it is also a loop homotopic to the null loop :
Pick a continuous map $\kappa : (S^1 \setminus \{p\}) \times [0;1] \to S^1$ such that $\kappa(x,0) = x$ and $\kappa(x,1) = p$ forall $x$, and define $\theta : [0,1] \times [0,1]$ by $\theta(t,s) = h(\kappa(\gamma_1(t),s),\gamma_2(t))$. It is a loop homotopy between $h \circ \gamma$ and $p$ :
$\theta(0,s) = h(\kappa(q,s),0) = f(\kappa(q,s)) = (\kappa(q,s),0)$, which is identified to
$\theta(1,s) = h(\kappa(q,s),1) = g(\kappa(q,s)) = (\kappa(q,s),1)$.
$\theta(t,0) = h(\kappa(\gamma_1(t),0),\gamma_2(t)) = h(\gamma_1(t),\gamma_2(t)) = h \circ \gamma(t)$
$\theta(t,1) = h(\kappa(\gamma_1(t),1),\gamma_2(t)) = h(p,\gamma_2(t)) = (p,0)$
This is impossible too, so there can be no such $h$.
Comment: Sadly in this case the set $\{x \in X| f(x) = g(x)\}$ is empty, so this doesn't answer the question.
Comment: $(p,0)$ and $(p,1)$ are identified in $Y$ so $A=\{p\}$.
Comment: My bad, so now the two maps are maps from $S^1$ to the torus and are the same map, am I correct? (in this case, I suppose that the two maps are homotopic relatively to the whole space........)
Comment: No, $p$ is only one point of the circle, $Y$ is not the torus, it's a cylinder where the end circles are glued at one point. I think I could have picked a torus minus one point for $Y$, maybe it would have been clearer
Comment: Ah, ok thanks now I get it, could you add the details of the non existence of the relative homotopy, so I can accept the answer?
Comment: @GerryMyerson you're right, I apologize, but I think I've started to make up for that. :)
Comment: @mercio I apologize to continue to bore you but I guess there are some typos could you fix it, please?
Comment: @ineff : it's hard to spot the typos when you write something. What exactly is wrong or unclear ?
Comment: @mercio you're right sorry, here're the problems. in the second paragraph there's a homotopy $\bar h$ which is defined as $\bar h(x) = \dots$ instead of something like $\bar h(x,t) = \dots$, and it's also not clear (at least to me) why this map should be continuous, it doesn't seem to me that we can apply the gluing lemma.
Comment: Ok,now I get it thanks @mercio .
Answer: Actually I recently come back to this problem and I've found myself another counterexample.
Consider the space
$$X= \{ (x,y) \in \mathbb R^2| (x \ne 0 \land y/x \in \mathbb Q) \lor x=0\}$$
this is the space formed by the straight lines with rational slope.
This space can be deformation retracted on the point $(0,0)$, I'm going to call $p \colon X \to X$ the constant map sending $X$ in this point, and so the identity is relative homotopic to $p$.
The point $(0,0)$ is the only point to which the whole space can deformation retract.
Clearly every other constant map is homotopic to this map, so every other constant map is homotopic to the identity.
Any constant map have a unique fixed point, which clearly is fixed by the identity too. The identity cannot be homotopy equivalent to any constant map
relatively to the fixed point, with the exception of $p$, because otherwise the relative homotopy would be a deformation retraction of $X$ on this other point, which is not possible for said above.


Como fazer um campo data contendo apenas Mês e Ano Html

Question: Necessito de um campo data contendo apenas Mês e Ano Html de preferencia que habilite na tela algo parecido com um calendário contendo apenas os meses e anos.
obs: Estou usando angularJs, javascript
Answer: Com HTML5 pode usar o type="month"

<input type="month">

Suportado pelos navegadores:

Chrome 20+
Edge 12
Opera 10.62+
Answer: Cria um select COm o mês eos anos.

   <select>
      <option>01</option>
      <option>02</option>
      <option>03</option>
      <option>04</option>
      <option>05</option>
      <option>06</option>
      <option>07</option>
      <option>08</option>
      <option>09</option>
      <option>10</option>
      <option>11</option>
      <option>12</option>
   </select>

   <select>
      <option>1990</option>
      <option>1991</option>
      <option>1992</option>
      <option>1993</option>
      <option>1994</option>
      <option>1995>/option>
      <option>1996</option>
      <option>1997</option>
      <option>1998</option>
      <option>1999</option>
      <option>2000</option>
      <option>2001</option>
   </select>


Como pegar um valor entre colchete na string?

Question: Tenho uma string que vai variar os valores, preciso pegar os valores dentro do [],
{"time_zones":[]}

No caso estaria vazia, ela poderá vir preenchida:
{"time_zones":[teste]}

Estou tentando fazer assim
 var palavras = a.Split('[');
 var palavra = palavras[1];

Porém ele me retorna o resto do código: ]}
No caso se não tivesse nada, o valor era vazio, caso fosse preenchido eu precisava do teste. (esse valor varia);
Comment: Você pode fazer assim... mas se a sua string é um deseralizável como parece, existem outras abordagens para isso
Comment: trata como json que é melhor....
Comment: Definitivamente o [comentário do @RovannLinhalis é a linha a seguir](https://pt.stackoverflow.com/questions/306818/como-pegar-um-valor-entre-colchete-na-string#comment622636_306818). Isso é um json, tratá-lo como tal vai facilitar a vida. Não vale a pena mirabolar uma solução desse tipo, a manutenção vai cobrar caro.
Comment: Tratando como string ou Json?
Comment: Uma hora vai chegar um `{"time_zones":[teste, teste2]}` para bagunçar o meio de campo (=C
Comment: Conseguir resolver @LeandroAngelo, obrigado.
Comment: String, fiz dessa forma   string[] split = a.Split(new char[] { '[', ']' });
            MessageBox.Show(split[1]);
Comment: Aceitaria um Regex? você está tentando pegar a palavra teste?
Comment: Sim eu preciso pegar a palavra teste, porém nem sempre vai ter esta palavra, inclusive pode conter outros caracteres, e várias palavras.
Comment: @marianac_costa adicionei regex a sua pergunta, você disse que poderia ser :)
Answer: Você pode fazer isso com o REGEX "\[(.*)\]"

\[ Escape é  necessário para ser tratado como texto e não como um conjunto.
.* Procure por nenhuma ou várias ocorrências.
No C# pegue o primeiro Grupo, será onde está a palavra teste(demonstrada no segundo exemplo) ou qualquer coisa que esteja entre os colchetes.

Funcionando em dotnetfiddle
 using System;
    using static System.Console;
    using System.Text.RegularExpressions;
        public class Program {
            public static void Main() {
                string texto = "{\"time_zones\":[teste]}";
                Regex rgx = new Regex(@"\[(.*)\]");
                Console.Write(rgx.Match(texto).Groups[1]);
            }
        }

Answer: Dentro de um método do controller, faz
public string GetMinhaString()
{
    string tuaString = @"{ ""time_zones"": [ ""teste"", ""zero"", ""um"" ] }";

    var o = JsonConvert.DeserializeObject<MeuObjeto>(tuaString);

    return string.Join("-", o.time_zones) + ", total de " + o.time_zones.Length ;
}

e declara uma classe privada, dentro do controller, da seguinte forma,
private class MeuObjeto
{
    public string[] time_zones { get; set; }
}

Dessa forma, vais obter a informação que precisa e tipada de acordo com o JSON fornecido.
Comment: Já sei que a @marianac_costa está a usar ASP.NET Core


Query Different Condition With 1 Column

Question: I have table like :
+-------+--------+----------+------------+-------+
| cd_hs | cd_cnt | name_cnt |   dates    | value |
+-------+--------+----------+------------+-------+
|     1 |      1 | aaa      | 2018-06-01 |    50 |
|     1 |      2 | bbb      | 2018-07-01 |   150 |
|     1 |      3 | ccc      | 2018-08-01 |    20 |
|     1 |      1 | aaa      | 2018-06-02 |    40 |
|     1 |      2 | bbb      | 2018-07-02 |    70 |
|     1 |      3 | ccc      | 2018-08-02 |    80 |
+-------+--------+----------+------------+-------+

Actually I have more data but I am just show the sample and what I want to do is
I want to group by cd_hs, name_cnt and based on year in dates column and do sum(value) but I have the 2 condition. First is to show value with condition cd_cnt with 1 and 2 and second condition cd_cnt without 1 and 2 so meaning I have much value other than 1 and 2 and do aliasing as other in one column
Expected Result :
+-------+------+----------+-------------+
| cd_hs | year | name_cnt | total_value |
+-------+------+----------+-------------+
|     1 | 2018 | aaa      |          90 |
|     1 | 2018 | bbb      |         220 |
|     1 | 2018 | other    |         100 |
+-------+------+----------+-------------+

how can I do that? I am new in query and don't know what to do..
Answer: Your question is a bit confusing considering your spec doesn't seem to exactly line up with what you requested.
If the sample result you've provided is actually what you're looking for, a simple SUM and GROUP BY should do the trick here:
SELECT cd_hs, EXTRACT(YEAR from dates) as year, name_cnt, SUM(value_)
FROM foo
GROUP BY cd_hs, EXTRACT(YEAR from dates), name_cnt

Result:
| cd_hs | year | name_cnt | sum |
|-------|------|----------|-----|
|     1 | 2018 |      aaa |  90 |
|     1 | 2018 |      bbb | 220 |
|     1 | 2018 |      ccc | 100 |

SQLFiddle

Since you mentioned you wanted two different totals with two separate conditions, you could use JOIN in conjunction with some well-crafted subqueries:
SELECT a.cd_hs, EXTRACT(YEAR FROM a.dates), a.name_cnt, COALESCE(b.total_a, 0) as "Total A", COALESCE(c.total_b, 0) as "Total B"
FROM foo a
LEFT JOIN (
  SELECT b.cd_hs, b.name_cnt, EXTRACT(YEAR FROM b.dates), SUM(value_) as total_a
  FROM foo b
  WHERE b.cd_cnt NOT IN (1, 2)
  GROUP BY b.cd_hs, b.name_cnt, EXTRACT(YEAR from b.dates)
) b ON a.cd_hs = b.cd_hs AND a.name_cnt = b.name_cnt
LEFT JOIN (
  SELECT c.cd_hs, c.name_cnt, EXTRACT(YEAR FROM c.dates), SUM(value_) as total_b
  FROM foo c
  WHERE c.cd_cnt IN (1, 2)
  GROUP BY c.cd_hs, c.name_cnt, EXTRACT(YEAR from c.dates)
) c ON a.cd_hs = c.cd_hs AND a.name_cnt = c.name_cnt

This particular solution is readable and will get you to the correct end result but will most likely not be scalable in its current form.
Result:
| cd_hs | date_part | name_cnt | Total A | Total B |
|-------|-----------|----------|---------|---------|
|     1 |      2018 |      aaa |       0 |      90 |
|     1 |      2018 |      bbb |       0 |     220 |
|     1 |      2018 |      ccc |     100 |       0 |
|     1 |      2018 |      aaa |       0 |      90 |
|     1 |      2018 |      bbb |       0 |     220 |
|     1 |      2018 |      ccc |     100 |       0 |

SQLFiddle

Query Different Condition With 1 Column


Abrir página nova e dar scroll ate a ancora da página

Question: Tenho um problema que quando abro um link que direciona para uma ancora de outra página e fica escondido pelo header fixer.
Tenho um menu na minha página:
Dentro da Index.html tenho esse menu
Produto 1
Produto 2
Produto 3

Contudo, ao clicar e abrir, as ancoras ficam escondidas, pois tenho um header com position:fixed.
http://jsfiddle.net/thallysondias/q4hp3euv/
Jsfiddle -mostrando como a div fica escondida
Como faço para poder, ao clicar para abrir, automaticamente fazer um scroll de 100px para baixo?
Minha página é essa:
http://www.omnibees.com/novo3/clientes.html#case-studies
Se utilizar o os menus superiores para querer abrir uma nova pagina em determinada seção, vera q o titutlo da seção fica escondido.
Answer: Se o link âncora não está resolvendo, você pode tentar usar uma função para verificar qual parâmetro chega pela url e fazer um scroll até o local desejado.
if (param === "#produto1") {
  window.scrollTo(element)
}

Comment: a ancora funciona, meu problema é que eu preciso dar um scroll para baixo, para o conteudo nao ficar escondido pelo menu
Answer: Encontrei a solução:
/**
 * Check a href for an anchor. If exists, and in document, scroll to it.
 * If href argument ommited, assumes context (this) is HTML Element,
 * which will be the case when invoked by jQuery after an event
 */
function scroll_if_anchor(href) {
    href = typeof(href) == "string" ? href : $(this).attr("href");

    // You could easily calculate this dynamically if you prefer
    var fromTop = 180;

    // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
    // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
    if(href.indexOf("#") == 0) {
        var $target = $(href);

        // Older browser without pushState might flicker here, as they momentarily
        // jump to the wrong position (IE < 10)
        if($target.length) {
            $('html, body').animate({ scrollTop: $target.offset().top - fromTop } ,1000, 'easeOutSine');
            if(history && "pushState" in history) {
                history.pushState({}, document.title, window.location.pathname + href);
                return false;
            }
        }
    }
}

// When our page loads, check to see if it contains and anchor
scroll_if_anchor(window.location.hash);

// Intercept all anchor clicks
$("body").on("click", "a", scroll_if_anchor);

Foi a unica forma q encontrei de garantir que sempre o scroll ocorre.


Panel + views + taxonomy depth problem

Question: following this tutorial I create a Panel Page for the taxonomy term to display all the content related to the taxonomy term and it works.
But I need to have in all the nodes related to the taxonomy terms in the url and children.
So I sobstitute taxonomy term ID contex filter with taxonomy term ID (with depth) and do not work anymore -.-
This is the contex filter's setting
If I try this view block in view page [putting 'taxonomy-name' as argument] it works but not in the panel page.
Where is my mistake?
I don't know if this can help. This is the contex of panel page [I setup the view to take argument from URL.. but maybe it can help]
Answer: You should try to add a "Content pane" display on the view instead of using a page display (enable "Views content panes" module). "Content pane" allows to set the argument input from the views settings. On the "argument input" you can select "From context" as source, and the required term context.
EDIT: Like I've wrote on the following comments, the correct contextual filter settings is:
1) Content: Has taxonomy term ID (with depth). Provide a default value: Taxonomy term ID from URL (Load default filter from term page). Specify validation criteria: Taxonomy term, Filter value type: Term ID
2) Content: Has taxonomy term ID depth modifier
Comment: The configuration of the first contextual filter should be something like: Provide a default value: Taxonomy term ID from URL (Load default filter from term page). Specify validation criteria: Taxonomy term, Filter value type: Term ID
Comment: I already tried this solution but do not work too. I do not understand why if with "Has taxonomy term ID" context filter work and with depth do not work..
Comment: Recently I've used Views + Taxonomy Display instead of views + Panels module. With Taxonomy Display you can select a views block and substitute the default term display, maybe this module could help you too.

If you want display all nodes with the current term and all children nodes (on every depth starting from the selected term), you have to use two contextual filters:
1) Content: Has taxonomy term ID (with depth).
2) Content: Has taxonomy term ID depth modifier.
Comment: Thank you form help!

I changed the validation criteria from "Term name converted to Term ID" to "Term ID" and now it works ^^

Panel + views + taxonomy depth problem


Expected prediction error - classification

Question: I am trying to solve the equation 2.19 to 2.20, but I'm struggling to find the end of the problem.
$ \sum [L(G,\hat{G}(X)]p(G,\hat{G}(X))$
$ \sum_k \sum_X [L(G,\hat{G}(X)]p(G)p(\hat{G}(X)|G)$
And then I cannot find the same equation if I try to replace by expected value
Answer: Your first expression should be a double sum over all possible values of $X$ and $G$. And the weights should be $Pr(G,X)$. They tell you to use this in the second to last sentence.
For your second sum you should try factoring the joint as  $Pr(G,X) = Pr(G|X)Pr(X).$ It might help to rewrite 2.20 as
$$
\sum_x \left\{\sum_{k=1}^K L[\mathcal{G}_k, \hat{G}(x)]Pr(\mathcal{G}_k|x)\right\}Pr(x),
$$
if $X$ is discrete or
$$
\int \left\{\sum_{k=1}^K L[\mathcal{G}_k, \hat{G}(X)]Pr(\mathcal{G}_k|X)\right\}f(x)dx,
$$
if $X$ is continuous.


No Eulerian walk in a graph, and how to fix it

Question:
Explain why a simple graph $G=(V,E)$ has no Eulerian walk, where the vertices are $V =\{a,b,c,d,e,f\}$ and the edges are $E=\{ab,ae,af,be,cd,ce,cf,df\}$.
Show that it is possible to add one edge to $G$ to obtain a simple graph still, that does have an Eulerian walk, and find such a walk. There may be more than one way to do this; identify all ways to add the edge.

When working out this question, I found out that vertices $a,c,e$ and $f$ have odd degrees of 3. But a graph cannot have more than 2 vertices of odd degree to have a Eulerian path, so $G$ doesn't have an Eulerian path.
That is all that I have come up with and I am not sure how to approach the second question.
Answer: When approaching graph theory problems dealing with a specific graph, drawing always helps:

Since you have already shown that no Eulerian walk exists in the graph, I will concentrate on how to add an edge to this graph so that it does have an Eulerian walk.
Adding one edge to the graph flips the parities of the vertices it connects – odd to even, even to odd. We have four odd vertices and we need two, so we should add an edge between two vertices of odd degree; those vertices are $a,c,e,f$ and have a black spot in my drawing, so we would have six edges to choose from. However, to keep the graph simple we cannot add an edge between two vertices that are already connected by an edge; this whittles down the possible edges to $ac$ and $ef$.
Here are possible Eulerian paths for both augmented graphs.
 $+ac:$ fcdfaceabe
 $+ef:$ afeabecdfc
Comment: Thank you so much that makes so much sense. I was making the question more complicated in my head. :)
Comment: @user376279 Note that you can mark my answer as accepted (to show that you found it useful; you're new so I thought it would be good to explain this). There's a tick beside my answer you can click.


Separate tables for 1-1 relationship

Question: I'm creating an Access database to hold student internship information. The issue I'm having is I have three tables that have a one and only one relationship with the internship table (Assignment, Supervisor Evaluation, and Student Evaluation).
Since Access doesn't allow a table to have more than one auto generated number, I can't let the internship table create the ID number for each of the three tables. So, I'm not sure how to make it so when we enter data into these tables forms, I can assign it specifically to an internship. Any advice?
Answer: 1-1 relationships always smell like they should be merged into one table. This is particularly so if they are actually 1-1 and shouldn't be 1-0,1. In the latter case, if the dependent information can be missing and will be missing in a majority of cases, it might be helpful to separate it away into a table of its own. But even this can be expressed by giving null values to certain attributes.
Now if, for some reason, you insist on those 4 tables, there are two ways to go for the primary keys. One is, for the dependent tables, not to declare the primary key as auto-generated, but just as a number, and to assign to it the autogenerated value of the Internship record. Another is to auto-generate a primary key for each of the dependent tables, and have a foreign key in the Intership table for each of them. As I consider the entire construct of those dependent tables as unnecessarily complicated, I can't give a recommendation on which of these ways to prefer.
There is another concern I have about your data model. Your tables have those attributes like answer1, answer2, ... Now if you have a small fixed amount of those attributes, this might be okay. But could you have a larger set of fixed questions, maybe for each type of internship, that might vary dynamically and can't just be expressed by a fixed column structure? In that case you would need something like
Question(id, text)
Internship(id, ...)
Answer(id, internship_id, question_id, student_answer, supervisor_evaluation)

So your cardinalities would be
Internship 1-----0,n Answer 0,n------1 Question

Same for the other details of the internship.
Comment: I honestly don't mind merging them into one table but isn't there some sort of databse "rule" that having such a large table is bad?
Comment: The questions are all static. They've been the same for over 5 years. However, I agree with you, I think there is a better way than what I've done.

My solution I have thought of is making the assignmentId the same as the internshipId but without connecting them. I'll just use a combo box to select the internship and it will input the ID into the assignmentId.

Separate tables for 1-1 relationship


Can a Domain Admin login to domain machines using its username, but locally?

Question: My question is as follows:
If Domain Admins are members of every local Administrators group, isn't that mean that a domain admin user - let's say "test", can login via (let's say RDP) to a domain machine locally, by typing for example - "dom_machine\test"?
Also, why wouldn't you see by running net user on a domain machine all domain admins as well?
I don't have a test environment to check it so I'll be happy to know.
Thanks!
Answer: Tl;dr:
No, it doesn't work like that. You seem to have mixed up a few things! ;)
Longer version:
There is a difference between having the rights to do something on a domain computer and having the user created locally on that machine.
What happens when you log in normally is that the domain joined computer asks the domain controller if the user exists in this domain. And if you change the domain part to the name of the local computer. It will not ask the domain controller any more, it will instead ask the local computer if the user exists. And if you don't have the same user created on that machine. It will not let you in. So this is only a question of where you have created the user.
The reason why you want to have the user created on the domain controller is that it is easier to manage there, than if you had to create the user separately on each machine. Because every time you need to change anything on that user, like the password, you would have to go around to every machine and change it there too.
What happens when you try to do something as a domain user is that the computer asks the domain controller (Or the local computer if it is a local user) what rights the user has, and if the rights specified in the domain controller matches the rights that is required by the executed task it will continue. Otherwise it will tell you that you don't have the right to do what you were trying to do.
So while the domain admin might be in the local administrator group (which has the same rights as a local administrator has) it is not the same thing as if the account was created on the local machine.

About the net user command: This command gets the list of local accounts. And since it doesn't ask the domain controller for the users created there it doesn't show those users. (This is by design as it would be a security hole to let the domain users know about all the users that are created in the domain.)

I would recommend that you read a bit more about the concept of a domain network. I don't know what your setup looks like. But I got the feeling that you only have your domain admins created on the domain controller? If that's the case then you're missing out on a lot of the features that the domain controller brings! And I would recommend that you move the users from the local machines to the domain controller!


Images uploaded to S3 using MongoDB Stitch cannot be opened

Question: I'm using MongoDB Stitch to upload images using React Native, and I can successfully upload text and what appears to be an image, but I can't open the image from S3.
I'm using the following code from their example in a Stitch function (https://docs.mongodb.com/stitch/services/aws/):
exports = async function(key, body) {
  const s3 = context.services.get('MY_S3_SERVICE').s3("us-east-1");
  try {
    const result = await s3.PutObject({
      "Bucket": "my_bucket_on_s3",
      "Key": key,
      "Body": body
    });
    console.log(EJSON.stringify(result));
    return result;
  } catch(error) {
    console.error(EJSON.stringify(error));
  }
};

From the client side I'm using react-native-image-picker to pick the image, and upload it like so:
handleSelectedImage = response => {
    if (response.didCancel) {
      console.log('User cancelled image picker')
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error)
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton)
    } else {
      const source = { uri: response.uri }
      //const s = { uri: 'data:image/jpeg;base64,' + response.data }

      const imageId = generateUniqueId()
      const fileType = '.jpg'
      const key = imageId + fileType

      uploadImage(key, source.uri).then(result => {
        console.log('Did upload image!', result)
      })
    }
  }

And the client side function that calls the Stitch function:
export const uploadImage = (key, body) => {
  const client = Stitch.defaultAppClient
  return client.callFunction('uploadImage', [key, body])
}

I can successfully upload what appears to be an image file to S3, but when i download the file, I can't open it:
Answer: You have to convert the base64 image to BSON.Binary:
context.services.get("MY_S3_SERVICE").s3("us-east-1").PutObject({
    Bucket: "my_bucket_on_s3",
    Key: "hello.jpg",
    ContentType: "image/jpeg",
    Body: BSON.Binary.fromBase64("iVBORw0KGgoAA... (rest of the base64 string)", 0),
})


GraphicsMagick in Drupal 7

Question: D7 has ImageAPI and that ImageMagick Module is also installed. However I want to use GraphicsMagick with D7 but haven't been successful till now. I have both ImageMagick and GraphicsMagick installed in my Ubuntu Box, I also have pecl imagick and pecl gmagick installed. I know both pecls doesn't work at the same time, but I have been changing configs whenever necessary.
I have tested both ImageMagick and GraphicsMagick from command line, both works perfectly, but I couldn't make it work with Drupal. According to ImageMagick Module I just need to change in Image Toolkit from convert to gm, Drupal reads the executable binary perfectly. I try to upload photo which doesn't show after processing and is also not uploaded in the file. But when I change it back to convert and pecl imagick everything works smoothly.
Any suggestions how to use GraphicsMagick with Drupal 7 ?
I even tried that this http://drupal.org/sandbox/W32/1077458 sandbox project, but no luck...
Answer: Many years later, but for future reference, the problem might be related to the fact that you are using the PECL gmagick PHP extension. I believe the ImageMagick module is not meant to work with the gmagick PHP extension. There is a module meant to be used specifically with PECL's gmagick: https://www.drupal.org/project/gmagick . I hope that helps somebody.

GraphicsMagick in Drupal 7