text:
Q: Automatically add HStore extension Django I'm developing on a django app that has a directory like so:
App:
manage.py
  --App1:
    -models.py
    -etc.
  --App2:
    -models.py
    -etc.
  --App3:
    -models.py
    -etc.

Many of them use HStore field(s) in the model definition file and when I go to migrate them each time I have to do this sequence:

*

*run python manage.py makemigrations {app 1,2,3 and so on here}

*Add   HStoreExtension() to operations=[] in the first migration file like: 0001_initial.py

It becomes tedious to do that when there's a ton of migrations for one app. I realize there may be better ways to structure the application but that's how it was built.
Is there any way to avoid having to "makemigrations" then add the hstore extension to the operations each time? I don't want to create a lot of manual work for others to spin up the app.
I know there are similar questions where the solution is to run a query to the database to add the extension. In this multiple subdirectory apps situation would I just include that in the top level application init file?


text:
Q: Java interface and callback method Can anyone explain the concept behind this code? I don't know what to search for or where to start? I would like to more about this type of programming.
private static interface A {
    void apply(String name, int i, int j);
}
private final A method_A = (name, i, j) -> methodOne(name, i, j);
private final A method_B = (name, i, j) -> methodTwo(name, i, j);
public void methodOne(String name, int i, int j){
    // do something
}
public void methodTwo(String name, int i, int j){
    // do some other thing
}

Thanks

A: Since Java 8, interfaces with one non-default method can be expressed as lambda-expressions. Those interfaces are also called functional interfaces.
Your code creates two instances of the interface A as such lambda-expressions, which are implemented as adapters to the methods methodOne and methodTwo.
Basically this is a more compact way of writing
...

private final A method_A = new A{
    public void apply(String name, int i, int j){
        methodOne(name, i, j);
    }
};

private final A method_B = new A{
    public void apply(String name, int i, int j){
        methodOne(name, i, j);
    }
};

...

A: Your code can actually be simplfied to this:
private static interface A {
    void apply(String name, int i, int j);
}
private final A method_A = this::methodOne;
private final A method_B = this::methodTwo;
public void methodOne(String name, int i, int j){
    // do something
}
public void methodTwo(String name, int i, int j){
    // do some other thing
}

The two variables method_A and method_B are just regular variables that are of type A. The real special thing about this is the value you assign to the variables - this::methodOne.
I assume you have some knowledge about classes and interfaces and how their instances work. If not, learn those things first.
A has only one method, so you can treat it like a type that "stores" a method. I will explain why.
Prior to Java 8, you would write something like this:
private final A method_A = new A() {
    @Override
    public void apply(String name, int i, int j) {
        EnclosingClass.this.methodOne(name, i, j);
    }
};

You create an anonymous class that only has the apply method. See? Isn't the method_A object storing nothing but an implementation of a method?
Since Java 8, you can instead write this lambda expression:
private final A method_A = this::methodOne;

As you can probably guess by now, it's all syntactic sugar. You are basically saying that method_A will store methdOne. You can then pass method_A around and you are actually passing the implementation of a method!
The new stream API takes advantage of this and lets you do things like:
someList.stream().forEach(System.out::println);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Behavior of the cameranode is unclear when moving a 3D model in a scene with sceneKit When I setup the scene, the camera gets its position like here:
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    scene?.rootNode.addChildNode(cameraNode)
    cameraNode.position = SCNVector3(x: 0, y: 0, z: 20)

My (obviously wrong) assumption was that these position data will change when a user starts to move or zoom the 3D model. This would mean that actually not the 3D model is changing its position but just the view point (of the camera).
However, I notice that the initial data do never change and I cannot detect programmatically whether the user has zoomed in or out etc.
I would appreciate if someone could explain the logic which sceneKit is using here and whether I can derive the 3D model (or camera?) position change by any other method?

A: The documentation for allowsCameraControl mentions that the out of the box camera control mechanism doesn't modify the scene graph:

If you set this property to true, SceneKit creates a camera node and handles mouse or touch events to allow the user to pan, zoom, and rotate their view of the scene. (Enabling user camera control does not modify camera objects already existing in the scene graph or the nodes containing them.)


text:
Q: Do DC/DC converters provide reverse polarity protection? I plan on using a TPS63061 as DC/DC to get a steady 5V from 4xAA batteries. The data sheet says:

8.3.4 Undervoltage Lockout
  An undervoltage lockout function prevents device start-up if the supply voltage on VIN is lower than approximately its threshold (see the Electrical Characteristics table). When in operation, the device automatically enters the shutdown mode if the voltage on VIN drops below the undervoltage lockout threshold. The device automatically restarts if the input voltage recovers to the minimum operating input voltage.

The Electrical Characteristics table states:

UVLO Under voltage lockout threshold:
  Input voltage falling | min 1.8V | typ 1.9V | max 2.2V
UVLO hysteresis:
  300 mV

Does this mean that the TPS63061 protects me from reverse polarity if I place my batteries in reversed order? Which would yield -6V which would be below 1.8V and hence the under voltage lockout function would protect me?
Or do I need an additional protection e.g. using a Schottky diode or MOSFET to avoid damage to the DC/DC and other components?

A: Alas, no. If you give it a voltage under -0.3V it will probably be toast.

So yes, you need additional protection against reverse polarity.

A: No, generally, DC to DC components do not provide reverse polarity protection. Undervoltage lockout prevents starting with a too low voltage for the converter to work with. Certain components can tolerate reverse voltage, but this puts stress on the component, and is not recommended by the manufacturer.


text:
Q: Can't inject my factory in angular I'm trying to inject my custom factory that look like this:
var tester = angular.module('tester', ['example']);

tester.controller('TesterCtrl', ['Example', function(Example) {   console.log(Example.test()); }]);

var example = angular.module('example', []);

example.factory('Example', function() {
    return {
        test: function() {
            return 'test';
        }
    };
});

And i get the following error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.22/$injector/unpr?p0=ExampleProvider%20%3C-%20Example

I have other custom factorys made the same way, and i can inject them with no problems.
Plunker: http://plnkr.co/edit/5Qk2Raod6938aEhixz1r?p=preview

A: Example service is defined within example module. So if you want to use Example service in your tester module, you have to define example module as a dependency for tester module.
This is a little bit confusing because of the naming you used. But you should just do as the following code.
angular.module('tester', ['example']);

Here is the updated plunker.


text:
Q: When there is a persistent connection how does a server identify subsequent request? I am studying network sockets.
To my understanding ServerSocket accepts a new incoming request and returns a new socket. Now a persistent connection is established. A client and a server sockets are ready to communicate. The client sends a new request to the server host and port. Does this new request have to be handled by a ServerSocket first? Or in other words how does the server identify that this request should be handled by already existing connection?


text:
Q: How I can dynamically create new TabItems with views and viewModels for a TabControl in Silverlight with the MVVM Light Toolkit? I'm a starter with Silverlight and the MVVM Light Toolkit and I don't know how to proper solve the following scenario:
I have the following views with their corresponding viewModels:

*

*MainView , the Deault Startpage

*TabControlView, view with a single Tabcontrol, placed on the MainView…

*AllBugsGridView, datagrid with all bugs.

*BugDetailView, view where the details of a single bug is showed, or a new bug can be added.. (datafields, labels, etc)

Now my target is the following:
I want to have a tabitem with an AllBugsGridView as content. (No Problem)
Now when a user is making a double click on an item in the datagrid it should create a new tabItem with a bugDetailView inside showing the Details of the Grid Item. It Should be possible to have as many open tabitems as the user wants .
Further the user can add a new Bug over a button and  a new tab opens with an empty bugDetailView.
Has anybody a proper solution for that. I don't know how I can dynamically create new Views and ViewModels and wire them together.
Thank you very much for your answers.
Best regards
Hans

A: Take a look at my sample project here. While it's not using MVVM Light, it can be easily modified to work with it. The main idea is that the tab is defined as a "region" and you have a region manager that understands how to work with tab controls. Then, you simply route the view to the region and let it take care of the rest.
http://csharperimage.jeremylikness.com/2010/06/advanced-silverlight-applications-using.html

A: If you bind your TabControls source to your viewmodel's property of type ObservableCollection of ViewModelBase you can add new ViewModels to your collection or remove as needed.  This keeps the ViewModels only seeing themselves and not the views.  For the view side beyond binding the source to the collection you also set the Views and ViewModels as datatemplate and adorner pairs...
<Window.Resources>
    <DataTemplate DataType="{x:Type VM:ChangePasswordVM}">
        <AdornerDecorator>
            <localUserControls:ChangePasswordView />
        </AdornerDecorator>
    </DataTemplate>
</Window.Resources>


text:
Q: E2E Testing Angular with Karma - ng-scenario 'Module is not defined' I've been trying to run some e2e tests with Karma.
It's not working for me at all.
Right now I'm getting the following error:
    Firefox 28.0.0 (Windows 7) ERROR
  ReferenceError: module is not defined
  at C:/MYPATH/Test/node_modules/karma-ng-scenario/lib/ind
ex.js:12

Firefox 28.0.0 (Windows 7) ERROR
  ReferenceError: browser is not defined
  at C:/MYPATH/Test/e2e/scenarios.js:12

My config file looks like this:
module.exports = function(config){
  config.set({

    basePath : './',

    frameworks: ['ng-scenario'],

    files : [
    './node_modules/karma-ng-scenario/lib/*.js',
      './e2e/*.js'
    ],

    autoWatch : true,

    singleRun : true,

    browsers : ['Firefox'],

    plugins : [
            'karma-ng-scenario',
            'karma-chrome-launcher',
            'karma-firefox-launcher'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    },

    urlRoot : '/__karma/',

    proxies : {
      '/public/' : 'http://localhost:8080'
    }

  });
};

My scenarios file just tests to see if the base path redirects.
I've already done a lot of messing with npm to get to this point, most recently "npm install karma-ng-scenario --save-dev" but no luck unfortunately.

A: In files:[...] array you have to specify all the files that contain the actual code to which you are writing tests,  if your module is using other modules, then you should add  files  of all the modules on which your module depends.
suppose you are testing 'someModule' module you have to include the 'someModule' controllers, views, services, directives and other modules if your module depends on them
Note: Assuming your files are in their specific directories
files: [
  ...       //angularjs, angular-mocks, karma, protractor and other files you need
  ...
  'scripts/someModule/controllers/*.js',
  'scripts/someModule/services/*.js',
  'scripts/someModule/directives/*.js',
  'views/someModule/*.html'
]

or simply
files: [
   ...       //angularjs, angular-mocks, karma, protractor and other files you need
   ...
   'scripts/someModule/**/*.js',
   'views/someModule/*.html'
]

And make sure to install and include all the testing libraries you depend on (i.e, angularjs, angular-mocks, protrator, karma etc) in the files array

A: In files[] specify path to angular.js as a very first, then any other angular modules you use (angular-mocks.js, angular-resource.js, angular-cookies.js), then any library you use, then your own code.

A: So the configuration I finally got my E2E tests to work with was this:
// Karma configuration
// Generated on Fri Apr 11 2014 02:35:20 GMT+0800 (China Standard Time)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '..',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
    ANGULAR_SCENARIO,
    ANGULAR_SCENARIO_ADAPTER,
      'test/e2e/*.js',
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    //browsers: ['PhantomJS', 'Firefox', 'Chrome'],
    browsers: ['Firefox', 'Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    proxies : {
    "/": "http://localhost:8080"
    },

    urlRoot : "/__karma/"
  });
};

It seems that a better solution for running end to end tests is to use protractor. NG-SCENARIO is depreciated and will cause warnings but this should still run. https://github.com/angular/protractor


text:
Q: What happens when you boot the computer from a Unix perspective? Can anyone tell me how do I understand what happens when you boot up a Unix system? Like "BIOS" is loaded, it does a peripheral test etc until you get a shell?

A: For each unix it's different but for linux, from bios you go the bootloader (u-boot, lilo, grub..) then the kernel decompress itself, start himself and call init once booted.
This article explain well the process :
http://www.ibm.com/developerworks/linux/library/l-linuxboot/

A: It depends on the system, but in general, you want to start with a look at the init process: http://en.wikipedia.org/wiki/Init
I also recommend "Advanced Programming In the UNIX Environment" (I think in 3rd edition right now) which goes into much detail on this and many questions like it.

A: To make it easier, BIOS checks for bootable devices in order defined,
The first one that is found, First sector is copied to the memory.
The code at the memory position 0800 hex is then set to the Program Counter register and execution is delivered to the bootable media.


text:
Q: Elasticsearch not displaying all the versions which are having the same match body: {
    "query": {
      "bool": {
        "should": [

          { "match": { "content": "build" } },

        ]
      }
    }

I have given the search in this manner and i'm getting displayed only the latest version in which that match is present and the others are not getting displayed, can anyone find me a solution

A: As far as I know, elasticsearch does not store previous versions of documents. The version number is just a mechanism for managing concurrency.
For example: https://github.com/elastic/elasticsearch/issues/18825


text:
Q: Buttons in android are overlapping. Need a fix I am having some trouble with my xml file. Well it was working at first but the later I wanted to give it a scroll view so I added the scroll view on to the main.xml. After saving the file. The app used to crash without launching. Seeing this I removed the scroll view on the main.xml file, and am facing a new problem in which all of the buttons are being overlapped one another.
Also if you could tell me how can I give a scroll view tag correctly it would be helpful.
Cheers. Thank you !
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Creating and Using Databases without Content Provider"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edit"
android:padding="6dip"/>

 <EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/msg"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text = "Add a new book"
android:id="@+id/addTitle"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/upTitle"
android:text="Update a book"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/rtrTitles"
android:text="Retrieve all books"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/rtrTitle"
android:text="Retrieve Specific book"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/delTitle"
android:text="Delete a book"
android:padding="6dip"/>

<Button
android:text="Send SMS"
android:id="@+id/sms"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip"/>

</RelativeLayout>

This is the main xml file with the buttons overlapping.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Creating and Using Databases without Content Provider"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edit"
android:padding="6dip"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/msg"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text = "Add a new book"
android:id="@+id/addTitle"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/upTitle"
android:text="Update a book"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/rtrTitles"
android:text="Retrieve all books"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/rtrTitle"
android:text="Retrieve Specific book"
android:padding="6dip"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/delTitle"
android:text="Delete a book"
android:padding="6dip"/>

<Button
android:text="Send SMS"
android:id="@+id/sms"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip"/>
</ScrollView>
</RelativeLayout>

This is the main.xml with scroll view

A: You are using a RelativeLayout and not actually "placing" the buttons beside, or on top, or whatever of each other using something like the android:layout_toRightOf tags. The scrollview must be the parent view because it can only accept one child, which in your situation should be a LinearLayout (or a relative if your going to place your objects correctly). The main issue with your xml however is that RelativeLayout.

A: Using a RelativeLayout you should use ALIGN_LEFT, ALIGN_RIGHT, LEFT_OF etc in order to avoid such overlapping. Other way would be simply using LinearLayout.


text:
Q: What does "so" in "I am so out of here" mean? Ok,
The idiom "out of here" means going or leaving (source)
So, I am out of here=I am leaving (not sure it means "I am moving out right now" or "I will move out shortly")
Now, we also have "I am so out of here".
My question is: does "so"="extremely" in this case?
So, "I am so out of here" = "I am extremely out of here".
But, seem noone says "I am extremely out of here", right?

A: It is an intensifier; it emphasizes the emotional state of the speaker.
The implication of "so out of here" (and you do have to emphasize it when spoken) is that it's long past time, or that whatever is driving you away is obviously egregious.
Often we use swear words for this in English ("I am f---ing OUT of here"; "I am bloody well out of here" in UK English might be a minced version of this).
It's also an in-culture marker, used by a particular generation/culture exemplified by, say, the movie "Legally Blond".
Note: "[getting] out of here" always means "leaving this place", but the place might be metaphorical, as in "I am quitting this job".

A: "So" adjective to enhance a verb such as "out". 1) Together a stronger emotional emphasis of the verb not to be reversed in consolidation or emotional reprieve. 2) used to state the intent to ensure clarity and remove confusion of the intent or otherwise misinterpretation of the recepiant. 3) Used for clarity of emphasis.


text:
Q: querying on kinda EVA like model we have this table and some data

in some scenario we need to get the Entities that they have a property that have special Value and the property itself is not important.
the prob is we want to get entities that they have property where value is equal to 1 and also have a property with a value of 2
in a simple way we need something like this :

SELECT Entity_Id FROM table WHERE Value = 1 AND Value = 2

this query returns nothing because the Value column only have 1 value ^_^
actually we need something like this

SELECT Entity_Id FROM table
GROUP BY Entity_Id
HAVING Value = 1 AND Value = 2

MsSql do not support this query, u have to use an aggregate function. OTL
because in this scenario all filters set on Value column
u can parsing the first query to something like this :
SELECT
    DISTINCT Entity_Id,
    (SELECT COUNT(*) FROM table WHERE Value = 1 and Order_Id = outerTable.Order_Id)
    *
    (SELECT COUNT(*) FROM table WHERE Value = 2 and Order_Id = outerTable.Order_Id) as xxx
FROM table AS outerTable

currently what i do is get the first query predicates and pars it to third form query.
EDIT :
the filters that set on first query is optional and sent by user without knowing the background structure , he think that all of properties is saved as columns for this entity
thats why i parse the AND to
(subQry(filter1) * subQry(filter2) * .... * subQry(filter N))
OR to
(subQry(filter1) + subQry(filter2) + ..... + subQry(filter N))
looking for a better solution ^_^"
thanks in advance.

A: Here are two other ways, in addition to what the other answers already mention:
select entity_id from table where value = 1
intersect
select entity_id from table where value = 2

select t1.entity_id from table t1
join table t2 on t1.entity_id = t2.entity_id
where t1.value = 1 and t2.value = 2

A: Here is one method:
SELECT Entity_Id
FROM table
WHERE Value in (1, 2)
GROUP BY Entity_Id
HAVING COUNT(DISTINCT value) = 2;

A: You can do the check with exists clause, with something like this:
SELECT Entity_Id
FROM table t1
WHERE Value = 1 AND
exists (
  select 1
  from table t2
  where t1.entity_id = t2.entity_id and
  t2.Value = 2)


text:
Q: .NET projection (CRS conversation) library Is there any open-source library exist to calculate coordinate conversions from a CRS (coordinate reference system) to another?

A: I would look into Proj.NET. A fork of it is maintained in NetTopologySuite, which provides you with other spatial functionality.
Another option is to look at DotSpatial with its library DotSpatial.Projections.
Both are ported from the proj4 C++ library.
If you want to convert entire files then I would go with the GDAL/OGR tooling. Easy installation for this is provided by OSGeo4W. Note that there also GDAL/OGR .NET bindings available.

A: Look for conversion to ECEF (Earth Centered, Earth Focused) conversions. You would take your point in system A, covert to ECEF X,Y,Z from earth center, then convert that to system B.
I don't know of a specific library to recommend. There are lots of results on Google. Just hoping to give you a good direction to start your search.

A: check our gdal/ogr
Idont use it with .NET but i think it should work


text:
Q: C code compiles but in arduino sketch it doesn't I have some C code which compiles with GNU GCC but when i put it on an arduino sketch it says

cannot convert 'const float' to 'float ()[25]' for argument '1' to
  'float dot_product(float ()[25], float*)'

In the sketch there is function sigmoid and forward and dot_p which are all defined, I am trying to store some values on the sketch itself, because i cannot store all the values on the EEPROM, please any extra clarification i can provide if you can help
the sketch is as follows:
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const float a[25][25] = { A LONG LIST OF NUMBERS arranged in 25X25};

  float b[25]={Another list of numbers};
 void setup() {}

 void loop() {}

 float dot_product(float v[][25], float u[])
{

    for (int j = 0; j< 25; j++){
             float result = 0.0;
    for (int i = 0; i < 25; i++){
        result += u[i]*v[j][i];

    }
    return result;
    }
}
double forward(float x){

    float lm[25];
    double km[25];
    double t=0;
    double output=0;
    for(int i=0; i <25; i++){
        lm[i] = 0;
        km[i] = 0;
    }
    for (int k=0; k<25; k++){
        lm[k]= dot_product(a[k],x);
        /*** THIS IS THE ERROR SOURCE***/

    }

     for (int j=0; j<25;j++){
      km[j] = sigmoid(lm[j]);

    }

    t = dot_p(km,b);
    output = sigmoid(t);

    return output;

}

A: after removing all the 'unneeded' code and correcting several small errors, the result is:
// if you really want 'const',
// then all references must also be 'const'
float a[25][25];

// the second parameter is from a float value
// not from an array of float values
float dot_product( float v[][25], float u )
{
    // initialize the float variable from a float literal
    // rather than from a double literal
    float result = 0.0f;

    for (int i = 0; i < 25; i++)
    {
        // since the function exits after summing a single
        // row, the 'j' is replaced with 0
        result += u * v[0][i];
    }
    return result;
}

void forward(float x)
{
    float lm = 0.0f;

    for (int k=0; k<25; k++)
    {
        // note: passing address of 'a[k]'
        lm += dot_product( &a[k], x );
    }
}


text:
Q: A-Frame 0.6.1 - Camera rotation animation I'm currently trying to animate a camera's rotation in a scene. The animation should occur after looking at a circle for 1 second.
The problem is that the bottom of the scene don't seem reachable after the animation, althrough that it is before the animation occured.
I tried first to animate the camera, then a container of the camera. The second option produced an other problem, it seems that all the sky is displaced and I don't understand how to "correct" that.
Video of the problem when the animation is on the camera
Here are two codepens :

*

*Animation on the camera

          <a-entity id="cursor" cursor="fuse: true; fuseTimeout: 100"
              position="0 0 -1"
              geometry="primitive: ring; radiusInner: 0.013; radiusOuter: 0.02"
              material="color: #000; shader: flat"

              animation__fuse="startEvents: fusing;
                          property: scale;
                          dur: 1000;
                          to: 0.4 0.4 0.4"
              animation__fuseed="startEvents: animation__fuse-complete;
                          property: scale;
                          dur: 1;
                          to: 1 1 1"
              >

*Animation on a container

          <a-entity id="cursor" cursor="fuse: true; fuseTimeout: 100"
              position="0 0 -1"
              geometry="primitive: ring; radiusInner: 0.013; radiusOuter: 0.02"
              material="color: #000; shader: flat"

              animation__fuse="startEvents: fusing;
                      property: scale;
                      dur: 1000;
                      to: 0.4 0.4 0.4"
              animation__fuseed="startEvents: animation__fuse-complete;
                      property: scale;
                      dur: 1;
                      to: 1 1 1">

How to correctly animate the rotation of the camera ?
I'm on Windows 10, with Chrome 59, A-Frame 0.6.1 and aframe-animation-component
Thank you in advance and have a nice day !

A: I came across a similar problem with being unable to reach the bottom rotation position after executing setAttribute on the camera rotation. Here is what I think is happening:
The problem arises because the rotation on the X-axis changes via code, moving from 0 to 30 degrees without there being a corresponding head motion. As a result, 30 degrees are lost off of the lower limit of -90 degrees.
I think that there is a strong intention in the design of A-Frame that visual angles that arise via head position remain consistent. If you are looking straight ahead and suddenly the angle is 30 degrees higher, yet you haven't moved your head, everything will be askew. You'd have to look downward 30 degrees to see "straight ahead", etc.
It is easy to try and code these discontinuities when A-Frame is viewed through a desktop monitor rather than a visor. I think the "solution" is going to have to be to design some way to have the camera return to its starting position when you run your animation so that it doesn't lose its correspondence to the player's head.


text:
Q: Fragment Shader Error of writing to more than 1 ouput The following is my code for a fragment shader to generate a texture on the floor and sphere and a fog effect above it.
I get an error which says "Fragment shader writes to more than 1 type of output gl_FragData, gl_FragColor or user bound frag data." when I try to compile it.
out vec4 color;
out vec2 texCoord;

uniform int fogType;
uniform int enableFloorTexture;
uniform int sphereTexture;
uniform int objectType;
uniform sampler2D texture;
uniform sampler1D stexture;

void main()
{
vec4 finColor = color;
if (objectType == 1)
{
    if(enableFloorTexture == 1)
    {
        finColor = color * texture2D( texture, texCoord );
    }
}
else if (objectType == 2)
{
    if(sphereTexture != 0)
    {
        finColor = color * texture1D( stexture, texCoord.x );
    }
}

float fogFactor = 0.0;
float fogDepth = (18.0 - 0.0);
float fogDensity = 0.09;
vec4 fogColor = vec4(0.7, 0.7, 0.7, 0.5);
float z = gl_FragCoord.z / gl_FragCoord.w;

if(fogType == 1)
{
    fogFactor = (18.0 - z) / fogDepth;
}
else if (fogType == 2)
{
    fogFactor = exp( -fogDensity * z  );
}
else if (fogType == 3)
{
    fogFactor = exp( -fogDensity * fogDensity * z * z );
}
fogFactor = clamp(fogFactor, 0.0, 1.0);

if(fogType == 0)
{
    gl_FragColor = finColor;
}
else
{
    gl_FragColor = mix(fogColor, finColor, fogFactor);
}
}

A: What confuses me in your program is that you are using color as an output but you are using it in your program. Is this just a slip of a pen?
If you want to use #version 400output format,the output should be like this:
layout(location = 0) out vec4 color;

A: You have some outputs declared:
out vec4 color;
out vec2 texCoord;

Try making them inputs.


text:
Q: Integrating massive modes for supergraviton (D0 brane) scattering From this paper, I want to integrate out the massive degrees of freedom. When we expand the action about a classical background, diagonalizing the mass matrix gives us particles with the following masses squared:

*

*16 bosons with $m^2 = r^{2}$

*2 bosons with $m^2 = r^2 + 2v$

*2 bosons with $m^2 = r^2 - 2v$

*10 massless modes

*8 real fermions with $m^2 = r^2 + v$

*8 real fermions with $m^2 = r^2 - v$

*2 ghost bosons with $m^2 = r^2$

*1 massless ghost boson

For each bosonic field, integrating out yields an inverse square root of the determinant. For each fermionic field, integration gives the determinant. I'm not sure how to integrate a ghost particle. From integrating out the bosons of mass squared $r^{2} \pm 2v$, I get the correct determinants $\det^{-1}(-\partial^{2}_{\tau} + r^{2} - 2v) \det^{-1}(-\partial^{2}_{\tau} + r^{2} + 2v)$. However, I am unable to work out the following factors: $\det^{-6}(-\partial^{2}_{\tau} + r^{2}) \det^{4}(-\partial^{2}_{\tau} + r^{2} + v) \det^{4}(-\partial^{2}_{\tau} + r^{2} - v)$. I'm not sure what I'm missing here.
Furthermore, how does fact that the sum of the powers is zero follow from
super symmetry?


text:
Q: Symfony2 embedded forms are nullified despite of cascade_validation being false In a form (ContractType) I need the association to a Customer, which itself has an association to a Company and a BillingAddress. But the data itself of these 3 "nested entities" should not be editable at all in the contract view. That's why the field for the customer ManyToOne-Relation in the contract is hidden.
However for display purposes I need the whole customer-object in the form too (incl. the underlying company and billing address) - but as read-only. This is why I added an additional field customerFullObject to the contract form-type - which is not mapped (mapped => false). As it is an unmapped field, I set the data via a form event.
Now, when I edit the contract data, the company- and billing-address-data of the customer is nullified.
If I remove/comment the whole customerFullObject part, everything is fine.
I don't understand, how/why an unmapped field can change the data of an entity.
How can I prevent Symfony from this? Or is there a better "pattern"/way to achieve what I want? I couldn't find anything in the docs.
Below some code snippets from the model (removed namespaces for briefness):
Contract.php
/**
 * @ORM\Entity
 */
class Contract {
    /**
     * @var Customer
     * @ORM\ManyToOne(targetEntity="Customer", inversedBy="contracts")
     * @Assert\Type(type="Customer")
     * @Assert\NotBlank(message = "customer.notBlank")
     **/
    private $customer;

    // Other fields left out as irrelevant.
}

Customer.php
/**
 * @ORM\Entity
 */
class Customer {
    /**
     * @var Company
     * @ORM\OneToOne(targetEntity="Company")
     * @Assert\NotBlank(message="company.notBlank")
     **/
    private $company;

    /**
     * @var Address
     * @ORM\OneToOne(targetEntity="Address")
     * @Assert\NotBlank(message="billingAddress.notBlank")
     **/
    private $billingAddress;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="Contract", mappedBy="customer", orphanRemoval=true, cascade={"all"})
     **/
    private $contracts;

    // Other fields left out as irrelevant.
}

ContractType.php
class ContractType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add(
            'customer',
            'customerHiddenType',
            array(
                'label' => 'contract.customer',
            )
        );

        $builder->add(
            'customerFullObject',
            'customerType',
            array(
                'cascade_validation' => false,
                'mapped' => false
            )
        );

        $builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
                $form = $event->getForm();
                $editMode = $form->getConfig()->getOption('editMode');
                if (!empty($editMode) && $editMode === RequestAction::CREATE()) {
                    $form->remove('customerFullObject');
                } else {
                    $form->get('customerFullObject')->setData($event->getData()->getCustomer());
                }
            }
        );

        // Other children left out as irrelevant.
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(
             array(
                 'data_class' => 'Contract',
                 'cascade_validation' => true
             )
        );
    }

    public function getName() {
        return 'contractType';
    }
}

CustomerType.php
class CustomerType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add(
            'company',
            'companyType',
            array(
                'cascade_validation' => false,
                'label' => 'customer.company'
            )
        );

        $builder->add(
            'billingAddress',
            'addressType',
            array(
                'cascade_validation' => false,
                'label' => 'customer.billingAddress'
            )
        );

        // Other children left out as irrelevant.
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(
             array(
                 'data_class' => 'Customer',
                 'cascade_validation' => true
             )
        );
    }

    public function getName() {
        return 'customerType';
    }
}


text:
Q: PHP copys with wrong encoding I'm building WordPress plugin and need to move files extracted from rar to wp-uploads but copy function fails with failed to open stream: No such file or directory.
I opened xdebug tool in Atom editor to see what is going on. Xdebug says that filename of file I'm trying to copy is 2016-04-01_CZTERY KDTY_538589020.jpg where original name (the one on my drive) is 2016-04-01_CZTERY KĄTY_538589020.jpg. It all fails because of wrong encoding.
How can I check encoding of file name and set it properly?


text:
Q: WPF ComboBox update source I have a ComboBox with country codes and phone numbers (+43.., ..)
The ItemsSource is a list of Country objects with many properties (Code is one of them.)
The DataContext in which the ComboBox is located is an object with the PhoneNumber property.
When user selects a country in the list, I want to update the source PhoneNumber Property(which is a string) with the '+43' value from the Country object.
The list appears, but the source is never updated. How to do that?
When I replace it with this TextBox, everything works fine:
<TextBox Text="{Binding Path=CountryCode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

<ComboBox ItemsSource="{x:Static Member=data:Country.AllCountries}" SelectedValuePath="Country.Value.Code" SelectedValue="??" >

A: OK I found the solution by myself:
<ComboBox ItemsSource="{x:Static Member=data:Country.AllCountries}" SelectedValuePath="PhonePrefix" SelectedValue="{Binding Path=CountryCode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >


text:
Q: При выборе select добавить класс для div Есть необходимость при выборе option с определённым значением в select, задать класс active определённому div. На данный момент есть код; класс добавляется, но не убирается у остальных div.

$("#category").change(function(e) {
    e.preventDefault();
    $(".11, .22, .33, .44, .55, .66, .77, .88, .99, .100, .110, .120, .130")
        .not($(this.value).addClass('active'))
});
.markers_wrap a {
    display: block;
    text-decoration: none;
    color: #4d4d4d;
}
.active {
    color: red;
}

<select name="catlist[]" id="category">
    <option>Выбрать блок</option>
    <option value=".11">блок 1</option>
    <option value=".22">блок 2</option>
    <option value=".33">блок 3</option>
    <option value=".44">блок 4</option>
    <option value=".55">блок 5</option>
    <option value=".66">блок 6</option>
    <option value=".77">блок 7</option>
    <option value=".88">блок 8</option>
    <option value=".99">блок 9</option>
    <option value=".100">блок 10</option>
    <option value=".110">блок 11</option>
    <option value=".120">блок 12</option>
    <option value=".130">блок 13</option>
</select>

блок 1

блок 2

блок 3

блок 4

блок 5

блок 6

блок 7

блок 8

блок 9

блок 10

блок 11

блок 12

блок 13

A: Добавляем всем div-ам общий класс (допустим "test"), а перед добавлением класса указывающего на активность делаем так $('.test').removeClass('active');

A:

$("#category").change(function(e) {
  e.preventDefault();
  $('div').removeClass('active');
  $(this.value).addClass('active');
});
.markers_wrap a {
  display:block;
  text-decoration: none;
  color: #4d4d4d;
}
.active {
  color:red;
}

<select name="catlist[]" id="category">
    <option>Выбрать блок</option>
    <option value=".11">блок 1</option>
    <option value=".22">блок 2</option>
    <option value=".33">блок 3</option>
    <option value=".44">блок 4</option>
    <option value=".55">блок 5</option>
    <option value=".66">блок 6</option>
    <option value=".77">блок 7</option>
    <option value=".88">блок 8</option>
    <option value=".99">блок 9</option>
    <option value=".100">блок 10</option>
    <option value=".110">блок 11</option>
    <option value=".120">блок 12</option>
    <option value=".130">блок 13</option>
</select>

блок 1

блок 2

блок 3

блок 4

блок 5

блок 6

блок 7

блок 8

блок 9

блок 10

блок 11

блок 12

блок 13

A: Я бы завернул все дивы в общий родительский и сделал так (оставить нужно конечно же один из двух вариантов):

$("#category").change(function() {
// вариант №1
     $(".categories div" + $(this).val()).addClass('active').siblings().removeClass('active');
// вариант №2
     $(".categories div.active").removeClass('active');
     $($(this).val()).addClass('active');
  });
.markers_wrap a {
  display:block;
  text-decoration: none;
  color: #4d4d4d;
}
.active {
  color:red;
}

    <select name="catlist[]" id="category">
        <option>Выбрать блок</option>
        <option value=".11">блок 1</option>
        <option value=".22">блок 2</option>
        <option value=".33">блок 3</option>
        <option value=".44">блок 4</option>
        <option value=".55">блок 5</option>
        <option value=".66">блок 6</option>
        <option value=".77">блок 7</option>
        <option value=".88">блок 8</option>
        <option value=".99">блок 9</option>
        <option value=".100">блок 10</option>
        <option value=".110">блок 11</option>
        <option value=".120">блок 12</option>
        <option value=".130">блок 13</option>
    </select>

блок 1

блок 2

блок 3

блок 4

блок 5

блок 6

блок 7

блок 8

блок 9

блок 10

блок 11

блок 12

блок 13


text:
Q: Looking for comparisons of disk i/o for a dedicated MySQL server We hired a consultant to help us increase the capacity of our MySQL cluster, and the first thing (almost only thing) he did was to measure the disk i/o speed of our servers.
I am interested in a comparison of disk i/o on similar systems to what we have:

*

*Our MySQL servers are virtual servers running on 32 bit VMWare ESX 3.5 with a SCSI SAN (Raid 5), and the Virtual servers themselves are running Debian Etch, and MySQL version 5.0.32

Running the following commands on the MySQL box give these results for me (which the consultant described as "Terribly slow":
time dd if=/dev/zero of=OUT.tmp bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 71.3347 seconds, 14.7 MB/s
real    1m13.596s
user    0m0.052s
sys 0m56.932s

time dd if=OUT.tmp of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 21.8202 seconds, 48.1 MB/s
real    0m21.902s
user    0m0.012s
sys 0m7.948s

Are these results indeed "Terribly slow"?
I would be interested in comparing the results other people get from these 2 commands on their dedicated MySQL boxes - particularly if it is a 32-bit virtual machine.

A: Something to be aware of is that your dd command will not be bypassing the OS's filesystem cache. This means you'll get varying results depending on what else is going on, and you'll notice significant performance variation as you increase the output size (and thus exhaust your fs cache)
Add the "oflag=direct" to bypass the filesystem cache on the output file, eg
time dd if=/dev/zero of=OUT.tmp bs=1M count=1000 oflag=direct

You can bypass filesystem cache for read by using iflag=direct
Also, your performance will vary greatly with blocksize. While 1M is a pretty good tradeoff for testing sequential writes, unless your application is writing out 1M blocks it's not going to be representative of your actual performance.
As a general point, those throughput figures are pretty abysmal - a single sata drive (such as the Seagate ES.2 drives) can peak at 105MB/sec sequential write at the start of the drive, and will sustain ~60MB/sec over the whole drive.
Finally, general database "best practices" say to avoid RAID5/6 as an underlying system for a database, due to the relatively high overhead caused by parity writes (not the actual parity calculation itself, which is fairly cheap in hardware, but the effect of having to do extra reads and writes when writing out new parity).

A: Here's the results from my mysql server. It's a 64bit, not virtual machine, so not sure how much use it really is, but there is a very considerable difference.
time dd if=/dev/zero of=OUT.tmp bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 5.72139 s, 183 MB/s
0.00s user 1.55s system 27% cpu 5.725 total

time dd if=OUT.tmp of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 0.432328 s, 2.4 GB/s
0.00s user 0.45s system 103% cpu 0.436 total

A: in most cases you should also be comparing random io [ eg with bonnie++ ] not only linear read/write. or maybe it's one big data sink that takes logs and stores in un-indexed huge table?
results for dd 'benchmark'
szcapp1:/mnt/big/tmp# time dd if=/dev/zero of=OUT.tmp bs=1M count=1000
time dd if=OUT.tmp of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 4.26186 s, 246 MB/s

real    0m4.563s
user    0m0.001s
sys     0m2.255s
szcapp1:/mnt/big/tmp# time dd if=OUT.tmp of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 0.457162 s, 2.3 GB/s

real    0m0.459s
user    0m0.000s
sys     0m0.459s
szcapp1:/mnt/big/tmp#

64bit linux on dell poweredge 2950, perc6 raid 10 on 5x desktop 500GB sata disks. 16GB ram, 2x quad core 2.66GHz. but hey! this does not make sense - this data fits in 1/4 in cache memory of raid controler, and rest - in the system memory.
your results are slow indeed. results from vm running on linux above [ 32bit linux guest under vmware server 2.0 ]:
vfeed0:/tmp# time dd if=/dev/zero of=OUT.tmp bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 15.996 s, 65.6 MB/s

real    0m16.043s
user    0m0.016s
sys     0m13.117s
vfeed0:/tmp# time dd if=OUT.tmp of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 0.49413 s, 2.1 GB/s

real    0m0.505s
user    0m0.000s
sys     0m0.500s
vfeed0:/tmp#

keep in mind that read performance is fake - it's read from the cache - if not from the cache of guest, then surly from cache of vmware host.

A: In addition to what Daniel Lawson has noted about the cached GB/s results..
If your dd doesn't happen to support iflag/oflag then you can manually flush the disk cache between runs with the command:
sync; echo 3 > /proc/sys/vm/drop_caches

Or simply using a dataset that is twice as large as your RAM will ensure the data never has a chance to be cached between runs.

As for your consultant's dd test - it's a good starting point, but not a conclusive test. It is measuring sequential I/O. That is the reading and writing blocks that lie immediately next to one another on the physical disk. Unfortunately databases very rarely deal with sequential I/O. Records get written at different times and are usually not retrieved, over time, in the order which they were written.
With this in mind, the two utmost important factors that you need to measure are random I/O throughput and latency. These will have the greatest impact as to how MySQL behaves. To measure these I'd suggest using the utility bonnie++. It has preset tests to benchmark all of the above and is far more configurable if you want to test specific aspects.
You can also use MySQL super-smack to measure the repeated performance of individual SQL queries.

A: Somewhat away from your original question; but the SAN vendor response to "RAID 5 is slow", is to convert to RAID 1, or RAID 10.  Also consider VMFS alignment (PDF) may be severely impacting performance.

A: When my crappy old Dell Latitude D520 (80Go;5400RPM) challenges your MySQL server you know there is a problem somewhere ^^ :
$ time dd if=/dev/zero of=OUT.tmp bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 32.5178 s, 32.2 MB/s
real    0m32.662s
user    0m0.008s
sys 0m2.716s

$ time dd if=OUT.tmp of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 29.8311 s, 35.2 MB/s
real    0m29.892s
user    0m0.004s
sys 0m2.056s

You should first have a look on the strain those two tests put on the I/O load of the ESX nodes.
Then do a bonnie++ test coupled with iostat and mpstat running in parallel shells (ahoy screen !) on thoses nodes and on the SAN to find where the bottleneck stands. You'll surely find high amounts of iowaits somewhere, that will be the part to concentrate on.


text:
Q: Resolving Array of Promises in Javascript I am working on a little project currently and have come across this issue.
Here's a little context of what I am doing. First, I make a call to an API concurrently with Axios like so:
const [...result] = await Promise.all([
 axios.post('api-url', data, headers),
 axios.post('api-url', data, headers),
 axios.post('api-url', data, headers),
 axios.post('api-url', data, headers),
])

Then I map through the result array and get back an array of objects just like the one below:
//data array
const data = [{name: 'john'}, {name: 'jane'}, {name: 'doe}]

Based on the data array listed above, I create new users in my MongoDB collection like so.
const result = data.map(async (item) => {
        return Promise.all([
            User.create({ name: item.name, }),
        ])
    })

Now, here is the problem - when I do a console.log(result), I get an array of unresolved promises, e.g:
result [
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }
]

I don't know what's happening here. From my understanding Promise.all() is meant to return an array of resolved promises. What could I be doing wrong? And how do I resolve this issue? Any help is appreciated. Thank you very much.

A:
I don't know what's happening here, from my understanding Promise.all() is meant to return an array of resolved promises.

No. Promise.all() returns a promise which resolves when all the promises passed to it have resolved.
The first time you use it (in code block 1) you await the return value. result gets populated with the resolved values of all the promises passed to Promise.all.
The other time you have a variable called result:

const result = data.map(async (item) => {

You populate it with the results of mapping some data through async functions.
async functions always return Promises, so you get an array of promises stored in result.
Inside that async function you do this:

    return Promise.all([
        User.create({ name: item.name, }),
    ])

The use of Promise.all here is pointless. You only pass one promise to it in the first place.
You need to

*

*Collect the promises returned from each call to User.create

*Use Promise.all to get a single promise that resolves when they are all ready

*Wait for that promise to resolve

Such:
const promises = data.map( item => User.create({ name: item.name }) );
const results = await Promise.all(promises);


text:
Q: Multiplying permutation by itself prime times to get identity Let $p \in\mathbb{N}$ be a prime number and $\alpha \in S_n$. If ${\alpha}^p=1$ then $\alpha$ has three disjoint options:
$\ \bullet \alpha = 1$
$\ \bullet \alpha \text{ is a } p-cycle$
$\ \bullet \alpha \text{ is a product of } p-cycles$
Can someone give me some hints to do this? The only thing I know is that I can express $\alpha$ as a product of disjoint cycles, but I don't know how that will be relate to ${\alpha}^p$. Thanks!

A: The order of a product of disjoint cycles is the lowest common multiple of the lengths of its component cycles. If this order is a prime $p$, this implies that all the component cycles (of order greater than 1) have lengths at most $p$ (to keep the LCM at $p$) and also have lengths that are powers of $p$ (to prevent prime factors other than $p$ from creeping into the LCM). Thus those cycles must be of length exactly $p$, which accounts for the last two cases in the question.
Either the permutation $\alpha$ is non-trivial, which leads to the analysis above, or it is trivial and $\alpha^p=1$ still. Thus we have shown that if $\alpha^p=1$ then $\alpha$ is one of the three types of permutations described in the question.


text:
Q: MAX - MIN for each day in SQL I am using SQL Server. I am fetching information from various tables, and I am able to do that.
In my table I have sampletime column which is every 30 minutes, and a value column. I want to write a query to get difference (max-min) for each day, any suggestions how I can do that?
For example:
SIGNAL NAME     SAMPLETIME                  VALUE
Spazio-Percorso 2014-03-06 15:01:50.3170000 219345
Spazio-Percorso 2014-03-06 15:31:50.3260000 219384
Spazio-Percorso 2014-03-06 16:01:50.3380000 219388
Spazio-Percorso 2014-03-06 16:31:50.3460000 219388
Spazio-Percorso 2014-03-06 17:01:50.3590000 219400
Spazio-Percorso 2014-03-06 17:31:50.3690000 219434
Spazio-Percorso 2014-03-06 18:01:50.3760000 219471

In this example all the rows are from the same day, what I want is to have only 1 row for each day and in the value column want to have MAX-MIN of that day

A: Try this
SELECT [SIGNAL NAME], CAST(SAMPLETIME AS DATE) AS SAMPLEDATE, MAX(VALUE)-MIN(VALUE) As Diff_Value
FROM Table1
GROUP BY CAST(SAMPLETIME AS DATE),[SIGNAL NAME]

A: If you're using SQL Server 2008 or higher, you can convert your datetime column to DATE to get rid of the time value:
SELECT
    [SIGNAL NAME],
    CAST(SAMPLETIME AS DATE) AS SAMPLEDATE,
    MAX(VALUE) - MIN(VALUE) AS VALUE
FROM Table1
GROUP BY [SIGNAL NAME], CAST(SAMPLETIME AS DATE)


text:
Q: Can't understand this snippet with eval and call I found a demo that mixes VBScript and JScript at these two links here, and it mentions the full code here on code.google.com
Here is the code.
I don't understand the code, and that's ok. I'd like to try it out and see the results I can get from it or what similar things I can write, and then I can study it. It runs without error.
(This isn't the snippet I refer to in my title, this is the background to the snippet. The snippet follows this)
//
// JavaScript unit
// Wrapper for VBScript features in JScript
//
// Copyright (c) 2009 by Ildar Shaimordanov
//
// VERY IMPORTANT!
// InputBox/MsgBox/vbXXX and their descriptions are parts of the CHM-file named as
// "Windows Script Technologies " and all of them are properties of Microsoft
// accordingly their copyright as below:
//
// Copyright (c) 2001 Microsoft Corporation.
// Build: Topic Version 5.6.9309.1546
//

var vb = {};

/**
 * The helper method creates VBScript functions to be available in JScript.
 *
 * @param       String  The name of VBScript function.
 * @return      Function
 */
vb.Function = function(func)
{
        return function()
        {
                return vb.Function.eval.call(this, func, arguments);
        };
};

(function()
{

var vbe;

function VBEngine()
{
        if ( vbe ) {
                return;
        }

        vbe = new ActiveXObject('ScriptControl');
        vbe.Language = 'VBScript';
        vbe.AllowUI = true;
};

/**
 * The helper method runs VBScript functions to be available in JScript.
 *
 * @param       String  The name of VBScript function.
 * @param       Array   The list of arguments for a VBScript function.
 * @return      Function
 */
vb.Function.eval = function(func)
{
        var args = Array.prototype.slice.call(arguments[1]);
        for (var i = 0; i < args.length; i++) {
                if ( typeof args[i] != 'string' ) {
                        continue;
                }
                args[i] = args[i].replace(/["\n\r]/g, function($0)
                {
                        return '" + Chr(' + $0.charCodeAt($0) + ') + "';
                });
                args[i] = '"' + args[i] + '"';
        }

        VBEngine();

        return vbe.eval(func + '(' + args.join(', ') + ')');
};

})();

/**
 * vb.Function.declare()
 *
 * @description
 * Allows to declare custom VBScript functions.
 * Returns the reference to the htmlfile document.
 * All declarations are in the namespace of this document.
 *
 * @example
 * // declare the generator of integer number from L to U
 * var vbs = vb.Function.declare([
 *     'Randomize',
 *     'Function Random(L, U)',
 *     '    Random = Int((U - L + 1) * Rnd + L)',
 *     'End Function']);
 *
 * // The bones generator
 * var n = vbs.Random(1, 6);
 *
 * @param       Array|String    VBScript declaratiom
 * @return      HTMLDocument
 * @access      static
 */
vb.Function.declare = function()
{
        // Initialize the declarator of VBScript items
        vb.Function.declarator = (new ActiveXObject('htmlfile')).parentWindow;

        // Redeclare the method
        vb.Function.declare = function()
        {
                var declarator = vb.Function.declarator;

                if ( ! arguments.length ) {
                        return declarator;
                }

                var args = arguments;
                if ( args[0] && args[0].constructor == Array ) {
                        args = args[0];
                }
                var func = Array.prototype.slice.call(args).join('\n');

                var document = declarator.document;
                document.write('\x3Cscript language="VBScript"\x3E' + func + '\x3C/script\x3E');

                return declarator;
        };

        // Call new method
        return vb.Function.declare.apply(null, arguments);
};

/**
 * Displays a prompt in a dialog box, waits for the user to input
 * text or click a button, and returns the contents of the text box.
 *
 * InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
 *
 * prompt
 * String expression displayed as the message in the dialog box.
 * The maximum length of prompt is approximately 1024 characters,
 * depending on the width of the characters used. If prompt
 * consists of more than one line, you can separate the lines using
 * a carriage return character (Chr(13)), a linefeed character
 * (Chr(10)), or carriage return-linefeed character combination
 * (Chr(13) & Chr(10)) between each line.
 *
 * title
 * String expression displayed in the title bar of the dialog box.
 * If you omit title, the application name is placed in the title
 * bar.
 *
 * default
 * String expression displayed in the text box as the default
 * response if no other input is provided. If you omit default,
 * the text box is displayed empty.
 *
 * xpos
 * Numeric expression that specifies, in twips, the horizontal
 * distance of the left edge of the dialog box from the left edge
 * of the screen. If xpos is omitted, the dialog box is
 * horizontally centered.
 *
 * ypos
 * Numeric expression that specifies, in twips, the vertical
 * distance of the upper edge of the dialog box from the top of the
 * screen. If ypos is omitted, the dialog box is vertically
 * positioned approximately one-third of the way down the screen.
 *
 * helpfile
 * String expression that identifies the Help file to use to
 * provide context-sensitive Help for the dialog box. If helpfile is
 * provided, context must also be provided.
 *
 * context
 * Numeric expression that identifies the Help context number
 * assigned by the Help author to the appropriate Help topic.
 * If context is provided, helpfile must also be provided.
 *
 * Remarks
 * When both helpfile and context are supplied, a Help button is
 * automatically added to the dialog box.
 * If the user clicks OK or presses ENTER, the InputBox function
 * returns whatever is in the text box. If the user clicks Cancel,
 * the function returns a zero-length string ("").
 */
var InputBox = vb.Function('InputBox');

/**
 * Displays a message in a dialog box, waits for the user to click
 * a button, and returns a value indicating which button the user
 * clicked.
 *
 * MsgBox(prompt[, buttons][, title][, helpfile, context])
 *
 * prompt
 * String expression displayed as the message in the dialog box.
 * The maximum length of prompt is approximately 1024 characters,
 * depending on the width of the characters used. If prompt consists
 * of more than one line, you can separate the lines using a
 * carriage return character (Chr(13)), a linefeed character
 * (Chr(10)), or carriage return-linefeed character combination
 * (Chr(13) & Chr(10)) between each line.
 *
 * buttons
 * Numeric expression that is the sum of values specifying the
 * number and type of buttons to display, the icon style to use,
 * the identity of the default button, and the modality of the
 * message box. See vb.XXX constants for values. If omitted,
 * the default value for buttons is 0.
 *
 * title
 * String expression displayed in the title bar of the dialog box.
 * If you omit title, the application name is placed in the
 * title bar.
 *
 * helpfile
 * String expression that identifies the Help file to use to
 * provide context-sensitive Help for the dialog box. If helpfile
 * is provided, context must also be provided. Not available on
 * 16-bit platforms.
 *
 * context
 * Numeric expression that identifies the Help context number
 * assigned by the Help author to the appropriate Help topic.
 * If context is provided, helpfile must also be provided.
 * Not available on 16-bit platforms.
 *
 * Remarks
 * See vb.XXX constants for identify a returned value.
 * When both helpfile and context are provided, the user can
 * press F1 to view the Help topic corresponding to the context.
 * If the dialog box displays a Cancel button, pressing the ESC key
 * has the same effect as clicking Cancel. If the dialog box
 * contains a Help button, context-sensitive Help is provided for
 * the dialog box. However, no value is returned until one of the
 * other buttons is clicked.
 * When the MsgBox function is used with Microsoft Internet Explorer,
 * the title of any dialog presented always contains "VBScript:" to
 * differentiate it from standard system dialogs.
 */
var MsgBox = vb.Function('MsgBox');

/**
 * The following constants are used with the MsgBox function to
 * identify what buttons and icons appear on a message box and which
 * button is the default. In addition, the modality of the MsgBox
 * can be specified. Since these constants are built into VBScript,
 * you don't have to define them before using them. Use them
 * anywhere in your code to represent the values shown for each.
 */
vb.OKOnly           =    0; // Display OK button only.
vb.OKCancel         =    1; // Display OK and Cancel buttons.
vb.AbortRetryIgnore =    2; // Display Abort, Retry, and Ignore buttons.
vb.YesNoCancel      =    3; // Display Yes, No, and Cancel buttons.
vb.YesNo            =    4; // Display Yes and No buttons.
vb.RetryCancel      =    5; // Display Retry and Cancel buttons.
vb.Critical         =   16; // Display Critical Message icon.
vb.Question         =   32; // Display Warning Query icon.
vb.Exclamation      =   48; // Display Warning Message icon.
vb.Information      =   64; // Display Information Message icon.
vb.DefaultButton1   =    0; // First button is default.
vb.DefaultButton2   =  256; // Second button is default.
vb.DefaultButton3   =  512; // Third button is default.
vb.DefaultButton4   =  768; // Fourth button is default.
vb.ApplicationModal =    0; // Application modal; the user must respond to the message box before continuing work in the current application.
vb.SystemModal      = 4096; // System modal; all applications are suspended until the user responds to the message box.

/**
 * The following constants are used with the MsgBox function to
 * identify which button a user has selected. These constants are
 * only available when your project has an explicit reference to
 * the appropriate type library containing these constant
 * definitions. For VBScript, you must explicitly declare
 * these constants in your code.
 */
vb.OK     = 1; // OK
vb.Cancel = 2; // Cancel
vb.Abort  = 3; // Abort
vb.Retry  = 4; // Retry
vb.Ignore = 5; // Ignore
vb.Yes    = 6; // Yes
vb.No     = 7; // No

So that's some background to the following snippet I am trying out.
So I tried to write the following little snippet and it compiled/interpreted fine. no error
a={};
a.abc = function(func)
{
        return function()
        {
                return a.abc.eval.call(this, func, arguments);
        };
};

a.abc("asdf");

It runs without error.
I understand a is being defined there as an object, and we're adding a function to it, and the function returns a function. Though what that function does, I'm not sure.
In trying to understand it... it looks like eval is a function, because after it, call is invoked, and that couldn't be done if eval were a property.
(And I know I can do eval on its own, e.g. from the console eval("5+6"); so eval there is a function)
But if I put that snippet in the console (so as to create the a object and its abc function), and then I do
typeof a.abc.eval  <-- undefined
a.abc.eval() <-- "Uncaught TypeError: a.abc.eval is not a function"
I don't see why it'd say undefined and that a.abc.eval isn't a function when I have code that says "a.abc.eval.call"


text:
Q: find a unique output based on two inputs? I need to find a way, such that user has to input 2 numbers (int) and for every different value a single output (int preferably!) is returned.
Say user enters 6, 8 it returns k when user enter anything else like 6,7 or 9,8 or any other input m, n except for 6, 8 (even if only one input is changed) a completely different output is produced. But the thing is, it should be unique for only that m, n so I cant use something like m*n because 6 X 4 = 24 but also, 12 X 2 = 24 so the output is not unique, so I need to find a way where for every different input, there is a totally different output that is not repeated for any other value.
EDIT: In response to Nicolas: the input range can be anything but will be less then 1000 (but more then 1 of course!)
EDIT 2: In response to Rawling, I can use long (Int64) but not preferably use float or doulbe, becuase this output will be used in a for loop, and float and double are terrible for for loop, you can check it here

A: Since your two numbers are less than 1000, you can do k = (1000 * x1) + x2 to get a unique answer. The maximum value would be 999999, which is well within the range of a 32-bit int.

A: You can always return a long: from two integers a and b, return 2^|INT_SIZE|*a + b
It is easy to see from pigeonhole principle, that given two ints, one cannot return a unique int for every different input. Explanation: If you have 2 numbers, each containing n bits, then there are 2^n possibilities for each number, and thus there are (2^n)^2 possible pairs, so from piegeonhole principle - you need at least lg_2((2^n)^2) = 2n  bits to represent them,
EDIT: Your edit mentions the range of your numbers is [1,1000] - thus the same idea can be applied: 1000*a + b will generate a unique int for each pairs.
Note that for the same reasons, the range of the resulting integer must be [1,1000000] - or you will get clashes.

A: Because I don't have 50 posts to comment, I must say, there are functions
called Pairing Functions.
Pairing functions such as Cantor's Pairing Function(Shown on the previous link) and Szudzik's Pairing Function which allows the inputs to be infinite and still be able to provide an unique and deterministic output.
Here is another similar question on stackoverflow. (Great, I need 10 reputation to post more than two links..)
(http://) stackoverflow.com/questions/919612/mapping-two-integers-to-one-in-a-unique-and-deterministic-way
EDIT: I'm late.

A: If you didn't have a hard upper bound, you could do the following:
int Unique (int x, int y)
{
    int n = x + y;
    int t = (n%2==0) ? ((n/2) * (n+1)) : (n * ((n+1)/2));
    return t + x;
}

Mathematically speaking, this will return a unique non negative integer for each (non-negative) pair of integers with no upper bound.
Programatically speaking, it will run into overflow problems, which could be overcome by using long instead of int for everything except the input variables.

A: The canonical mathematical solution is to use prime powers. As every number can be decomposed uniquely into its prime factors, returning 2^n * 3^m will give you different results for every n and m.
This can be extended to 2^n * 3^m * 5^a * 7^b *11^c and so on; you only need to check that you do not run out of 32-bit integers. If there is a risk of overflowing, you can take the remainder after dividing by a prime larger than your input range, and you will still have uniqueness.


text:
Q: any run-time configurable parser library for C or C++? I have an inherited project that parses both binary and ascii data streams from various sources (fixed-repeat-length binary streams, fixed-repeat-length ascii streams, variable-repeat-length but fixed-number-of-fields csv-like ascii streams).  It is already run-time configurable as to on which input port to expect each format of input, defining either fixed length and what each group of bytes should be parsed as based on position, or for the variable length ones, which byte or set of bytes should be considered as the record separator and field separator, and what each field between the field separators should be parsed as.  The format of each stream is known before run-time and described in an ascii based config file.
However I now need this to be a little more generalizable to handle a new input device with basically an either-or type of grammar.  When the device is operating normally it outputs in the following line format, one line per second:
6.53m,48.31%
but when the device detects an out-of-range error condition, it outputs
999999
My current level of configurability (the inherited code) doesn't let me handle this, as it is firstly not fixed length, nor does it have a consistent number of field separators per "record", i.e. per line.
I need a parser configuration system that lets me say "if there's 2 fields in the record then parse a float followed by a string constant 'm', and a float followed by a string constant '%'; if there's only one field in the record, parse an int".
If anyone is aware of any packages out there that have addressed this type of need, I would appreciate pointers to them.  Obviously I've googled but I may not be using the correct terminology for this type of configurable parser so googling hasn't been very fruitful.

A: You can just use plain-old sscanf and friends to parse this. sscanf returns the number of fields successfully converted, which you can use to determine if the line parsed correctly. This doesn't even require a fancy parser generator!
Example program:
#include <stdio.h>

int main() {
    char line[256];

    while(fgets(line, 256, stdin)) {
        float f1, f2;
        int d1;
        if(sscanf(line, "%fm,%f%%", &f1, &f2) == 2) {
            printf("f1 = %f, f2 = %f\n", f1, f2);
        } else if(sscanf(line, "%d", &d1) == 1) {
            printf("d1 = %d\n", d1);
        } else {
            printf("Unrecognized input.\n");
        }
    }
    return 0;
}

Sample session:
6.53m,48.31%
f1 = 6.530000, f2 = 48.310001
999999
d1 = 999999
blah
Unrecognized input.


text:
Q: jQuery timer, ajax, and "nice time" So for this is what I've got:
$(document).ready(function () {
    $("#div p").load("/update/temp.php");

    function addOne() {
        var number = parseInt($("#div p").html());
        return number + 1;
    }
    setInterval(function () {
        $("#div p").text(addOne());
    }, 1000);
    setInterval(function () {
        $("#geupdate p").load("/update/temp.php");
    }, 10000);
});

So this grabs a a UNIX timestamp from temp.php and puts into into #div p, and then adds 1 to it every second, and then every 10 seconds it will check the original file to keep it up to speed.
My problem is that I need to format this UNIX timestamp into a format such as "1 day 3 hours 56 minutes and 3 seconds ago", while also doing all the incrementation and ajax calls.
I'm not very experienced with jquery/javascript, so I might be missing something basic.

A: http://www.datejs.com/ does everything you could possibly want to do with dates in javascript. The first available download is out of date, but the SVN version is fine.


text:
Q: I get an error (parse error) when i want to write the according formula in a google apps script sheet I get an parse error if i want to set this formula via apps script into a google sheet
cell.setFormula("=NORM.DIST(P16;P24;P25;WAHR)");


text:
Q: Preventing a single list subscriber from unsubscribing from a mailman list I run a technical mailman list with a lot of subscribers on it.  One company, whose presence on the list is highly desirable, has many of its readers subscribed by an internal "exploder" list; that is, a single address which is itself an internal mailing list is subscribed to my list.
The problem is that people who want to get off the exploder keep accidentally unsubscribing the exploder from the main list, instead of unsubscribing themselves from the exploder.
I have a good working relationship with the tech guys at that company, and they're asking me if there's a way to lock a single subscriber (ie, the exploder) to a mailman list, and prevent just that subscriber unsubscribing without administrative oversight.
Anyone?

A: I am unsure what version of mailman you are running, but according to the documentation for v2

Note: Mailman does not currently let the list manager block persons
  from leaving the list.

You could set "Should administrator get notices of subscribes/unsubscribes?" and have a filter on the administrator account that automatically re-subscribes them if they leave.


text:
Q: Why are boosted trees difficult to interpret? I might not fully understand the topic but: Bootstrapped/bagged trees are difficult to interpret because the decisions are made from averaging the prediction of possibly hundreds of trees (ensemble).
But with boosted trees, don't we end up with one tree?
If so, visualizing this tree should be as simple as visualizing a normal decision tree, right?
The only difference would be that it's more unclear how it got to those specific rules since it uses boosting.
However, I've also read that it's difficult to interpret a boosted tree. Could someone please clarify?

A: In short, the final ensemble is not a tree.
Consider this part of the Wikipedia article.
The $F_m(x)$ when $m=1$ is essentially a single tree $h_1(x)$ with its output multiplied by a learned number $\gamma_m$.
In the next iteration, you build $F_2(x)$ by using the previously created $F_1(x)$ and another initial tree $h_2(x)$.
This operation is repeated $m$ times, and then, for example if there were $m=100$ initial trees, you get your final ensemble, $F_{100}(x)=F_{99}(x)+F_{98}(x)+...+F_{1}(x) + \gamma_{100}h_{100}(x)$.
When you visualize a tree, you see the decision nodes. The output of the initial tree follows from its nodes.
However, the output of the final ensemble follows from a hundred of trees giving their outputs, then multiplying these outputs by the learned values and adding it all together.
Therefore, the final ensemble is not a tree, so you cannot visualize it as a tree. A tree is a decision graph, when a learned ensemble is a linear combination of what many trees decide to yield for a given input.
(Thanks to usεr11852 for clarifying my error. The comment section is about the previous version of the post before the fix.)


text:
Q: Count number of rows between start and end date I have a table with few hundred thousand rows, with columns containing a start and finish datetime, something like this:
ID    StartDateTime              FinishDateTime
--------------------------------------------------------
1     2001-01-01 04:05:06.789    2001-02-03 04:05:06.789
2     2001-01-01 05:05:06.789    2001-01-01 07:05:06.789
3     2001-01-01 06:05:06.789    2001-02-04 07:05:06.789
4     2001-03-01 06:05:06.789    2001-02-03 04:05:06.789

For each row, I need to count the number of 'active' rows at the start time; as in count rows that start before and finish after the startdatetime for each row. For instance: for ID=3, the startdatetime falls between the startdatetime and finishdatetime of ID=1 and ID=2, but not ID=3 or ID=4, so it should return 2.
The desired output is:
ID    ActiveRows
-----------------
1     0
2     1
3     2
4     0

I can get it to work using the query below, but it takes hours to run.
select
    ID,
    (select count(1)
     from table tbl2
     where tbl2.StartDateTime < tbl.StartDateTime
       and tbl2.FinishDateTime > tbl.StartDateTime) as 'ActiveRows'
from
    table tbl

I've also tried joining the table on itself, but it also seems extremely slow.
select
    tbl.ID, count(1)
from
    table tbl
left join table
    tbl2 on tbl2.StartDateTime < tbl.StartDateTime
         and tbl2.FinishDateTime > tbl.StartDateTime
group by
    tbl.ID

What is the fastest way to perform this calculation?

A: You can do this using Apply operator
SELECT tbl.id,
       oa.activerows
FROM   yourtable tbl
       OUTER apply(SELECT Count(tbl2.id)
                   FROM   yourtable tbl2
                   WHERE  tbl2.startdatetime < tbl.startdatetime
                          AND tbl2.finishdatetime > tbl.startdatetime) oa (activerows)

and your original query should be using LEFT JOIN to get the ID's with 0 count
To further improve the performance you can create a non clustered index on yourtable
Create Nonclustered Index Nix_table on
      yourtable (startdatetime,finishdatetime) Include (Id)

*

*Live Demo


text:
Q: XmlReader.ReadToNextSibling not working I'm trying to read an xml document but the XmlReader.ReadToNextSibling does not work as advertised on this MSDN Documentation
Here is a console example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace ConsoleTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlText = "<xmlRoot><group><item>Item 1</item><item>Item 2</item></group><group><item>Item 3</item><item>Item 4</item></group></xmlRoot>";

            using (XmlReader reader = XmlReader.Create(new StringReader(xmlText)))
            {
                reader.ReadToFollowing("item");
                do
                {
                    Console.WriteLine("Item: {0}", reader.ReadInnerXml());
                } while (reader.ReadToNextSibling("item"));
            }

            Console.WriteLine("Press any key to continue...");
            Console.Read();
        }
    }
}

This only outputs one item:

Item: Item 1

Anyone know how i can get this to work?
Please do not suggest using DOM model (XmlDocument). I cannot because these xml files are from different sources and can have many different namespaces and is a huge hassle. I need to get this working.

A: This is because ReadInnerXml also advances the reader. So when you get to your first ReadToNextSibling, you are positioned on Item 2, and there is no next sibling.
This code will read both your items:
string xmlText = "<xmlRoot><group><item>Item 1</item><item>Item 2</item></group><group><item>Item 3</item><item>Item 4</item></group></xmlRoot>";

using (XmlReader reader = XmlReader.Create(new StringReader(xmlText)))
{
    reader.ReadToFollowing("item");
    do
    {
        Console.WriteLine("Item: {0}", reader.ReadInnerXml());
    } while (reader.Name == "item");
}


text:
Q: Python: TypeError: 'file' object has no attribute '__getitem__' I have a .gpx file which is cut off int the middle of the file. When I try to parse it using the gpxpy library I run into the following error.
Parsing points in track.gpx
ERROR:root:expected '>', line 3125, column 29
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/gpxpy-0.8.7-py2.7.egg/gpxpy/parser.py", line 209, in parse
    self.xml_parser = LXMLParser(self.xml)
  File "/usr/local/lib/python2.7/dist-packages/gpxpy-0.8.7-py2.7.egg/gpxpy/parser.py", line 107, in __init__
    self.dom = mod_etree.XML(self.xml)
  File "lxml.etree.pyx", line 2734, in lxml.etree.XML (src/lxml/lxml.etree.c:54411)
  File "parser.pxi", line 1578, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:82748)
  File "parser.pxi", line 1457, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:81546)
  File "parser.pxi", line 965, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:78216)
  File "parser.pxi", line 569, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:74472)
  File "parser.pxi", line 650, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:75363)
  File "parser.pxi", line 590, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74696)
XMLSyntaxError: expected '>', line 3125, column 29

File "gpxscript.py", line 370, in extractpoints gpx = gpxpy.parse(file)
File "/usr/local/lib/python2.7/dist-packages/gpxpy-0.8.7-py2.7.egg/gpxpy/__init__.py",
     line 28, in parse raise mod_gpx.GPXException('Error parsing {0}: {1}'
                       .format(xml_or_file[0 : 100], parser.get_error()))
TypeError: 'file' object has no attribute '__getitem__'

These are the relevant commands of the script which produces the error.
368  file = open(filepath)
369  try:
370      gpx = gpxpy.parse(file)
371  except gpxpy.gpx.GPXException:
372      print "GPXException for %s." % filepath
373      return 1

I filed a bug for the library as suggested. I added a sample file to the bug report which produces the syntax error.

A: This appears to be a bug in gpxpy's error handling.
Looking at the source to parse, when the parser fails without raising an exception, it tries to raise an exception with this:
raise mod_gpx.GPXException('Error parsing {0}: {1}'.format(xml_or_file[0 : 100], parser.get_error()))

This assumes that xml_or_file is an XML string—but, as the name implies, it's allowed to be either a string or a file object. So, what you're doing (giving it a file object) is perfectly legal and should work, and it doesn't, and therefore it's a bug.
So, you should file an issue. The correct patch should be something like:
if not parser.is_valid():
    try:
        fragment = xml_or_file[0 : 100]
    except TypeError:
        xml_or_file.seek(0)
        fragment = xml_or_file.read(100)
    raise mod_gpx.GPXException('Error parsing {0}: {1}'.format(fragment, parser.get_error()))

So, how do you work around this? A few options:

*

*Since it only happens with invalid files anyway, you can just use except Exception or except (gpxpy.gpx.GPXException, TypeError).

*Since it only happens when you give it a the file object, give it a string instead: gpx = gpx.parse(file.read()). This is a bad idea if the file is very large, of course.

*Since the buggy function is only 12 lines of trivial code wrapping the real function, just use the real function directly. Or, if you like the wrapper, copy it, fix it, and use your own copy instead.

Meanwhile, given that the very first bit of code I looked at in this library has some obvious red flags (Why xml_or_file[0 : 100] instead of just xml_or_file[:100]? Why catch exceptions, throw them away and just set a flag, and then use that flag to raise a new exception with all the information missing?), if you're not able to debug libraries on your own, I don't think this one is ready for you to use.


text:
Q: Associate invoice to a Sales Order I am not able to set "Created From" on Invoice to reference a Sales Order record through the SOAP web service. I have tried setting this field directly and also through Initialize API (initializing a invoice record using the sales order and then copying the CreatedFrom field from the initialized invoice to the invoice being created).
I don't get any errors yet the Created From field doesn't get set on the created invoice record.
The code I am trying looks something like this:
// initialize invoice from sales order
var initializeRecord = new InitializeRecord()
            {
                type = InitializeType.invoice,
                reference = new InitializeRef() { internalId = "sales-order-internal-id", type = InitializeRefType.salesOrder, typeSpecified = true }
            };
            var result = Utility.Do(async () => await connector.NetSuiteClient.initializeAsync(initializeRecord));
SuiteTalk.Invoice initializedInvoice = result.record;

// create a invoice and copy over the "createdFrom" field
var invoice = new SuiteTalk.Invoice();
invoice.createdFrom = initializedInvoice.createdFrom;

/* set other fields on the invoice and add some line items
....
...
..
*/

// finally create the invoice
var result = Utility.Do(async () => await connector.NetSuiteClient.addAsync(invoice));

How I can associate this invoice to a sales order while creating it?

A: What you will have to do -- as painful as it is -- is to use the transformed record provided to you by netsuite from the initializeRecord call, and then modify it.  It is a pain because there are several fields that you will have to unset as you fill in the record.
The issue is that there are createdFrom associations on both the header level, and the line level, that need to be filled in for the sales order to invoice association to take.
here are the list of line fields that I had to unset in the invoice:
line-level:

*

*quantityRemaining

*quantityAvailable

*quantityFulfilled

*quantityOrdered

*quantityOnHand

*costEstimate

*taxRate1
here are the header-level fields:

*

*subTotal

*total

*totalCostEstimate

*estGrossProfit

*estGrossProfitPercent

*discountTotal

*giftCertApplied

*shippingTax1Rate

A: Thank you 2ps.
In my case this code was enough
Invoice invoice = (Invoice)initializeResponse.record;
                    invoice.totalCostEstimateSpecified = false;
                    invoice.estGrossProfitPercentSpecified = false;
                    invoice.discountTotalSpecified = false;
                    invoice.totalSpecified = false;

                    foreach (var item in invoice.itemList?.item)
                    {
                        item.quantityRemainingSpecified = false;
                        item.costEstimateSpecified = false;
                    }

                    var writeResponse = svc2.add(invoice);


text:
Q: Java 8 - External Iteration performing better than Internal Iteration? So I was reading a book for Java 8, when I saw them doing comparison between external and internal iteration and thought about comparing the two, performance wise.
I have a method that just sums up a sequence of integers up to n.
Iterative one:
private static long iterativeSum(long n) {

    long startTime = System.nanoTime();
    long sum = 0;

    for(long i=1; i<=n; i++) {
        sum+=i;
    }

    long endTime = System.nanoTime();
    System.out.println("Iterative Sum Duration: " + (endTime-startTime)/1000000);

    return sum;
}

Sequential One - using internal iteration
private static long sequentialSum(long n) {

    long startTime = System.nanoTime();

    //long sum = LongStream.rangeClosed(1L, n)
    long sum = Stream.iterate(1L, i -> i+1)
            .limit(n)
            .reduce(0L, (i,j) -> i+j);

    long endTime = System.nanoTime();
    System.out.println("Sequential Sum Duration: " + (endTime-startTime)/1000000);

    return sum;
}

I tried to do some benchmarking on them, it turns out that the one using external iteration performs far better than the one using internal iteration.
Here's my driver code:
public static void main(String[] args) {

    long n = 100000000L;

    for(int i=0;i<10000;i++){
    iterativeSum(n);
    sequentialSum(n);
    }
    iterativeSum(n);
    sequentialSum(n);
}

The running time for the Iteravtive one was always < 50ms whereas the execution time for Sequential one was always > 250ms.
I am not able to understand why internal iteration is not out performing external iteration here?

A: Even though the presented results are completely irrelevant, the observed effect actually takes place: the Stream API do has an overhead which for such simple tasks cannot be totally eliminated in real applications even after warm-up. Let's write a JMH benchmark:
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(3)
@State(Scope.Benchmark)
public class IterativeSum {
    @Param({ "100", "10000", "1000000" })
    private int n;

    public static long iterativeSum(long n) {
        long sum = 0;

        for(long i=1; i<=n; i++) {
            sum+=i;
        }
        return sum;
    }

    @Benchmark
    public long is() {
        return iterativeSum(n);
    }
}

Here's baseline test: plain loop. The results on my box are the following:
Benchmark             (n)  Mode  Cnt     Score     Error  Units
IterativeSum.is       100  avgt   30     0.074 ±   0.001  us/op
IterativeSum.is     10000  avgt   30     6.361 ±   0.009  us/op
IterativeSum.is   1000000  avgt   30   688.527 ±   0.910  us/op

Here's your version of Stream API based iteration:
public static long sequentialSumBoxed(long n) {
    return Stream.iterate(1L, i -> i+1).limit(n)
                 .reduce(0L, (i,j) -> i+j);
}

@Benchmark
public long ssb() {
    return sequentialSumBoxed(n);
}

The results look like this:
Benchmark             (n)  Mode  Cnt     Score     Error  Units
IterativeSum.ssb      100  avgt   30     1.253 ±   0.084  us/op
IterativeSum.ssb    10000  avgt   30   134.959 ±   0.421  us/op
IterativeSum.ssb  1000000  avgt   30  9119.422 ±  22.817  us/op

Very disappointing: 13-21x slower. This version has many boxing operations inside, that's why primitive stream specializations were created. Let's check non-boxed version:
public static long sequentialSum(long n) {
    return LongStream.iterate(1L, i -> i+1).limit(n)
                     .reduce(0L, (i,j) -> i+j);
}

@Benchmark
public long ss() {
    return sequentialSum(n);
}

The results are the following:
Benchmark             (n)  Mode  Cnt     Score     Error  Units
IterativeSum.ss       100  avgt   30     0.661 ±   0.001  us/op
IterativeSum.ss     10000  avgt   30    67.498 ±   5.732  us/op
IterativeSum.ss   1000000  avgt   30  1982.687 ±  38.501  us/op

Much better now, but still 2.8-10x times slower. An alternative would be to use the range:
public static long rangeSum(long n) {
    return LongStream.rangeClosed(1, n).sum();
}

@Benchmark
public long rs() {
    return rangeSum(n);
}

The results are the following:
Benchmark             (n)  Mode  Cnt     Score     Error  Units
IterativeSum.rs       100  avgt   30     0.316 ±   0.001  us/op
IterativeSum.rs     10000  avgt   30    28.646 ±   0.065  us/op
IterativeSum.rs   1000000  avgt   30  2158.962 ± 514.780  us/op

Now it's 3.1-4.5x times slower. The cause of this slowness is that Stream API has very long call chain which hits the MaxInlineLevel JVM limit, so it cannot be fully inlined by default. You may increase this limit setting like -XX:MaxInlineLevel=20 and get the following result:
Benchmark             (n)  Mode  Cnt     Score     Error  Units
IterativeSum.rs       100  avgt   30     0.111 ±   0.001  us/op
IterativeSum.rs     10000  avgt   30     9.552 ±   0.017  us/op
IterativeSum.rs   1000000  avgt   30   729.935 ±  31.915  us/op

Much better: now it's only 1.05-1.5x slower.
The problem with this test is that the loop body of iterative version is very simple, thus could be efficiently unrolled and vectorized by JIT-compiler, and it's much harder to do this with the same efficiency for sophisticated Stream API code. However in real applications you're unlikely to sum consequtive numbers in a loop (why not write n*(n+1)/2 instead?). With real problems Stream API overhead is much lower even with default MaxInlineLevel setting.


text:
Q: twilio sms verification through mobile I have tested the twilio sms code but I am having some issues. The library can be found at https://www.twilio.com/docs/php/install.
Here is the code I used:
<?php

require "twilio-php/Services/Twilio.php";

// set your AccountSid and AuthToken from www.twilio.com/user/account
$AccountSid = "*******";
$AuthToken = "*********";

$client = new Services_Twilio($AccountSid, $AuthToken);

$message = $client->account->messages->create(array(
"From" => "+14806669029",
"To" => "923331524145",
"Body" => "Test message!",
));

// Display a confirmation message on the screen
echo "Sent message {$message->sid}";

?>

When running this, the following error occurs:
Fatal error: Uncaught exception 'Services_Twilio_TinyHttpException'
with message 'SSL certificate problem: self signed certificate in
certificate chain' in
C:\xampp\htdocs\sms\twilio-php\Services\Twilio\TinyHttp.php:119 Stack
trace: #0 C:\xampp\htdocs\sms\twilio-php\Services\Twilio.php(181):
Services_Twilio_TinyHttp->__call('post', Array) #1
C:\xampp\htdocs\sms\twilio-php\Services\Twilio.php(181):
Services_Twilio_TinyHttp->post('/2010-04-01/Acc...', Array,
'From=%2B1480666...') #2
C:\xampp\htdocs\sms\twilio-php\Services\Twilio\ListResource.php(92):
Base_Services_Twilio->createData('/2010-04-01/Acc...', Array) #3
C:\xampp\htdocs\sms\twilio-php\Services\Twilio\Rest\Messages.php(24):
Services_Twilio_ListResource->_create(Array) #4
C:\xampp\htdocs\sms\send-sms.php(15):
Services_Twilio_Rest_Messages->create(Array) #5 {main} thrown in
C:\xampp\htdocs\sms\twilio-php\Services\Twilio\TinyHttp.php on line
119

A: Refer this: https://github.com/twilio/twilio-php/blob/master/docs/faq.rst
It says:
SSL Validation Exceptions
If you are using an outdated version of libcurl, you may encounter SSL validation exceptions. If you see the following error message, you have a SSL validation exception:
Fatal error: Uncaught exception 'Services_Twilio_TinyHttpException'
with message 'SSL certificate problem, verify that the CA cert is OK.

Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate
verify failed' in [MY PATH]\Services\Twilio\TinyHttp.php:89

This means that Twilio is trying to offer a certificate to verify that you are actually connecting to https://api.twilio.com, but your curl client cannot verify our certificate.

A: Follow the instruction by skimbrel from this link. Then add the certificate from hairys comment. Your problem should be solved.

A: I solved the problem downloading the cacert.pem from  http://curl.haxx.se/docs/caextract.html and modifying my php.ini to include the path of the downloaded file (in my case I copied it into C:\xampp\php), adding the following line at the end of the php.ini file:
curl.cainfo=c:\xampp\php\cacert.pem

After saving the file and restarting Apache the error dissapeared and I was able to send sms using the Twilio system.

A: step 1 : download file and save as 'cacert.pem' into your project root directory
https://www.thawte.com/roots/thawte_Premium_Server_CA.pem
step 2: open php.ini file (:\xampp\php\php.ini) add following line at the end.
curl.cainfo="C:\xampp\htdocs\smstest\cacert.pem"

step 3 : run your code.
Example :
<?php

require '/twilio-php/Services/Twilio.php';

$sid = "ACxxxxxxxxxxxxxxx"; // Your Account SID from www.twilio.com/user/account
$token = "Auth token"; // Your Auth Token from www.twilio.com/user/account

$client = new Services_Twilio($sid, $token);

$message = $client->account->messages->sendMessage(
  '+1123-456-0789', // From a valid Twilio number
  '+9112346790', // Text this number
  "Hello,you get an contact request from webiste"
);

print $message->sid;

?>