Spring 3.1, Aspect, Tomcat - circularity error

Question: I have a pretty complex web-application where the whole DAO has been outsourced to an @Aspect class which will load database entities whenever methods are accessed which need those.
This whole approach is working wonderfully when the web app is launched from netbeans. However, when I try to deploy the same .war to a standalone tomcat (same version of tomcat, same version of java), I get the following exception upon startup:
Caused by: java.lang.IllegalArgumentException: Advice precedence circularity error
And I just can't figure out what is causing the problem and why the application runs fine when starting through netbeans.
Maven config:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <fork>false</fork>
                <meminitial>256m</meminitial>
                <maxmem>768m</maxmem>
                <source>1.6</source>
                <target>1.6</target>
                <encoding>${project.build.sourceEncoding}</encoding>
                <showWarnings>true</showWarnings>
                <showDeprecation>false</showDeprecation>
                <debug>true</debug>
                <debuglevel>lines,vars,source</debuglevel>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                    </manifest>
                </archive>
                <webXml>src\main\webapp\WEB-INF\web.xml</webXml>
            </configuration>
        </plugin>

Spring: 3.1.0.RELEASE:
<context:annotation-config />
<context:component-scan base-package="my.package" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<aop:aspectj-autoproxy />

Java version:
java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)

I honestly don't know what info I should include in this post as I don't even know where to start... Feel free to ask for more information if needed.
Comment: When you say 'the same WAR', do you mean the *same*? Or is the WAR running in NetBeans generated by NetBeans and the other by the maven-war-plugin?
Comment: Hm.. I always thought both are built using the maven-war-plugin? But one is run by pressing 'Run' in netbeans and the other one is built by maven-war-plugin
Comment: Maybe, I have not used NetBeans for a long time but depends on your run configuration. I use IntelliJ, and it does not (at least for my default setup). I suppose it'd be worth comparing the WARs, perhaps running both exploded would help to diagnose the problem.
Comment: There is not much to compare - I have only one war. I don't know what netbeans does different .. maybe changing something on the tomcat? I copied my exploded directory from netbeans /target/ directory onto my server machine. Running the exploded war didn't change anything
Comment: Oh ok. So two different machines, both 64bit? And the working WAR when run via NetBeans is copied across to the server machine, dropped in the 'webapps' directory of Tomcat, Tomcat then fails to deploy it with the error above? Have you got any other exceptions (regardless of whether they are all linked) or any WARNINGs/SEVEREs logged?
Comment: Two different machines. One is Win7 64bit (where netbeans is run) the other is a Linux version 2.6.32-5-amd64 (Debian 2.6.32-35squeeze2). I run via netbeans (or build - makes no difference), take the localy working .war, copy it over to the linux's tomcat's webapp dir, start the linux's tomcat and get just that error I stated.
Answer: This isn't necessarily a complete answer but the links should be helpful:
It sounds as if the difference here is that your machines are returning the order of declared methods, of a particular class, differently, which changes how Aspect advices are run:

Spring uses getDeclaredMethods to determine the order of the advices,
  but getDeclaredMethods returns methods in unspecified order. (see more)

There is also a Spring ticket for an issue that sounds very similar to yours:
SPR-5314
Hope that's a little helpful. Good luck.
Comment: http://forum.springsource.org/archive/index.php/t-58498.html - might also be a good read.
Comment: It indeed looks like the different JDKs cause the problems. I will get a Win7 machine tomorrow to where I can deploy - maybe this will fix things..
Comment: Thanks for your help. I stumbled across all these postings already - not very satisfied with my research though. The ticket is from 2008. There has to be some fixing until now I suppose. This problem can't be THAT uncommon, can it?
Comment: A little late to the party, but apparently the different JDKs was the problem :)


Identity for natural log of matrices

Question: Let $A$ and $B$ be square matrices such that $\ln (A)$ , $\ln (B)$ and $\ln (AB)$ are all defined. Is it true that $$\ln (AB)= \ln (A) + \ln(B)$$ only if $AB=BA$ ?
I appreciate any help, Thanks
Comment: If $A$ and $B$ commute, we can check that $\ln(AB) = \ln(A) + \ln(B)$ by considering the series involved. And if $A$ and $B$ do not commute, we can't have both $\ln(AB) = \ln(A) + \ln(B)$ and $\ln(BA) = \ln(A) + \ln(B)$, as that would imply $\ln(AB) = \ln(BA)$.
Comment: @JoelCohen Thank you !
Answer: If $A$ and $B$ commute, we can check that $\ln(AB)=\ln(A)+\ln(B)$ by considering the series involved. And if $A$ and $B$ do not commute, we can't have both $\ln(AB)=\ln(A)+\ln(B)$ and $\ln(BA)=\ln(A)+\ln(B)$, as that would imply $\ln(AB)=\ln(BA)$.
In all generality, we have the Baker-Campbell-Hausdorff to express $Z = \ln(AB)$ in terms of $X = \ln(A)$ and $Y = \ln(B)$ (whether $A$ and $B$ commute or not). The formula is rather complicated and involves nested commutators : if $C$ $D$ are matrices, we define the commutator of $C$ and $D$ to be $[C,D] = CD-DC$ (this quantity is $0$ if and only if $C$ and $D$ commute). With this notations, the formula can be written as
\begin{eqnarray*}
Z &=& X + Y \\
&+& \frac{1}{2}[X,Y] \\
&+& \frac{1}{12}([X,[X,Y]]+[Y,[Y,X]]) \\
&-& \frac{1}{24} [Y,[X,[X,Y]]] \\
&& \quad\vdots
\end{eqnarray*}
Of course, if $A$ and $B$ commute, all commutators terms vanish and we simply get $Z = X + Y$, as expected.

Identity for natural log of matrices


How can we move recent updated item on top in AdvancedCollectionView uwp

Question: I  have a ListView which ItemSource is binded to an AdvancedCollectionView. This collection stores a list of some users' chat messages. Now I want to shift that item on top whenever that user receives a new chat message. Likewise in WhatsApp and slack app.
Right now I am Removing and adding items every time I receive a new message.
So I want to know if there is any property of AdvancedCollectionView which I can use or if sorting is possible.
Comment: Have you checked my reply and does it work for your?
Answer: I have to say that there is no such property of AdvancedCollectionView could directly do that. But a workaround for your scenario is that you could apply another SortDescription for the AdvancedCollectionView at the same time. This makes it possible to shift an item on top with a new property.
For example, you could add a new property called Top in your model, the default value is B. When you need to put an item on the top, change the Top value to A. Then apply a new sort description that relies on the Top property.
I've made a simple demo and you could refer to it.
Code-behind:
 public ObservableCollection<Person> oc { get; set; }
    public MainPage()
    {
        this.InitializeComponent();

         oc = new ObservableCollection<Person>{
            new Person { Name = "Staff" ,Top="a"},
            new Person { Name = "Orchid",Top="b" },
            new Person { Name = "Tempest" ,Top="b"},
            new Person { Name = "Lamp Post",Top="b" },
            new Person { Name = "Arrow" ,Top="b"},
            new Person { Name = "Swan" ,Top="b"},
            new Person { Name = "Flame",Top="b" },
            new Person { Name = "Pearl" ,Top="b"},
            new Person { Name = "Hydra" ,Top="b"},
            new Person { Name = "Looking Glass",Top="b" },
        };

        var acv = new AdvancedCollectionView(oc, true);
        //make the Staff item always on the top
        acv.SortDescriptions.Add(new SortDescription("Top", SortDirection.Ascending));
        // sort by name
        acv.SortDescriptions.Add(new SortDescription("Name", SortDirection.Ascending));

        MyListView.ItemsSource = acv;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var person = new Person { Name = "Aardvark",Top = "b" };
        oc.Add(person);
    }

 public class Person
    {
        public string Name { get; set; }
        public string Top { get; set; }
    }

XAML:
 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Button Content="Click" Click="Button_Click"/>
    <ListView x:Name="MyListView" Grid.Row="1">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Person">
                <Grid>
                    <TextBlock Text="{x:Bind Name}"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

The result looks like this:


Resizing a triangle with a scalar value

Question: I have came across a really sticky problem here. I am asked to resize a triangle by a given scalar value. (I am given the co-ordinates of the 3 vertices and the center of triangle can easily be evaluated as a result).That would be all.
Thanks in advance
Comment: If you multiply all coordinates by a scalar $k$ you resize the triangle. If there are more restrictions that make this solution unacceptable you need to edit your question to tell us what they are.
Comment: @EthanBolker basically I am told to design a program that takes a scalar value and resizes the triangle to a triangle with area k times the area of the original triangle. as long as this condition is met, it should be all good
Comment: If you scale all the coordinates  (hence all the lengths)  by $k$ you scale the area by $k^2$. Now can you figure out how to scale the area by $k$?
Comment: @EthanBolker By multiplying the lengths by square root of k. but I am just lost when it comes to co-ordinates should I just multiply each (x,y) with square root of k?
Comment: That's all you have to do. I suggest drawing a picture of a triangle with simple coordinates and seeing  what happens when $k=4$, doubling all the coordinates.
Comment: @EthanBolker Wow that worked really, thanks alot! how didn't I think of that :D
Comment: You can post an answer to your own question now.
Answer: It's simply multiplying the (x,y) co-ordinates of each vertex by square root of the desired scalar value.

Resizing a triangle with a scalar value


Optimize Xeon 1270

Question: We have a new server with a Xeon 1270 processor. Looking at CPU-Z I see the Core Speed as 1596MHz, with a Multiplier of x16, and a Bus Speed of 99.8MHz.
I've been watching it for a while and sometimes noticed how the core speed jumps up to about 3GHz, which would match the advertised Clock Speed of 3.4GHz on Intel's website.
Is the core speed reported by CPU-Z and the clock speed on the Intel's website the same thing? Should I expect to have the core speed to be at 3.4GHz, rather than 1.5GHz?
The server doesn't have a lot of constant traffic, rather small bursts that don't seem to be enough to kick the CPU into a higher frequency. Am I correct in thinking that in my scenario, given that the CPU stays mostly constant at 1595MHz, we are getting much less than the benchmarked performance for this CPU?
Would you disable the Intel Turbo Boost? We have configured the power options to be high performance, but it doesn't seem to make a difference -- I read somewhere that the BIOS probably doesn't let Windows make the necessary changes.
Thank you,
Peter
Comment: Are you monitoring performance because it seems like good practice or because of a throughput issue? Does performance monitoring show a bottleneck with the CPU? As Coding Gorilla says, the modern processors will adjust their clock speed to deal with the workload facing them efficiently.
Comment: I'm "monitoring" it with the goal of having fast page loads. If it really doesn't matter if the frequency is 1.5GHz or 3.4GHz, as counter intuitive as it is, I'd be willing to let it go. Are there any tests/benchmarks about this scenario?
Answer: If you check wikipedia's description of "Intel Turbo Boost" (http://en.wikipedia.org/wiki/Intel_Turbo_Boost) you'll probably understand this a little better.  Essentially, the CPU stays at a lower clock speed to conserve power until the system decides that it needs the extra horse power, in which case (as you noted) the CPU frequency jumps up for a few seconds to finish that workload, and then drops back down.
This doesn't mean you're getting any less performance, realistically; if the work load required more performance the clock speed would likely stay at the higher rate for a longer period of time.  But since it's going right back down, then you just don't need the extra performance.  I personally would leave it alone, save on your electric bill, your server is obviously not overloaded or anything so the performance is fine.
Comment: It doesn't work that way; the only way to increase a pages rendering speed (or any other process completion time generally) is to start doing multi-threading and stuff like that.  It takes a fixed amount of time for the processor to process a set of instructions, the clock speed doesn't really affect that time.  In reallity, those kinds of things are almost always more affected by things external to the CPU such as disk i/o, memory i/o, network i/o, etc.  Unless you're doing some extremely intense computations, you're not losing anything.
Comment: The question is how you define workload. If rending a page takes let's say 800ms, but at full speed it would take 400ms, then, proved it takes 1s for the CPU to bump up the frequency, all my pages would render in 800ms rather than 400ms. That 1s is a guess...
Comment: What do you mean the CPU clock doesn't affect page rendering? Why are people overclocking then?
Comment: Typically you will see people overclocking for things like better 3d rendering and physics (games); that requires a lot of intense calculations, which perform [marginally] better under higher CPU clocks.  I've never heard of someone over-clocking a server (not that you couldn't); and it's not 100% true to say it has _no_ impact, but the impact is very minimal, I would go out on a limb and say that if you turned of Turbo Boost and forced the higher clock rate, you would not be able to see the difference in render speeds of the typical web page.
Comment: The way I understand it, this Turbo Boost is like an automatic "underclocking" to save power and then when it thinks it needs more power it clocks it back to the "base" (which if I understand correctly is 3.4GHz, anything higher is overclocking, up to a maximum of 3.8GHz), but normally runs underclocked at about 1.5GHz. If there is very little difference between 1.5GHz and 3.4GHz then wonderful, but I would need some kind of test/benchmark. Unfortunately I don't have one in front of me to try things out.
Comment: That's essentially correct (however Wikipedia describes it as the other way around), and it's not that there's no difference in the speed.  It's just not as simple as "faster cpu clock means everything gets done faster".  Again, you're not going to hurt anything by disabling it, so if that's your preference then do it.
Comment: Just to add onto what coding gorilla says, if disabling it does produce some massive leap in performance, this is a bug (whether with the motherboard firmware, OS or app) not a case of "oh that's the right way to configure that option".

Optimize Xeon 1270


Image style URL does not work

Question: I have an issue related to drupal image styles, and I am not able to fix it since last two days. Have searched and tried everything on google, but of not help.
I have a drupal instance on production where all the images are stored at imgs/<entity_type>/<entity_id>/<filename>.  All these files have three different styles: thumbnail, entity_image, and slide. All the styles were working initially. Now suddenly most of the times styles do not work. If I change the image, most of the time styles show old images, even if at the URL location no image is present. Sometimes, thumbnails are not getting created.
To resolve this, the following are the things I already tried:

drush image-flush: Did not help
Changed permissions of styles to 777:  Did not help
Cleared all caches several times: Did not help
Disabled and re-enabled clean URLs: Did not help
Created another instance and tested: Issue persists
Tried to create style forcefully using image_style_url: Did not help
Changed +FollowSymLinks to +SymLinksIfOwnerMatch in .htaccess: Did not help.
Commented Options None and Options +FollowSymLinks in .htaccess: Did not help

Initially it looked like a permission issue but after all this, I am not getting what could be wrong. It could be some issue with inode creation, but not sure. So, please let me know your suggestions, what should be done in this case.
EDIT: I disabled clean URLs and everything worked fine. Enabling clean URLs again gives the same issue. SO it has to do something with the menu I guess, but not sure about the fix. Need a permanent solution as I can not afford to keep clean URLs disabled.
Comment: @AnishSheela check my edit 2 in the problem statement, that should work...
Comment: Does your production environment have more than one server for the sake of performance (or whatever)? If so, do you have a shared file system so that the same images (at the same location) are always available regardless of which server a user or your site happens to be using?
Comment: No, there is only one server on production, hence there is not shared file system.
Comment: Can you check the response header of images? See if it is responded from server cache.
Comment: Same issue for me. I am using responsive module. The fallback image style only gets rendered.
Answer: I added following lines in modules/image/image.module, on line 1056 and it started working.
// Create derivated image if it doesn't exist.
  if (!file_exists($file_url) && !file_exists($uri)) {
    if (file_exists($path)) {
      $current_style = image_style_load($style_name);
      image_style_create_derivative($current_style, $path, $uri);
    }
  }

FYI: This change comes with a risk of when Drupal core updates, this will get removed. Also, I found it affected the performance of search in our platform. So, need a permanent solution.

Image style URL does not work


Want a clean explanation for GCC preprocessors

Question: When reading this document, at the end of it, there is one sentence:

Historically, compilers for many languages, including C++ and Fortran, have been implemented as "preprocessors" which emit another high level language such as C.

Have no idea about preprocessors, any document? Does it mean all these languages will be translated into C source codes?
Comment: Yes, that's what it means (assuming that by "C codes" you mean C source code).
Answer: I think it would have been better to use  the term  source-to-source translator instead of "preprocessors" which makes it ambiguous in meaning , but it ain't any wrong to use it either.
Basically , A compiler is a computer program  translates source code from a high-level programming language to a lower level language (e.g., assembly language or machine code).But the document in the question says :

Historically, compilers for many languages, including C++ and Fortran,
  have been implemented as "preprocessors" which emit another high level
  language such as C.

As per this description , it can be said that earlier , the compilers were implemented as source-to-source translator . A translator is also a form of preprocessor but its different from the preprocessor used in a program.

A translator is a computer program that translates a program written
  in a given programming language into a functionally equivalent program
  in a different language.

Now, coming to  preprocessor used in a program , lets take an example  :
#include <stdio.h>// a PREPROCESSOR directive

A preprocessor is a program that processes a source file before the
main compilation takes place,( similar to a translator ) but the difference lies in the fact that HERE it handles directives whose names begin with #.
Here #include is a directive. This directive causes the preprocessor to add the contents of the stdio.h file to your
program.This is a typical preprocessor action: adding or replacing text in the source code
before it's compiled.
Comment: After reading all answers here, now I got two points:

1. preprocessors here means source-to-source translator

2. GCC doesn't use this way today, generates machine codes directly
Comment: Nice! where did you find this detail? link may I have?
Comment: @DeanChen yeah !! there you go :)
Comment: @GrijeshChauhan Thanks !! Actually only the compiler and translator definition has been taken from http://en.wikipedia.org/wiki/Compiler" .. everything else is written by me :)
Answer: Some languages have been implemented by having the compiler generate C code which is then compiled by the C compiler.  Notable examples include:

C++ in the earliest days (and C with Classes before that) — cfront generated C code from the C++ code.  It ceased to be practical once C++ supported exceptions (read Stroustrup The Design and Evolution of C++ for more information), but not all C++ compilers used the technique (in fact, I don't know of any other compiler than cfront that did it).
Yacc is compiled to C code.  Bison can be compiled to C or C++ code.
Lex is compiled to C code. Flex can be compiled to C or C++ code, I believe.
Informix ESQL/C converts Embedded SQL into pure C.
Informix 4GL converts I4GL source into ESQL/C, and then uses the ESQL/C compiler to create C code (and the C compiler to create object code and executables), so it has a multi-stage compiler (and I'm simplifying a bit).
Answer: The phrase "preprocessor" now has a totally different meaning, and is confusing to be used here. But, yes, here it means some compilers emits its source to another language.
It should be called source to source compiler. One of the examples is Cfront (designed by Bjarne Stroustrup himself), which converted C++ to C.
For the normal meaning of the phrase  "preprocessor" in C++, see here.
Comment: @PHIfounder Maybe I didn't make myself clear enough. That's exactly what I meant. The last link is just for reference not to be confused about the normal meaning of the phrase "preprocessor".
Comment: I don't know if it is reasonable to call what Dart does "precompiling"; it implies that Javascript is itself compiled. Of course, most implementations of Javascript compile to some virtual machine or other, and some even have JITs which produce some machine code. Still, it seems like it is stretching the meanings. Also, you've left out the "ce" in "preprocessor", twice.
Comment: @rici Thanks, I deleted the Dart example from the answer, since it's not that relevant to the question(about gcc). Corrected the typo.
Comment: The "preprocessor" described in the document has a different meaning than that you prescribed the link for . It is clearly written that *This sort of preprocessor should not be confused with the C preprocessor, which is an integral feature of the C, C++, Objective-C and Objective-C++ languages.*
Comment: I think "preprocessor" is used just as a metaphor( I don't know what to call it ) which means other compilers produce another high-level language like C , unlike gcc compilers which produce machine code directly .
Answer: No. Not necessarily.  Many C++ compilers, LIKE THE GCC DOCUMENT SAID, (but not gcc/g++) produce C code output.  Why do they do this?  So they can piggyback on all the backend executable code that C compilers can compile to (X86, AMD, etc.)  By having C as their destination code,they save alot of low end coding on the back end.  Such compilers include the original Cfront and Comeau C/C++.
Comment: g++ certainly does not produce C code output, and neither does clang (compiling C++). I don't believe MS Visual C++ does -- it barely supports C. So what are these *most C++ compilers* of which you speak?
Comment: g++ never did. cfront was a quick proof of concept for c++, long abandoned, and hardly qualifies as "most if not all".
Comment: Cfront did it.  I think g++ used to do it, maybe not anymore.
Comment: You think wrong. And Cfront was only "most C++ compilers" back when it was the only one.
Comment: Comeau C/C++  was/is another one.


The search bar does not show any results

Question: I'm having a problem with the search bar. I typed the text I wanted to search into the search box but found nothing appeared even though the text was displayed in the normal ListView builder. Before I tried refactoring the code because I was stuck with the search bar. It doesn't work (not showing search results), but my ListView builder works fine.
enter image description here
<code>class _view_problemState extends State<view_problem> {
  TextEditingController _searchController = TextEditingController();

  List<problemModel> problemlist = [];
  List<problemModel> originalList = [];
  StreamController _streamController = StreamController();
  Future getAllProblem() async {
    problemlist = await problemcontrollers().getProblem();
    originalList = problemlist;
    _streamController.sink.add(problemlist);
  }

  @override
  void initState() {
    getAllProblem();
    super.initState();
  }

  void _filterSearch(String query) {
    List<problemModel> filteredList = [];
    for (var item in originalList) {
      if (item.toString().contains(query.toString())) {
        filteredList.add(item);
      }
    }
      setState(() {
      problemlist = filteredList;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color.fromARGB(255, 14, 12, 134),
        title: const Text('search'),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                onChanged: (value) {
                  _filterSearch(value);
                },
                 controller: _searchController,
                decoration: InputDecoration(
                    labelText: "search",
                    prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(25.0)))),
              ),
            ),
            Expanded(
              child: StreamBuilder(
                stream: _streamController.stream,
                builder: (context, snapshots) {
                  if (snapshots.hasData) {
                    return ListView.builder(
                        itemCount: problemlist.length,
                        itemBuilder: ((context, index) {
                          problemModel problem = problemlist[index];
                          return Card(
                            margin: EdgeInsets.all(10),
                            child: ListTile(
                              title: Text(
                                problem.name_surname,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 19),
                              ),
                              subtitle: Text(
                                problem.area,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 17),
                              ),
                            ),
                          );
                        }));
                  }
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                },
             ),
           )
         ],
       ),
     ),
   );
 }
</code>
}
Answer: <code>  void _filterSearch(String query) {
    List<problemModel> filteredList = [];
    for (var item in originalList) {
      if (item.name_surname.toLowerCase().contains(query.toString())) {
        filteredList.add(item);
      }
    }
      setState(() {
      problemlist = filteredList;
    });
  }
</code>


Wordpress Insert Query not working

Question: I am creating web services for an App, but I am stuck with a insert query. Actually I made a rating system and want to insert value in database with wordpress standard.
Here is my query:
$res = $wpdb->query( $wpdb->prepare(
                "INSERT INTO $table_name(rating_postid, rating_posttile, rating_rating, rating_username, rating_userid) VALUES (%d, %s, %d, %s, $d )",
                    array(
                        $rating_postid,
                        $post_title,
                        $post_rating,
                        $user_name,
                        $rating_userid
                    )
                )
            );

and here is the other one:
$res = $wpdb->insert(
                $table_name,
                array(
                    'rating_postid' => $rating_postid,
                    'rating_posttile' => $post_title,
                    'rating_rating' => $post_rating,
                    'rating_username' => $user_name,
                    'rating_userid' => $rating_userid
                )
            );

But no one is working, why?
if($res){
        echo 'inserted';
    }else{
        echo 'not inserted';
    }

I am getting else part alwasy
I used these queries very often and they worked me very well, But I am not sure what's wrong with them now... :(
Comment: Too many bees or candles, or something! No seriously, you've given us next to nothing that we can work with. What errors are you getting? How are you incorporating this code? Where is the rest of your code? What is the rest of your code?
Comment: Updated the post. There is no error while I am running this. I am just want to know if the query is correct or not?
Comment: @ManishNegi your query is correct.
Comment: @ManishNegi To answer that we need context! Since you say your query isn't doing what you want, the answer would presumably be 'NO'. ;-)
Answer: Try this.
        $wpdb->insert(
            $table_name,
            array(
                'rating_postid' => $rating_postid,
                'rating_posttile' => $post_title,
                'rating_rating' => $post_rating,
                'rating_username' => $user_name,
                'rating_userid' => $rating_userid
            ),
            array(
                '%d',
                '%s',
                '%s',
                '%s',
                '%d'
            )
        );

Comment: add this before insert query `$wpdb->show_errors();`.  and add this `exit( var_dump( $wpdb->last_query ) );` after insert query
Comment: Glad to help you.
Answer: Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object
global $wpdb;
$table_name = $wpdb->prefix . "YOUR_TABLE_NAME";    // Enter without prefix
$data = array(
    'rating_postid' => $rating_postid,
    'rating_posttile' => $post_title,
    'rating_rating' => $post_rating,
    'rating_username' => $user_name,
    'rating_userid' => $rating_userid
);

$result = $wpdb->insert($table_name, $data);
if( $result ){
    echo "Inserted..!";
}else{
    echo "Something wrong..!";
    $wpdb->show_errors();
}

Comment: @ManishNegi have you set this field `rating_postid` as a primary key?
Comment: @ManishNegi add this line `$wpdb->show_errors();` in `else` statement.
Comment: No 'rating_postid' is not not primary key. Primary key is 'rating_id' which is auto_increment in table

Wordpress Insert Query not working


Preenchendo textbox de um formulario com informações de um datagridview

Question: Tenho um datagrideview em um formulário, e preciso que quando clique na célula de datagridview ele preencha dois campos em outro form.
Como mostro na imagem abaixo.

segue também meu código
public partial class frmFaturaAnual : Form
{

    SqlConnection conexao = null;
    SqlCommand comando = null;

    public frmFaturaAnual()
    {
        InitializeComponent();
    }

    private void ListaGrid()
    {
        string strSQL = @"SELECT
                          RTRIM(B1_COD) + ' - ' + B1_DESC AS PRODUTO,
                          [Janeiro], [Fevereiro], [Março], [Abril], [Maio], [Junho], [Julho],
                          [Agosto], [Setembro], [Outubro], [Novembro], [Dezembro]
      FROM ( SELECT SB.B1_COD, SB.B1_DESC, m.nm_mes, SD.D2_QUANT FROM  SD2010 AS SD left outer join mes m on m.cd_mes = month(SD.D2_EMISSAO)
      INNER JOIN SB1010 AS SB WITH (NOLOCK) ON SB.B1_COD = SD.D2_COD
      WHERE SD.D_E_L_E_T_ <> '*'
      AND SD.D2_CF IN ('5102', '5117', '5119', '5123', '5124', '5403', '5405', '6102', '6108', '6110', '6117', '6119', '6123', '6124', '6403', '6405', '7102')
      AND YEAR(SD.D2_EMISSAO) = '" + txtAno.Text +"' ) AS F PIVOT (SUM(D2_QUANT) FOR nm_mes IN  ([Janeiro], [Fevereiro], [Março], [Abril], [Maio], [Junho], [Julho], [Agosto], [Setembro], [Outubro], [Novembro], [Dezembro])) AS P";

        conexao = new SqlConnection(conm);
        comando = new SqlCommand(strSQL, conexao);

        try
        {
            SqlDataAdapter dados = new SqlDataAdapter(comando);
            DataTable dtLista = new DataTable();
            dados.Fill(dtLista);

            dgAnual.DataSource = dtLista;
        }
        catch
        {
            MessageBox.Show("Não existem dados a serem encontrados");
        }
    }

    private void btnPesquisar_Click(object sender, EventArgs e)
    {
        ListaGrid();
    }

    private void btnFechar_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frmImpFatAnual imp = new frmImpFatAnual(txtAno.Text);
        imp.Show();
    }

    private void dgAnual_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {

        frmQtdaCliente custo = new frmQtdaCliente(txtAno.Text);
        custo.Show();
    }
}

Answer: Considerando que, você vá utilizar o evento doubleclick no datagridview, e que sempre será aberto um novo form, quando o evento ocorrer:
no seu frmQtdaCliente, crie duas propriedades
public string Mes {get;set;}
public string Produto {get;set;}

no evento load do form, preencha os textbox.
para chamar o form, no evento dgAnual_CellDoubleClick:
frmQtdaCliente custo = new frmQtdaCliente(txtAno.Text);
custo.Mes= dgAnual.Rows[e.RowIndex].Cell["nome da sua coluna mes"].Value.ToString();
custo.Produto = dgAnual.Rows[e.RowIndex].Cell["nome da sua coluna produto"].Value.ToString();

custo.Show();
Comment: Rovann ate deu certo seu procedimento, mas no txtMes eu preciso do nome do Mes sendo preenchido no txtbox, do jeito que esta seu código esta trazendo o txtMes o conteúdo da célula, não e isso que quero, e sim o nome da coluna que estou selecionando a celula.
Comment: Na hora de preencher a variável mês, utilize dgAnual.Colums[e.ColumnIndex].Name
Comment: Desculpe se tiver algum erro na sintaxe, estou no celular, se ajudou, marca como resposta por favor
Comment: Obrigado deu certinho aqui vlw
Comment: Agora estou com outro erro em algumas colunas quando cliko.
 Ocorreu uma exceção sem tratamento do tipo "System.Data.SqlClient.SqlException" em System.Data.dll

Informações adicionais: Divide by zero error encountered.
Comment: aí temos que ver onde exatamente acontece o outro erro, se é nesse primeiro form, ou no outro, Divide by zero está acontecendo em algum cálculo de um comando sql. No evento double click, convém colocar o trecho "if(e.RowIndex < 0 || e.ColumnIndex < 0)  return;"  para não entrar no código se for clicado em um header. Por favor, marque como resposta
Comment: Bom dia Rovann. Engraçado que só acontece na coluna do Mes de Janeiro do datagriview, as outras colunas funcionam normalmente.
Comment: possívelmente pelo valor 0 (zerado) que tenta realizar a divisão, mostre a sintaxe sql para tentar te ajudar, se possível o código do outro form
Comment: amigo, você marcou a resposta do outro membro como resposta da sua questão !? Não que a dele esteja errada, também funciona, mas marque a minha também
Comment: Me desculpe acho que agora marquei certo.
Answer: Há diversas maneiras de se fazer isso. Eu quase sempre opto pela ideia de enviar os dados via construtor para o novo form, isso facilita colocar valores nos controles logo depois que eles forem criados e também impede que estes controles sejam acessados fora do form.
Minha dica se baseia, basicamente, em três coisas a fazer

Adicionar um evento de click (ou double click) no DataGridView (não nas células - porque o evento é disparado em qualquer lugar da linha que for clicado, se você não quer isto use o evento CellDoubleClick mesmo);
Capturar as informações necessárias;
Passar estas informações como parâmetro no construtor do novo form.

Exemplo:
private void dgAnual_DoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if(e.RowIndex < 0 || e.ColumnIndex < 0)
        return;

    var row = dgAnual.Rows[e.RowIndex];
    var nomeProduto = row["NomeDaColunaProduto"].Value;
    var mes = row["NomeDaColunaMes"].Value;

    FormNovo form = new FormNovo(nomeProduto, mes);
    form.Show();
}


Understand differences between gnls and nls - step halving factor reduced below minimum in NLS step

Question: <code>## you can download the "Daata" object from here
## https://drive.google.com/file/d/17WNTCwCqpixHf-AdUiOn6IEpmLzAsetA/view

> head(Daata)
  thinning      dista rn
1        1 0.05787222  1
2        1 0.13197649  2
3        1 1.63724360  3
4        1 1.83829279  4
5        1 1.84211536  5
6        1 1.84909713  6
</code>
While this code runs without problems...
<code>> nls(rn ~ Asym/(1+exp((xmid-dista)/scal)),
+      data = Daata,
+      start=c(Asym = 55208.08,
+              xmid = 9.384632,
+              scal = 1.702107))
Nonlinear regression model
  model: rn ~ Asym/(1 + exp((xmid - dista)/scal))
   data: Daata
     Asym      xmid      scal
53073.228     9.368     1.699
 residual sum-of-squares: 2.07e+11

Number of iterations to convergence: 3
Achieved convergence tolerance: 8.548e-07
</code>
... this one delivers an error
<code>> gnls(rn ~ Asym/(1+exp((xmid-dista)/scal)),
+      data = Daata,
+      start=c(Asym = 55208.08,
+              xmid = 9.384632,
+              scal = 1.702107))
Error in gnls(rn ~ Asym/(1 + exp((xmid - dista)/scal)), data = Daata,  :
  step halving factor reduced below minimum in NLS step
</code>
Can anyone explain to me why?
Answer: I'm having the same problem with gnls() function. Seeking the solution, I read that the problem is about the model conception don't fit to your data. Possible solutions are use the argument in gnls() function   control=gnlscontrol(nlsTol=100) or the gnlscontrol(tolerance=100)
Edit: I tryed with the argument control=gnlsControl (nlsTol=50) and the problem was solved. Reasons to use gnls rather than nls are when the residuals increase when the variance increases. Note that my code has the argument weights with varPower function in which means my data is heteroscedastic and my residuals increases as a power function of the variance.
<code> model1=gnls(di_d~b1*(h_rel-1)+b2*sin(c*pi*h_rel)+b3*(cotan),
                                     data = treat_db_pr[[i]],
                                     start =list(b1=b1[i],b2=b2[i],b3=b3[i], c=c.sin[i]), control = gnlsControl(nlsTol = 50),na.action = na.omit, weights = varPower())
</code>
I recomend to use nls() instead gnls() if you're not aimed an heteroscedastic or generalized model.
Comment: Perfect
I finally used the nls function, mostly because It allows me to use the [SSlogis](https://www.rdocumentation.org/packages/stats/versions/3.6.1/topics/SSlogis) function (that I found super useful)!


What happens in CouchDB when I create an index repeatedly?

Question: To implement sorting, in CouchDB we have to create an index (otherwise the corresponding mango query fails). I haven't found a way to do this in Fauxton (if I have missed something, please comment in Github), so I've decided to create it programmatically. As I'm using couchdb-nano, I've added:
this.clientAuthPromise.then(async () => {
    try {
        await this.client.use('test_polling_storage').createIndex({
            index: {
                fields: [
                    'isoDate',
                ],
            },
            name: 'test_polling_storage--time_index',
        })
        console.log('index created?')
    } catch (error) {
        console.log(`failed to create index:`, error)
    }
})

into the storage class constructor, where
this.clientAuthPromise = this.client.auth(connectionParams.auth.user, connectionParams.auth.password)

Now, on each run of the server, I'm getting index created?, so the createIndex method (which presumably POSTs to /db/_index) doesn't fail (and sorting works, too). But as I haven't found indexes viewer in Fauxton either, I wonder what actually happens on each call of createIndex: does it create a new index? Does it rebuild the index? Or sees that the index with such name already exists and doesn't do anything? It's annoying to deal with this in a blind fashion, so please clarify or suggest a way to clarify.
Answer: Ok, as the docs suggest that the response will contain "created" or "exists", I've tried
const result = await this.client.use('test_polling_storage').createIndex({
...
console.log('index created?', result.result)

got index created? exists and concluded that if the index was created before, it won't be re-created. It's not clear what will happen if I try to change the index, but at least now I have a mean to find out.


How to prove that, the set of all matrices $M_n{\mathbb R}$ with distinct eigen values is dense in $\mathbb R^n$?

Question: How to prove that the set of all matrices $M_n{\mathbb R}$  with distinct eigen values is dense in $\mathbb R^n$?
Is there any geometric interpretations behind this.. if it is so, then tell me how to construct a dense subset of $\mathbb R^n$ geometrically.
Comment: A crude outline: The set of matrices such that their characteristic polynomial has multiple zeros is Zariski closed. The set $U$ of diagonalizable matrices contains the complement of that set. Because $M_n(\Bbb{R})$ is irreducible, any Zariski open set is dense w.r.t. both Zariski topology and the usual topology. Not sure this is very useful :-/
Comment: Do you mean $\Bbb R^{n \times n}$? as opposed to $\Bbb R^n$?
Comment: yes@Omnomnomnom
Comment: Hint: the set of the all points of $\mathbb{R}^n$ in wich all entries are distincts are dense in $\mathbb{R}^n$
Answer: It suffices to note that for any $A \in \Bbb R^{n \times n}$, we may construct a sequence $A_m \to A$ where each $A_m$ has distinct eigenvalues.
We begin by noting that $A$ is block upper-triangularizable, so that $A = STS^{-1}$, with
$$
T = \pmatrix{T_1&&* \\&\ddots\\&&T_k}
$$
Where $T_i$ is either an element of $\Bbb R$ or a block of the form
$$
T_i = \pmatrix{a&-b\\b&a}
$$
with $a,b \in \Bbb R$.  Now define
$$
T^{(m)} = \pmatrix{\left(1 - \frac 1m\right) T_1&&* \\&\ddots\\&& \left( 1 - \frac km\right) T_k}
$$
We note that $T^{(m)}$ has distinct eigenvalues for all but finitely many $m$ (i.e. for all $m$ bigger than some $M \in \Bbb N$).  Now, define the sequence by $A_m = ST^{(m)}S^{-1}$.
Comment: i am sorry .. i could not under stand.. should i need any pre requisite for this...@omnomnomnom
Comment: Could you be more specific about what you didn't understand?  One way to view this is to say that $STS^{-1}$ is the [real Schur decomposition](http://en.wikipedia.org/wiki/Schur_decomposition) of a matrix $A$.
Comment: @Omnomnomnom: May I ask why in the last sentence of your proof " for all but finitely many $m$" $T^{m}$ has distinct eigenvalues? It seems to me for all $m \ge 2$, the eigenvalues are different.
Comment: @iris2017 we might end up with a repeated eigenvalue by coincidence for some values $m \geq 2$.  However, this can happen at most finitely many times.
Comment: @Omnomnomnom: Could you give an example? I could not see the case. Thanks.
Comment: @iris2017 with
$$
T = \pmatrix{3&0\\0&4}
$$
we find that $T^{(5)}$ has repeated eigenvalues.
Comment: @Omnomnomnom: I see. Thanks. But then intuitively I can see this can happen only finitely many times. Is there a formal argument?
Comment: For each pair $T_p,T_q$, there is at most one value of $m$ such that
$$
(1 - \frac pm)T_p = (1 - \frac qm)T_q
$$
and there are only finitely many pairs
Comment: @Omnomnomnom: Thanks so much for answering my questions.
Answer: Consider a map $f$ which takes an appropriately sized set of eigenvalues paired with their respective eigenvectors and outputs the (unique) matrix having those eigenvalues and eigenvectors. This function is bijective and continuous almost everywhere (since each entry of the outputed matrix would be a rational function of the input) and, clearly, in the input domain the set of sets of eigenvalues with no repeats would be dense, and by continuity, the image of this set would be dense too.


Show that diagonals intersect at common point

Question: Given is octagon where opposite sides are equal length and parallel. Show that diagonals: $AE,DH, BF, CG$ intersects at point $S$
So I have tried to create a parallelograms $AHED$ and $BCFG$ and use that $AE=GC$
Answer: Show that $AHED$, $BGFC$ and $AGEC$ are parallelograms (which is quite obvious). Then their diagonals bisect each other. And the lines meet at their midpoints.
Comment: i think $AGEC$ is even a square, because of $AE$=$GC$ by the way do you know how to show this equality? It suffice to notice that they are respective diagonals at octagon?
Comment: they need not be equal!
Comment: yes, I unnecessarily suggested a drawing
Answer: Since opposite sides are parallel, angles $BAH$ and $DEF$ are equal. Similarly angle $AHG$ and $EDC$ are equal. Also, lengths of parallel sides are equal. Now consider the line $GC$. It forms two pentagons $GHABC$ and $CDEFG$ which are equal for the reasons mentioned above.Since $S$ is the point at which line $AE$ crosses $GC$, it would be the midpoint of $AE$. Similarly using pentagons $AHBFE$ and $EDCBA$, it can be proved that the point at which $GC$ crosses $AE$ will be the midpoint of $GC$. Taking similar pairs such as BF and GC etc it can be proved that midpoint of all diagonals lie at the same point. And it is $S$


If A is open in the Borel $\sigma$ alg. is it open in the original Topology?

Question: Here is what I have:
$(X,\mathcal{T})$ is a topological space, and $\mathcal{B}$ is the Borel $\sigma-$algebra corresponding to the topology $\mathcal{T}$.
By definition $\mathcal{B}$ is the smallest $\sigma-$algebra containing all open sets.( So if $A_1$ is open in $\mathcal{T}$ then it is open in $\mathcal{B}$...correct?)
My real question is if I take any arbitrary $A_2$ that is open in the $\sigma-$algebra ($A_2\in \mathcal{B}$) then is it open in original the topology? So is $A_2\in\mathcal{T}$?
Comment: What do you mean by « open in the $\sigma$ algebra »? The notion of openness is a topological one, not a measure-theoretic one. An open set in B has to be open according to some topology, and if it is according to the one that generates the Borel algebra, it is of course open in the topology . However there are many sets that are in the Borel sigma algebra, but are not open. (For instance, any closed set that is not open)
Answer: This is false. Consider $\mathbb{R}$ with the usual topology $\mathfrak{T}$ and let $\mathcal{B}$ be the Borel algebra on $\mathbb{R}$ generated by $\mathfrak{T}$. Then, the closed interval $[0,1]$ belongs to $\mathcal{B}$ (its complement is an open set and $\mathcal{B}$ is closed under complements), but $[0,1]$ is not open in $\mathbb{R}$. That is, $[0,1] \notin \mathfrak{T}$.
The issue here is that topologies are not usually $\sigma$-algebras (and $\sigma$-algebras are not always topologies)! More importantly, topologies need not be closed under complements. It is for this reason that is dangerous to use the terminology "$A$ is open in $\mathcal{B}$" to say that $A \in \mathcal{B}$.
Fundamentally, topologies and $\sigma$-algebras are very different structures. We typically only discuss openness relative to a topology, and it does not make much sense to say that a set is open relative to an algebra. Here are some important distinctions between $\sigma$-algebras an topologies:

$\sigma$-algebras are only closed under countable unions; a topology must be closed with respect to arbitrary (even uncountable) unions.
$\sigma$-algebras must be closed relative to complements. On the other hand, topologies need not satisfy this property.
Topologies are closed under finitely many intersections. However, $\sigma$-algebras are closed under countably many intersections!

Nonetheless, because $\mathcal{B}$ must always contain the original topology $\mathcal{T}$, it is true that $\mathcal{T} \subseteq \mathcal{B}$.


When is $\| X \| _\star = \| F X \| _2$ submultiplicative?

Question: All matrices are real. By $\| \cdot \|_2$ denote the matrix norm induced by $L_2$.
Assume $F$ is an invertible matrix.
Consider the norm $\| X \| _\star = \| F X \| _2$.
What is the condition on $F$ so that the norm $\| \cdot \|_\star$ is sub-multiplicative?
Answer: A simple condition could be $\|F^{-1}\|_2\leq 1$ because then
$$
\|XY\|_*=\|FXF^{-1}FY\|_2\leq\|FX\|_2\|F^{-1}\|_2\|FY\|_2\leq\|X\|_*\|Y\|_*.
$$
It is also a necessary condition, however. Assume for simplicity that $F=\alpha I$ where $0<\alpha < 1$ so that $\|F^{-1}\|_2=\alpha^{-1}>1$, and $X=Y=I$. Then
$$
\|XY\|_*=\alpha\|XY\|_2 =\alpha\not\leq \|X\|_*\|Y\|_*=\alpha^2\|X\|_2\|Y\|_2=\alpha^2.
$$
In general, if $\|F^{-1}\|_2>1$ then you can find $X$ and $Y$ for which
$$
\|XY\|_*\not\leq\|X\|_*\|Y\|_*.
$$


jquery mobile and MVC - have 3 lists next to each other without ui-grid or tables

Question: I have a problem in with setting up 3 lists to go side by side to each other in jQuery Mobile. I can't use ui-grid unfortunately because I have a script that hides them and based on the number from 0-3 (this is another list), the same number of lists will appear (I have the lists to be dynamically centered). Also, I can't use data-role="fieldcontain" because each list should have round edges according to my boss (the middle list has sharp edges). Here is my code:

   @Html.DropDownListFor(x => x.ChildAge_A1, ChildAge,
   new { data_mini = "true", data_inline = "true", data_icon = "false"})

   @Html.DropDownListFor(x => x.ChildAge_A2, ChildAge,
   new { data_mini = "true", data_inline = "true", data_icon = "false"})

   @Html.DropDownListFor(x => x.ChildAge_A3, ChildAge,
   new { data_mini = "true", data_inline = "true", data_icon = "false"})

Thanks for your help!
Answer: This fiddle might help:
http://jsfiddle.net/dhavaln/y8JAs/
I have put following css to align the select boxes together.
.ui-select{
    float: left;
    width: 33%;
}


Sum of squares of normal distribution

Question: I have a problem in which I need to apply weak law of large numbers to sum of squares of normal distribution with mean $1$ and variance $1$.
$X_1, X_2,\dots \sim \mathcal{N}(1,1).$  They are iid.
$V(X_1^2+X_2^2+\dots\X_n^2)/n$ what will be the limit value of this when $n$ tends to infinite.
My views:
I know sum of squares of SNV is chi square.
Variance of this chi square will be $2n$.
But I don't know if it follows central chi square in case when mean is not $0$.
In this particular case, will my variance be $2n$?
Comment: What is $V$ doing in the third line? Do you have finite sum or an infinite sum in the numerator?
Comment: It's a finite sum
Comment: What do you call "the limit value" of this random variable, and what is $V$ ?
Comment: V is the variance
Answer:
My views:
I know sum of squares of SNV is chi square.
Variance of this chi square will be 2n.
But I don't know if it follows central chi square in case when mean is not 0.

sum of square of SNV is a chi-squared but your Gaussian are not centered thus the sum of your iid reduced gaussian is a Noncentral chi-squared distribution with variance $2(k+2\lambda)$ where $\lambda$ is the noncentrality parameter.
As @Kavi Rama Murthy already asked, we have to know what is there in the numerator:

$\frac{1}{n}\mathbb{V}\left[\sum_{k=1}^{\infty}X_k^2\right]$

$\frac{1}{n}\mathbb{V}\left[\sum_{k=1}^{n}X_k^2\right]$

Something else?

EDIT

I have a finite sum up to n

Thus the result is simply
$$\frac{1}{n}\mathbb{V}\left[\sum_{k=1}^{n}X_k^2\right]=\frac{1}{n}\cdot n\mathbb{V}[X_1^2]=2(1+2)=6$$
Comment: I have a finite sum up to n

Sum of squares of normal distribution


Field Label for Content Type

Question: I need to find where the field label for a content type is stored within the database. I tried the field_config_instance, it's not there.
Answer: Yes it is, you just need to look a bit harder ;)
Have a look at the serialised array in the data column of that table. You'll find the label for the field listed in there.
If you want to extract this in code the best way is to use the field API functions, it saves you having to mess about with the serialised array directly:
$entity_type = 'node';
$field_name = 'body';
$bundle = 'article';

$info = field_info_instance($entity_type, $field_name, $bundle);
$label = $info['label'];

Comment: In that case you're fine...grab the contents of the `data` column from `field_config_instance` using whatever method you want, and run: `$info = unserialize($data_column_value); $label = $info['label'];`
Comment: I see, so that's where drupal stores it. But I have a problem now. I wrote my own function to generate a xml file based on url parameter. A couple fields are named with integer values, one of them is like "0+". And it gives me error when my function tries to generate xml. Is there anyway to pull the label from the data column without using drupal or field API? Or is there a way to access the API outside of drupal installation?
Comment: Without using Drupal/field API, sure, but definitely not without using PHP. The string is a serialised PHP array so only PHP (or a crazy-assed custom MySQL parser, of which I don't think there are any for this purpose) will be able to extract it again
Comment: My function is in PHP

Field Label for Content Type


ValueError creating an array from a list

Question: Trying to create an array from a list fails for me, under some cases. The error is: 'ValueError: setting an array element with a sequence'
The basic case works as expected:
foo = [(0,1),(2,3),(4,5)]
bar=np.array(foo)

But:
foo = [ ("Hello", [0,1,2,3]) , ("Goodbye",[9,8,7,6]) ]
bar=np.array(foo)

Blows up with the described error. Why does it fail when the list contains an array? What is the pythonic solution?
Answer: The answer to "Why does it fail ?" is in the description of the ndarray object you'd like to create.

An array object represents a multidimensional, homogeneous array of fixed-size items

It blows up because your second case is not a homogeneous array of fixed-size items


Loop character variable and interact it to create names in dplyr

Question: I want to loop through the names of a character variable of this type:
names_list <- c("USA", "VEN", "CHE")

Then, I create the following loop:
for (i in names_list) {
  set.seed(123333)
  test <- predictors_no_NA %>%
    filter(ISO3_baci != i)

predictions <- predict(rf150, test, predict.all=TRUE, type = "prob")
  predictions <- as.data.frame(predictions[1])
  predictions <- predictions %>%
    select(aggregate.1) %>%
    rename(predictions[i] = aggregate.1)    % HERE APPEARS THE 1st PROBLEM

  test_RF_[i] <- cbind(test, predictions)   % HERE APPEARS THE 2nd PROBLEM
}

Note that variable "rf150" is created inside the loop without any problem (don't show the code here).
The problem arises when I want to add the string element of the loop (e.g. "USA") to my created name "predictions_[i]" or "test_RF_[i]", so that I can get a variable that is called: "predictions_USA" or "test_RF_USA" as well as "predictions_VEN" or "test_RF_VEN" and "predictions_CHE" or "test_RF_CHE"
Any clue?
Regards
Comment: Your problem is that `deplyr`, along with other `tidyverse` packages, uses non-standard evaluation.  One solution is to use `{{`` and `}}` as suggested by @SantiagoI.Hurtado.  However, the structure I think you are trying to use is not [tidy](https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html).  I strongly suggest adapting your workflow to make it tidy.  A little effort now will save you much pain later on.
Comment: Have you try with assign + pasteo ??
Comment: I have tried it but either I don't implement I correctly or it really does not work inside a dplyr framework
Comment: I the second problem it should work, I think. In the first maybe using {{ }}
Comment: Thanks to both @SantiagoI.Hurtado and Limey. Helpful recommendations!
Answer: Firstly, for the dynamic renaming in your loop, the following snippet should help (I've taken the freedom to alter it a little:
library(tibble) # if you want to use as_tibble() rather than as.data.frame()
library(dplyr)

predictions <- predict(rf150, test, predict.all=TRUE, type = "prob") %>%
    .[1] %>%
    as_tibble() %>%
    select(!!paste0('predictions_',i) := aggregate.1)

There's a very helpful and detailed answer on the topic of dynamic variable names in dplyr over here.
Alternative solution, since you had already selected only the one column that you wanted to colbind:
predictions  <- [...] %>%
    select(aggregate.1) %>%
    `colnames<-`(paste0('predictions_',i))

Secondly, to assign the data frame to a variable, as commented by Santiago above, assign should get you there:
assign(
    paste0('test_RF_',i),
    cbind(test, predictions),
    envir=globalenv()
)


Stack + variable behaviour

Question: I just have a  small confusion on understanding the stack execution and variables. Below is the code .
  var getDetails=false;

   function firstFunction(){
      getDetails=true;

//      ajax call

   }

   function secondFunction(){
      getDetails=false;
     subFunction();
   }

    fucntion subFunction(){
        if(getDetails){

     }
    }

As you noticed there is one global variable , i am setting the value of global variable in both first and second function and make use of it in my subFucntion.
Now lets say i call fistFunction( this function makes an ajax call and gets data little late).
Now while fistFunction is executing i will second function where i am changing the global variable and i also call subFucntion which  uses the global variable .Now lets say while subfunction is executing even my FirstFunction is also executing what will be the value of global variable?
Comment: JavaScript is single-threaded.
Answer: In your code above, getDetails is definitely false when you call subFunction, since you set it to false immediately before calling subFunction.
You have a misconception about how Javascript works:

while subfunction is executing my FirstFunction is also executing

That situation cannot occur.
Javascript is single-threaded, so there can only ever be one function executing at a time. An AJAX call, like a setTimeout, is asynchronous, but the callback function will only execute once your other execution path has completed, the earliest point that the thread becomes available after the response is ready. If the thread is busy executing another function, then your callback will not run until it is done.
Try this for an example:
var start = new Date().getTime();
// Logs first
console.log('Start time: ', start);

// Asynchronous, but still won't run until after the spin lock finishes
// A result of Javascript being single-threaded
setTimeout(function(){
    // Logs last
    console.log('Asynchronous callback time: ', new Date().getTime());
}, 500);

// Two second spin-lock
while(start + 2000 > new Date().getTime());

// Logs second
console.log('Spin lock finished', new Date().getTime());

Stack + variable behaviour


FlexSlider fail slideshow

Question: I installed FlexSlider as suggested on the module's in Drupal7. I try to put a slideshow on my home page with no luck. I tried to create the FlexSlider Example content but it does not create a slideshow, but only lists the images.
The FlexSlider libs are version 2.4.
The website is here: http://projects.busoniu.net/
the images are uploaded in the FLEXSLIDER EXAMPLE SLIDESHOW and I didn't upload any of it in the FLEXSLIDER EXAMPLE IMAGE.
I get an error when I try to edit the content:

Notice: Undefined property: stdClass::$name in flexslider_add() (line
  395 of
  /data/home/buso01/domains/busoniu.net/public_html/projects/sites/all/modules/flexslider/flexslider.module).
  Notice: Undefined property: stdClass::$name in flexslider_add() (line
  398 of
  /data/home/buso01/domains/busoniu.net/public_html/projects/sites/all/modules/flexslider/flexslider.module).

In console chrome I can see this error:

Uncaught TypeError: undefined is not a
  functionflexslider.load.js?nk4e6d:41 (anonymous
  function)jquery.js?v=1.4.4:34 b.extend.eachjquery.js?v=1.4.4:27
  b.fn.b.eachjquery.once.js?v=1.2:55
  $.fn.onceflexslider.load.js?nk4e6d:34
  _flexslider_initflexslider.load.js?nk4e6d:24 Drupal.behaviors.flexslider.attachdrupal.js?nk4e6d:76 (anonymous
  function)jquery.js?v=1.4.4:33 b.extend.eachdrupal.js?nk4e6d:74
  Drupal.attachBehaviorsdrupal.js?nk4e6d:412 (anonymous
  function)jquery.js?v=1.4.4:30 b.extend.readyjquery.js?v=1.4.4:38 u
Comment: What versions are you using? Which jQuery Update you installed? What jQuery version is required?
Comment: I have drupal 7 and flexSlider 2.4. I don't know other specifications because I'm only creating the web site, but the host is someone else. sorry.
Answer: Put the Flexslider library in sites/all/libraries.
Check Status page for error with flexslider (admin/reports/status).
Comment: I did copy the lib to that location and the status is: `FlexSlider - FlexSlider library installed. version 2.4 '
Comment: From what I see on your page the flexslider js gets not loaded 'sites/all/libraries/flexslider/jquery.flexslider-min.js' missing in the html. Maybe try to use another theme to see if it is theme related.
Comment: On Bartik 7.34 happens the same. can this be blocked by my online server provider?
Comment: and clear your cache too.
Comment: Ohh, now works... so do u know if I could be able to use the other theme with FlixSlider, or how to fix this issue with that theme? thank for helping
Comment: Try enabling other theme again and clear cache afterwards, maybe it will work then too. If not maybe rise a issue at themes queue
Comment: FYI: Googling this error brought me here. I already had the necessary javascript libraries, as this answer suggests. However, I migrated an impartial feature configuration from one site to another. Keep in mind that my FS implementation includes a view, FS definition and image style definition. Migrating these as well addressed the problem.

FlexSlider fail slideshow


Why this code cannot delete the rows that i want?

Question: i want keep the 100 rows that has the biggest timestamp and delete all the other rows... Here follow the code that i have create :
<code>$values_to_delete = db_delete('table1', 't');
  $values_to_delete->orderBy('t.timestamp');
  $values_to_delete->range(101, 99999999);
  $values_to_delete->execute();
</code>
Answer: The DeleteQuery class doesn't have orderBy or range functions, so I would imagine you would need to write your own DELETE with SELECT subquery. An example from Stack Overflow
Comment: Drupal doesn't have its own version of SQL @Karmen, that's just a plain old SQL issue. The link in the answer should help you to get closer to what's required. If you have trouble, you can always ask SQL questions yourself on Stack Overflow. Just be sure to do due diligence beforehand - it's quite a lot stricter over there and questions without plenty of explanation tend to get downvoted/closed pretty quickly
Comment: could you help me to do this difficult thing?? I am new in drupal coding..


Some time silent recording with Audio Record

Question: I am using  Audio Record to record voice using android phone. It is working most of the time but some time on my moto g phone it records silent data. When I replay it I do not hear any thing. When I checked the
audio file it was there in the storage I played using media play from pc it was playing with out any voice .
my code:
int mSampleRate = 8000;
int mBufferSize = AudioRecord.getMinBufferSize(mSampleRate,AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT);
byte bData[] = new byte[mBufferSize];
ByteArrayOutputStream encodedStream = new ByteArrayOutputStream( );
while (mIsRecording) {
    mRecorder.read(bData, 0, mBufferSize);
    encode(bData,encodedStream);
}

Any help will be highly appreciated
Comment: Have you tested your code in another phone?
Comment: Yes I have tested my code with samsung phone too but it did not come
Comment: this code is not complete: E.g. where is the line(s) with `mRecorder=new AudioRecord(...,mSampleRate,AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT,mBufferSize);`?
Comment: Its there I have not posted it
Answer: Thanks for the help guys . Its was my mistake. I was using the audio recorder through JNI too and I was not releasing the audio record that's why whenever I tried to use audio record from java (Android SDK) it was not capturing any voice . Hope this will help to some one else .


Upgrade SF from 2.8 to 3.x.x

Question: I have a problem with the migration from Symfony 2.8 to Symfony 3 and higher. I've been trying to update my project for a few days, but I'm blocking the same mistakes. I tried all the solutions I could find on google but no evolutions. Here is my file composer.json
{
"name": "My/project",
"license": "proprietary",
"type": "project",
"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"require": {
    "php": ">=5.3.9",
    "symfony/symfony": "3.0.*",
    "doctrine/orm": "^2.5",
    "doctrine/doctrine-bundle": "^1.6",
    "symfony/swiftmailer-bundle": "~2.3",
    "symfony/monolog-bundle": "~2.4",
    "sensio/distribution-bundle": "~5.0",
    "sensio/framework-extra-bundle": "^3.0.2",
    "incenteev/composer-parameter-handler": "~2.0",
    "sonata-project/admin-bundle": "3.13",
    "sonata-project/doctrine-orm-admin-bundle": "^3.1",
    "friendsofsymfony/user-bundle": "^1.3",
    "sonata-project/core-bundle": "^3.1",
    "sonata-project/easy-extends-bundle": "^2.1",
    "sonata-project/user-bundle": "^3.2",
    "sonata-project/formatter-bundle": "^3.1",
    "knplabs/knp-paginator-bundle": "^2.5",
    "sonata-project/intl-bundle": "^2.3",
    "google/recaptcha": "^1.1",
    "twig/twig": "1.28.2",
    "friendsofsymfony/jsrouting-bundle": "^1.6",
    "helios-ag/fm-elfinder-bundle": "^6.2",
    "vich/uploader-bundle": "1.5.3",
    "beberlei/doctrineextensions": "^1.0",
    "simplethings/entity-audit-bundle": "^1.0",
    "sentry/sentry-symfony": "^1.0",
    "rollbar/rollbar": "~1.1",
    "mikey179/vfsstream": "^1.6"
},
"require-dev": {
    "sensio/generator-bundle": "~3.0",
    "doctrine/doctrine-fixtures-bundle": "^2.3",
    "hautelook/alice-bundle": "^2.0@beta",
    "nelmio/alice": "^3.0@beta",
    "theofidry/alice-data-fixtures": "^1.0@beta",
    "symfony/phpunit-bridge": "^4.2",
    "phpunit/phpunit": "^6.1",
    "behat/behat": "^3.4",
    "behat/mink": "^1.7",
    "behat/mink-selenium2-driver": "^1.3",
    "behat/symfony2-extension": "^2.1",
    "behat/mink-extension": "^2.2",
    "behat/mink-browserkit-driver": "^1.3",
    "behat/mink-goutte-driver": "^1.2",
    "emuse/behat-html-formatter": "^0.1.0",
    "phing/phing": "2.*"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
"config": {
    "component-dir": "web/assets"
},
"extra": {
    "symfony-app-dir": "app",
    "symfony-bin-dir": "bin",
    "symfony-var-dir": "var",
    "symfony-web-dir": "web",
    "symfony-tests-dir": "tests",
    "symfony-assets-install": "relative",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    }
}

}
I use this command to update : $ composer update symfony/symfony --with-dependencies --no-scripts
update is not done because apparently I have conflicts with different versions of my dependencies..yet I can't update my dependencies in a more recent version

Need your help please..
Answer: You have a conflict because you cannot have symfony/symfony 3.0.* and symfony/cache 3.4 at the same time.
In fact, other bundles that you have locked at a version are not compatible with symfony 3.0, so you need to bump them up as well.
The minimum viable would be to use these dependencies :
"symfony/symfony": "3.2.*",
"friendsofsymfony/user-bundle": "^2.0",
"sonata-project/user-bundle": "^4.0",

Then just run composer install instead of composer update symfony/symfony. Composer will do its job, and then you'll have to adapt your code to mitigate all the BC breaks, etc ...
If you cannot change your other dependencies, then you're stuck with Sf 2.8.

Upgrade SF from 2.8 to 3.x.x


Violin - Slurring double stops

Question: I was reading some violin sheet music when I came across something that looked like a slurred double stop. Here is an image:

The problem is that both double stops use the same fingers, but on opposite strings. Assuming first position, the first double stop uses second finger on D string and first on A string, and the next note uses first finger on D string and second on A string.
How can you move both fingers to other strings, under a slur, without playing a little bit of open strings?
Comment: Is this a question about violin technique, or a question about phrasing, that is, what the slur is asking you to do?
Comment: I second replete. Assuming your badges and score here, I do not quite understand what you find perplexing about legato. I am assuming the notes are difficult to bow? Hard to tell, given we do not know the key signature.
Comment: @Xilpex, you'd play it as written.  Just because you're fingering multiple notes doesn't change what a slur is.
Comment: Have you thought about using all four fingers.
Answer: You have several options depending musical context.

The best thing is to see this challenge coming and prepare by putting your first finger equally on both D and A strings, as if you were playing a double stop of a fifth, the E on D string and the B on A string. (Note, this is very different from a fretted-instrument "barre" technique, since your finger is still oriented as normal, not at all "sideways.") Then you only have to move your second finger.
Your second finger can switch strings quite quickly, but you still want to avoid sounding that "E/B" fifth that your first finger is responsible for, even for the millisecond that your second finger moves. If the musical context is appropriate, you can simply use a bit of portato in the bow, slowing or stopping ever so slightly at the moment of transfer. If not, you can momentarily rock the bow away from D string as your second finger moves, so that for a split second you're bowing only A string, and then return the bow to D string as your second finger lands. Since the A string sustains throughout, the listener won't notice any "stoppage" in the sound and it will be perceived as a seamless slur.
This example isn't the most conducive, but you can often avoid the issue by shifting during the slur. For instance, if you started the slur in fourth position (using 3rd and 2nd fingers on G and D strings), you could shift on the second note to fifth position. Your 2nd finger simply slides up D string, and the G string note changes from 3rd to 1st finger; no finger has to switch strings. For this particular pair of notes it's a bit hard to imagine why you'd be up in fourth position in the first place, but for other similar scenarios a shift could be convenient, especially if the audible slide is expressively appropriate.
Answer: You don't write the key signature, but even assuming it is C major, you can play both low notes with the index finger (pressing down on both strings in what guitar players call barré) while changing from ring finger on the D string to middle finger on the A string.  That allows reasonably uninterrupted notes.
Some composers treat a violin like a guitar (or a lute or a viol, depending on the historic frame) and sometimes it is an advantage for a performer when they happen to have some experience across the aisle that was a lot less pronounced in early string instrument history.
Or like an advanced piano player: don't think in terms of fingerings but rather of notes, and whatever finger can be brought over conveniently to do the job is responsible for doing it.  In terms of reliable intonation and fast runs, fixed positions and fingerings are a strategic advantage for playing, but sometimes the music does not leave the leeway for using those aids.

Violin - Slurring double stops


ERRO AO INSERIR PHPMYADMIN

Question:

não insere informação nenhuma no banco da o erro abaixo:

Fatal error: Uncaught Error: Call to a member function prepare() on
  null in C:\xampp\htdocs\TELA DE LOGIN\classes\videos.php:11 Stack
  trace: #0 C:\xampp\htdocs\TELA DE LOGIN\php\addGaleria.php(25):
  Videos->cadastrar('escola_online', '127.0.0.1', 'root', '') #1 {main}
  thrown in C:\xampp\htdocs\TELA DE LOGIN\classes\videos.php on line 11
Comment: Os valores estão indo sem Aspas para o banco, não pode ser esse problema? pois são strings
Comment: então coloquei mas mesmo assim, não insere!
Comment: nao da mas o erro porem ainda não insere no banco!!!
Comment: O bindValue é com aspas simples tambem
Comment: faz um debug nele, coloca pra imprimir a string que ele cria com o VAR_DUMP() e coloca na pergunta
Answer: Seguindo o Manual do PHP pode-se ver que o insert com o bindValue se utiliza aspas simples, creio que isso esteja impactando no seu código.
Ficando assim:
<code><?php
  Class videos
  {
     try{

          $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
           $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        public function cadastrar($titulo, $thumb, $descricao, $idVid)
        {
       $sql = $pdo-> prepare("INSERT INTO video(titulo, thumb, descricao, embed) VALUES (':t',':th',':d',':vi')");
       $sql->execute(array(
              ':t'=> $titulo,
              ':th' => $thumb,
              ':d' => $descricao,
              ':vi' => $idVid
       ));
      }

       echo $sql->rowCount();
     }
     catch(PDOException $e) {
          echo 'Error: ' . $e->getMessage();
        }
  }
?>
</code>

Eu adicionei uma conexão em PDO pressupondo que tenha feito isso no
  seu código porém não postou, caso não, o problema pode estar sendo ai
Comment: testei o que me passou tb e não tive sucesso, que estranho tenho a outra que esta funcionando ok essa não vai de jeito nenhum
Comment: Poderia inserir outra colocando afundo o erro que ele mostra? Fazendo um debug comm var_dump e vendo se ele está inserindo realmente o que vpcê deseja e colando no banco pra ver se está tendo um erro de sintaxe ou algo do gênero
Comment: setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

     public function cadastrar($titulo, $thumb, $descricao, $idVid)

     {
       $sql = $pdo-> prepare("INSERT INTO video(titulo, thumb, descricao, embed) VALUES (':t',':th',':d',':vi')");
       $sql->execute(array(
              ':t'=> $titulo,
              ':th' => $thumb,
              ':d' => $descricao,
              ':vi' => $idVid
       ));  }?>
Comment: sou novo com php não consegui debugar, se poder ajudar agradeço muito assim aprendo.
Comment: email@example.com

ERRO AO INSERIR PHPMYADMIN


Python classes - instances being overwritten?

Question: When calling on a new instance of an object for a class I've created, my one instance of the class is just being overwritten.  Why could this be?  Example is below.
My class is defined as follows:
class my_class:
    attribute = ""
    examples = []
    children = []
    d = {}
    def __init__(self, attribute, e):
        self.attribute = attribute
        self.examples = e

        for ex in self.examples:
            self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1

I am making an initial instance as such:
root = my_class(some_attribute, data)

Then, I create another instance as such:
child = my_class(different_attribute, root.examples[somewhere_1:somewhere_2])

In the end, my initial 'root' is now somehow identical to 'child', where 'root' should have gone unchanged.  Why is this!?
Answer: I don't think you are doing with the initializations of attribute, examples, children and d what you think you are doing.  Those are now attributes of the class, not of each instance.  If you want each instance of the class to have its own attributes for attribute, examples, children and d, you should instead write:
class my_class:
    def __init__(self, attribute, e):

        self.attribute = attribute
        self.examples = e
        self.children = []
        self.d = {}

        for ex in self.examples:
            self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1

Answer: When you define variables in the class definition, they are class attributes.
>>> my_class.examples is my_class().examples
True

(is checks that they are exactly the same object, not just equal. For example, True == 1, but True is not 1.)
As lists and dicts are mutable, this means that changes in my_class.examples or root.examples or child.examples will be reflected in all the others.
The way you should do such a thing is by setting it inside the constructor:
class my_class:
    def __init__(self, attribute, e):
        self.attribute = attribute
        self.examples = e
        self.children = []
        self.d = {}

        for ex in self.examples:
            self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1

You probably also wish to replace self.examples = e with self.examples = e[:] which will make a shallow copy of the list. Otherwise:
>>> data
[1, 2, 3, 4, 5]
>>> root = my_class(some_attribute, data)
>>> root.examples
[1, 2, 3, 4, 5]
>>> data += [6, 7]
>>> root.examples
[1, 2, 3, 4, 5, 6, 7]
>>> # ... because:
>>> root.examples is data
True

Side-note: the recommended Python style would have your class as MyClass. I recommend that you read PEP 8.


How can I restrict users to only see products of a certain store?

Question: I am using Drupal 10 with Commerce 2. I would like to add a user, where the user can only see the products of a single store. For example, let's say there is Store A and Store B. I'd like to be able to create a User A and User B where User A only sees products from Store A and User B only sees products from Store B.
As of right now, the permissions for a certain role only allow me to restrict a user to Delete, Update, Create own/all products. For View products, it's either all or nothing.
This question is similar, but I wasn't able to figure out how the Group module could help. This was also for Drupal 8... I'm thinking maybe with Drupal 10 there's a more trivial answer.
Answer: There is no more trivial answer; Drupal 10 is functionally equivalent to Drupal 8 in many respects. As with any content entity, if you want to control access in a fine-grained fashion, you'll have to use a separate module. Group might do just fine for ya, with some custom code ensuring products are related to groups that correspond to stores. (I haven't looked recently, but modules like Content Access or ACL supporting any content entity type would do the trick, too ... I just can't say if they've abstracted their functionality to this extent yet.)


Flutter - Navegação entre telas

Question: Eu sou iniciante em flutter e estou com dúvidas em como fazer alternância entre páginas. A seguir um código que eu construí para realizar essa função, mas não deu certo.
_buttons(context) {
    return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            _button(context,"Page 1", () => _onClickNavigator(context, HelloPage1())),
            _button(context,"Page 2", () => _onClickNavigator(context, HelloPage2())),
            _button(context,"Page 3", () => _onClickNavigator(context, HelloPage3())),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            _button(context,"Page 4", () => _onClickNavigator(context, HelloPage4())),
            _button(context,"Page 5", () => _onClickNavigator(context, HelloPage5())),
            _button(context,"Page 6", () => _onClickNavigator(context, HelloPage6()))
          ],
        )
      ],
    );
  }

  _button(BuildContext context, String text, Function onPressed) {
    return ElevatedButton(
        child: Text(
          text,
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
          ),
        ),
        onPressed : () => onPressed
        );
  }
  void _onClickNavigator(BuildContext context, Widget page) {
    Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
      return page;
    }));
  }

Alguém poderia me ajudar? As páginas HelloPage (1 a 6) estão retornando apenas um appBar da seguinte maneira:
import 'package:flutter/material.dart';
class HelloPage1 extends StatelessWidget {
  const HelloPage1({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text ("Teste 1")),
    );
  }
}

Answer: Olá. As tuas páginas HelloPage... devolvem o Widget Scaffold no método build, porém você não definiu o parâmetro nomeado body que é justamente o corpo da tua página, trazendo visível somente o AppBar, como já notou.
Exemplo de Scaffold:
Scaffold(
  appBar: AppBar(
    title: Text('Teste 1),
  ),
  body: Center(child: Text('Olá mundo'))
)

Abs

Flutter - Navegação entre telas


404 page when accessing http://localhost:1111/

Question: Is the port 1111 reserved as a default port for the ODBC connection?
When I try to point my browser to
http://localhost:1111/
it gives a 404 and not a page not found.
What is the best way to debug 404's from the ODBC ?
I am using Ubuntu and Apache (is Apache related to this?)
Comment: I don't know what being asked here. Is your apache running on port 1111? I think you should rephrase your question with an explanation of what you are trying to accomplish.
Comment: Just rephrased my question.  Hopefully it is more clear now.
Comment: This question can't be answered in it's current form. See all of @micah points below.
Answer:
Is the port 1111 reserved as a default port for the ODBC connection?

no

When I try to point my browser to http://localhost:1111/ it gives a 404 and not a page not found. What is the best way to debug 404's from the ODBC ?

404 is the HTTP response code for "page not found". Do you have a webserver running on port 1111 that you are trying to communicate with? I don't understand what that has to do with ODBC.

I am using Ubuntu and Apache (is Apache related to this?)

I can not tell if this has anything to do with Apache with the information provided so far.


How to edit Commerce to display more than 3 products in a row

Question: I'm using Commerce Kickstart, I am not able to figure out how to display more than 3 products in a row. Even if I created a new View mode using Entity View Mode it still behaves the same.
How shall I go about changing this? Is there a setting somewhere in the View UI that's controlling this?
Thanks very much!
Answer: Think I found a way to resolve this simply via CSS.
There is this styles in global.css:

.page-products .view-display-products li:nth-child(3n+4) {
      clear: left;
      /* LTR */
      float: left;
      /** LTR */ }

so we can overwrite it with a sub-theme CSS with "clear:none".
By re-sizing browser window, looks like it still works well when window get smaller.
Earlier on didn't quite look close enough into this, partly due to meddling too  much in Views Format settings. So assuming reverting to default Views setting, the above CSS change should work fine. Will update again if otherwise.
BK :)


How to grant userpoints only for modifying nodes last changed at least 20 days ago?

Question: I am not sure how to go about this. I use the Userpoints module in Drupal 7 to attribute points to users who create nodes ('reviews'). I also want to allow them to gain some points if they supersede or modify an existing node... but only if the previous creation/mod was done over 20 days before.
How can I do this with Rules? Or else, how should I code it manually?
Comment: I will have a look at it in the next week. A bit short on time at the moment (the dreaded deadline...). Thanks for your answer anyway.
Answer: Sorry to say, but the previous answer has some challenges:

Rules Event After saving new content is not the right event.
I disagree with the "You will need a custom module ...", since there is an out-of-the-Rules-box Rules Condition you can use ... Read on for more details on that.

Here is a rule (in Rules Export format) that does what you're asking for:
{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Some more details about the above rule:

Rules Event: After updating existing content (you may want to limit it to selected content types only).
Rules Condition: Token [node-unchanged:changed] is at least from 20 days ago.
Rules Actions:

Grant 123 user points (adapt the number and the other options as you want).
Load the current userpoints balance.
Display a message with the current userpoints balance.

If you have the Rules UI enabled (and the Userpoints Rules module, you should be able to just import the above rule in your own site.
PS: After you're convinced the rule works as you want, you may want to remove the last 2 Rules Actions about the message shown to the user after user points were granted.
Comment: This worked as well. It is a good non-code alternative. Thanks for the input!
Answer: Giving points for adding new Review nodes:

Create new Rule; event: After saving new content + restrict by type: Review.
Action: Grant points to a user.

Note: you need to have Userpoints rules integration installed.

Giving points for updating Review nodes after certain period of time
You will need a custom module where you will create a new rule Condition using hook_rules_condition_info().
This condition will check if previous node revision is older than XX days (in your case 20 days).
Here's an example:
function YOUR_MODULE_rules_condition_info() {
  return array(
    'YOUR_MODULE_condition_compare_revision' => array(
      'label' => t('Compare date of last revision'),
      'parameter' => array(
        'node' => array(
          'label' => t('Node'),
          'type' => 'node',
        ),
      ),
    ),
  );
}

function YOUR_MODULE_condition_compare_revision($node) {
  $revision = db_select('node_revision', 'r')
    ->fields('r', array('nid'))
    ->condition('nid', $node->nid)
    // Make sure this is not the last revision.
    ->condition('vid', $node->vid, '!=')
    // Make sure this revision is older than your desired period of time.
    ->condition('timestamp', REQUEST_TIME - 20 * 24 * 60 * 60, '<=')
    ->execute()
    ->fetchObject();

  return $revision;
}

This could would go to YOUR_MODULE.rules.inc.
Note: I wrote this quickly and without testing. Should be working fine though.
Comment: Thanks a lot for your help. This was critical in achieving my goal. I do however want to make a correction. Since I want the user to get points only if the 'previous' update is older than a certain date, I actually needed to make sure that there were no reviews between the date of the latest review and 20 days before. I therefore used:
->condition('timestamp', array(REQUEST_TIME - 15 * 24 * 60 * 60, REQUEST_TIME), 'BETWEEN')
    ->execute()
    ->fetchAll();
Comment: Glad it was useful. If it solved your problem, accept the answer as a solution. It will help others with similar problem in the future, comments can get deleted.


Why does this two-element field not have a supremum if we disregard the Completeness Axiom for the reals?

Question: I have two questions, and I address them in two seperate paragraphs below.
I read that if we do not accept the Completeness Axiom for the reals and fields but accept all the other axioms for fields and the reals, then given any two-element field, whose elements are denoted by $0$ and $1$, we can show that the field does not have a supremum. I'm not sure how to prove this, but I believe it may be a consequence of the fact this two-element field cannot be totally ordered but I don't know how to then show that this field does not have a supremum; for, it seems to me that the supremum is simply $1$ since it is the smallest element such that all the other elements ($0$) in the field are smaller than it.
Also, I have another question, in my textbook, where it tries to verify that this set of reals will be field it assumes that $0+0=1+1=0$. Now, I can't simply understand how $1+1=0$ but I do believe that the author is trying to show, somehow, the inverse of $1$, but surely that would be $-1$? Now, if it were group theory, this might have made sense since $1+1=0$ for the set of integers in modulo $2$. After some speculation, I noticed that the author said, for fields, we define two operations to have the properties of inverses, identities, associative law Et Cetera. So, does it mean that for this field $1+1=0$ is defined this way?
(Note: By the other "axioms" I mean the distributive, associative, and commutative laws, the identity property and the inverse property.
Also, the reason I am asking this question is to clarify a statement the author makes to show that without the completeness axioms some fields may not have a supremum: "we will see in Example 1.1.2 (the field wih elements $0$ and $1$) that properties A-H does not gurantee that every nonempty set that is bounded above has a supremum". And, the text I am quoting from is http://ramanujan.math.trinity.edu/wtrench/texts/TRENCH_REAL_ANALYSIS.PDF)
Comment: Where did you read what you say you read? Makes very little sense to me. The elements of the two-element field are not real numbers. (Or at least thinking of them as reals is a very bad idea.) Saying the two-element field has no supremum makes no sense because there's no order on it, as you note. Yes, when they _define_ that field they _define_ the operations, and $1+1=0$ is part of that definition.
Comment: You probably read instead that a field that is not complete (but has all the other axioms of the real field) has not the least upper bound property.
Comment: This question is quite incomplete. It would be better if you could be more specific, including the language of the source, if possible
Comment: I may be misinterpreting (having read it again I believe I am, in the sense, as you noted, that they are not a field on the reals), but it's from http://ramanujan.math.trinity.edu/wtrench/texts/TRENCH_REAL_ANALYSIS.PDF on the first couple of pages.
Comment: @DavidC.Ullrich Sorry for the terrible question and my misrepresentation of the text and the words "we will see" in the text as they go on to prove, as you also said, that the field will not be totally ordered so it having a supremum does not make sense. Although this question should be deleted for its vague character now that I have re-read it, I believe it useful to someone who is wondering the same thing and looks for some guidance.
Answer: In a finite set that is linearly ordered every non-empty subset has a supremum that is actually a maximum.
"all the other axioms for fields and the reals" is highly non-specific, and precision in matters of this sort may be just the thing needed to clear up confusions.
A field with two elements can have its elements linearly ordered so that $0<1$, but that is not what is called an "ordered field" because it fails to satisfy the rule that if $a<b$ then $a+c<b+c$.  Thus
\begin{align}
0 & < 1 \\[10pt] \text{but }0+1 & \not < 1+1.
\end{align}
Your question isn't clear enough to me for me to be confident as to whether this answers it or not.
Comment: By the other axioms, or properties, I mean the inverse property, the identity property, the associative property, the distributive property, and the commutative property.
Comment: I edited the question with additional detail if that helps.


Login flutuante e Login query

Question: Quero criar um retangulo com login sobre a página que estou a trabalhar. Nao quero que o login vá para uma página só com o login.
Isso é possível ?
Outra duvida e fazer com cada login veja uma query especifica. Isso é possivel?
Comment: Quanto a primeira pergunta: **Sim**. E a segunda: **Sim**.
Answer: Quanto a primeira parte da sua dúvida você pode fazer com algo do tipo que montei agora, clique em "Executar trecho de código" para ver o código em ação:
(note que não mexi com nada de alinhamentos)

$(function(){

  // Ao clicar para mostrar o formulário de login

  $("button.fazer-login").click(function(){
    $("#login-container").fadeIn("fast");
  });

  // Ao clicar para fechar o formulário de login

  $("button.fechar-login").click(function(){
    $("#login-container").fadeOut("fast");
  });

  // Se preferir que o login seja por AJAX

  $("#login-container #login").submit(function(e){

    // O e.preventDefault impede do formulário ser enviado para o faz_login.php, recarregando a página imediatamente

    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: 'faz_login.php',
        data: $("#login").serialize(),
        success: function(data){
          // Mostrar a resposta em um alert
          alert(data);
          // Ou se preferir fazer o debug pelo console
          console.log(data);
        }
    });

  });

});
body{
  background:#ECECEC;
  margin:0;
  padding:0;
}

#login-container{
  background: rgba(0,0,0,0.8);
  width:100%;
  height:100%;
  margin:0;
  padding:0;
  position:fixed;
  z-index:999;
}

#login{
  margin:0 auto;
  width:500px;
  height:500px;
  text-align:center;

  margin-top:100px;
}

#login input[name=usuario]{
  margin:0px 0 5px;
}

#login input[type=submit]{
  margin:15px 0 5px;
}

  <form id="login" method="post" action="faz_login.php">
    <input type="text" placeholder="Usuário" name="usuario" />

    <input type="password" placeholder="Senha" name="senha" />

    <input type="submit" value="Entrar" />

    <button class="fechar-login">Fechar login</button>
  </form>

Aqui é a sua página.

<button class="fazer-login">Clique aqui para fazer login!</button>

Se você quiser que o formulário de login fique centralizado na vertical, irá ter que fazer ajustes no código.
EDITADO
Adicionei o código de ajax no evento de enviar o formulário.
Agora no faz_login.php
<?php

$usuario = $_POST['usuario'];
$senha = $_POST['senha'];

$query = "SELECT count(*) FROM usuarios WHERE usuario = '".$usuario."' AND senha = '".$senha."'";
$consulta = mysql_query($query);
$resultado = mysql_fetch_array($consulta);

if($resultado[0]){
echo "Login realizado com sucesso!";
}
else{
echo "Dados incorretos.";
}

?>

Nesse código PHP você pode manipular a consulta da forma que preferir.
Comment: Sim, é só trocar o button pelo img e no jQuery, todas as chamadas para "button.fazer-login" você vai trocar para "img.fazer-login" ou simplesmente ".fazer-login".
Comment: secalhar nao me expliquei bem mas depois do login dependendo do login utilizado mostrar uma query especifica.
Se for o login 1 mostrar a query X
Se for o login 2 mostrar a query Y
Comment: Depende da query (consulta) que você quer. A consulta vai ser realizada onde? No banco de dados ou dentro de um condição montada na hora no javascript?
Comment: um banco de dados Mysql
Comment: Você trabalha com PHP?
Comment: Sim so com php e Mysql
Comment: Nesse caso, vou editar a resposta acima.
Comment: Surgiu-me um problema a ver se me consegue ajudar nisto.
é possivel fazer o login em fez de ser o botão..Clique aqui para fazer login! usar isto :
Comment: a ver se me consegue ajudar. fiz isso mas nao acontece nada. Deixo aqui o codigo: http://jsfiddle.net/7yfs4rzr/
Comment: Você não pode esquecer de inicializar o jquery com "$(function(){". Fora isso sempre indenize o código para não esquecer de fechar tags do HTML. Aqui o jsfiddle editado: http://jsfiddle.net/7yfs4rzr/2/
Comment: boas, tive um tempo fora e agora fui novamente pegar nisso e o resultado é me mostrado numa pequena janela em vez de ser numa pagina nova ..
Answer: Amigo você pode usar o dialog do JQuery. Abaixo segue o link:
http://jqueryui.com/dialog/#modal-form

Login flutuante e Login query