How to create file->node relations use relations modules?

Question: I have a little issue that How to create file->node relations use relations modules?
In my case:
   I need to create music(mp3) and album relations. After i check some information and said that music(mp3) and album is file->node relations.
But, i don't know that how to do this relations.
when i create a relation type, which bundles need to selected?
Answer: [Resolved]
1. Create relation between Node and file
2. Create a view for relation and only view out all related file
3. setting view to relation select values


What happens when I start the rails server locally?

Question: I'm learning Ruby on Rails. Currently I'm doing basic development on my local machine. What happens when I run rails server in the terminal (OS X)? I'd just like to understand what the Rails architecture is doing and which Ruby scripts are run.
Answer: One of the things rails server does is that it loads all the dependencies/gems required by your Rails app, or at least sets them up to be auto-loaded later when they are needed.  This is sometimes called "booting" or loading the "Rails environment".  This is also done when you run other rails commands like rails console or rails runner.
It also starts a web server named WebRick.  The web server is a piece of ruby code that, when run, binds itself to a port (by default port 3000) on your computer and starts listening for incoming HTTP requests on that port.
When a request comes in (for example an HTTP GET request of a user loading your from page), the web server works together with rails to handle the request.  I'm not sure exactly how the work is divided, but the web server should take care of the lower-level stuff like reading HTTP headers and rails should take care of figuring out what controller and action to route the request to (using your routes.rb file).  I think the component of rails that does this work is called action_dispatch, and it is in the actionpack gem.


Combine two items in a list

Question: I need a way to reduce a list, or calculate a "Total." I have a class, lets call it Prod. Prod contains 4 values. One is the name of the product, the id, a serial number, and a quantity. Basically I have one product but 2 different serial numbers. So when I get my data back from my query I have 2 items which I want to treat as a single item. How can I go about using LINQ or something else (I cannot foreach over them. There are many more class members and that would take a while plus look terrible). I want to be able to take the 2 instances and combine their serial numbers (not add just Serail1 - Serial 2) and also calculate the quantities together.
Comment: Can you give us example? data for lists samples ? Not marked answer
Answer: I think what you want is the Linq grouping function (see GroupBy - Simple 3). This should give you a list of serial numbers and their quantity count:
public void Linq42()
{
    List<Prod> products = GetProductList();

    var serialCombined =
        from p in products
        group p by p.SerialNumber into g
        select new { SerialNumber = g.Key, Total = g.Count() };
}

Answer: Use the join operator and place them in a Tuple. You can then call more LINQ on the tuples or iterate over them.
var combinedProducts =
    from product1 in products1
    join product2 in products2 on product1.serial equals product2.serial
    select Tuple.Create(product1, product2);

// Use LINQ to calculate a total
combinedProducts.Sum(combined => combined.Item1.count * combined.Item2.price);

// Or use foreach to iterate over the tuples
foreach (var combined in combinedProducts) {
    Console.WriteLine("{0} and {1}", combined.Item1.name, combined.Item2.name);
}

Combine two items in a list


change the position of a line in a file using sed

Question: I would like to know how to change the position of a line in a file (preferably using sed). For example, consider the file that contains
goal identifier statement
let statement 1
let statement 2
forall statement
other statements

I would like to be able to do this
goal identifier statement
forall statement
let statement 1
let statement 2
other statements

where I change the position of the forall line and bring it after the goal line. forall and goal are regexps that can be used to identify the lines.
Comment: This is an interesting problem. To make it a good question on StackOverflow, please add the code you've tried to use to achieve a solution. Check out the [MCVE](http://stackoverflow.com/help/mcve) and [how-to-ask](http://stackoverflow.com/help/how-to-ask) pages for some guidelines on what makes a good question.
Answer: you can try, for move line 4 to line 2, I want to move line A to line B, where A>B
sed -n '2{h; :a; n; 4{p;x;bb}; H; ba}; :b; p' file

or A<B
sed -n '2{h; d}; 4{p; x;}; p' file

you get, in first case: move line 4 to line 2
goal identifier statement
forall statement
let statement 1
let statement 2
other statements

you get, in second case: move line 2 to line 4
goal identifier statement
let statement 2
forall statement
let statement 1
other statements

Explanation
sed -n '              #silent option ON
    2{                #if is line 2
        h             #Replace the contents of the hold space with the contents of the pattern space
        :a            #label "a"
        n             #fetch the next line
        4{            #if is line 4
            p         #print line 4
            x         #Exchange the contents of the hold and pattern spaces
            bb        #goto "b"
        }
        H             #appends line from the pattern space to the hold space, with a newline before it.
        ba            #goto "a"
    }
    :b                #Label "b"
    p                 #print
' file

EDIT
If You want use regex for identify the lines, you can modify first command
sed -n '/goal/{p;n;h;:a;n;/forall/{p;x;bb};H;ba};:b;p' file

Comment: Nice could use a single branch though using something like `sed -n '/goal/{p;:1;n;/forall/!{H;b1};p;x;D};p'`
Comment: I think they want to move lines based on regexp match not position?
Comment: @123 It's true, I misunderstood, I'm going to modify
Comment: @Jose The regex (2nd command) works like a charm. Could you add the explanation for the regex command as well ?
Comment: @123 Works as well. Kindly explain the 'single branch' concept though.
Answer: $ cat r.awk
BEGIN {
    forall_re = "^forall" # examples of regexps
    goal_re   = "^goal"
}

function tag(l) { # tag a line
    if      (l ~ goal_re  ) return "goal"
    else if (l ~ forall_re) return "forall"
    else                    return "rest"
}

{ # store entire file in array; give a tag to every line
    lines[NR] = $0
    tags[NR]  = tag($0)
}

function swap0(a, i, j,   tmp) {
    tmp = a[i]; a[i] = a[j]; a[j] = tmp
}

function swap(i, j) {
    swap0(lines, i, j); swap0(tags, i, j)
}

function rise(i) {
    # TODO: add error check
    while (i - 1 > 0 && tags[i - 1] != "goal") {
        swap(i, i - 1); i--
    }
}

function process(    i) {
    for (i = 1; i <= NR; i++)
        if (tags[i] == "forall") rise(i)
}

function dump(    i) { # print the array
    for (i = 1; i <= NR; i++)
        print lines[i]
}

END {
    process()
    dump()
}

An example of input file
$ cat r.txt
goal identifier statement
let statement 1
let statement 2
forall statement A
other statements

goal identifier statement
let statement 1
let statement 2
forall statement B
other statements

Usage:
$ awk -f r.awk r.txt
goal identifier statement
forall statement A
let statement 1
let statement 2
other statements

goal identifier statement
forall statement B
let statement 1
let statement 2
other statements

Answer: sed is for simple substitutions on individual lines, that is all. For anything else you should use awk for every desirable attribute of software (clarity, simplicity, portability, etc.:
$ awk 'NR==FNR{if (/forall/) {f=FNR; v=$0} next} FNR!=f; /goal/{print v} ' file file
goal identifier statement
forall statement
let statement 1
let statement 2
other statements

Comment: Would be helpful with an explanation of each awk item...
Comment: @not2qubit no, it's all trivial and obvious after a quick read of the awk manual.
Answer: sed -r '/goal/{                 # if match "goal" line
    :X                          # this is a lable for branch command
    N                           # append next line
    /forall[^\n]*$/{            # if match "forall" line move to "goal" line below
        s#^([^\n]*)(.*)(\n[^\n]*)$#\1\3\2#
        b                       # after move finished branch to end
    }
    bX                          # branch to :X for appending next line
}' file
goal identifier statement
forall statement
let statement 1
let statement 2
other statements

Comment: Please consider adding a brief explanation of *how* the above solves the issue.
Answer: A less terrible way using vim to find a line in $FILENAME using regex $REGEX_EXPRESSION and move that line to $LINE_NUMBER:
vim -c "g:$REGEX_EXPRESSION:m$LINE_NUMBER" -cwq "$FILENAME"

explanation: -c is command in vim, so it goes to the first line that matches that regex and then moves it to the line number specified, and then does the command wq (or write and quit).


Music notations of sounds, from harmonica?

Question: I have these 2 audio files. They are the sounds of harmonica, from my favourite song, which I like best.
The samples are:
Sample 1
Sample 2

To create a music sheet for the sounds of harmonica, I have use many software for notation recognition; but, I always get a complex-sheet, like this:

I want to get the sound of harmonica, only. I don't want to get any beat.

Can you help me to recognite these sounds of harmonica to music sheet, with simpler notes?
Answer: Somebody else may know better, but as far as I know there's yet no simple to use piece of software that allows what you need. Polyphonic pitch recogniton software exists with pretty sophiscated capabilities, but they cannot guess what part of the signal is of interest to you or simply distinguish a melody from accompaniment. In simple terms, the sw is going to try do identify clear harmonic  components (the type of sound generated by pitched musical instruments) in the signal and detect the base picth (the so called "fundamental") for each harmonic component. Instruments in the same pitch range and the presence of other types of signal, like noise or percussion instruments may make this task extremely difficult, providing chaotic results like the one you show.
It's possible to "help" a sw tool by telling what parts of the audio signal you are looking for, but it's an interactive error and trial process and you have to know a bit about audio signal processing to understand how the sw works and how to provide it with useful information. HPCP for example is such a tool, but it's an engineering more than a musical tool and will not by itself provide you with musical notation.
Even if you can isolate the harmonica component of the tracks, an aditional difficulty is the characteristic expression playing of the harmonica (bends and draws with sub tonal inflexions) that will make pitch recognition more difficult, as pitch recognition sw looks for a stable pitch for a specific amount of time before declaring it a found "note".
Again, someone may have a better answer but I don't see an alternative to the good old method of going about it by ear.
Comment: Nothing can remove beats with 100% consistency.
Comment: "Nothing can remove beats with 100% consistency" ... except those two funny-looking appendages that stick out of the sides of your head, and the big lump of wet grey stuff that sits in between them ;)


Globally add selector to all my CSS selector with Webpack (at build time)

Question: I would like to globally append a specific selector to all CSS selector used in my application.
I'm using React and those Webpack loaders post-css, css-loader, sass-loader and extract-text-webpack-plugin.
I don't want to edit all my classname within jsx files. I just want to append this specific selector at build time.
Is there a loader to achieve this? Or any other solution...
What I actually have:
.myClass {
  ...

  &--blue { ... }
}

What I want after Webpack transpilation:
.specificClass .myClass { ... }
.specificClass .myClass--blue { ... }

Thanks
Gautier
PS: The reason I need this feature is to avoid CSS selector collision with the Website I'm integrating my application. I don't wan't to manually edit all my scss files to append the selector.
Answer: this should be solvable by in you main sass file:
.specificClass {
    @import 'variables';
    @import 'fonts';
    // ... do more imports
}

Comment: I don't have single sass entry point. I import all my scss files directly on React components.


Unable to fathom update count INSERT on billions of rows

Question: I am running a Netezza SQL query that is creating a table from a select statement returning almost 8 billion rows. Here is the query:
CREATE TABLE
    table1 AS
    (
        SELECT
            column1
        FROM
            table2 qt
        WHERE
           qt.column1 = '2016-04-04'
        UNION ALL
        SELECT
            column1
        FROM
            table3 qt
        WHERE
           qt.column1 = '2016-04-04'
   )

The driver is throwing this error:
org.springframework.jdbc.UncategorizedSQLException: SqlMapClient operation; uncategorized SQLException for SQL []; SQL state [UNDEFINED]; error code [0];
    --- The error occurred while applying a parameter map.
    --- Check the statement (update failed).
    --- Cause: Unable to fathom update count INSERT 0 7779737732

Does anyone know what's causing this?
Comment: What database are you using?  What is the SQL query you're running?
Comment: @SnakeDoc, that Netazza provides a 64-bit integer data type in no way guarantees that the JDBC driver can handle an update count exceeding the capacity of a 32-bit integer.  In addition, it is unclear whether the error arises inherently because of the large update count, or because of something Spring does with that update count (e.g. writes it to an auxilliary table, maybe into a column of type (32-bit) `Int`).
Comment: in the sense "did you mean to create a table with billions of rows?".
Comment: Perhaps the driver / db handles only integers that can be represented with 32 bits or fewer, at least in that context.  You haven't really given us much to go on.
Comment: @azurefrog It was tagged as Netezza. I added the query too, although I don't think its particularly useful in this case.
Comment: @JohnBollinger That is my guess as well, but I wanted to know if there were any other potential reasons.
Comment: `SQL state [UNDEFINED]` just a sanity check, you are indeed connected and have a working/live connection?
Comment: @JohnBollinger According to ibm, it should support INTEGER and BIGINT types (32 bit and 64 bit, respectively) http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_odiagntz_026.htm
Comment: Is this really a legitimate CREATE TABLE? If yes, can you place it into a stored procedure?
Comment: @Arkadiy Legitimate in what sense? It functions perfectly if I simply place a limit on the number of rows
Answer: I think you are running into a JDBC driver limitation. If you run a INSERT, UPDATE, CREATE AS SELECT via JDBC and the number of rows INSERTed, UPDATEd or CREATEd exceeds 2147483647, you will receive an error message similar to the following:
Unable to fathom update count INSERT 0 5120000160

The above error message may be different given whether an INSERT, UPDATE or CREATE as SELECT and given the number of rows actually affected. This is a limitation of JDBC specification itself.
Thanks,
Sanjit


Are there plugins available for an "improved" Find Content admin interface?

Question: One of our clients has a lot of content over a number of languages and has expressed that they don't really like the Filter/Sort options available on the Find Content page.
Are there any plugins available that present this information in a different manner...maybe something like Windows Explorer?
Answer: Have you tried VBO module? that, allows you create custom admin interface.
Comment: An odd request for sure...if I find, or develop something, I'll let you know ;)
Comment: Thanks for the plugin could be useful on other projects, but not quite what this client is looking for. They want something that makes its easier to navigate through their content to manage it; something like a folder viewer where each page is a folder...strange request I know.
Comment: Not sure what you mean by each page is a folder? Can you elaborate more?
Comment: Non-technical people get used to certain idioms like folders and files. We've had more than one client complain about the Find Content page and the difficulty in finding the content that they're looking for. If the "Our Company" page is under the "About Us" page, they sometimes expect to have to go to "About Us" first, then to the "Our Company" page. Just curious if someone came up with a different Content Management interface for Drupal.
Comment: I don't think you'll find anything (would love to be proven wrong though); it's a very difficult concept to make generic. What constitutes a 'folder'? Is it a taxonomy term reference? A menu hierarchy (in which case what happens when some of the menu items link to non-content pages)? If it's done by menu links, what happens when a piece of content has stuff under it in the hierarchy? Technically that content should be a folder, but it's also a file...because of the difficulty in defining these things I don't it would be an easy thing to do
Comment: Agree with Clive. 'Technically that content should be a folder, but it's also a file'  . So explorer / finder style will not be suitable.
Comment: @SomethingOn Please do, I'd love to get that particular recurring complaint off my back too!


Error message BAD_GATEWAY on app engine

Question: I'm receiving this 502 and bad_gateway error on my app engine ,Can anyone resolve my issue and indicate what am I doing wrong?
Answer: An error code 502 with BAD_GATEWAY in the message usually indicates that App Engine terminated the application because it ran out of memory. The default App Engine flexible VM only has 1GB of memory, with only 600MB available for the application container.

Error message BAD_GATEWAY on app engine


Making a conditional for table view buttonpress

Question: I have a table view and don't know how to access the row number when the user presses one of the cells. The data of the table view is a small array and this is the closest I could come... In the IB, I control dragged the reusable cell to the view controller I push which works fine. I am unsure how to get the row number in a conditional like this...
<code> - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath      *)indexPath
 {
// A bunch of stuff is before this, but not important to the question
//-- > This line if([indexPath row] == 1) This doesn't work... any ideas?
{
    if(totalPoints < 10 && number != 0)
    {
        [self saveNumber:@"1"];
    }
    else if (totalPoints < 10 && attachment == 0)
    {
        [self saveData:@"1"];
        int newPnts = totalPoints + 1;
        [self savePoints:[NSString stringWithFormat: @"%d", newPnts]];
    }
</code>
Thanks
Comment: Have you tried `indexPath.row`?
Comment: Yes but it still doesn't work it's strange
Comment: indexPath.row should work. Show the code where you tried that.
Answer: the row number is [indexPath row] . in tableview you have a dataSource which save the data array used to reload table
Answer: It should work
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
     {
         NSLog(@"%@",indexPath.row);

        if(indexPath.row==1)
        {
            NSLog(@"Do Somthing..");
        }
        else
        {
             NSLog(@"Do Somthing..");
        }

}
</code>
Comment: Thanks I created a dummy project and that worked so it's something wrong with my data sync then...
Answer: Ok I was doing something wrong elsewhere and the view controller doesn't update it's label from the saved data. I will post a seperate question if you're interested


$x \in \operatorname{Int}(A) \iff d(x, A^c) > 0$.

Question: In $\Bbb R$ with the usual metric $|\cdot|$. I have to show that
$$x\in \text{Int}(A) \iff  d(x,A^{c})>0$$
where $\text{Int}(A)$ is the interior  of $A$. When i suppose that $d(x,A^{c})>0$ I have to show that $x\in \text{Int}(A)$. For this, let  $x\in A$ and I consider $\epsilon = d(x,A^{c})$, and I construct $B_{\epsilon} (x)=${$y\in \Bbb R  :  |x-y|<\epsilon$}. Am I in the right way? and if I am, how i can conclude that?.
When I suppose that $x\in \text{Int}(A)$ so I know that $d(x,A^{c})\geq 0$ so $d(x,A^{c})=0$ or $d(x,A^{c})\gt 0$ but if I consider the case $d(x,A^{c})= 0$ that is $d(x,A^{c})= \sup \{|x-y|$ : $y \notin \Bbb R \}=0$ but I know there exist some $\epsilon >0$ such that  $B_{\epsilon} (x)\subset A$ and i don't know if it follows. I accept any suggestions or comments. Thank you.
Answer: Let $r=d(x,A^{c}) >0$. Then $B(x,r) \subseteq A$ because if $d(y,x) <r$ but $y \in A^{c}$ then we get the contradiction $r=d(x,A^{c}) \leq d(y,x) <r$.
Now suppose $B(x,r) \subseteq A$. Then $y \in A^{c}$ implies that  $y \notin B(x,r)$ which means $d(y,x) \geq r$. Since this is true for all $y \in A^{c}$ we get $d(x,A^{c}) \geq r$ so $d(x,A^{c})>0$.
Answer: We will prove the contrapositive.
For the first part, suppose $x \notin \text{Int}(A)$. Then $x \in \overline{A^c}$ i.e. $d(x, A^c) = 0$. So $d(x, A^c)$ is not strictly greater than $0$.
For the second part. Suppose $d(x, A^c)$ is not strictly greater than $0$. Then this forces $d(x, A^c) = 0$ which implies $x \in \overline{A^c}$ i.e $x \not\in \text{Int}(A)$.


SonarQube + Lombok configuration

Question: I am starting a new project and I need to Use SonarQube, and I want to use Lombok, I already configured it within Eclipse and everything works fine except the static analysis.

Unusued private fields: When I have a @Data class, all the fields are reported as Unused private field.
@Getter(lazy=true): When I use this annotation I get the Redundant nullcheck of value known to be non-null  see @Getter(lazy=true) (this is related to compiled code).

I think a possible solution is delombok the project, compile and run Sonar.
Similar issues in SonarQube Jira:

[CodeGen - Lombok] false warning hint (Unused Private Field)
Provide a new java rule to check for unused private field and which would support bytecode generation (cd Lombok)
[CodeGen - Lombok] false warning hint

(The @SuppressWarnings("PMD.UnusedPrivateField") solution don't work with latest SonarQube 4.2 )
How can I solve this problem?
Answer: As a workaround, I'm now letting sonar do the analysis over the code that delombok generates.
I guess this is also not a perfect solution, because I'm analyzing generated code instead of code that is actually written by a developer. I find it's a better solution though than using @SuppressWarnings, //NOSONAR or switching off rules in Sonar itself.
See below an example to achieve this in Maven. Add this to your pom.xml:
<properties>
    ...

    <src.dir>src/main/java</src.dir>
    ...
</properties>
...
<plugins>
    ...
    <plugin>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok-maven-plugin</artifactId>
        <version>${lombok-plugin.version}</version>
        <executions>
            <execution>
                <phase>verify</phase>
                <goals>
                    <goal>delombok</goal>
                </goals>
                <configuration>
                    <addOutputDirectory>false</addOutputDirectory>
                    <sourceDirectory>src/main/java</sourceDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
    ...
</plugins>
...
<profiles>
...
<profile>

        <id>sonar</id>
        <properties>
            <src.dir>target/generated-sources/delombok</src.dir>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.projectlombok</groupId>
                    <artifactId>lombok-maven-plugin</artifactId>
                    <version>${lombok-plugin.version}</version>
                    <executions>
                        <execution>
                            <phase>verify</phase>
                            <goals>
                                <goal>delombok</goal>
                            </goals>
                            <configuration>
                                <addOutputDirectory>true</addOutputDirectory>
                                <sourceDirectory>src/main/java</sourceDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
            </plugins>
        </build>
    </profile>
    ...
</profiles>

Comment: I added a maven example above in my answer. I tried to put only the relevant parts of the pom so if you have further questions please feel free to ask.

Also I noticed that in the meantime https://jira.codehaus.org/browse/MSONAR-70 is fixed, so probably the above code can somehow be simplified.
Comment: Won't this cause problems with SCM plugin/blame?
Answer: I have add a pull request to support more annotation from Lombok.
For the binary, please visit here:

SonarQube 4.5.X (or ships sonar-java-plugin-2.4.jar)
SonarQube 5.0.X (or ships sonar-java-plugin-2.8.jar)
Answer: I asked a similar question some time ago:
sonarqube 4.2 and lombok
Basically, you can't do it with annotation (like @SuppressWarnings) in the code anymore. Instead, you need to set up a (global) rule exclusion in SonarQube:
Click on Settings -> Exclusions -> Issues
and adding entries in 'Ignore Issues on Multiple Criteria' section, and enter something like:
Rule Key Pattern  File Path Pattern
squid:S1068       **/models/**/*.java

It makes your source code a little bit cleaner (since you don't need @SuppressWarnings anymore), but I don't like the idea of setting global rules, as it may cause other problems.

Update:
For 'Redundant nullcheck of value known to be non-null', you can add something like following:
Rule Key Pattern                                   File Path Pattern
findbugs:RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE  **/xxxxx.java

And another one that may (or may not) be useful for you:
Rule Key Pattern                        File Path Pattern
common-java:InsufficientBranchCoverage  **/models/**/*.java

Comment: Yes, I upvoted your question, but your solution only works for the `@Data` annotation, and I have some `@ManagedBeans (JSF)` classes with `@Getter @Setter`, and not all projects use `lombock`, and not all fields uses the annotations, so, I think, in my case, this is not a solution. And with the `@Getter(lazy=true)` this solution don't apply.
Comment: In my project, I have settings to cover 'Redundant nullcheck' warning too. You just need to find those rule keys and add exception to them. (also see my update above)
Comment: I think `lombok` should increase the legibility and reduce the size of code, not forces to disable sonar rules that may be useful for some cases.
Comment: @AVolpe: I'd bet, Lombok does it just right and Sonar is wrong. **1.** With `@Data`, the fields are indeed unused until Lombok generates the getters. It doesn't matter *how* it does it, the problem is with the checking tool not taking the generation into account. **2.** Concerning "Redundant nullcheck of value known to be non-null", the problem is that the value is not *guaranteed* to be non-null, [details](http://code.google.com/p/projectlombok/issues/detail?id=681).
Comment: @maaartinus the `Redundant nullcheck` don't appear when uses in conjuntion with `@Data`, it's appear in a class without the `@Data`. And you're rigth, it's not a lombok problem, it's a SonarQube issue, I don't blame lombok for this problem, I only say that is necessary another solution that don't force the reduce the rule set, for example, when you mark a method with `@PostConstruct` and make it private, Sonar will throw the unused rule, I think we need to define a mechanism to skil some method/fields with a specific annotation.
Comment: @AVolpe I see. I misunderstood your comment (as if you were requesting Lombok doing things differently). I've never tried Sonar, but I'm having similar problems with FindBugs; surprisingly, no single wrong message because of Lombok, but quite a few because of using Gson (which reads and write fields via reflection).
Comment: @AVolpe Would it help, if Lombok added e.g. `@lombok.LombokGenerated` to all the stuff it generates? Could you then define a specific rule?
Answer: for multi-modules projects, building on what is mentioned in finrod's answer, I had to add below property in my sonar profile to avoid having duplicated violations (Sonar was analysing both src/main/java and target/generated-sources/delombok)
<properties>

    <sonar.exclusions>src/main/java/**/*</sonar.exclusions>

</properties>

SonarQube + Lombok configuration


Does $p(a) = p(b) \Rightarrow a=b \ $?

Question: Let $S = (P_1,P_2, \ldots,P_n)$ be a set of polynomials with complex coefficients.
I call S critical if set of solutions of $\{P_n(a) = P_n(b)\forall n \}$ in $\Bbb C^2$ is $\{ (a=b) \cup (\text{some finite points in }\Bbb C^2)\}$
I call  a set minimal critical set  if it is a critical set but no proper subset of it is critical.
Examples of minimal critical sets are (a*z +b) ($z^2, z^3$) or ($z^2 +z, z^4$)
Question is does there exist minimal critical sets of cardinality n for every n ?
for example what are the examples for n=3,4  with proof?
It is easy to find infinite subsets T of polynomials which do not have any minimal critical subset, for example $\{P(z^2)\ \forall P\}$, but then is there a condition on such sets?
Answer: Let $m=2\cdot 3\cdot 5\cdots p_n$ be the product of the first $n$ primes.
Let $P_k(x)=x^{m/p_k}$.
Then $P_k(a)=P_k(b)$ implies $|a|=|b|$ and (assuming they are nonzero) $\zeta:=\frac ab$ is a $\frac m{p_k}$th root of unity, that is the order of $\zeta$ is a divisor of $\frac m{p_k}$. Thus if $P_k(a)=P_k(b)$ for all $k$, we conclude that the order of $\zeta$ is $1$, i.e. $a=b$. Hence the set is critical.
On the other hand, if just one $k$ is missing, then $b=\xi a$ with $\xi$ a  nontrivial $p_k$th root of unity gives you infinitely many solutions, i.e. no proper subset of the above is critical.
Comment: if i put one additional condition on Pi(z) that each Pi(z) is not of the form  (z-a)^k +c for any a,k,c , then how to tackle?

Does $p(a) = p(b) \Rightarrow a=b \ $?


InvalidOperationException ao utilizar o método Set do DatabaseContext

Question: Ao utilizar o método DbContext.Set(), a seguinte exceção é levantada:

The entity type  is not part of the model for the current
  context

Caso eu crie um DbSet diretamente no DatabaseContext, funciona. Mas a minha necessidade atual é criar um repositório genérico, e a partir dele conseguir o DbSet referente a entidade passada em parâmetro, como mostra o código abaixo.
O que há de errado com a implementação para levantar esta exception? Estou utilizando CodeFirst.
Controller
public class QualquerController<TEntidade> : Controller
{
    public DatabaseContext contexto;

    public Repositorio<TEntidade> repositorio;

    public QualquerController()
    {
            repositorio = new Repositorio<TEntidade>(contexto);
    }
}

Repositorio
public class Repositorio<TEntidade> : where TEntidade : EntidadeBase
{
    public DbSet<TEntidade> Entidade;

    public Repositorio(DatabaseContext contexto)
    {
         Entidade = contexto.Set<TEntidade>();
    }
}

Comment: testa sem essa linha `Entidade = contexto.Set();`. Acho que nao precisa disso
Comment: Oi Lucas, não estou em meu DbContext, então preciso desta linha para instanciar o DbSet. Se eu tiro, dá NullReferenceException.
Comment: Essa entidade que voce esta tentando adicionar ja existe nesse contexto?
Answer: A questão é que o método contexto.Set<TEntidade>() não adiciona essa entidade ao contexto. Ele apenas retorna um DbSet para você poder manipular o repositório.
Comment: Vou tentar explicar melhor a necessidade do gerenciamento centralizado. Você cria a tabela Clientes apenas quando acessa a página de clientes. Então você vai pra outra tela. Quando você voltar para a tela de clientes, você irá verificar de novo se a tabela existe? Isso irá consumir muitos recursos de máquina. E para se ter um gerenciamento centralizado, a única forma é com o DBContext. Todos as ORMs que eu conheço gerenciam as tabelas de forma centralizada. Tudo em um lugar só. E sempre verificado na inicialização da aplicação. Espero ter ajudado :)
Comment: Imaginei que fosse este o motivo, mas minha implementação segue vários exemplos na internet que supostamente funcionam... Você sabe algum modo de aprimorar este código para evitar esta exception? Como havia lhe dito, caso eu crie um DbSet diretamente no DatabaseContext, este funciona corretamente, mas preciso faze-lo de modo genérico com n dbsets.
Comment: Como você vai gerenciar as tabelas no banco de dados se não coloca-lás no DBContext? Da forma que você quer fazer, uma tabela só vai existir quando o controller da entidade for chamado. Então digamos que voce tenha 2 tabelas. A primeira é chamada logo quando inicia a aplicação(neste momento ela é criada). E a segunda é chamada quando clica em algum link. Você vai criar as tabelas separadamente em tempo de execução caso elas não existam?
Comment: Lucas, como você sugere então? Preciso de um Repositorio genérico. Já trabalhei em projetos em que existia apenas um DbContext sem dbSet, contudo, o mapeamento das classes estavam no OnModelCreating. Eu não tenho este mapeamento porque estou utilizando data annotations. Existe uma outra forma de adicionar as tabelas ao contexto sem utilizar o dbSet para que eu possa manter a criação do dbset no repositorio, e não no context?
Comment: Vinícius, sempre há uma forma. Mas como eu disse no comentário acima, as tabelas precisam ser gerenciadas no classe do DBContext mesmo. Ou pelo DBSet ou pelo OnModelCreating.
Comment: Ajudou sim Lucas, através de seu comentário consegui realizar a inicialização das tabelas no OnModelCreating, como dito em minha resposta abaixo. Se tiver alguma pontuação sobre o método que implementei para registrar as tabelas no contexto, por favor, o faça :)
Answer: Consegui solucionar o problema através das dicas que Lucas me informou. Utilizando o método Entity do modelbuilder passado como parâmetro no método OnModelCreating, consegui registrar minhas entidades no contexto. Segue abaixo o código utilizado:
public class DatabaseContext : DbContext
{
     public DatabaseContext()
        : base("DefaultConnection")
    {
        Database.SetInitializer<DatabaseContext>(new DropCreateDatabaseAlways<DatabaseContext>());
    }

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Foo>();
         modelBuilder.Entity<Bar>();

         base.OnModelCreating(modelBuilder);
     }
}


Extract more data on field_collection_item from REST APIs of Drupal

Question: I am trying to display information regarding Contributed modules available on Drupal programmatically.
For that, I am taking the help of this documentation :
https://www.drupal.org/drupalorg/docs/apis/rest-and-other-apis
When I am calling API like:
https://www.drupal.org/api-d7/node.json?field_project_machine_name=ctools
In return I am receiving a JSON object with the following details:
"field_supporting_organizations": [
                {
                    "uri": "https://www.drupal.org/api-d7/field_collection_item/1381907",
                    "id": "1381907",
                    "resource": "field_collection_item"
                }
],

Now, I want to extract more data on this field collection item, but I am unable to find the right API filters to do so.
Any help would be much appreciated.
Answer: To extrach more information from that field collection item, you just use the URI reported from that JSON data, but appending .json to the URI.
In your case, the URI is https://www.drupal.org/api-d7/field_collection_item/1381907.json, which returns the following data.
{
  "field_how_they_helped": "Maintenance",
  "field_supporting_organization": {
    "uri": "https://www.drupal.org/api-d7/node/2808667",
    "id": "2808667",
    "resource": "node"
  },
  "item_id": "1381907",
  "revision_id": "1675252",
  "field_name": "field_supporting_organizations",
  "archived": "0",
  "url": "https://www.drupal.org/field-collection/field-supporting-organizations/1381907",
  "host_entity": {
    "uri": "https://www.drupal.org/api-d7/node/343333",
    "id": "343333",
    "resource": "node"
  },
  "feeds_item_guid": null,
  "feeds_item_url": null,
  "feed_nid": null
}

If then you need to get more information about the organization, you visit https://www.drupal.org/api-d7/node/2808667.json, which returns the following data.
{
  "body": {
    "value": "
The University of British Columbia is a global centre for research and teaching, consistently ranked among the top 20 public universities in the world. Since 1915, UBC's entrepreneurial spirit has embraced innovation and challenged the status quo. UBC encourages its students, staff and faculty to challenge convention, lead discovery and explore new ways of learning. At UBC, bold thinking is given a place to develop into ideas that can change the world.
",
    "summary": "",
    "format": "1"
  },
  "taxonomy_vocabulary_48": [],
  "taxonomy_vocabulary_50": [
    {
      "uri": "https://www.drupal.org/api-d7/taxonomy_term/24656",
      "id": "24656",
      "resource": "taxonomy_term"
    }
  ],
  "taxonomy_vocabulary_52": [
    {
      "uri": "https://www.drupal.org/api-d7/taxonomy_term/24104",
      "id": "24104",
      "resource": "taxonomy_term"
    }
  ],
  "field_budget": "",
  "field_contributions": {
    "value": "
Web services offer Drupal integration to the faculty and staff and they have provided a theme and commerce payment gateway integration module. Also have staff members contribute to Drupal and meetups for users within the University staff.
",
  "format": "1"
  },
  "field_link": {
    "url": "https://www.ubc.ca",
    "attributes": [],
    "display_url": null
  },
  "field_logo": {
    "file": {
      "uri": "https://www.drupal.org/api-d7/file/5711845",
      "id": "5711845",
      "resource": "file"
    },
    "alt": "The University of British Columbia",
    "title": ""
  },
  "field_org_marketplace_request": false,
  "field_org_training_request": false,
  "field_organization_headquarters": "Vancouver",
  "field_organization_list_rule": "never",
  "field_organization_training_desc": {
    "value": "",
    "format": "1"
  },
  "field_organization_training_list": "off",
  "field_organization_training_url": {
    "url": "",
    "attributes": [],
    "display_url": null
  },
  "field_organization_technologies": "off",
  "field_organization_support": [],
  "field_short_description": null,
  "field_hosting_type": [],
  "field_org_issue_credit_count": "12",
  "field_organization_type": {
    "uri": "https://www.drupal.org/api-d7/taxonomy_term/182533",
    "id": "182533",
    "resource": "taxonomy_term"
  },
  "field_org_membership_status": null,
  "field_organization_loc_served": [],
  "nid": "2808667",
  "vid": "10103871",
  "is_new": false,
  "type": "organization",
  "title": "The University of British Columbia",
  "language": "en",
  "url": "https://www.drupal.org/the-university-of-british-columbia",
  "edit_url": "https://www.drupal.org/node/2808667/edit",
  "status": "1",
  "promote": "0",
  "sticky": "0",
  "created": "1475153665",
  "changed": "1623042361",
  "author": {
    "uri": "https://www.drupal.org/api-d7/user/160302",
    "id": "160302",
    "resource": "user"
  },
  "book_ancestors": [],
  "comment": "1",
  "comments": [],
  "comment_count": "0",
  "comment_count_new": false,
  "feeds_item_guid": null,
  "feeds_item_url": null,
  "feed_nid": null,
  "flag_flag_tracker_follow_user": [],
  "flag_tracker_follower_count": null,
  "has_new_content": null,
  "last_comment_timestamp": "1475153665",
  "projects_supported": [
    {
      "id": "3054475",
      "title": "Maintainer Support",
      "uri": "https://www.drupal.org/api-d7/node/3054475"
    },
    {
      "id": "2920939",
      "title": "Responsive Table Filter",
      "uri": "https://www.drupal.org/api-d7/node/2920939"
    },
    {
      "id": "2724893",
      "title": "Composer Deploy",
      "uri": "https://www.drupal.org/api-d7/node/2724893"
    },
    {
      "id": "2632164",
      "title": "Twig Extensions",
      "uri": "https://www.drupal.org/api-d7/node/2632164"
    },
    {
      "id": "2162097",
      "title": "Views Selective Filters",
      "uri": "https://www.drupal.org/api-d7/node/2162097"
    },
    {
      "id": "1612464",
      "title": "SAML Service Provider",
      "uri": "https://www.drupal.org/api-d7/node/1612464"
    },
    {
      "id": "1378306",
      "title": "Entityform",
      "uri": "https://www.drupal.org/api-d7/node/1378306"
    },
    {
      "id": "1173784",
      "title": "Node authorize link",
      "uri": "https://www.drupal.org/api-d7/node/1173784"
    },
    {
      "id": "948986",
      "title": "Menu Position",
      "uri": "https://www.drupal.org/api-d7/node/948986"
    },
    {
      "id": "756434",
      "title": "Form Tips",
      "uri": "https://www.drupal.org/api-d7/node/756434"
    },
    {
      "id": "460628",
      "title": "Views Natural Sort",
      "uri": "https://www.drupal.org/api-d7/node/460628"
    },
    {
      "id": "343333",
      "title": "Chaos Tool Suite (ctools)",
      "uri": "https://www.drupal.org/api-d7/node/343333"
    },
    {
      "id": "265945",
      "title": "Menu Block",
      "uri": "https://www.drupal.org/api-d7/node/265945"
    },
    {
      "id": "165016",
      "title": "Editable Fields",
      "uri": "https://www.drupal.org/api-d7/node/165016"
    },
    {
      "id": "161539",
      "title": "Views Bulk Operations (VBO)",
      "uri": "https://www.drupal.org/api-d7/node/161539"
    },
    {
      "id": "92594",
      "title": "Calendar",
      "uri": "https://www.drupal.org/api-d7/node/92594"
    },
    {
      "id": "74958",
      "title": "Panels",
      "uri": "https://www.drupal.org/api-d7/node/74958"
    },
    {
      "id": "9044",
      "title": "Code Filter",
      "uri": "https://www.drupal.org/api-d7/node/9044"
    }
  ]
}

In general, to access the URI returned from that data, you need to append .json to the URI. For example, for https://www.drupal.org/api-d7/taxonomy_term/24656, you use https://www.drupal.org/api-d7/taxonomy_term/24656.json.


hook_node_insert, hook_entity_insert, hool_node_presave not triggering

Question: I just got a  drupal 7 site with a custom theme handed over to me.
I have to do some stuff when a curtain content type is created by a user, but i am so far unable to get any related hooks working.
So far i tried to add the following to the tempalte.php file
<code>function MYTHEME_node_insert($node) {}

function MYTHEME_entity_insert($entity, $type) {}

function MYTHEME_node_presave($node) {}
</code>
Changing MYTHEME to the name of my theme.
I doubbledchecked and the template.php file is used.
Answer: Only certain theme-related hooks, and alter hooks, can be implemented by a theme. The hooks you're trying to implement aren't in that list, as they're unrelated to theming.
You'll need to create a custom module and implement he hooks there instead.
Comment: Yeah, just realized. Thank you for the answer though. Have a great weekend!


Back-propagation Algorithm

Question: Why does Backpropagation Algorithm backpropagate a value back on a neuron with activation zero which can't have an influence on the error ? I assume binary activations of the neurons.
<code>float[] feedbackError(bool[] inputs, float[] errors, bool[] output){

float[] feedbackError = new float[inputs.length];
for(int i = 0; i < inputs.length; i++){
  float errorSum = 0.0;
  for(int j = 0; j < this.weights[i].length; j++){
        errorSum           += errors[j] * weights[i][j] * output[i] ; !!! This is the line I'm talking about and I added the output node which has to be corrected as multiplicator !!!
        this.weights[i][j] += inputs[i] * errors[j] * 0.1 ;
  }
  feedbackError[i] = errorSum;
}
//Process Bias (? doesn't count to feedbackError:(!)

int i = weights.length-1;
float errorSum = 0.0;
for(int j = 0; j < this.weights[i].length; j++){
      this.weights[i][j] += 1.0       * errors[j] * 0.1;
}

return feedbackError;
</code>
}
I suggest also another possible approach in my repository:
Another potential candidate for training several layers in one displayed matrix
(Be careful, it's very Alpha and does not converge smoothly but it's very easy and efficient in paralelization)
Answer: Think of it as a trial and error scenario. If the error is backpropagated, the weights will change through gradient descent. In the next forward pass, the new weights with the neuron's new input might help the neuron activate (if the neuron's output is above a threshold). If the activated neuron helps reduce the loss, the previously dead neuron has now "learned" some relationship between the input and output through its updated weights and activation.
On the other hand, if the neuron activation led to an increase in loss, backpropagation algorithm will trace back the loss (or error) and update the weights through gradient descent to ensure the neuron is dead in future passes. Practically, this scenario is very rare, since every neuron should learn something about a task. If you have dead neurons in your model, then your model is said to be performing inefficiently.
This trial and error (or to and fro) is called learning or training a model.
Comment: I can't understand why a node that has no influence to the result should be considered in the equation. It' just too irrational.

Back-propagation Algorithm


Rotate apache logs based on file size in Ubuntu

Question: I have three sites on my server and their logs (Apache logs) are in their root folder not in /var/log. I need a script that rotates the access_log and error_log base on their file size for example rotates them when their file size exceeds 1G .
Server's OS is Ubuntu.
I have a basic skill of shell programing but good talent in learing ;)
would you help me in this issue?
Answer: logrotate can be configured tn only rotate when logs exceed a certain size, see the minsize option. Typically logrotate runs daily though, if you wanted to rotate when the logfile was more or less exactly 1GB, you might need a script which watches the logfile and triggers logrotate when it exceeds your limit.
Alternatively, you could stick with daily rotation of smaller logfiles, but have a postrotate script which concatenates the rotated logs together into 1GB clumps of data.
Answer: You can use managelogs exactly for that.
It will automatically rotate the logs when the limit is reached.
It also has other neat features like directly writing to compressed files, keep a larger amount of archive files, etc.


using svnadmin as www-data user

Question: Howdie
Scenario:
Allow developers to submit new application packages to a market server. Developers run a bash script which contains a cURL call to market server (localhost/market/submit/$app-name). The submit script on the server creates a new folder in existing svn server with the name of the submitted app. Script on dev side waits for HTTP to issue a success message and then do a svn checkout in dev local machine.
Problem:
The submit script on the market server failed to create new svn directory through code:
echo `svnadmin mkdir -m 'added new package $package' http://localhost/market/packages/$package`;

this does not echo nothing and when I go on http://localhost/market/packages, the folder has not been added and the revision number has not been incremented.
I've tried from a terminal in market server
chown root:www-data /usr/bin/svnadmin

or
chmod 777 /usr/bin/svnadmin

but still no luck. Somebody has come acrosss similar problem? Any solutions? Thanks!
Profile:
Linux/Ubuntu, apache subversion
Comment: ok, I've made an error, it should be `svn mkdir`and not `svnadmin mkdir`. working from terminal but still not working from apache ...
Answer: ok, noob mistake I did not set right the permissions of the folder that contains the svn server.
chown -R www-data:subversion /var/www/market/packages
chmod -R 750 /var/www/market/packages

now it works!

using svnadmin as www-data user


Javascript não reconhece Json

Question: tenho a seguinte ideia que o moderador Sergio enviou
var obj = [JSON]

var mydiv = document.getElementById("tabLista");
mydiv.innerHTML = "";
var ul = document.createElement("ul");
mydiv.appendChild(ul);

var escolhidas = [];
obj.forEach(function(obj) {
  obj = obj.List;
  var li = document.createElement("li");
  ul.appendChild(li);
  Object.keys(obj).forEach(function(chave) {
    var div = document.createElement("div");
    div.classList.add(chave);
    div.textContent = obj[chave];
    li.appendChild(div);
  });
  var checkbox = document.createElement("input");
  checkbox.type = 'checkbox';
  checkbox.addEventListener('change', function() {
    this.closest('li').classList.toggle('selecionado', this.checked);
    if (this.checked) escolhidas.push(obj);
    else escolhidas = escolhidas.filter(function(el) {
      return el != obj;
    });
    console.log(escolhidas);
  });
  li.appendChild(checkbox);
});

Só que na hora de inserir o json que o meu servidor responde o script não reconhece as chaves, somente imprime
[object Object]
[object Object]
[object Object]

Json que o meu servidor responde
{
    "api": "api",
    "List": [{
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Marcelo"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Pedro"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Lucas"
    }],
    "arq": "1",
    "paste": "2"
}

Json Da ideia original
var obj = [{
    nome: 'a',
    data: '13/09/2017'
  },
  {
    nome: 'b',
    data: '13/09/2017'
  },
  {
    nome: 'c',
    data: '13/09/2017'
  },
  {
    nome: 'd',
    data: '13/09/2017'
  },
]

Obigado :)
Comment: Ok, então muda para `var obj = JSON.parse(req.responseText).List;` e depois tira o `obj = obj.List;` dentro do `.forEach`. O problema é que estás a passar o objeto e não uma array. Ou então deixa como está mas passa uma array, no caso de teres vários desses JSONs.
Comment: Em qual trecho isso é impresso? Porque ele está imprimindo um objeto, talvez tenha que imprimir uma string ou trabalhar o objeto.
Comment: E se você trocar console.log(escolhidas) por console.log(JSON.stringify(escolhidas, null, 2)); o que exibe?
Comment: Ele está sendo impresso na div tabLista, com o json do Sergio funciona normalmente, mas com o meu não, trocando o console.log volta "Null"
Comment: @PlanetWar estás com problemas a enviar para o servidor ou a receber do servidor?
Comment: Receber o json e imprimir na li
Comment: Ok, qual é o código JavaScript que vai buscar o JSON?
Comment: Outra coisa, estás a dar o nome de `JSON` à variável? `JSON` (com letra grande) é uma palavra reservada em JavaScript, deves usar outra.
Comment: Não, só coloquei JSON ali para mostrar onde o meu json vai, mas estou colocando ali a resposta do JSON.parse(req.responseText);
Comment: E depois estás a usar `var obj = JSON.parse(req.responseText);` ou `var obj = [JSON.parse(req.responseText)];`?
Comment: Estou usando var obj = JSON.parse(req.responseText);
Comment: Funcionou perfeitamente, obrigado por esclarecer :)
Answer: O JSON que recebes do servidor é um objeto:
{
    "api": "api",
    "List": [{

e o .forEach trabalha sobre arrays. Assim tens de passar o .List diretamente pois o .List é uma array.
var obj = JSON.parse(req.responseText);

var mydiv = document.getElementById("tabLista");
mydiv.innerHTML = "";
var ul = document.createElement("ul");
mydiv.appendChild(ul);

var escolhidas = [];
obj.forEach(function(obj) {
  // obj = obj.List; // <--- tira isto. Isto era util caso `obj` fosse uma array.
  var li = document.createElement("li");
  ul.appendChild(li);
  Object.keys(obj).forEach(function(chave) {
  // etc...

Javascript não reconhece Json


Using standalone.sh but cant see welcome page or web mgmt interface

Question: I downloaded and extracted JBOSS AS 7.1.1. I executed the Standalone.sh script also.
However, now when I try to go to
 http:// IP-address:8080

or
  http:// IP-address:9990/console

I get an error that Google Chrome cannot display the web page.
In the console(Putty) I can see that JBOSS has started successfully. Why am I unable to see the welcome page/admin interface?
UPDATE- Output of command
netstat -tulpen

is given below--
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State           User       Inode      PID/Program name
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      27         428559475  31847/mysqld
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      0          428559730  7714/httpd
tcp        0      0 0.0.0.0:10000               0.0.0.0:*                   LISTEN      0          428554917  31428/perl
tcp        0      0 22.214.171.124:53             0.0.0.0:*                   LISTEN      25         428559819  32162/named
tcp        0      0 22.214.171.124:53             0.0.0.0:*                   LISTEN      25         428559817  32162/named
tcp        0      0 127.0.0.1:53                0.0.0.0:*                   LISTEN      25         428559815  32162/named
tcp        0      0 0.0.0.0:21                  0.0.0.0:*                   LISTEN      99         428559363  31674/proftpd: (acc
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      0          428518498  24097/sshd
tcp        0      0 127.0.0.1:11000             0.0.0.0:*                   LISTEN      0          428566351  6633/lookup-domain-
tcp        0      0 127.0.0.1:5432              0.0.0.0:*                   LISTEN      26         428559680  32048/postmaster
tcp        0      0 127.0.0.1:953               0.0.0.0:*                   LISTEN      25         428559820  32162/named
tcp        0      0 0.0.0.0:25                  0.0.0.0:*                   LISTEN      0          428555252  31610/master
tcp        0      0 0.0.0.0:443                 0.0.0.0:*                   LISTEN      0          428559732  7714/httpd
udp        0      0 188.8.131.52:53             0.0.0.0:*                               25         428559818  32162/named
udp        0      0 22.214.171.124:53             0.0.0.0:*                               25         428559816  32162/named
udp        0      0 127.11.107.1:53             0.0.0.0:*                               25         428559814  32162/named
udp        0      0 0.0.0.0:10000               0.0.0.0:*                               0          428554918  31428/perl

Comment: Can you update your post with results for the following commands: `iptables -L -v -n` and `netstat -tulpen`?
Comment: @BartDeVos for the first command(iptables) I am getting this output--  can't initialize iptables table `filter': Permission denied (you must be root) Is there something I am doing wrong here? I have logged in as root user and I am executing the command as root... Thanks...
Comment: Are you on an OpenVZ VPS? Then, this is to be expected.
Comment: @BartDeVos - yes I am on an OpenVZ VPS...
Answer: No process is listening on 8080 or 9990, so your service isn't running. What is the command you ran to start the server? Do you have a configuration file?
Since you are using an OpenVZ-VPS, there might be an issue with your java. Take a look at this:
http://davidanand.blogspot.com/2010/06/jboss-tomcat-on-openvz-centos.html
Comment: I used the following command to start the server: nohup /usr/java/jboss-as-7.1.1.Final/bin/standalone.sh &, i have created a file at /etc/init.d/jboss-which behaves like a jboss startup/shutdown script...the above command is part of that file...
Comment: Try running `/usr/java/jboss-as-7.1.1.Final/bin/standalone.sh` (without the `&`) and see if any errors pop up.
Comment: @BartDeVos- I ran "sh /usr/java/jboss-as-7.1.1.Final/bin/standalone.sh" and it shows that JBOSS has started successfully...however I still cant access the console or web interface...


Equivalent of Conjugate Priors for Marginal Probability Distributions

Question: In probability, there are nice "conjugate prior" distributions that enable closed-form Bayesian updating – e.g. if you have a Normal likelihood and Normal prior (on the mean parameter), you get a Normal posterior.
Is there an equivalent concept for "nice" (e.g. closed form) marginal distributions? For example, if I have a "A"-distributed likelihood for random variable X (conditional on parameter M) and a "B"-distributed prior on parameter M, I can integrate out the uncertainty of M to get the unconditional distribution of X -- let's say that it is "C"-distributed. My question is: are there well-known pairings of "A" and "B" that lead to well-known "C" here?

The only example I can think of is for a Normal likelihood and Normal prior on the mean, but in particular I was wondering if there were example of this for "heavy"-tailed distributions like Student-t, Pareto, etc.
Obviously, you can just flip Bayes Rule to calculate the Marginal Distribution given the likelihood, the prior, and the posterior --- but that doesn't always result in a well known probability distribution.
Answer: The ones I encounter the most in practice are:

Poisson rates with between subject variation on rates following a Gamma distribution: Negative binomial when you integrate out the random subject effect (that version of the negative binomial distribution is used a lot for negative-binomial regression of overdispersed count data)
Binomial with between subject variation on probabilities following a Beta distribution: Betabinomial when you integrate out the random subject effect
Normal distribution with inverse-gamma distribution on the variance: Student-t distribution when you integrate out the uncertainty on the variance

You can find some more examples in the "posterior predictive distribution" column of the Wikipedia table of conjugate prior distributions - unsurprisingly the topics are closely linked.


Are Hidden Markov Models the right tool for signal segmentation task?

Question: I have a particular problem, and I would like to know if using a HMM is the correct tool for it. Apologies for the poor wording of the problem, HMMs are definitely not my specialty.
I have the following data:

Several sequences of continuous values
Each sequence can be of a different length
All sequences come from the same underlying Markov chain
The number of states (N) is known
The structure of the Markov chain is known: a state always stays as the same state ($N_i$) or transitions to the next state ($N_{i+1}$)

I would like to segment a sequence into the underlying states to be able to calculate the mean value of each state.
For example:
# observable values
x = [0.80, 0.75, 0.85, 1.20, 1.15, 1.20, 1.15, 2.10, 2.05, 2.10]
# label states (we do not know)
y = [   A,    A,    A,    B,    B,    B,    B,    C,    C,    C]
# what I would like to learn in the end
state_means = {'A': 0.80, 'B': 1.175, 'C: 2.075}

I have the feeling that it might be possible to train a HMM with the objective function to minimize the mean squared error between the estimated state_means and the observed values.
Answer: Yes you totally are in the context of an HMM with discrete hidden states and continuous observations, in an unsupervised setting.
Once the probability model is set up, you will need to learn the parameters of the distributions. This can be done with the Expectation Maximization algorithm, have a look at Section III.C of this article "A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition" by Lawrence R. Rabiner. This set of parameters include the transition of the hidden random process and the means and variances of the Gaussian emission distribution (the latter choice of distribution is the most common one).


Como configurar a localização do diretório de trabalho no Git?

Question: Ao instalar o Git, não consegui configurar a localização do meu diretório de trabalho.
Já alterei para "Iniciar em:"C:\Users\Renata Mendes\Documents\Projetos"" nas propriedades do Git Bash, mas a alteração não fica salva e toda vez que inicializo o terminal tenho que entrar manualmente no diretório.
Qual a melhor maneira de se fazer isso?
P.S: Sou iniciante em Git e em Programação.
Comment: "Qual" Git você instalou? Exemplo: [git-scm](http://git-scm.com/downloads), [Tortoise git](https://code.google.com/p/tortoisegit/wiki/Download), etc.. O que você quer dizer com "localização do meu diretório de trabalho"? Você só possui um único repositório git na sua máquina e quer que a janela prompt do git abra sempre no caminho desse repositório? Ou é alguma outra coisa que eu não entendi?
Answer: Olá,
Consegui alterar o caminho inicial do git bash alterando o parâmetro 'iniciar em' nas propriedades, aqui deu certo, acho que o problema que você esta tendo é por causa do caractere espaço. Tente utilizar um caminho sem espaço para testar.
Comment: Bem vindo ao StackOverflow em Português. Editei sua resposta para remover as saudações pois costumamos manter o texto o mais limpo possível para focar na sua resposta sobre programação. Caso tenha interesse em visitar uma parte do site que não é voltado para tirar dúvidas pode conhecer o [chat]. Se tiver dúvidas quanto ao funcionamento, regras e procedimentos do site visite o [meta] :)
Answer: Olá,
Tente seguir estes passos:
1- Campo destino : remover oque estiver depois das aspas, deixando apenas a até a terminação "xxxxxx\Git\git-bash.exe" nada além disso.
2- Campo iniciar em: Colocar a pasta o atalho que deseja que seja inicializado o programa.
Dessa forma ao reabrir o Git Bash ele já irá estar configurado com o caminho indicado no campo 2.
Comment: Bem vindo ao StackOverflow em Português. Editei sua resposta para remover as saudações pois costumamos manter o texto o mais limpo possível para focar na sua resposta sobre programação. Caso tenha interesse em visitar uma parte do site que não é voltado para tirar dúvidas pode conhecer o [chat]. Se tiver dúvidas quanto ao funcionamento, regras e procedimentos do site visite o [meta] :)


How to re-instantiate a Part Class From Menu Handler?

Question: I am new to Eclipse RCP and I am working on an application (Eclipse 4), I have multiple parts within I display data from different sources. I would like to add a menu that displays a Dialog that offers the possibility to select dynamically the data sources that the user wants. When the options are selected I would like to re-instantiate the Part's class using the options as parameters and refresh the view. Is that possible ?
My Part's createComposite method :
    @PostConstruct
    public void createComposite(Composite parent) {
        Composite composite = new Composite(parent, SWT.EMBEDDED);
        parent_C = parent;
        Frame frame_1 = SWT_AWT.new_Frame(composite);
        JPanel mainPanel = new JPanel();
        BorderLayout layout = new BorderLayout();
        mainPanel.setLayout(layout);

          /* Layout Definition */
     }

I would like to add another parameter to the createComposite Method that indicates the options :
@PostConstruct
    public void createComposite(Composite parent, String[] options) {
    /*Code Here*/
}

The Value of the String array changes when the user validate the options from the Menu. When the users validate his options the part's class should be called with the new options.
Is there any way to do this ? Thank You
Answer: To do this you need to get the values in the IEclipseContext of the part being created. One way to do this is to subscribe to the UIEvents.Context.TOPIC_CONTEXT event and modify the new part's context in that event.
@Inject
IEventBroker eventBroker;

eventBroker.subscribe(UIEvents.Context.TOPIC_CONTEXT, this::handleContextEvent);

private void handleContextEvent(Event event)
{
  Object origin = event.getProperty(UIEvents.EventTags.ELEMENT);
  if (!(origin instanceof MPart))
    return;

  MPart part = (MPart)origin;

  // TODO check this is the MPart you want

  Object context = event.getProperty(UIEvents.EventTags.NEW_VALUE);
  if (!(context instanceof IEclipseContext))
    return;

  IEclipseContext newContext = (IEclipseContext)context;

  newContext.set("nameForOptions", .... options ....);
}

I have used a name for the options here so you would use @Named:
@PostConstruct
public void createComposite(Composite parent, @Named("nameForOptions") String[] options)

Comment: Thank You for your response, I should add a Context handler event to each part and the question is how to call the part's class from an Menu Item handler ? how to instantiate it knowing that my part's class doesn't extend from any other class , the part were created from the wizard in the Application.e4xmi file and linked with a Java class as a Class URI
Comment: No, you only use one context handler for the whole RCP. You set this up in whatever you are using to create your parts.
Comment: I created the parts from the Application.e4xmi file. it is not clear how to change the context and refresh the part's content when a menu item is clicked
Comment: Well how are you (re)creating the part? Are you using EPartService? You have to close and reopen a part to get the @PostConstruct method called again. Alternatively you could just call some other method of your part.
Comment: I didn't use EPartService, but I will , I just want to know how it works because I 'am not Familiar with RCP and I am required to develop a feature that filters data basing on the user's choice. Thank You greg-449 for your help
Answer: Instead of recreating the entire part again, it will be easier to refresh of re-create the content inside the part itself. That should be possible by either disposing the content of the part and recreate the content again under that container, or by refresh mechanism of any table/table viewer.


SQL Server express - Management studio installation hangs at native images installation

Question: I've been trying to install SQL server express edition (2014) with management studio and consistently failing to do so because installation stalls at step 'Install_sql_common_core_Cpu64_Action : Write_NativeImage_64. Generating Native images'. I've tried several time but still it hangs at this point. I even left it overnight but no progress.
I've even tried installing SQL Server 2012 management studio installation file but same issue again.
I tried to search for this kind of issue but no discussion found anywhere on internet. Any clue or pointers will be greatly appreciated. I've been trying since last couple of days but no luck.
Other details:

OS: Windows 10 Pro
Visual Studio 2015 Community edition installed
All windows updates are up to date
Downloaded management studio from MS site and File version is 12.0.2000.8

If any other details needed please let me know.
See below image:
Answer: Disabling AVG virus protection before starting the install setup allowed me to proceed with the install past this point
Answer: Try to  search for ngen.exe in task manager. After shutting down the process, installation runs smoothly. It might occur several times, so keep an eye if it`s not restarting.
Hope that helps :)


Tabela mestre detalhe, campos totalizadores

Question: Estou fazendo um controle de ordem de serviço onde em uma ordem de serviço vários usuários irão cadastrar produtos e mão de obra, sendo assim possuo três tabelas:
- Ordem de serviço (mestre)
- Produtos (detalhe)
- Mão de obra (detalhe)
As tabelas detalhes geram valores que terão que representar um total na tabela mestre, por exemplo um valor total de produtos e um valor total de mão de obra.
Gostaria de saber qual a melhor forma de obter este valor total se é usando recurso de consulta do banco de dados ou é melhor fazer um loop usando programação nas tabelas detalhes, lembrando que o sistema será multiusuário.
Answer: Tanto faz, na verdade, você pode obter esta soma com um SUM e trazer os dados já mastigados para a aplicação, isso ganha um pouco na performance e na facilidade de programar, visto que a complexidade para gerar este cálculo no banco é realmente muito menor e você não tem que adicionar a complexidade lógica da iteração na sua aplicação, ela se torna literalmente um processador apenas.
Eu votaria pelo banco.


Prove that there exists a unique topology $T$ for which $ P $ is its subbasis and that topological space $ ( T, \mathbb{N ^{*}})$ is metrisable .

Question: Let  $ \infty = \left\{ \mathbb{N} \right\}$ and $ \mathbb{N ^{*}} = \mathbb{N} \cup \left\{ \infty \right\}$. Let $$ P = \left\{ \left\{1\right\} \right\} \cup
\left\{ \left\{n, n+1 \right\} \mid n \in \mathbb{N} \right\} \cup
\left\{ \left\{ k \in \mathbb{N} \colon k \geq 2n \right\} \cup \left\{ \infty \right\} \mid n \in \mathbb{N} \right\} $$
Prove that there exists a unique topology $T$ for which  $ P $ is its subbasis and that topological space $ ( T, \mathbb{N ^{*}})$ is metrisable .
Proving that there exists a unique topology should be simple enough by showing that $P$ covers $ \mathbb{N ^{*}}$ . But as for the metrisability I am thinking maybe it can be metrisable with discrete metric, but I can't prove that $ \left\{ \left\{ \mathbb{N} \right\} \right\}$ is open ( all other sets $ \left\{ n \right\} $ are open)
Comment: Define $d(n,\infty)=1/n$ and $d(n,m)=1$ for $n\neq m$ and both $\neq\infty$.
Comment: The topology consists of all subsets of $\mathbb{N}$ together with the sets $V_{U,k}=U\cup\{n\in \mathbb{N}:\ n>k\}\cup\{\infty\}$, for $k\in\mathbb{N}$ and $U\subset \mathbb{N}$.
Comment: "All other sets $\{n\}$ are open" Why don't you union them then?
Comment: Don't I then get $ \mathbb{N} $, not $ \left\{  \mathbb{N} \right\}$ ( the set that contains it)
Answer: This topology is basically the one point compactification of $\mathbb N$, which is homeomorphic to $X=\{0\}\cup\{\frac{1}{n}\}_{n\in \mathbb N}$ in the usual metric topology via the map
\begin{align}& n\mapsto\frac{1}{n},  \quad n\in \mathbb N \\ &\infty\mapsto0 \end{align}
It is easy to prove that every element of $P$ is open in the metric topology. We consider the reverse direction. Let $U$ be an open set (in the metric topology) and $x\in U$. We want to find an open set $V$ (in the topology generated by $P$) such that $x\in V\subset U$.
If $x\neq0$, then $x=\frac{1}{n}$ for some $n$. we can let $V=\{\frac{1}{n}\}$. If $n=1$, then $V$, being an element of $P$, is open. If $n\neq1$, notice $$V=\left\{\frac{1}{n-1},\frac{1}{n}\right\}\bigcap\left\{\frac{1}{n},\frac{1}{n+1}\right\},$$ which is the intersection of two elements of $P$, hence open.
If $x=0$, there exists $n\in \mathbb N$ such that $0\in[0,\frac{1}{n}]\cap X\subset U$ ($\because$every open set in the metric topology is a union of open balls). Without loss of generality, we can assume $n$ is even. Then we can simply let $V=[0,\frac{1}{n}]\cap X$. Again, $V$ being an elements of $P$, is open.


How to restore solaris zone?

Question: I posted an earlier question on how to backup and delete the solaris zone:
How to backup and remove solaris zones?
But i like to ask also how can i restore the solaris zone just in case next time i need to access the files or the environment inside the old solaris zone?
Comment: This would depend on how you chose to back up your zones.
Answer: Here is one way I've done it.  Depends on whether you backed up the zone with the pax command
<code># mkdir -m 700 -p /zpool/zones/10gr2
# cd /zpool/zones/10gr2/
# ls ../..
oracle10gr2.pax  zones
# pax -r@f ../../oracle10gr2.pax
# zonecfg -z oracle10gr2
oracle10gr2: No such zone configured
Use 'create' to begin configuring a new zone.
zonecfg:oracle10gr2> create -a /zpool/zones/10gr2
zonecfg:oracle10gr2> exit
</code>
Attach the new zone to the new host
<code># zoneadm -z oracle10gr2 attach
These packages installed on this system were not installed on the source system:
        SUNWpostgr-82-client (11.10.0,REV=2007.04.27.13.04)
        SUNWpostgr-82-contrib (11.10.0,REV=2007.04.27.13.04)
        SUNWpostgr-82-devel (11.10.0,REV=2007.04.27.13.04)
        SUNWpostgr-82-libs (11.10.0,REV=2007.04.27.13.04)
        SUNWpostgr-82-server (11.10.0,REV=2007.04.27.13.04)
        SUNWpostgr-82-server-data-root (11.10.0,REV=2007.04.27.13.04)
        SUNWpostgr-83-server-data-root (11.10.0,REV=2008.06.05.09.31)
</code>
At this point, we'll have to upgrade the new zone's packages, so run with the -u option:
<code># zoneadm -z oracle10gr2 attach -u
Getting the list of files to remove
Removing 5 files
Remove 12 of 12 packages
Installing 24 files
Add 19 of 19 packages
Installation of these packages generated warnings: SUNWpostgr-82-server-data-root
Updating editable files
The file </var/sadm/system/logs/update_log> within the zone contains a log of the zone update.
# zoneadm -z oracle10gr2 boot
# zlogin -C oracle10gr2
</code>

How to restore solaris zone?


Functional Equation: $f \left(x+\cos(2017y) \right)=f(x)+2017\cos\left(f(y)\right)$

Question:
Find all functions $f: \mathbb R \rightarrow \mathbb R$, such that for all $x,y \in \mathbb R$ satisfies the equation:
  $$f \left(x+\cos(2017y) \right)=f(x)+2017\cos\left(f(y)\right)$$

My work so far:
Let $f(0)=c$.
1) $x=0 \Rightarrow f\left(\cos(2017y)\right)=c+2017\cos\left(f(y)\right)$
2) $y=0\Rightarrow f(x+1)=f(x)+2017 \cos c$
Comment: Can we assume that $f$ is continuous? Can we assume $f$ is differentiable?
Comment: @flawr: We can't assume that $f$ is continuous
Answer: For simplicity, let $ a := 2017 $. I claim that the only solutions to the functional equation
$$ f \big( x + \cos ( a y ) \big) = f ( x ) + a \cos f ( y ) \tag 0 \label 0 $$
are the functions of the form $ f ( x ) = n \pi + ( - 1 ) ^ n a x $, where $ n $ is a constant integer. It's easy to check that these functions indeed satisfy \eqref{0} and we only need to prove that every solution is of this form.
First, defining $ c := f ( 0 ) $ and letting $ x = 0 $ in \eqref{0} we have:
$$ f \big( \cos ( a y ) \big) = c + a \cos f ( y ) \tag 1 \label 1 $$
So, combining \eqref{0} and \eqref{1} and substituting $ \frac y a $ for $ y $, we get:
$$ f ( x + \cos y ) = f ( x ) + f ( \cos y ) - c \tag 2 \label 2 $$
For simplicity, we define $ g ( x ) := f ( x ) - c $ and \eqref{2} gives us:
$$ g ( x + \cos y ) = g ( x ) + g ( \cos y ) \tag 3 \label 3 $$
By \eqref{3}, we can inductively show that for every positive integer $ m $:
$$ g ( m \cos y ) = m g ( \cos y ) \tag 4 \label 4 $$
Now, for arbitrary real number $ x $ and $ y $, we choose the positive integer $ m $ in a way that $ \big| \frac x m \big| < 1 $, $ \big| \frac y m \big| < 1 $ and $ \big| \frac { x + y } m \big| < 1 $. So there are real numbers $ \alpha $, $ \beta $ and $ \gamma $ such that $ \frac x m = \cos \alpha $, $ \frac y m = \cos \beta $ and $ \frac { x + y } m = \cos \gamma $. Now by \eqref{3} and \eqref{4} we have:
$$ g ( x + y ) = g ( m \cos \gamma ) = m g ( \cos \gamma ) = m g \Big( \frac { x + y } m \Big) = m g ( \cos \alpha + \cos \beta ) \\ = m g ( \cos \alpha ) + m g ( \cos \beta ) = g ( m \cos \alpha ) + g ( m \cos \beta ) = g ( x ) + g ( y ) $$
So $ g $ satisfies Cauch's functional equation. Also by \eqref{1} we have $g \big( \cos ( a y ) \big) = a \cos \big( c + g ( y ) \big)$. Thus $ g $ is a bounded function on the interval $ [ -1 , 1 ] $, since $ \cos $ is a bounded function. This shows that $ g $ must be of the form $ g ( x ) = b x $ for some constant real number $ b $ (see here). Hence we have:
$$ b \cos ( a y ) = a \cos ( b y + c ) $$
It takes some effort to show that this leads to $ c = n \pi $ for some constant integer $ n $, and $ b = ( - 1 ) ^ n a $ for the same $ n $.


How does pooling work with crossed effects in multilevel models?

Question: In Section 12.2 of Gelman and Hill, The authors mention that one of the main benefits of creating a multi-level model is that you can take advantage of "partial pooling". As an example, if you were creating a two-level hierarchical model of test scores by state and county, then each county's predicted estimate would be a weighted average of that county's average test score and the overall state's score.
In more complex models, I've seen additional random effects added. For example, a model might contain state, county, gender, and race. In this case, the model is no longer strictly hierarchical, and we now have crossed effects.
In this case,
1) I assume the effect of county is still based on a pooled estimate. Are the effects of gender and race still being pooled in some way? If so, how?
2) Would this model be considered a two-level model or a four-level model?
edit: For clarification, the data for race and gender in this example would be at the individual level (they are not county or state-level characteristics).
Comment: I think you need to clarify your question about race. If you are talking about individuals within the county, within the state, you are adding levels to your model. If you are talking about race and gender in terms of county estimates, you are not adding levels. The main thing is to determine your unit of analysis and then the hierarchical structure of the groups associated with that unit.
Comment: Please register &/or merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own question.
Answer: I don't have access to the Gelman and Hill book at the moment. However, the normal meaning of "partial pooling" simply refers to a model with random effects. It is "partial" pooling because (in the case of random intercepts) each subject has their own intercept (often assumed to be normally distributed across subjects) plus the additional group level mean estimate.
The number of levels in a mixed / multilevel model is determined by the levels of nesting. If your unit of measurement is individuals, and they are nested within counties, and counties are nested within states, then you have a 3-level model. The addition of gender and race does not affect this (because they are measured at the individual level. If you had states nested within countries, then you would have a 4-level model.


How to solve error Conversion failed when converting the nvarchar value to data type integer?

Question: I work on SQL Server 2014 with a dynamic query; I get this error when I run the query:

Conversion failed when converting the nvarchar value '24VAC/DC' to data type int.

I got error when executing this dynamic SQL
EXEC (@SQL)

How to solve this error please?
Data sample
IF OBJECT_ID('dbo.TAllfeatures') IS NOT NULL
    DROP TABLE dbo.TAllfeatures

IF OBJECT_ID('dbo.TCondition') IS NOT NULL
    DROP TABLE dbo.TCondition

IF OBJECT_ID('dbo.TPartAttributes') IS NOT NULL
    DROP TABLE dbo.TPartAttributes

IF OBJECT_ID('dbo.TAllData') IS NOT NULL
    DROP TABLE dbo.TAllData

CREATE TABLE [dbo].[TAllfeatures]
(
     [ZPLID] [int] NULL,
     [ZfeatureKey] [bigint] NULL,
     [FeatType] [int] NULL,
     [AcceptedValueID] [int] NULL,
     [IsNumericValues] [int] NULL
) ON [PRIMARY]
GO

INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, NULL, 0, 0, 0)
INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, 1505730001, 2044, 155, 0)
INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, 1505730011, 2044, 274, 1)

INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, 1505730036, 2044, 271, 0)

CREATE TABLE [dbo].[TCondition]
(
     [TradeCodeControlID] [int]  NOT NULL,
     [VersionYear] [int] NULL,
     [Version] [float] NULL,
     [CodeTypeID] [int] NULL,
     [RevisionID] [bigint] NULL,
     [Code] [varchar](20) NULL,
     [ZPLID] [int] NULL,
     [ZfeatureKey] [bigint] NULL,
     [ZfeatureType] [nvarchar](200) NULL,
     [EStrat] [nvarchar](2500) NULL,
     [EEnd] [nvarchar](2500) NULL
) ON [PRIMARY]

INSERT INTO [dbo].[TCondition] ([TradeCodeControlID], [VersionYear], [Version], [CodeTypeID], [RevisionID], [Code], [ZPLID], [ZfeatureKey], [ZfeatureType], [EStrat], [EEnd])
VALUES (8123, 2020, 26, 849774, 307683692, N'8535400000', 75533, 1505730001, NULL, N'In(''Surge Protector'',''Surge Protector for Media Lines Only'',''Outlet Strip, Surge Protector'',''PDU, Surge Protector'',''Surge Lightning Arrester'',''Surge Arrester'',''Surge Protection Module'',''Lightning Arrester'',''Lightning Current Arrester'',''Protection Device'',''Surge Voltage Equipment'',''Isolated'',''Surge Protection'',''Coaxial'',''Base Element'')', N'')

INSERT INTO [dbo].[TCondition] ([TradeCodeControlID], [VersionYear], [Version], [CodeTypeID], [RevisionID], [Code], [ZPLID], [ZfeatureKey], [ZfeatureType], [EStrat], [EEnd])
VALUES (8124, 2020, 26, 849774, 307683692, N'8535400000', 75533, 1505730036, NULL, N'>1000', N'')

CREATE TABLE [dbo].[TPartAttributes]
(
     [PartID] [int] NOT NULL,
     [ZfeatureKey] [bigint] NULL,
     [AcceptedValuesOption_Value] [float] NULL,
     [Name] [nvarchar](500) NOT NULL
) ON [PRIMARY]
GO

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128078, 1505730036, 24, N'24VAC/DC')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128078, 1505730001, NULL, N'Surge Voltage Equipment')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128089, 1505730036, 5, N'5V')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128089, 1505730001, NULL, N'Attachment Plug')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (27912821, 1505730001, NULL, N'Surge Protection Module')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (27912821, 1505730036, 480, N'480V')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (32817870, 1505730001, NULL, N'Surge Protector')

INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (32817870, 1505730036, NULL, N'120V, 240V')

CREATE TABLE dbo.TAllData
(
         PartID INT,
         Code VARCHAR(20),
         CodeTypeID INT,
         RevisionID BIGINT,
         ZPLID INT,
         ConCount INT
)

SET ANSI_PADDING ON
SET ANSI_WARNINGS ON

DECLARE @ConStr nvarchar(max) = STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , CAST(EStrat AS NVARCHAR(2500)),')')   --ValueName
                 FROM dbo.TCondition CC  INNER JOIN dbo.TAllfeatures AL with(nolock) ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValues =0
                 FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')

                 DECLARE @Sql nvarchar(max)= CONCAT('INSERT INTO dbo.TAllData(PartID,Code,CodeTypeID,RevisionID,ZPLID ,ConCount)',' SELECT  PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID,Count(1) as ConCount

                 FROM
                 dbo.TPartAttributes PM with(nolock)
                 INNER JOIN    dbo.TCondition Co with(nolock) ON Co.ZfeatureKey = PM.ZfeatureKey ',
                 'Where (1=1 and  ' ,  @ConStr,' ) Group By PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID ' ,
                 ' Having Count(1)>= ',(SELECT COUNT(1) FROM TCondition with(nolock)))

            --print @SQL
             EXEC (@SQL)

I try to solve issue but still issue exist
DECLARE @ConStr nvarchar(max)=  STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ''', CC.ZfeatureKey , '''', IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , LEFT(EStrat, 1), '''', SUBSTRING(EStrat, 2, LEN(EStrat) -1), ''')')   --ValueName
                       FROM dbo.TCondition  CC INNER JOIN dbo.TAllfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValues =0
                       FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')

Comment: Finally, why are you spamming the `NOLOCK` hint all over your queries here? Why are you using such a hint? `NOLOCK` isn't a "magic go faster button", it's a don't care about wrong data button. I suggest having a read of [Bad habits : Putting NOLOCK everywhere](https://www.sentryone.com/blog/aaronbertrand/bad-habits-nolock-everywhere)
Comment: Honestly, this is why I'm a massive advocate for making the dynamic SQL you produce well formatted too... A single line of SQL that is 600+ characters long isn't easy to read.
Comment: It's also generally advised to not use syntax such as `EXEC (@SQL);`. Such statements cannot be parametrised, which promote bad habits that result in security flaws like SQL injection. If you need to run a statement that is within a variable or literal string then use [`sys.sp_executesql`](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql). Then you can easily parametrise the statement if you need to.
Comment: The easiest way to debug dynamic SQL is to `PRINT`/`SELECT` the statement first. Then you can debug that SQL first, and solve the problem before propagating the solution to your SQL that generates the dynamic statement. Often you'll find that the problems are quite simple, such as a typographical error that is difficult to stop in the literal strings, a missing whitespace/linebreak, or leading/trailing delimiters. Taking the time to get the non-dynamic statement working first is really important, as if that doesn't work the dynamic one will have no chance of working correctly.
Comment: Actually, I'm not even sure why the above statement is dynamic; it seems you're using the dynamic statement to inject values for `Name` for the `IN` but you could just just an `EXISTS` for that. The more i look at this, more more I think this is a [XY Problem](//xyproblem.info).
Comment: Looking at said `PRINT`ed statement, what does `Name > 1000` mean? How can someone's name have a value greater than the `int` value `1000`?
Comment: query above exactly i need to change it from Name>1000 to Name >'1000' so can you help me . this is actually what i need to change
Comment: My honest answer is, probably get rid of the whole dynamic statement. Why are you using Dynamic SQL at all here?
Comment: because i have parameters variables
Comment: *"because i have parameters variables"* Huh? Parameters are allowed in normal statements...
Comment: [Dup on MS Q&A](https://learn.microsoft.com/en-us/answers/questions/648029/how-to-solve-error-conversion-failed-when-converti.html)
Comment: Aside... `VALUES`, it's plural. You can insert multiple rows in a single statement by comma-delimiting them, e.g.: `insert dbo.Example (A, B) values ('a', 1), ('b', 2), ... , ('z', 26);`
Comment: The MS Q&A dup is now marked as solved.
Answer: It appears you do not need dynamic SQL at all here.
It's hard to know what logic you are trying to achieve, owing to a lack of sample data and expected output, and your existing query could do with better formatting. But it looks like it's some kind of relational division.

Note that you should not use WITH (NOLOCK) unless you really know what you are doing. It can give wildly incorrect results.

I also strongly suggest you use table references on each column, especially within subqueries

INSERT INTO dbo.TAllData
    (PartID, Code, CodeTypeID, RevisionID, ZPLID, ConCount)
SELECT
  PartID,
  Code,
  Co.CodeTypeID,
  Co.RevisionID,
  Co.ZPLID,
  Count(1) as ConCount
FROM dbo.TPartAttributes PM
INNER JOIN dbo.TCondition Co ON Co.ZfeatureKey = PM.ZfeatureKey
Where EXISTS (SELECT 1
    FROM dbo.TAllfeatures AL
    WHERE AL.ZfeatureKey = Co.ZfeatureKey
      AND AL.IsNumericValues = 0
      AND IIF(Co.ZfeatureType = 'Qualifications', AcceptedValuesOption_Value, Name) = EStrat
)
Group By
  PartID,
  Code,
  Co.CodeTypeID,
  Co.RevisionID,
  Co.ZPLID
Having Count(1) >= (SELECT COUNT(1) FROM TCondition);


Let $(G,*)$ be a finite group and $a \in G$. Show that $\circ(a) \le |G|$.

Question: Let $(G,*)$ be a finite group and
$a \in G$. Show that $\circ(a) \le |G|$.
($\circ(a)$ denote the order of $a$.)
This is the given hint:
Suppose that $|G|=n$. Note that
$\{e_G,a,a^2,\ldots,a^n\} \subseteq G$ and $G$ has $n$ elements.
How to approach $\circ(a) \le |G|$?
Does the given hint means that: "there exists integers $p$ and $q$ with $p>q$ such that $a^p=a^q$.
Then, $a^{p-q} = e_G$. Write $m=p-q$ and hence $a^m = e_G$ for some integer $m$, with $0\le m \le n-1$." ?
Comment: What is ○? Order of the element?
Comment: the given "hint" is almost a complete answer, lol.
Comment: Yes, if you proceed by contradiction, ie, suppose that $o(a)\gt n$, then the hint implies there exist integers $0\le q\lt p\le n$ such that $a^{p-q}=e_G$ but note that $p-q\lt n$, which contradicts $o(a)\gt n$; the crux is that $\{a^0,a^1,\ldots,a^n\}\subseteq G$ has two elements same by PHP (pigeonhole principle) since it has $n+1$ elements which is greater than the cardinality of $G$ itself.
Comment: @SeanRoberson yes, the order of an element.
Comment: @Masacroso But, how to imply $\circ(a) \le |G|$ ?
Comment: @user795084 because $p,q\leqslant n+1$, that is, observe that the list $g,g^2,g^3,\ldots ,g^{n+1}$ have at most $n$ distinct elements
Comment: It is a normal English word, not a particular mathematical term: look up "crux definition" on Google.
Comment: No, I'm considering $0\le q$ because my argument uses the span of $a$ starting from $a^0=e_G$; since $q\lt p$, we have that $p-q$ is a positive integer and the argument applies. You can also consider $0\lt q\lt p\leq n\color{red}{+1}$ if your argument uses the list $a,a^2,\ldots,a^{n+1}$ and the previous argument applies.
Comment: @PrasunBiswas Why can $o(a) \gt n$ implies exists integers such that?
Answer: If all the elements of the set $\{e_G,a,a^2,\ldots, a^n\}$ were distinct, it would contain $n+1$ elements. As $G$ has only $n$ elements, there must be a repeat. Therefore, the argument you propose must follow.
Comment: Is ".... argument you propose...." refers to "Does the given .... ?" ?
Comment: Yes. $\hspace{1in}
Comment: If $a^m = e_G$ for some integer $0\le m \le n-1$, then it follows that the order of $a$ is always less than or equal to $|G|$, isn't it?
Answer: What about this approach?
Suppose that $|G| = n$. Let $a \in G$
and $\circ(a) = k$. Let $H = \langle a \rangle$. Then, $|H| = |\langle a \rangle| = \circ(a) = k$. Hence, by Langrange's Theorem, $k$ divides $n$ and
thus $k \le n$ as desired.
Comment: All I'm saying is that if you just want to prove $k\leq n$, then you don't need Lagrange's Theorem. You have the set $H$ (which has size $k$) as a subset of the set $G$ (which has size $n$). So clearly $k\leq n$. In other words, in your proof replace "Hence, by Lagrange's Theorem, $k$ divides $n$" with "$H$ is a subset of $G$". You obtain a perfectly good proof of $k\leq n$ that does not mention Lagrange's Theorem.
Comment: Can I write $\langle a \rangle$ by $\{e_G,a,a^2,\ldots,a^{n-1}\}$?
Comment: If $\circ(a)=k$ then $\langle a\rangle =\{e_G,a,a^2,\ldots,a^{k-1}\}$. Note that Lagrange's Theorem is overkill if you just want $k\leq n$ (versus $k|n$ which is stronger). You have $|H|=k$, $|G|=n$, and $H\subseteq G$. So $k=|H|\leq |G|=n$.
Comment: @halrankard2 What proof that not using Lagrange? I mean, the elementary proof.
Comment: @halrankard2 Is the above approach (on question) implies order of $a$ is less than or equal to order of $G$?
Answer: How about the theorem of Lagrange?  For one number to divide another it must not be greater than it.
Comment: Since two of the first $n+1$ powers of $a$ have to be equal, we get that $a^k=a^l\implies a^{k-l}=e\implies |a|\mid(k-l)\implies|a|\le n$.
Comment: How to prove without Lagrange? I mean, the elementary proof and only using the definition of order of an element in group.


Rules token one-time-login-url is showing up empty

Question: I have a rule that, after submitting a webform, a user gets created and then sends two emails to that user.  One saying their form data is being looked at by someone for review before they get a certain role, and another that gives them the one-time login url.  The problem is the that, while the rule works and both emails get sent, the login url is not displayed in the second email.
<code>{ "rules_application_submission_affiliate" : {
    "LABEL" : "Application submission: Affiliate",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules", "php" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "[form-id:value]",
          "selected_webform" : { "value" : { "webform-client-form-101" : "webform-client-form-101" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_name" : "\u003C?php echo $data[\u0027components\u0027][\u0027your_username\u0027][\u0027value\u0027][0]; ?\u003E",
            "param_mail" : "\u003C?php echo $data[\u0027components\u0027][\u0027your_e_mail\u0027][\u0027value\u0027][0]; ?\u003E"
          },
          "PROVIDE" : { "entity_created" : { "new_user" : "New user" } }
        }
      },
      { "entity_save" : { "data" : [ "new-user" ] } },
      { "user_unblock" : { "account" : [ "new-user" ] } },
      { "mail" : {
          "to" : "[data:your_e_mail-value]",
          "subject" : "Thank you for your application!",
          "message" : "Your application is being processed.  You will receive another email when your account is ready for activation.",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : "[new-user:mail]",
          "subject" : "Your account is ready!",
          "message" : "You may activate your account by going to this link to set your password:\r\n[new-user:one-time-login-url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}
</code>
Answer: The problem was on the "save entity" action, I had to force it to save by checking "force" on the action, because the entity would only get saved after the other actions had been applied.


Array de dados recuperados de uma response

Question: tenho um serviço rest q retorna macs provenientes de uma varredura,o modelo de json e este:
{
"macs": [
    {
        "mac": "9C:5C:F9:66:73:34"
    },
    {
        "mac": "B8:A3:E0:72:9E:EA"
    },
    {
        "mac": "00:E0:4C:2A:26:60"
    },
    {
        "mac": "00:E0:4C:76:0A:A7"
    },
    {
        "mac": "00:E0:4C:0D:C7:58"
    },
    {
        "mac": "00:E0:4C:79:7A:17"
    },
    {
        "mac": "00:E0:4C:07:72:D9"
    },
    {
        "mac": "00:E0:4C:60:97:77"
    }
  ]
}

Tenho os sequintes arquivos:
mac.component
export class MacComponent implements OnInit {
@Input() mac:Mac
constructor() { }

 ngOnInit() {
  }

 }

mac.model
export interface Mac{
mac:string
}

mac.service
@Injectable()
 export class MacService {

 constructor(private http: Http) { }

 getMacs():Observable<Mac[]>{
 return this.http.get('http://localhost:3000/macs')
 .map(response => response.json())

  }

 }

macs.component
export class MacsComponent implements OnInit {
macs:Mac[]
constructor(private service:MacService) { }

ngOnInit() {
    this.getMacs()
}
getMacs(){
    this.service.getMacs().subscribe(macs => this.macs = macs)
    console.log(this.macs);

}
printMacs(){
    console.log(this.macs);

}
}

quando eu dou o print no 'macs' ele vem como undefined,eu preciso de um array de macs de retorno
Answer: A chamada ao serviço está correta. Mas ela pode ter falhado e, por isto, você não teve um objeto de retorno. Olhe no console do navegador se a chamada foi bem sucedida, o erro por ser de  CORS.
Além disso, o retorno da sua API não é um array, mas sim um objeto que possui um membro (macs) que é um array. Você precisa atualizar sua API para retornar diretamente um array ou atualizar a chamada da API, como abaixo:
@Injectable()
 export class MacService {

 constructor(private http: Http) { }

 getMacs():Observable<Mac[]>{

      return this.http.get('http://localhost:3000/macs')
       .map(response => response.json())
       .map(jsonRet => jsonRet.macs);

  }

 }

A sua chamada do console.log dentro do método getMacs(), sempre retornará null (se nunca for inicializada), porque ela deve ficar dentro do subscribe, já que a chamada é sempre assíncrona, veja:
getMacs(){
  this.service.getMacs().subscribe(macs => {

      this.macs = macs;
      console.log(this.macs);

    }, error => console.log('ocorreu um erro na chamada', error)
  );

}
Comment: Tentei fazer isso e deu esse erro Property 'macs' does not exist on type 'Mac[],tentei ate mudar de interface a classe mas permaneceu o mesmo
Comment: Tenta razão, o Typscript vai dar erro mesmo. Isto, porque seu Observable é do tipo Observable. A minha sugestão foi pelo retorno da sua API, não tinha prestado muita atenção no retorno do observable. Vou atualizar minha resposta.
Comment: funcionou,muito obrigado!!