text:
Q: Convert one Column to Row - SQL Server I have this query:
SELECT U.UserName, C.Name,
FROM CompanyUserMapping CU
INNER JOIN Users U ON U.ID = CU.USERID
INNER JOIN Company C ON C.ID = CU.CompanyID

This returns a result of which user has access to which company:
UserNAme     CompanyName
------------------------
userOne      CompanyOne
UserOne      CompanyTwo
UserTwo      CompanyOne

I want to modify the query so that I get :
Username     CompanyName1   CompanyName2
----------------------------------------
UserOne      CompanyOne     CompanyTwo
UserTwo      CompanyOne     NULL

Also, something like:
UserNAme     CompanyName
-------------------------------------
userOne      CompanyOne, CompanyTwo
UserTwo      CompanyOne

Any help is appreciated.

A: You can achieve second result it as below:
SELECT UI.UserName, Name =
    STUFF((SELECT ', ' + C.Name
           FROM CompanyUserMapping CU
           INNER JOIN Users U ON U.ID = CU.USERID
           INNER JOIN Company C on  C.ID = CU.CompanyID
           WHERE U.UserName = UI.UserName
          FOR XML PATH('')), 1, 2, '')
FROM Users UI
GROUP BY UserName

A: You can try this use dynamic SQL to make solution one.
make row number to be the pivot base condition (condition aggregate function) MAX with CASE WHEN, then use var @col to carry the SQL syntax.
then use EXEC execute the SQL dynamically.
CREATE TABLE T(
   UserName VARCHAR(50),
   CompanyName VARCHAR(50)
);

INSERT INTO T VALUES ('UserOne','CompanyOne');
INSERT INTO T VALUES ('UserOne','CompanyTwo');
INSERT INTO T VALUES ('UserTwo','CompanyOne');

DECLARE @tables AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX),
        @col AS NVARCHAR(MAX);

WITH CTE AS (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY UserName ORDER BY UserName) rn
    FROM T
),CTE1 AS(
    SELECT MIN(rn) smallRN,MAX(rn) bigRN,UserName
    FROM CTE
    group by UserName
    UNION ALL
    SELECT smallRN+1,bigRN,UserName
    FROM CTE1
    WHERE smallRN < bigRN
)
SELECT @col = STUFF((SELECT distinct ', MAX(CASE WHEN rn = '+CAST(smallRN AS VARCHAR(50)) +' then CompanyName end) as CompanyName' +CAST(smallRN AS VARCHAR(50))
            FROM CTE1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = '
WITH CTE AS (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY UserName ORDER BY UserName) rn
    FROM T
)
SELECT UserName,'+@col+'
FROM CTE t1
GROUP BY UserName

'

EXEC (@query)

RESULT
UserName    CompanyName1    CompanyName2
UserOne     CompanyOne      CompanyTwo
UserTwo     CompanyOne

sqlfiddle


text:
Q: Зациклить воспроизведения звука в chrome есть подключенный файл звука через html5.
<audio  loop controls  id="rain_audio">
         <source src="audio/rain.mp3">
</audio>

let audioRain = document.getElementById('rain_audio');

audioRain.addEventListener('pause', function() {
    this.currentTime = 0;
    this.play();
}, false);

Пытаюсь зациклить воспроизведения звука, в firefoxe все работает в chrome нет.
Так же почему то не работает событие ended в chrome, но когда звук доигрывается то срабатывает событие pause.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flow Polymorphic Type Definition for Binary and Unary Functional Expressions I'm trying to define a generic type that is polymorphic for both binary and unary curry functions with Flow. So far it only works when the type definition only contains one of these definitions. For example this will work:
type tOr<X, Y, XX: X, YY: Y> =
  & (((...a: [XX]) => YY) => ((...b: [XX]) => YY) => (x: XX) => boolean)

const Or2: tOr<number, Array<number>, *, *> = f => g => x => !!f(x) || !!g(x);

This reports errors:
type tOr<X, Y, XX: X, YY: Y> =
  & (((...a: [XX]) => YY) => ((...b: [XX]) => YY) => (x: XX) => boolean)
  & ((a: XX => YY, b: XX => YY) => (x: XX) => boolean);

const Or: tOr<number, Array<number>, *, *> = (f, g) => (x) => !!f(x) || !!g(x);

const Or: tOr, *, *> = (f, g) => (x) => !!f(x) || !!g(x);
               ^ Cannot instantiate tOr because function type [1] is incompatible with number [2] in type argument XX.

The full expression is on Flow try

A: After doing more investigation I found that Flow can overload a polymorphic type by using the disjoint union. This was tested without error on the Flow try editor.
type tOrUnary<X, Y, XX:X, YY:Y> =
  & (((...a: [XX]) => YY) => ((...b: [XX]) => YY) => (x: XX) => boolean)

type tOrBinary<X, Y, XX:X, YY:Y> =
  & (((a: XX) => YY, (b: XX) => YY) => (x: XX) => boolean);

type ORpoly<X, Y, XX:X, YY:Y> = tOrUnary<X, Y, *, *> | tOrBinary<X, Y, *, *> ;

const Or1: tOrBinary<number, Array<number>, *, *> = (f, g) => (x) => !!f(x) || !!g(x);
const Or2: tOrUnary<number, Array<number>, *, *> = f => g => x => !!f(x) || !!g(x);
let OR: ORpoly<number, Array<number>, *, *> = Or1;
OR = Or2;


text:
Q: List of books in which at the end I can understand most mathematical symbols I am so sorry if my question seems selfish. There are already so many existing questions asking for a list of books to better learn math is some way or another.
This is a list of all the math symbols:
https://www.rapidtables.com/math/symbols/Basic_Math_Symbols.html
Can anyone recommend a short list, possibly of 10-20 books (for beginners or easy to read) in which through learning their subjects, at the end I will have a basic understanding with at least most symbols?
Update: My knowledge ends with high school symbols: Basic Algebra, Basic Geometry and Basic calculus. I was very good in math in high school, but my life took another direction. I am very good at understanding theorems, but in a very procedural fashion. I would like to close the gap with better understanding of symbols.
If it helps to understand what my goal is: my goal is to read these books and be able to come back to this forum and understand most questions in this forum (not necessarily their answers). From there I would be able to further my studies in the directions I want.
What I am trying to do is to get the most knowledge of most symbols in an elementary way, Instead of diving through topics. My assumption is that it will then be easier for me to dive into a specific topic.
I know there is Khan Academy, but I am a little bit old fashioned and my plan is to buy 10 books.

A: Maybe you are interested:
A history of mathematical notations, Florian Cajori 1928


text:
Q: How can I copy the value of a previous row, on the same column in a DataFrame? I have the following DataFrame:

Date
Track
Surface
FGrating
HorseId
Last FGrating at Sha Tin, grass

2017-09-03
Sha Tin
Grass
110
1736

2017-09-16
Sha Tin
Grass
124
1736
110

2017-10-14
Sha Tin
Grass
118
1736
124

2017-11-11
Sha Tin
Grass
107
1736
118

2018-03-28
Happy Valley
Grass
117
1736

2018-04-11
Happy Valley
Grass
114
1736

2018-09-22
Sha Tin
Grass
124
1736
107

As you can see, there are spaces for the Last FGrating at Sha Tin, grass. These spaces have two causes:

*

*There is no last FGrating (the first record);

*There is a last FGrating for this track, but it was not written when the race for the same horse was on another track (Happy Valley grass, in this table).

So far, I managed to do only the filling part, according to this code:
def return_mask_and_text_from_tracks(data, track_no, metric):
    if track_no == 0:  # Sha Tin - grass
        mask = (data.Track == 'Sha Tin') & (data.Surface == 'Grass')
        text = str(metric) + ' at Sha-Tin Grass'
    if track_no == 1:  # Sha Tin - dirt
        mask = (data.Track == 'Sha Tin') & (data.Surface == 'Dirt')
        text = str(metric) + ' at Sha-Tin Dirt'
    if track_no == 2:  # Happy Valley - grass
        mask = (data.Track == 'Happy Valley') & (data.Surface == 'Grass')
        text = str(metric) + ' at Happy Valley Grass'
    return mask, text

def compute_last_fgrating(data, mask=''):
    if len(mask) == 0:
        return data.groupby('HorseId')['FGrating'].apply(lambda x: x.shift(1))
    else:
        return data.loc[mask][['HorseId', 'FGrating']].groupby('HorseId')['FGrating'].apply(lambda x: x.shift(1))

for i in range(3):
    mask, text = return_mask_and_text_from_tracks(featured_data, i, 'Last FGrating')
    featured_data[text] = compute_last_fgrating(featured_data, mask=mask)

I am looking for ways to fill the rightmost column with the following values:

*

*0, when no last FGrating exist (the first record, in this case)

*The last FGrating on Sha Tin grass on the records where the race was on other tracks, for the same horse.

The final table should look like this:

Date
Track
Surface
FGrating
HorseId
Last FGrating at Sha Tin, grass

2017-09-03
Sha Tin
Grass
110
1736
0 (no previous FGrating exists)

2017-09-16
Sha Tin
Grass
124
1736
110

2017-10-14
Sha Tin
Grass
118
1736
124

2017-11-11
Sha Tin
Grass
107
1736
118

2018-03-28
Happy Valley
Grass
117
1736
118 (the lastFGrating on Sha Tin grass at this point)

2018-04-11
Happy Valley
Grass
114
1736
118

2018-09-22
Sha Tin
Grass
124
1736
107

How can I do it?

A: Here you only need
df["Last FGrating at Sha Tin, grass"] = df["Last FGrating at Sha Tin, grass"].fillna(method="ffill").fillna(0)

Explanation
The first fillna fill NaN with the latest value available (method="ffill") then you have left only one NaN on your first row and you can fill it with 0.


text:
Q: GeoServer RASTER cql filter I have a layer in GeoServer based on a raster file (GEOTIFF)
I can visualize the layer, but I want to apply dynamic filters. Before I used CQL for vector data, no problem.
But not sure if the procedure is the same for raster data. First of all, I see that on the GeoServer layer preview, the option to apply a CQL Filter is not available. Bad sign I guess.
Clicking on the preview map, I can see we have 2 attributes: fid (empty) and GRAY_INDEX (from 0.0 to 10.0).
GRAY_INDEX is used for layer symbolization, and no problem at all.
But when I try to apply a cql_filter (with Leaflet, for example),
trying all options below did not work not even one (and the error for sure is not on the JS)
cql_filter: 'GRAY_INDEX >2'
cql_filter: 'GRAY_INDEX >2.0'
cql_filter: 'GRAY_INDEX LIKE 2.0'
cql_filter: 'GRAY_INDEX LIKE 2'
cql_filter: "GRAY_INDEX >'2.0'"
There is GeoServer Raster WMS Layer update/filter like CQL, ECQL but that gives an internal error when trying to create a similar style.

A: CQL_FILTER can only work on attributes of vector data.
When it comes to rasters, if the data source backing them is an image mosaic, it will be applied to the attributes in the mosaic index (e.g., time, elevation, whatever other metadata attribute collected for the single image in the mosaic).
For your use case, please have a look at the Jiffle map algebra instead:
https://docs.geoserver.org/latest/en/user/styling/sld/extensions/rendering-transform.html#running-map-algebra-on-the-fly-using-jiffle

A: My solution has been creating a PHP file that dynamically creates an SLD. This php gets a list of codes to switch on/off.
In Leaflet we setup the layer:
layer.setParams({
   layers: 'store:my_layer_name',
   SLD: 'http://myserver/sld_generate.php?visible_code[]=3&visible_code[]=1',
});

If your PHP 'echoes' a correctly formatted SLD, it works :.)


text:
Q: How to store ids with mongoid? I have a user model and user references_many folders. I want to add a field where current user can store ids of other users folders. What is the best way to implement this?

A: The documentation on the mongoid site says you should references_many :preferences, :stored_as => :array, :inverse_of => :people but in recent mongoid builds this is not available. Instead, you should use references_and_referenced_in_many.
class User
  include Mongoid::Document
  references_and_referenced_in_many :favorite_folders, :class_name=>'Folder'
end

This will create an field of folder_id, :type=>Array and will store the array of the object
user = User.new
other_user = User.first
user.favorite_folders << other_user.folders.first #assuming this exists
user.save


text:
Q: Instantiate a PHP stdClass in my namespace – fatal error I want to write a small add on for an existing CMS. To do so, I need to extend a class from that CMS' code.
My code will be written inside its own namespace, while the CMS' code does not use namespacing, which basically means it exists inside the global namespace.
Inside my code, I create a new stdClass:
$var = new stdClass();
With that code is place, it always produces a fatal error:
Fatal error: Class 'MyNamespace\something\StdClass' not found in /some/rather/long/path/to/class.php on line 123

Creating the stdClass like this solves that problem:
$var = new \stdClass();
Since I am still pretty new to namespaces, I am not exactly sure what the problem here is?
My guess is that in the first example, the stdClass would be created in the namespace of my class. This actually means the constructor of a class called stdClass existing in my namespace would be called, but since that class does not exist, an error is thrown.
In the second example, I signalize that I want to instantiate the class called stdClass from the global namespace, which somehow suddenly makes sense.
If anyone could elaborate what is happening here I would be very happy.

A: You appear to understand the concept behind namespaces, and you are headed in the right direction on your analysis of what is happening.
When you are working inside of a namespace you are able to refer to names as unqualified, qualified, and fully qualified.
When you make a namespace you are telling PHP to organize (and resolve) the names of your classes, function, methods, etc. away from the same scope where the built-in PHP code lives along with any other code behind its own namespace.  It is away to organize your code and avoid naming collisions among libraries and built-in PHP functions.
Here is a brief on how names get resolved:

*

*If you are trying to resolve a name within the same namespace you can use the unqualified name.  So  for class \Foo\Bar\Baz you can use new Baz(); as long as you are in namespace \Foo\Bar.

*If you are trying to resolve a name that is lower in the same parent namespace you can use the qualified name. So for class \Foo\Bar\Baz you would need to use new Bar\Baz(); if you were in namespace \Foo.

*If you are trying to resolve a name that is not in your namespace or is in the global namespace (built-in PHP stuff) then you must use the fully qualified name.  If you are in namespace \Foo\Bar and you want to make use of something like the mysqli class you would need to call it by its fully qualified name. e.g. new \mysqli() Your question above is a perfect example that illustrates this.  Likewise, if you need to access a class in a totally different namespace you would also need the fully qualified name: new \Third\Party\AppClass();
So to summarize, you are right, the built-in stdClass does not exist in your namespace, therefore you need to access it by the fully qualified name.  The reason you must do thing this way had to do with conforming to the rules PHP uses when resolving names.
If you ever need to find out what namespace you are in it will be in the __NAMESPACE__ constant.
In case you haven't already read it, here is the documentation on name resolution in PHP: http://php.net/manual/en/language.namespaces.rules.php

A: The code is evaluated in your namespace and stdClass doesn't exist there. You are effectively answering your own question with your guess.

A: Your guess is correct. Look at the comments in "class references" section of Example #1 on this page.
http://php.net/manual/en/language.namespaces.rules.php


text:
Q: java store objects that may be garbage collected In Java, I recall there is a way to store objects in a usable format that may be garbage collected.  It is some sort of loose reference.   If they get garbage collected there is a way to detect and reload.
I'm having a hard time finding this.  There is so much information about GC in general.  Anyone know the name?

A: I believe you are looking for WeakReference

A: You're thinking of Weak References.

A: I think you're looking for the *Reference classes in java.lang.ref. The ReferenceQueue class allows you to be notified when a reference is collected.
You might also find FinalizableReference from Google Guava useful.


text:
Q: SharePoint 2013 Workflows I have documents held in a SharePoint document library. I was a workflow that moves a document from one document library to another BUT if a document with the same name exists in the library that the document is moved to I want it to be added as a new version keeping the previous version history from the document that it has replaced.
E.g.
Doc A moved to Library x
Doc already exists in Library x called Doc A
Doc A replaced Doc A but keeps all DOC a versioning held in Library x
Hope that makes sense!
Thanks.

A: Go to library / list settings >> Versioning Settings
Set "Yes" where is says " Create a version each time you edit an item in this list? "
Then what you need will happen automatically.


text:
Q: Image path not working correctly In my main directory I created a folder called 'washingtondc'.  In this folder I put a folder called 'images' and an index.html file.  In the images folder is an image enter1.jpg.  I can't get the image to appear on my webpage.  Does anyone see why?
Here is the url that is working correctly:
http://yourfantasyfootballreality.com/washingtondc/index.html
here is the code:

Washington DC 11/9/13

A: I think there might be a problem with your server's configuration, maybe there is an .htaccess redirecting second level subfolders? I suppose this because trying to access your image: enter1.jpg loads your main site, as well as accessing /images/ folder. Check if your images folder has reading access.

A: As you have the images folder and index file in same folder, I think you just need is,

A: check whether the image extension is jpg or jpeg. Enter the src path accordingly.

A: I named the images folder dcimages.  Sorry but thanks for the help


text:
Q: Oveflow even when an int is mod by 10^9+7 I wrote the following code for factorial of a number :
long int fac[max+1];
    fac[0]=1;

    for(int j=1;j<=max;j++)
        {
            fac[j]=(fac[j-1]*j)%1000000007;
        }

    //Printing
    for(int i=0;i<T;i++)
        {
            cout<<fac[N[i]]<<"\n";
        }

This works perfectly for long int but we get a wrong answer if we change the array to int.
Please tell me why this is happening when range of int is greater than 10^9+7.

A: with int fac[max+1];, fac[j-1] * j is int * int with results in int.
if you overflow, you have UB and even with unsigned, you would lose data.
with long int fac[max+1];, then fac[j-1] * j is long int * long int (int -> long int for j) with results in long int.

A: We know that 0 ≤ fac[j - 1] < 109 + 7. But fac[j - 1] * j will be up to j times greater than that, and long is occasionally only 32-bit long (Windows). The absolute maximum value you can fit into a 32-bit number is 4294967295, only about four times your modulus.
Consider using unsigned long long instead of long int - that should work until j > 234.
In fact, given that (a * b) % N is mathematically equivalent to (a % N) * (b % N), once you have replaced long int with unsigned long long you can rewrite
fac[j] = (fac[j - 1] * j) % 1000000007

to
fac[j] = (fac[j - 1] * (j % 1000000007)) % 1000000007

Then, because 10000000072 < 264, you should be able to continue this on forever (although you will eventually run out of space for fac, of course).


text:
Q: "engine.rootObjects().first()" in main.cpp crashes when main.qml imports over HTTP We have a line of code that I've been using forever (or longer) to fetch a pointer to the root window. We've recently started importing our components from a server using the HTTP syntax for import. When we put then together, the program crashes, with engine.rootObjects().first() returning empty. Here is a simplified "main.cpp":
#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    QObject* rootWindowPointer = (engine.rootObjects().first());        // <-- this is the function that fails

    return app.exec();
}

And here is a simplified "main.qml" with the import that caused the problem:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

import "http://eggs:88/empty"       // <-- this is the added line that caused the problem

ApplicationWindow {
    id: window
    visible: true
    width: 200
    height: 100
    title: qsTr("Liblo Server Test")

    Text {
        text: "Made it this far . . ."
        anchors.centerIn: parent
    }
}

If we comment out the following line in main.cpp that gets the root window pointer, the program runs:
QObject* rootWindowPointer = (engine.rootObjects().first();
If we comment out the following line in main.qml that 'imports' our components, the program also runs:
Import "http://eggs:88/empty"
But if you have both lines enabled, then you get the following crash when that line in main.cpp tries to fetch the pointer:
20:37:03: Starting /xxxx/mark/QtApps/build-libloServer-Desktop_Qt_5_15_0_GCC_64bit-Debug/rootwindow ...
QML debugging is enabled. Only use this in a safe environment.
ASSERT: "!isEmpty()" in file ../../Qt/5.15.0/gcc_64/include/QtCore/qlist.h, line 361
20:37:04: The program has unexpectedly finished.
20:37:04: The process was ended forcefully.
20:37:04: /xxxx/xxxx/QtApps/build-libloServer-Desktop_Qt_5_15_0_GCC_64bit-Debug/rootwindow crashed.

Having no idea why these two things would be related, we considered that it might be timing (unlikely, but possible). So we put a wait line in front of the pointer fetch:
Do {} while ( engine.rootObjects().isEmpty());
But it never becomes non-empty. We also tried our real HTTP library, an empty library, and a bogus URL, with the exact same results each time (so you can try it without actually having a URL).
Does anyone have any insight on why this is happening?
If this is an obscure bug, can anyone think of a work-around?
Is there another way to fetch a pointer to the root window for C++ use?

A: There is nothing obscure but it is expected behavior. The rootObjects are assigned to C++ when the object is finished building and since you have an asynchronous loading url (the http) then the construction is asynchronous. So if you want to get root then you must use the objectCreated signal:
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                 &app, [url, &engine](QObject *obj, const QUrl &objUrl) {
    if (!obj && url == objUrl)
        QCoreApplication::exit(-1);
    else{
        if(engine.rootObjects().isEmpty())
            return;
        QObject* rootWindowPointer = engine.rootObjects().first();
        qDebug() << rootWindowPointer;
    }
}, Qt::QueuedConnection);


text:
Q: Data not passing in ajax call in Codeigniter I am sending a file through ajax. Instead of passing the csrf token its not available in the controller
Bellow is code
<script type="text/javascript">
var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
    csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
$(document).on("change","#channel_setup_file",function(e){

    var formData = new FormData($("#process-form")[0]);
    $.ajax({
        url: "<?php echo site_url('parse-setup-file')?>",
        type:   "POST",
        data: {cform : formData,csrfName:csrfHash},
        mimeType: "multipart/form-data",
        contentType: false,
        cache: false,
        processData: false,
        error:  function(msg){
        },
        success: function(msg){
        }
    });
});
</script>

I am getting only the url in the controller.

A: Expecting that you are getting both token and name so in context to that I am writing the code
var formData = new FormData($("#process-form")[0]);
    $.ajax({
        url: "<?php echo site_url('parse-setup-file')?>",
        type:   "POST",
        data: {cform : formData,cName:csrfName,cToken:csrfHash},
        mimeType: "multipart/form-data",
        contentType: false,
        cache: false,
        processData: false,
        error:  function(msg){
        },
        success: function(msg){
        }
    });


text:
Q: Install Grequests (stuck on gevent) mac OS 10.8 I try the last hours to install grequests on my mac 10.8.
When I pip install it I get:
$ pip install grequests
Requirement already satisfied (use --upgrade to upgrade): grequests in /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages
Downloading/unpacking gevent (from grequests)
  Running setup.py egg_info for package gevent
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/private/var/folders/hx/_6mzcrld6777n9mfkx7g9dmc0000gp/T/pip-build-ddl449/gevent/setup.py", line 95
        print 'Linking %s to %s' % (path_to_build_core_so, path_to_core_so)
                               ^
    SyntaxError: invalid syntax
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/private/var/folders/hx/_6mzcrld6777n9mfkx7g9dmc0000gp/T/pip-build-ddl449/gevent/setup.py", line 95

    print 'Linking %s to %s' % (path_to_build_core_so, path_to_core_so)

                           ^

SyntaxError: invalid syntax

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /private/var/folders/hx/_6mzcrld6777n9mfkx7g9dmc0000gp/T/pip-build-ddl449/gevent
Storing complete log in /Users/ddl449/.pip/pip.log

Which seems to be a gevent installation problem as I get the same error when I use:
 pip install gevent #same with pip-3.2

So I went to seem how I can install gevent manually .
And I see as prerequisite greenlet .
And I pip install it but I get:
lipo: can't figure out the architecture type of: /var/folders/hx/_6mzcrld6777n9mfkx7g9dmc0000gp/T//ccRlrUpW.out
error: Setup script exited with error: command 'gcc-4.2' failed with exit status 1

However I have GCC:
$ gcc
i686-apple-darwin11-llvm-gcc-4.2: no input files

Maybe I have messed up something with GCC..
Also:
$ sudo port install py-greenlet
Error: Port py-greenlet not found

So, that's how far I have gone. Any ideas?
Update:
I worked around the GCC error with simply compiling the tarballs python setup.py build install. Although I have Cython installed I get error when I try to install the gevent built tarball.
$ sudo python3.3 setup.py install
running install
running bdist_egg
running egg_info
writing requirements to gevent.egg-info/requires.txt
writing dependency_links to gevent.egg-info/dependency_links.txt
writing top-level names to gevent.egg-info/top_level.txt
writing gevent.egg-info/PKG-INFO
reading manifest file 'gevent.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'Makefile.ext'
writing manifest file 'gevent.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.6-intel/egg
running install_lib
running build_py
running build_ext
/usr/local/bin/python3.3 util/cythonpp.py -o gevent.core.c gevent/core.ppyx
Running cython -o gevent.core.c gevent/core.pyx  # !EV_USE_SIGNALFD && !defined(LIBEV_EMBED) && !defined(_WIN32)
sh: cython: command not found
Traceback (most recent call last):
  File "util/cythonpp.py", line 801, in <module>
    process_filename(filename, options.output_file)
  File "util/cythonpp.py", line 85, in process_filename
    output = run_cython(pyx_filename, sourcehash, output_filename, banner, comment)
  File "util/cythonpp.py", line 529, in run_cython
    system(command, comment)
  File "util/cythonpp.py", line 539, in system
    raise AssertionError('%r failed with code %s' % (command, result))
AssertionError: 'cython -o gevent.core.c gevent/core.pyx' failed with code 32512
make: *** [gevent/gevent.core.c] Error 1

A: Ok here is all I did.
I cleared GCC which was in /usr/local/bin. Now it's in /usr/bin. I used ggc installer package I don't know if that helped but I did it.
I updated to 2.7.5 (I had 2.7.2) and pip install cython. I was installed. The same with gevent and grequest. And done.
However gevent and maybe cython seems to break in python 3.3.


text:
Q: How to optimize a table for fast inserts only? I have a log table that will receive inserts from several web apps.  I wont be doing any searching/sorting/querying of this data.  I will be pulling the data out to another database to run reports.  The initial table is strictly for RECEIVING the log messages.
Is there a way to ensure that the web applications don't have to wait on these inserts? For example I know that adding a lot of indexes would slow inserts, so I won't.  What else is there?  Should I not add a primary key? (Each night the table will be pumped to a reports DB which will have a lot of keys/indexes)

A: Here are a few ideas, note for the last ones to be important you would have extremly high volumns:

*

*do not have a primary key, it is enforced via an index

*do not have any other index

*Create the database large enough that you do not have any database growth

*Place the database on it's own disk to avoid contention

*Avoid software RAID

*place the database on a mirrored disk, saves the calculating done on RAID 5

A: No keys,
no constraints,
no validation,
no triggers,
No calculated columns
If you can, have the services insert async, so as to not wait for the results (if that is acceptable).
You can even try to insert into a "daily" table, which should then be less records,
and then move this across before the batch runs at night.
But mostly on the table NO KEYS/Validation (PK and Unique indexes will kill you)

A: If performance is key, you may not want to write this data to a database. I think most everything will process a database write as a round-trip, but it sounds like you don't want to wait for the returned confirmation message. Check if, as S. Lott suggests, it might not be faster to just append a row to a simple text file somewhere.
If the database write is faster (or necessary, for security or other business/operational reasons), I would put no indexes on the table--and that includes a primary key.  If it won't be used for reads or updates, and if you don't need relational integrity, then you just don't need a PK on this table.
To recommend the obvious: as part of the nightly reports run, clear out the contents of the table. Also, never reset the database file sizes (ye olde shrink database command); after a week or so of regular use, the database files should be as big as they'll ever need to be and you won't have to worry about the file growth performance hit.


text:
Q: How to return object from Asynchronous call in NodeJS? Returning Object from callback [object Object] Trying to get a single object returned by request using callbacks.

Error:undefined
Data:[object Object]
Why are there two objects being returned when I am returning only one error and one object?

A: Actually, there is only one object being returned from the callback. The reason why [object Object] is printed, is because that is the default serialization of an object.
You can see this answer for a detailed explanation:
what does [object Object] mean?
To print the data contained in the object, you can JSON.stringify it like this:
    console.log("Data:"+JSON.stringify(data))


text:
Q: Calculate number of words in Python This is my sample dataset
I need to create a new column "number of characters". This column should indicate the number of words in the queries. I tried to use this code,
df.words = [len(df.query.split()) for sentence in df.query]

but this error returns:

AttributeError: 'Series' object has no attribute 'query'

A: This will do the job:
df['words'] =df['query'].str.split().apply(len)

For example,
import pandas as pd
df=pd.DataFrame({'query':['asd vbg ffd','fd vv']})
df['words'] =df['query'].str.split().apply(len)

Then df is
    query       words
0   asd vbg ffd 3
1   fd vv       2

A: You can use str.split and str.len what nice working with None and missing values also:
df = pd.DataFrame({'query':['asd vbg ffd','fd vv', None, np.nan]})

df['words'] = df['query'].str.split().str.len()
print (df)
         query  words
0  asd vbg ffd    3.0
1        fd vv    2.0
2         None    NaN
3          NaN    NaN

df['words'] =df['query'].str.split().apply(len)

TypeError: object of type 'NoneType' has no len()


text:
Q: Find all current files that Ruby opened when running a program This is someone of an esoteric request, and is just of theoretical interest to me (In other words, I am not used this in production code). I'd like to know if it is possible to figure out all the files involved when running a ruby program. That is, files required by said program during its execution (or involved some other way, such as autoloaded by Rails midway through the program).
I know that one can use ObjectSpace and loop through the object, excluding all but File and its descendants, and I had partial success with this method when I disable garbage collection (otherwise the list shrinks at random times, understandably). However, doing this at the start of the program ignores those files that are required in the middle of it, so I can run the same code at the end, and get the union of said files?

A: lsof
On linux, you could use lsof :
puts `lsof -a -p #{Process.pid}`

It gives you the files held open by the current process.
The list is far from being complete, though : Once this line executes, many files have been read, parsed, executed and closed.
When lsof scans for open files, they don't appear in the list anymore.
strace
strace (also on Linux) is a great tool for what you want to achieve (see this thread). It will give a lot (possibly way too much) information :
strace -e trace=open -o opened_files.txt ruby hello_world.rb
#=> Hello world

opened_files.txt now begins with :
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/tls/x86_64/libruby.so.2.3", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/tls/libruby.so.2.3", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/x86_64/libruby.so.2.3", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/libruby.so.2.3", O_RDONLY|O_CLOEXEC) = 3
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/libc.so.6", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/libpthread.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
open("/home/ricou/.rvm/rubies/ruby-2.3.1/lib/libgmp.so.10", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
....

It has 571 lines for a "Hello World" script and 112302 (!) for a "rails runner hello_world.rb" script.
The output file has many "ENOENT (No such file or directory)" lines, so you might want to parse and filter it.
For macOS and other *nix, there should be dtrace.

A: I did exactly the same a couple months ago. Here is my dirty little program:
REQUIRE_FILE = ENV.fetch('REQUIRE_FILE', '/tmp/requires.txt')

File.open(REQUIRE_FILE, 'w')

Kernel.module_eval do
  alias_method :require_without_benchmark, :require

  def require(name)
    start = Time.now
    begin
      require_without_benchmark(name)
    ensure
      time = Time.now - start
      File.write(REQUIRE_FILE, [name, time.to_f].join(',').concat("\n"), mode: 'a')
    end
  end
end

Then run your program as:
ruby -r ./require-benchmark.rb program.rb

A: See How do I get a list of files that have been `required` in Ruby? for required files.
For all the dependencies of a gem see How do I find out all the dependencies of a gem?
The constant $LOADED_FEATURES holds an array of all files with paths that are loaded with a require, not just the gems themselves but all files involved.
Try $LOADED_FEATURES.dup.uniq at the end of your script.
For the normal files opened by File you could overwrite IO.open and/or File.open and sister methods read, binread etc in the way KARASZI shows in his answer.


text:
Q: Differentiate formatting changes in Revision Diff from text content changes In the current style of diff pages, all changes made in an edit are shown as deletions and additions.
This makes it rather difficult to distinguish between formatting and capitalization changes from content changes. It is also misleading as the revision would appear as though a lot of content is changing, when in truth, only a small part of content is changing, and the rest of the changes are merely formatting improvements. This can lead to rejection of legitimate edits because of how the reviewer misinterpreted the diff display.
This is most pronounced in the Inline view, but can also be seen easily in the Side-by-Side views. As an example, I have the following original screenshot:

In the example, you can see that there's a lot of red and a lot of green. You can also see double words like "i I" and "unix Unix". At first glance, it's not easy to judge how much of changes are merely formatting or capitalization changes, and how much change the actual text content.
My suggestion is to show formatting and capitalization changes in a different way. I have created the following mock-up to demonstrate how this might look like:

In this, the formatting and capitalization changes are shown in a pale shade of yellow, without any repetitions. It's easy to focus on actual text changes which are still shown in red and green. For example, the change of "data's are" to "data is" or the deletion of "pasting my" are easier to spot.
I believe reviewers would be more interested in focusing on the text content changes when reviewing revisions, and highlighting only such changes distinguished from less important changes could be very helpful in determining whether an edit is worthy of an Approve vote.
I would imagine the detection algorithm could be tweaked to compare the deleted text (red) and the added text (green) -- if the plain text content matches (ignoring case), mark this as a change (yellow). It could also be further refined to detect substrings (on word level) where text content matches, splitting them appropriately into change and deletion/addition (e.g. "Unix environment" in screenshots above).
The suggestion can be expanded to both Side-by-Side views by showing the less important changes in yellow on both sides.


text:
Q: IPv6 connectivity suddenly lost, IPv6 neighbour router status becomes STALE at the same time. How can I avoid it? I have a VM on a host with bridged networking (hence, with its own MAC address).  Both host and VM run CentOS.  Their network is managed by simple /etc/sysconfig/network-scripts/ifcfg-enpXsY files which contains the static IP addresses. IPv4 works just fine.
I have assigned an IPv6 address to the VM (the host also has one) which is routed correctly in the data centre.  Most connections use IPv4, however (no DNS AAAA entry for the machine yet, still testing IPv6).
When I boot up the VM it has full IPv6 connectivity.  However, after a while IPv6 connectivity stops working (IPv6 magic?).  I have narrowed to problem down to neighbour (ARP/NDISC cache) data:
IPv6 not working, cannot ping or connect by IPv6 in or out, then I see:
# ip -6 neighbour
fe80::1 dev enp1s2 lladdr 0c:86:72:2e:04:28 router STALE

Fix/workaround to refresh the cache:
# ip -6 neighbour flush dev enp1s2
# ip -6 neighbour
(empty, as expected)

Then ping6 the host from within the VM to fill the cache:
# ping6 2912:1375:23:9a6c::2
PING 2912:1375:23:9a6c::2(2912:1375:23:9a6c::2) 56 data bytes
64 bytes from 2912:1375:23:9a6c::2: icmp_seq=1 ttl=64 time=2.35 ms
64 bytes from 2912:1375:23:9a6c::2: icmp_seq=2 ttl=64 time=0.468 ms
^C
# ip -6 neighbour
fe80::1 dev enp1s2 lladdr 0c:86:72:2e:04:28 router REACHABLE
2912:1375:23:9a6c::2 dev enp1s2 lladdr 08:21:4b:b7:f8:31 DELAY

IPv6 neighbour/ARP table restored to validity and connectivity is working in and out!
So my questions are:

*

*Why does the cache become stale?

*What can I do to avoid it?'

*Why/how does the command above fix it?

Of course I could run those commands in a cron job (how often?) but I suppose that cannot really be needed for IPv6 to work in general?
PS: I used a script for tests: The IPv6 stack breaks down about every 20 minutes. Can that be explained by RFCs?
PPS: Firewall config (shortened output, hopefully all relevant bits):
# ip6tables -nvL
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 9023  709K ACCEPT     icmpv6    !lo    *       ::/0                 ::/0
Chain OUTPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 9360  785K ACCEPT     icmpv6    *      !lo     ::/0                 ::/0

So, ICMPv6 accepted in/out on the VM. Do I need to check filtering on the host?

A: Generally Stale State is a good thing, actually its acceptable we have a Stale State.
Let's look at RFC 4861, section 5.1. :

  STALE       The neighbor is no longer known to be reachable but until traffic is sent to the neighbor, no attempt should be made to verify its reachability.

The neighbor is no longer known to be reachable (timer expired, no traffic lately, whatever) and reachability will be 'verfied' once traffic is sent to the neighbor again.
So there isn't any issue if you can send traffic to the neighbor again.


text:
Q: Whether there should be a difference to copy files in parallel and not in parallel? I tried to copy 200 files with both below solutions but I didn't saw the difference ( I used System.Diagnostics.Stopwatch to measure time). In both cases it took 8 seconds. Should not the second(Parallel) solution be faster? I thought because it is IO operations using Parallel will speed up the copy.
What I'm missing?
// Case1 - Regular iteration
foreach (FileInfo file in files)
{
    string temppath = Path.Combine(destDirName, file.Name);
    file.CopyTo(temppath, false);
}

// Case2 - Parallel
Parallel.ForEach(files, file =>
{
    string temppath = Path.Combine(destDirName, file.Name);
    file.CopyTo(temppath, false);
});

A: Parallel execution of tasks doesn't guarantee performance improvements.
In your case, file copying will likely be IO bound, not CPU bound. The CPU typically has much more bandwidth available than the IO device (unless you happen to be using a Fusion IO card or something), so IO actions tend to cause the CPU to wait a lot.
Tasks that use a lot of CPU can be done in parallel to get performance gains. Tasks that also wait on external factors can also benefit from being shifted onto another thread so as not to become a blocking task.
However, tasks that are waiting for the same external resource will likely see little benefit unless that external resource can itself handle the traffic associated with multiple threads (IO tends to never be able to handle the traffic and could in fact cause contention of the resource, slowing it down).

A: Exactly the same as @Adam above, but with added points:
If you get a chance, you might like to try this with one, or two networked drives.  File transfer on high-latency connections have a large setup latency that may well give an advantage to the multithreaded solution, especially with large numbers of small files.
It may well be also useful to use a pool with a small, fixed number of threads, (2 say), to see if that reduces disk contention and improves performance.
If you like my answer, please upvote @Adam, not me.


text:
Q: Can't unmarshall REST response Spring-Jibx I have a problem unmarshalling a RESTful request body using Spring and Jibx.
This is the request body I'm sending through Postman:
<?xml version="1.0" encoding="utf-8"?>
<locationRequest xmlns="urn:ietf:params:xml:ns:geopriv:held" responseTime="30000">
  <locationType exact="true">
    geodetic
    civic
    locationURI
  </locationType>
  <device xmlns="urn:ietf:params:xml:ns:geopriv:held:id">
    <uri>tel:123456789;phone-context=+1</uri>
  </device>
</locationRequest>

This is my binding.xml
...
<mapping name="locationRequest" class="com.example.integrations.models.LocationRequest" ordered="true">
    <namespace uri="urn:ietf:params:xml:ns:geopriv:held" default="elements" />
    <value name="responseTime" field="responseTime" style="attribute" usage="optional"/>
    <structure name="locationType" field="locationType" map-as="locationType" usage="required"/>
    <structure field="device" usage="required"/>
</mapping>

<mapping name="device" class="com.example.integrations.models.Device" >
    <namespace uri="urn:ietf:params:xml:ns:geopriv:held:id" default="elements" />
    <value name="uri" field="uri" />
</mapping>

<mapping abstract="true" type-name="locationType" class="com.example.integrations.models.LocationType">
    <value name="exact" field="exact" style="attribute"/>
    <value field="types" style="text"
           serializer="com.example.integrations.ParseUtil.serializeStringList"
           deserializer="com.example.integrations.ParseUtil.deserializeStringList" />
</mapping>
...

When I run the Jibx compiler everything is fine and all classes are detected and modified by the compiler correctly
This is the method that receive the web service call:

The request its unmarshalled correctly if I use a .xml file as the input, but if I go through the web service its missing some data:
...
 <locationType exact="true">
    geodetic
    civic
    locationURI
  </locationType>
...

The "exact" attribute is parsed correctly, but the content, while on the xml file was parsed ok, is missing in the web service object... and for the love of me I can't figure out why.
(Note: Also the response object (LocationResponse) is not marshalled correctly when returning to Postman)
This is my Spring-servlet configuration relevant to jibx:
...
    <beans:bean id="unmarshaller" class="org.springframework.oxm.jibx.JibxMarshaller">
        <beans:property name="targetClass" value="org.dellroad.jibxbindings.pidf.held.LocationRequest"/>
        <beans:property name="bindingName" value="locationRequest"/>
    </beans:bean>

    <beans:bean id="marshaller" class="org.springframework.oxm.jibx.JibxMarshaller">
        <beans:property name="targetClass" value="org.dellroad.jibxbindings.pidf.held.LocationRequest"/>
        <beans:property name="bindingName" value="locationRequest"/>
    </beans:bean>
...

What am I missing here? I suspect is a missconfiguration in the Spring side


text:
Q: Asymptotic behaviour of function from integral representation In Appendix A of this paper, it is claimed that the asymptotic behaviour of
$$\phi_1(y,\lambda)=\frac{1}{\Gamma(\frac{1-\lambda}{2})}\int_0^\infty dt~e^{-t}\cos(2y\sqrt{t})t^{-\frac{1+\lambda}{2}},$$
for $\lambda_2=\text{Im}(\lambda)\to+\infty$ (where $\lambda=\lambda_1+i\lambda_2$), is
$$\phi_1(y,\lambda_1+i\lambda_2)\sim\cosh[y\sqrt{\lambda_2-i\lambda_1}(1+i)]\exp(-y^2/2) .$$
I have been trying various asymptotic methods to arrive at this result, such as the method of stationary phase, without success. How might one derive this result?

A: If we expand $\cos{(2y\sqrt{t})}$ into  Taylor series and integrate term by term, we get $$\phi_1(y,\lambda)=\sum\limits_{n=0}^\infty\frac{(-1)^n}{(2n)!}\frac{\Gamma\left(n+\frac{1}{2}-\frac{\lambda}{2}\right)}{\Gamma{\left(\frac{1}{2}-\frac{\lambda}{2}\right)}}(2y)^{2n}.$$ Now let us use the following asymptotic expansion of Tricomi and Erdelyi (see, for example, https://www.sciencedirect.com/science/article/pii/S0022247X11011280 ) $$\frac{\Gamma(z+\alpha)}{\Gamma(z+\beta)}=\sum_{n=O}^\infty C_n(\alpha-\beta,\beta)z^{\alpha-\beta-n},$$ where $|z|\to\infty$ and the coefficients are given by reccurence relations (with $C_0=1$) $$C_n(\alpha-\beta,\beta)=\frac{1}{n}\sum_{i=0}^{n-1}\left[\binom{\alpha-\beta-i}{n-i+1}-(-1)^{n+i}(\alpha-\beta)\beta^{n-i}\right]C_i(\alpha-\beta,\beta).$$ As a result we get (asymptotically) $$\phi_1(y,\lambda)=\sum_{n=0}^\infty\sum_{m=0}^\infty\frac{(-1)^n}{(2n)!}C_m\left(n,1/2\right)\left(-\frac{\lambda}{2}\right)^{n-m}(2y)^{2n}.$$ It  follows from the equation 1.4 of the mentioned paper that $C_m(n,\beta)$ is proportional to $1/(n-m)!$. Therefore $C_m(0,\beta)=C_m(1,\beta)=\cdots=C_m(m-1,\beta)=0$. As a result $$\phi_1(y,\lambda)=\sum_{m=0}^\infty\sum_{n=m}^\infty\frac{(-1)^n}{(2n)!}C_m(n,1/2)\left(-\frac{\lambda}{2}\right)^{n-m}(2y)^{2n}=\\ \sum_{m=0}^\infty\sum_{n=0}^\infty\frac{(-1)^{n+m}}{[2(n+m)]!}C_m(n+m,1/2)\left(-\frac{\lambda}{2}\right)^n(2y)^{2n+2m}.$$ We can rewrite this as follows $$\phi_1(y,\lambda)=\sum_{m=0}^\infty\sum_{n=0}^\infty\frac{(-1)^n}{(2n)!}\left(\sqrt{-\frac{\lambda}{2}}\;2y\right)^{2n}\frac{(2n)!}{[2(n+m)]!}C_m(n+m,1/2)(-4y^2)^m.$$ As $|\lambda|\to\infty$, we can assume that for any fixed $m$ only terms $n\gg m$ are relevant (this is somewhat not rigorous. Can one make it more precise?). But then $$\frac{(2n)!}{[2(n+m)]!}\to\frac{1}{(2n)^{2m}}.$$ On the other hand, in the $n\gg m$ limit we get from the reccurence relations $$\frac{C_m(n,1/2)}{n^{2m}}=\frac{1}{m}\frac{1}{n^{2m}}\left [\binom{n}{2}+\frac{n}{2}\right]C_{m-1}(n,1/2)=\frac{1}{2m}\frac{C_{m-1}(n,1/2)}{n^{2(m-1)}}.$$ This implies that $$\frac{C_m(n,1/2)}{n^{2m}}\to \frac{1}{2^m\, m!}.$$ Therefore asymptotically $$\phi_1(y,\lambda)=\sum_{m=0}^\infty\sum_{n=0}^\infty\frac{(-1)^n}{(2n)!}\left(\sqrt{-\frac{\lambda}{2}}\,2y\right)^{2n}\frac{1}{m!}\left(-\frac{y^2}{2}\right)^m=\cos{\left(\sqrt{-\frac{\lambda}{2}}\,2y\right)}e^{-y^2/2}.$$ To finish the proof, let us note that $$\sqrt{-\frac{\lambda}{2}}\,2y=iy\sqrt{\lambda_2-i\lambda_1}\,(1+i)$$  because $\sqrt{i}=(1+i)/\sqrt{2}$.


text:
Q: IS NULL with symfony2 and doctrine I'm trying this piece of code but I keep bumping into an error
$q = $this->_em->createQueryBuilder('p')
    ->select('p')
    ->from('ClendarRecipeBundle:RecipePlan', 'p')
    ->leftJoin('p.recipeCalendars', 'c')
    ->groupBy('c.recipePlan')
    ->having('p.portions > SUM(c.portions)')
    ->orHaving('SUM(c.portions) IS NULL')
    ->getQuery();

when SUM(c.portions) is NULL the first having doesn't select it, so I tried to add orHaving but symfony2 gives me the following error:
[Syntax Error] line 0, col 204: Error: Expected =, <, <=, <>, >, >=, !=, got 'IS'

I tried a few different ways to write, any of you have a good suggestion what I could try?
I could try RAWS Sql but I prefer the code in the QueryBuilder with objects as a result.

A: It should have been:
SUM(c.portions) != 0


text:
Q: Help identifying IC damaged by wrong voltage I accidentally fried an IC when switching out a power supply; sent 12V instead of 5V. I've been trying to find some information on this drive, a Corsair M500 240GB, (CT240M500SSD1) - maybe a datasheet, but I haven't found zilch.
IC below - the damage is pretty visible. Maybe it's some sort of regulator? Not sure:


text:
Q: Rx: How to modify a shared source observable within a retry Top Level Question:
I want to know how, within a retry, I can modify its source observable if it is an observable shared between multiple subscribers (in this case a BehaviorSubject/Relay).
Solution(s) I have considered:
The suggestion of using defer from this post doesn't seem to naturally port over if the source observable needs to be shared.
Use case (to fully elaborate the question)
Say I have a server connection object that, when initialized, connects to an url. Once it is created, I can also use it to get a data stream for a particular input.
class ServerConnection {
    var url: URL
    init(url: URL)
    func getDataStream(input: String) -> Observable<Data> // the observable also errors when the instance is destroyed.
}

However, one particular url or another may be broken or overloaded. So I may want to obtain the address of a mirror and generate a new ServerConnection object. Let's say I have such a function.
// At any point in time, gets the mirror of the url with the lowest load
func getLowestLoadMirror(url: URL) -> URL {}

Ideally, I want this "mirror url" switching should be an implementation detail. The user of my code may only care about the data they receive. So we would want to encapsulate this logic in a new class:
class ServerConnectionWithMirrors {
    private var currentConnection: BehaviorRelay<ServerConnection>
    init(startingURL: URL)
    func dataStream(for inputParams: String) -> Observable<Data>
}

// usage
let connection = ServerConnectionWithMirrors(startingURL: "www.example.com")
connection.dataStream(for: "channel1")
    .subscribe { channel1Data in
        // do something with channel1Data
    }.disposed(by: disposeBag)

connection.dataStream(for: "channel2")
    .subscribe { channel2Data in
        // do something with channel2Data
    }.disposed(by: disposeBag)

How should I write the dataStream() function for ServerConnectionWithMirrors? I should be using retries,  but I need to ensure that the retries, when faced with a particular error (ServerOverLoadedError) update the value on the behaviorRelay.
Here is code that I have so far that demonstrates the crux at what I am trying to do. One problem is that multiple subscribers to the behaviorRelay may all update it in rapid succession when they get an error, where only one update would do.
func dataStream(for inputParams: String) -> Observable<Data> {
    self.currentConnection.asObservable()
        .flatMapLatest { server in
            return server.getDataStream(input: inputParams)
        }
        .retryWhen { errors in
            errors.flatMapLatest { error in
                if error is ServerOverLoadedError {
                    self.currentConnection.accept(ServerConnection(url: getLowestLoadURL()))
                } else {
                    return Observable.error(error)
                }
            }
        }
}

A: The answer to your top level question:

I want to know how, within a retry, I can modify its source observable if it is an observable shared between multiple subscribers (in this case a BehaviorSubject/Relay).

You cannot modify a retry's source observable from within the retry. (full stop) You cannot do this whether it is shared or not. What you can do is make the source observable in such a way that it naturally updates its data for every subscription.
That is what the question you referred to is trying to explain.
func getData(from initialRequest: URLRequest) -> Observable<Data> {
    return Observable.deferred {
        var correctRequest = initialRequest
        let correctURL = getLowestLoadMirror(url: initialRequest.url!)
        correctRequest.url = correctURL
        return Observable.just(correctRequest)
    }
    .flatMapLatest {
        getDataFromServer(request: $0)
    }
    .retryWhen { error in
        error
            .do(onNext: {
                guard $0 is ServerOverloadedError else { throw $0 }
            })
    }
}

With the above code, every time deferred is retried, it will call its closure and every time its closure is called, the URL will the lowest load will be used.


text:
Q: How to use a symbol as an option value in a select element in a react component I'm trying to set up a part of my program to use symbols much like a C# enum as per below but the value is always blank. Is there a better way to accomplish this?
const options = [
    {
        display: 'option1',
        value: Symbol('option1')
    },
    {
        display: 'option2',
        value: Symbol('option2')
    },
    {
        display: 'option3',
        value: Symbol('option3')
    },
];

const SymbolSelect = () => {
    return (
        <Select>
            {options.map(({ value, display }, i) => (
                <option value={value} key={i}>{display}</option>
            ))}
        </Select>
    );
}


text:
Q: CAT(0) groups that does not act on CAT(0) cubical complex CAT(0) groups are groups that act on a CAT(0) space properly and cocompactly. If a group acts on a CAT(0) cubical complex properly and cocompactly, then of course it is a CAT(0) Group. I am wondering the other direction,
Quesion: Given a CAT(0) group G , will one always be able to find a CAT(0) cubical complex such that G acts properly and cocompactly.
I assume the answer is no, but I could not find any counter example by google. If the answer is indeed no, one can further ask does there exists a CAT(0) group that can not act on a CAT(0) cubical complex properly.

A: Many CAT(0) groups cannot act geometrically on CAT(0) cube complexes. For instance:

*

*CAT(0) groups satisfying Kazhdan's property (T), eg. uniform lattices in simple Lie groups of higher rank or in quaternionic hyperbolic spaces (as mentioned by Jean Raimbault in the comments).

*Some Kähler groups (as mentioned by Misha in the comments), including uniform lattices in complex hyperbolic spaces.

*Some crystallographic groups, as proved by Mark Hagen.

*Some Coxeter groups (see Niblo and Reeves' article for more details).

*Some braid groups, eg. $B_n$ for $n=4,5,6$ (see Haettel's article Virtually cocompactly cubulated Artin-Tits groups and references therein).

*The group $\mathrm{Aut}(B_4) \simeq \mathrm{Aut}(\mathbb{F}_2)$ (see Piggott, Ruane and Walsh's article The automorphism group of the free group of
rank two is a CAT(0) group).

Probably, the easiest example of such a group is the triangle group
$$T=\langle a,b,c \mid a^2=b^2=c^2=(ab)^3=(bc)^3=(ac)^3=1 \rangle.$$
It coincides with the symmetry group of the regular tilling of the Euclidean plane by equilateral triangles. So it acts geometrically on the Euclidean plane: it is a CAT(0) group.
As observed by Wise, if a virtually $\mathbb{Z}^n$ group $G$ acts geometrically on a CAT(0) cube complex, then it acts geometrically on $\mathbb{E}^n$ endowed with its usual cubulation. (See Lemma 16.12 in his long paper The structure of groups with a quasiconvex hierarchy. Essentially, the idea is the following: apply the flat torus theorem to find a $G$-invariant flat $\mathbb{R}^n$ inside your cube complex $C$, and look at the CAT(0) cube complex obtained by cubulating the wallspace defined by the intersections of the hyperplanes of $C$ with your flat.) Consequently, if $T$ were cubulable then it would act geometrically on the square complex $\mathbb{E}^2$.
Notice that $\mathrm{Isom}(\mathbb{E}^2)= (D_{\infty} \times D_{\infty}) \rtimes \mathbb{Z}_2$ does not contain elements of order three, so, for any action $T \curvearrowright \mathbb{E}^2$ by isometries, the elements $ab$, $bc$ and $ac$ must be trivial. Consequently, such an action must factorise through the quotient $T \twoheadrightarrow \mathbb{Z}_2$ sending all the generators to $1$. A fortiori, the action cannot be geometric (and even proper).


text:
Q: Binding event to chosen select I have this code for a select box which is being displayed by the Chosen jQuery plugin. What I am trying to achieve is to get the value from the current item that has been selected:

  <select id="schedule_event" name="schedule[event]" style="display: none; " class="chzn-done"><option value="Game" selected="selected">Game</option>
    <option value="Event">Event</option>
    <option value="Training">Training</option>
  </select>

      Game

        <input type="text" autocomplete="off" style="width: 814px; " tabindex="0">

Game

Event

Training

The JavaScript I'm using at the moment to find the current value is:
$("#schedule_event").chosen().change( function() {
    alert(+ $(this).text());
    $('#' + $(this).val()).show();
});

However, I keep getting a 'NaN', ie no value.

A: Personally I prefer use this:
$(document).on('change', '#mychosen', function(evt, params) {
    if (params.selected != undefined)
    {
        console.log('selected: ' + params.selected);
    }
    if (params.deselected != undefined)
    {
        console.log('deselected: ' + params.deselected);
    }
});

A: Code:
$(".chzn-select").chosen().change(function() {
    alert(+$(this).val());
    //$('#' + $(this).val()).show();
});

Demo:
Working demo: http://jsfiddle.net/MM7wh/
Edit  (6th July 2015)
cdns are changed now.
Working demo: http://jsfiddle.net/uk82dm5L/
Please use $(this).val() instead of .text().


text:
Q: How to change the default cursor position of a JTextArea? In previous question I asked how to set cursor to the bottom of the JTextArea. The answer was textField.getDocument().getLength()   Technically, I can use textField.getDocument().getLength() after every text insert, but this is not convenient.
However, this is not exactly what I meant. I need to change the JTextArea PROPERTY of cursor position. In my program _result is JTextArea. It gets texts from multiple classes and methods, so using textField.getDocument().getLength() everytime after _result.append("text") is not convenient and makes code error prone and not flexible
Is there any way I could do something like:
// this is just a pseudocode
_result.setDefaultCursorPosition(bottom);

and then whenever text goes there (NO MATTER from what class or method), the cursor is always at the bottom.

A: This would move the caret to the end position after each document change:
_result.getDocument().addDocumentListener(new DocumentListener() {
        private void atEnd() {
            _result.setCaretPosition(_result.getText().length());
        }
        public void insertUpdate(DocumentEvent evt) { atEnd(); }
        public void removeUpdate(DocumentEvent evt) { atEnd(); }
        public void changedUpdate(DocumentEvent evt) { atEnd(); }
    });

It still allows the user to re-position the caret by clicking, or by other calls to setCaretPosition.


text:
Q: Is $O(|E|*\Delta)$ algorithm pseudo-polynomial or just polynomial? If we have graph $G=(V,E)$, and we also have some graph algorithm which complexity is $O(
|E|*\Delta)$ or $O(|V|*\Delta)$, so it depends on the $\Delta$ value, where $\Delta$ is a maximum degree of a graph ($max\ {deg(v)}$).
Is this algorithm pseudo-polynomial or just polynomial ?
Edited: By polynomial I mean polynomial time where the input is $V$ and $E$.
P.S.
I think it's polynomial because $\Delta$ is not a numerical value of some part of the input, but I'm not sure.

A: I think part of what is confusing you is that when you say "polynomial" you should say "polynomial in what". For example, our standard algorithms for prime factorization take "polynomial time"...in the number itself. But in that field "polynomial" means "polynomial in the number of digits".
In your case, note $\Delta \leq |V|$, so something $O(|E| |V|)$ is polynomial in $|E|$ and $|V|$.


text:
Q: Save dictionary to model object I have a dictionary like this one:
{'company_name': 'Google', 'title': 'headline', ...}

I know that i can store the values using this way:
user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...)

However this is not good if I have many form fields.
There is any way to do this without hard code all the maps? The key value of the dictionary is the same of his model.

A: You can use the following:
user = User(**data_db_form)

Here is the full example:
class User():
    def __init__(self, company_name='unknown', title='unknown'):
        self.company_name = company_name
        self.title = title

data_db_form = {'company_name': 'Google', 'title': 'headline'}

user = User(**data_db_form)

print user.company_name # prints Google
print user.title        # prints headline

A: Loop over the dictionary using for key, value in dic.iteritems():, then in each iteration you have company_name, title, etc. in key and Google, headline, etc. in value.


text:
Q: Example of weakly separated function A function $f:X \rightarrow Z$, where $X$ is a topological space and $Z$ is a metric space, is called weakly separated if for every $\epsilon>0$, there is a neighbourhood assignment $(V_x)_{x \in X}$ such that $d(f(x),f(y))\leq \epsilon$ whenever $(x,y) \in V_y \times V_x$.
The definition is extracted from the paper 'the point of continuity property neighbourhood assignments and filter convergences' by Ahmed Bouziad.
I am having difficulty to understand the definition.
Suppose $X=Z=\mathbb{R}$ and $f(x)=x$. Then my difficulty is I don't know how to find $(V_x)_{x \in \mathbb{R}}$. Can anyone enlighten me?
EDIT(1): a neighbourhood assignment means that each $V_x$ is an open neighbourhood of $x$ in $X$.
EDIT (2): May I know what is the intuition behind the definition?

A: In this example, you can let $V_x$ be the ball of radius $\epsilon$ centered at $x$, ie the open interval $(x-\epsilon, x+\epsilon)$.  Then, if $(x,y) \in V_y \times V_x$, you have $x\in V_y$ and $y\in V_x$ both implying that $|x-y| < \epsilon$, as desired.


text:
Q: Rotating a shape in KineticJS seems to move it out of sync with it's group I am working on some image viewing tools in KineticJS.  I have a rotate tool.  When you move the mouse over an image, a line appears from the centre of the image to the mouse position, and then when you click and move, the line follows and the image rotates around that point, in sync with the line.  This works great.
My issue is, I have the following set up:
Canvas->
Stage->
Layer->
GroupA->
GroupB->
Image
This is because I draw tabs for options on GroupA and regard it as a container for the image.  GroupB is used because I flip GroupB to flip the image ( and down the track, any objects like Text and Paths that I add to the image ), so that it flips but stays in place.  This all works well.  I am also hoping when I offer zoom, to zoom groupb and thus zoom anything drawn on the image, but for groupA to create clipping and continue to support drag buttons, etc.
The object I am rotating, is GroupA.  Here is the method I call to set up rotation:
this.init = function(control)
{
    console.log("Initing rotate for : " + control.id());

    RotateTool.isMouseDown = false;
    RotateTool.startRot = isNaN(control.getRotationDeg()) ? 0 : control.getRotationDeg();
    RotateTool.lastAngle = control.parent.rotation() / RotateTool.factor;
    RotateTool.startAngle = control.parent.rotation();

    this.image = control.parent;

    var center = this.getCentrePoint();

    RotateTool.middleX = this.image.getAbsolutePosition().x + center.x;
    RotateTool.middleY = this.image.getAbsolutePosition().y + center.y;

    this.image.x(this.image.x() + center.x - this.image.offsetX());
    this.image.y(this.image.y() + center.y - this.image.offsetY());
    this.image.offsetX(center.x);
    this.image.offsetY(center.y);
}

getCentrePoint is a method that uses trig to get the size of the image, based on the rotation.  As I draw a line to the centre of the image, I can tell it's working well, to start with.  I've also stepped in to it and it always returns values only slightly higher than the actual width and height, they always look like they should be about what I'd expect, for the angle of the image.
Here is the code I use on mouse move to rotate the image:
this.layerMouseMove = function (evt, layer)
{
    if (RotateTool.isRotating == false)
        return;

    if (!Util.isNull(this.image) && !Util.isNull(this.line))
    {
        if (Item.moving && !RotateTool.isRotating)
        {
            console.log("layer mousemove item moving");

            RotateTool.layerMouseUp(evt, layer);
        }
        else
        {
            var pt = this.translatePoint(evt.x, evt.y);
            var x = pt.x;
            var y = pt.y;

            var end = this.getPoint(x, y, .8);

            RotateTool.line.points([this.middleX, this.middleY, end.x, end.y]);
            RotateTool.line.parent.draw();

            RotateTool.sign.x(x - 20);
            RotateTool.sign.y(y - 20);

            var angle = Util.findAngle({ x: RotateTool.startX, y: RotateTool.startY }, { x: x, y: y }, { x: RotateTool.middleX, y: RotateTool.middleY });

            var newRot = (angle) + RotateTool.startAngle;

            RotateTool.image.rotation(newRot);

            console.log(newRot);
        }
    }
}

Much of this code is ephemeral, it's maintaining the line ( which is 80% of the length from the centre to my mouse, as I also show a rotate icon, over the mouse.
Sorry for the long windedness, I'm trying to make sure I am clear, and that it's obvious that I've done a lot of work before asking for help.
So, here is my issue.  After I've rotated a few times, when I click again, the 'centre' point that the line draws to, is way off the bottom right of my screen, and if I set a break point, sure enough, the absolute position of my groups are no longer in sync.  This seems to me like my rotation has moved the image in the manner I hoped, but moved my group off screen.  When I set offsetX and offsetY, do I need to also set it on all the children ? But, it's the bottom child I can see, and the top group I set those things on, so I don't really understand how this is happening.
I do notice my image jumps a few pixels when I move the mouse over it ( which is when the init method is called ) so I feel like perhaps I am just out slightly somewhere, and it's causing this flow on effect.  I've done some more testing, and my image always jumps slightly up and to the right when I move the mouse over it, and the rotate tool continues to work reliably, so long as I don't move the mouse over the image again, causing my init method to call.  It seems like every time this is called, is when it breaks.  So, I could just call it once, but I'd have to associate the data with the image then, for the simple reason that once I have many images, I'll need to change my data as my selected image changes.  Either way, I'd prefer to understand and resolve the issue, than just hide it.
Any help appreciated.


text:
Q: How to generate Random point(x,y) in Java I want to generate a random point(x,y) in java which should lie within a 2D plane {(1,1)(1,-1)(-1,1)(-1,-1)} where both positive & negative X & Y axis is considered.Thank you

A: Take a look at article https://www.tutorialspoint.com/java/util/java_util_random.htm. All you need to do is to generate pairs of floats in range (-1,1). You should use method nextFloat() from class Random. It will give you numbers in range (0,1). Then multiply it by 2 and subtract 1 and you will have numbers in desired interval.

A: Please use SecureRandom see: StackOverflow

A: Use this method below to return you the random points
public String randXYPoint(){
    //For x and y, the maximum point is 1 and Minimum point is -1
    //maximum number
    int min = -1;
    //minimum number
    int max = 1;

    // generates x values
    double xValue = min + Math.random() * (max - min);
    // generates y values
    double yValue = min + Math.random() * (max - min);
    //returns and converts points to string
    return  String.valueOf(xValue)+ ", "+ String.valueOf(yValue);
}

Just call the method
System.out.println(randrandXYPoint())


text:
Q: In Ajax Image not uploading with other forms data,shows blank array in $_FILES I am trying to save image and other forms data with ajax, But Some problems facing while uploading image. Image is selected and Sent from js but in php $_FILES not getting this image its return blank

IN js

     var datastr = 'productionstrategyno='+productionstrategyno+
'&manufacturingleadtime='+manufacturingleadtime;
     if (($("#item-master-image"))[0].files.length > 0) {
                                    file = ($("#item-master-image"))[0].files[0];
                                    datastr += '&images='+file;
                                }

                                $.ajax({
                                url: base_url+'ajax_response/item_master',
                                type: 'post',
                                data: datastr,
                                dataType: 'json',
                                enctype: 'multipart/form-data',
                                processData: false,  // do not process the data as url encoded params
                                success: function(json) {

                                    if(json.status="200"){
                                        msgalert(json.msg,"success");
                                        window.location.href=base_url+"master/listItem";
                                    }else{
                                        msgalert(json.msg,"danger");

                                    }
                                }
                                });

It's send to php giving

isstandardmaterial:1
ismaintainbincard:1
images:[object File]

In PHP

<?php print_r($_FILES['images']); ?>

It return blank array value


text:
Q: Where in the registry does CoCreateInstance() look? Delphi Where in the registry does CoCreateInstance() look?
Looking for the Class ID: {000209FF-0000-0000-C000-000000000046} (Microsoft Word Application)
My guess is Computer\HKEY_CLASSES_ROOT\CLSID\{000209FF-0000-0000-C000-000000000046}\LocalServer32 if I'm looking for that Class ID. Can I get a confirmation?
Delphi calls:
CoWordApplication.Create;

That calls:
CreateComObject(CLASS_WordApplication) as _Application;

and that calls:
OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
        CLSCTX_LOCAL_SERVER, IUnknown, Result));


text:
Q: Issue with removing padding or margin http://www.coffeeproteindrink.com/method-athlete/
I am trying to remove the open space below the main wrapper, in Firefox it shows about a 20px open area, with a verticalscroll bar on the main page in order to see it.
In IE there is a visible 115px area, with no scroll bar.
My goal is to have the main_wrap + footer sit flush to the bottom of the page, but nothing I am trying is seeming to help.
#main_wrap {height: 390px;
background: url(images/content_back.png) repeat-y top left;
margin: 0 0 0 240px;
opacity: .8;
position:absolute;
top:325px;
overflow: hidden;
}

#main
{position: relative;
width: 680px;
padding: 0 40px 5px 40px;
font: normal 12px Verdana, Arial, sans-serif;
line-height: 20px;
display: inline-block;
z-index: 2;
}

#footer
{
width: 680px;
padding: 25px 40px 0 0px;
font-size: 12px;
position: relative;
height: auto;
clear: both;
bottom:50px;}

Example of what I am trying to accomplish: http://www.bio-genix.com/
Thanks for any help,
Ken

A: Turns out you don't need a sticky-footer technique because your background image is stretching to the screen, meaning you can use height: 100% and it's reliably set to the full height.
So, seeing that, bottom: 0 will work on #main_wrap. The next puzzle was where the phantom 60px or so of bottom margin was coming from; finally, after tweaking, it was determined that overflow: hidden would hide the additional height that was developed by the margins and paddings within the #main_wrap element.
This is what ended up working (the h2 part a fix for a fix):
#main_wrap {
    position: absolute;
    height: 390px;
    bottom: 0;
    margin-top: 0;
    margin-bottom: 0;
    overflow: hidden;
}
#main {
    padding-bottom: 0;
}
#main_wrap #main h2.section_title {
    margin: 20px 0 40px
}

http://jfcoder.com/test/methodsite.html


text:
Q: How to get data from asp.net webapi from wpf datagrid without the app freeze? I created an asp.net web api. It works superbly, tested with postman. I would like to display the users on the wpf datagrid. The code is as follows:
    public partial class ListUsers : Page
{
    public ListUsers()
    {
        InitializeComponent();
        GetData();

    }

    public void GetData()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:1234/");

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("api/users").Result;

        if (response.IsSuccessStatusCode)
        {
            var users = response.Content.ReadAsAsync<IEnumerable<Users>>().Result;

            UserGrid.ItemsSource = users;

        }
        else
        {
            MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
        }
    }
}

But unfortunately they appear very slowly on the data. For a moment the frost off the application. How to accelerate?
Sorry for the bad english.

A: Make your method async:
public async Task GetData()

and await the server's response:
var users = await response.Content.ReadAsAsync<IEnumerable<Users>>();

(It's very rare that you actually ever want to call .Result directly.)
This will allow the application host to return control to the UI while awaiting the I/O operation in the background.


text:
Q: Files missing in /mnt/hgfs on Ubuntu VM? I am running Ubuntu 64-bit on VMWare workstation 10. I want to access the files on my windows 8 PC (both on same PC). I have checked "always enabled" for folder sharing on VMWare and gave path to my drives (E,F,G and a folder on my PC). Installed VM tools, they're upto date.
The first two worked fine for me. But for the third one - "Error: cannot mount filesystem: No such device" is being displayed. I am not able to find the shared files in /mnt/hgfs.
sudo apt-get install open-vm-tools
sudo mkdir /mnt/hgfs
sudo mount -t vmhgfs .host:/ /mnt/hgfs

Should I enable any permission access for my drives. For the sharing properties of the drives on W8, I enabled "Share this folder" option. Even then I cannot see shared folders in my hgfs (ubuntu). I am a new bee to linux OS, so please help.
Thanks,
Ramu.

A: I have a similar problem and I solved it with the procedure suggested here, as indicated in Jorge's comment:
$ git clone https://github.com/rasa/vmware-tools-patches.git
$ cd vmware-tools-patches
$ ./patched-open-vm-tools.sh

I hope this can help you.
Good luck!

A: There is a known incompatibility between the VMware tools and the kernel in 14.10 and later.  It is yet unpatched by VMware.
We have to use an alternative to VMware Tools, the open source variant, open-vm-tools.  This should be patched for the issue and shared folders should then work again.  First, remove the VMware tools.  Then, reboot the guest, and run sudo apt-get install open-vm-tools. Reboot again.  It should then have hgfs support again.


text:
Q: Moments of products of independent random variables: $E[X^mY^n]$ Part II This is a follow up question from here.
Let $X$ and $Y$ denote two real-valued bounded random variables. Then all joint moments exist and uniquely define their joint probability $P(X,Y)$.
Given for all $m,n\in\mathbb{N}\cup\{0\}$ we have $E[X^m Y^n]=a_m b_n$ with $a_m, b_n \in \mathbb{R}$. Does it follow that $X$ and $Y$ are independent random variables and, thus, $a_m=E[X^m]$, $b_n=E[Y^n]$ and $E[X^m Y^n]=E[X^m]E[Y^n]$?
If yes, is it a straight forward result?
Thanks for your comments / suggestions.

A: Assuming that the equation $EX^{m}Y^{n}=a_mb_n$ holds for all $n, m \geq 0$ and $a_0b_0=1$ the answer is YES. In this case $a_mb_0=EX^{m}$ and $b_na_0=EY^{n}$ so we get  $EX^{m}Y^{n}=EX^{m}EY^{n}$.
From the fact that the moments uniquely determine the joint distribution it follows that $X$ and $Y$ are independent. The reason is if $U$ and $V$ are independent with the same distributions as $X$ and $Y$ respectively then  $(U,V)$ and $(X,Y)$ have the same moments. The uniqueness of the  joint distribution now implies that $(U,V)$ has same distribution as $(X,Y)$ which implies that $X$ and $Y$ are independent.


text:
Q: What is a purpose of BJT in an LED driver circuit with MOSFET? I am trying to turn an LED on and off repeatedly with a square wave.
Yesterday, I've checked the following circuit works:

(Please note that, the figure has one voltage source Vdd. But I've connected a square wave source to the resistor Rg)
But, the most of LED driving circuits have a form of the following:

I am curious that what roll a BJT does in this circuit. From this article, it has something to do with a constant current source. Then, what is an advantage if there is a constant current source?

A: The npn Transistor is used to control the current flow through the LED. The resistor Rs can be chosen using the formula below:
ILED = 0.7 V / Rs
Note that this type of current limiter is far from perfect. You actually have to expect base voltages of 0.5...0.9 V, and they will vary greatly with temperature and depend on the exact type of transistor used. Consider this as a mere starting point for digging deeper into the subject of transistor current sources...
For more detail you can refer the below link
http://www.physics.unlv.edu/~bill/PHYS483/current_lim.pdf


text:
Q: 32/64 bit CGPoint Persistence in iOS across devices I've inherited some freehand drawing code which records a CGPathRef of points that are then converted to a collection of CGPoints which eventually get saved within our core data DB as NSData.
Current conversion code looks like this:
    @interface StoredPath : NSObject
    {
        CGPathRef path;
    }

@implementation StoredPath

            - (NSArray *)getPoints
            {
                // Convert path to an array
                NSMutableArray *a = [NSMutableArray arrayWithObject:[NSNumber numberWithBool:YES]];

                CGPathApply(path, (__bridge void *)(a), saveApplier);
                if (![[a objectAtIndex:0] boolValue])
                {
                    return nil;
                }

                [a removeObjectAtIndex:0];

                return (a);
            }

        static void saveApplier(void *info, const CGPathElement *element)
        {
            NSMutableArray *a = (__bridge NSMutableArray*) info;

            int nPoints;
            switch (element->type)
            {
                case kCGPathElementMoveToPoint:
                    nPoints = 1;
                    break;
                case kCGPathElementAddLineToPoint:
                    nPoints = 1;
                    break;
                case kCGPathElementAddQuadCurveToPoint:
                    nPoints = 2;
                    break;
                case kCGPathElementAddCurveToPoint:
                    nPoints = 3;
                    break;
                case kCGPathElementCloseSubpath:
                    nPoints = 0;
                    break;
                default:
                    [a replaceObjectAtIndex:0 withObject:[NSNumber numberWithBool:NO]];
                    return;
            }

            NSNumber *type = [NSNumber numberWithInt:element->type];

            NSData *points = [NSData dataWithBytes:element->points length:nPoints*sizeof(CGPoint)];

            [a addObject:[NSDictionary dictionaryWithObjectsAndKeys:type, @"type", points, @"points", nil]];
        }

@end

The important part to notice here is the line:
NSData *points = [NSData dataWithBytes:element->points length:nPoints*sizeof(CGPoint)];

It preserves the CGPoint data into a compact NSData object, which then gets saved in our core data DB.
This was fine when the app's data only lived on a single device.  But now that this data is synced to other devices, it breaks down due to CGFloat (makes up CGPoint struct) being 32bit or 64bit on various iOS devices.
When the 32bit NSData of CGPoints is read on a 64bit iOS device, the bytes don't quite align and the drawing gets mangled.  The same of course happens in vice-versa (64bit NSData of CGPoints is read on a 32bit iOS device).
I've been struggling to refactor this saveApplier: method in a way that is platform independent and can be easily saved in core data.
Update:
I'm considering packing the points into a "|" separated string.
example:  pointsToSave = {442, 797.5}|{442, 797.5}|{442, 797.5}
NSString *pointsToSave = [[NSString alloc] init];

// Convert CGPoint's to a "|" separated string.
for (int i=0; i<nPoints; i++)
{
    pointsToSave = [pointsToSave stringByAppendingString:NSStringFromCGPoint(element->points[i])];

    if ((i+1)<nPoints)
    {
        pointsToSave = [pointsToSave stringByAppendingString:@"|"];
    }
}

It makes it fairly simple to parse between platforms as well.
Thoughts?

A: You could pick either float or double as the data type to save with. This will explicitly set the size, since float is 32-bit and double is 64-bit.
For example, if you want more compactness, you could do this:
float *floats = [self pointsToFloats:element->points];
NSData *points = [NSData dataWithBytes:floats length:nPoints*sizeof(float)*2];

free(floats); // Note will need to free, since assuming pointsToFloats uses malloc. Use delete if you use new.

Where pointsToFloats would be defined something like:
- (float *)pointsToFloats:(CGPoint *)points; // Assuming this is straight-forward enough to implement

This also means you'll need something to unpack the data too.
- (CGPoint *)floatsToPoints:(float *)floats;

You can also use double if you need more precision.
There are of course others ways of doing this too.


text:
Q: How to remove added done button from numeric keyboard This is my code....
`
- ( void ) registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
}

    // Called when the UIKeyboardDidShowNotification is sent.
- ( void ) keyboardWasShown:(NSNotification*)notification {
    [self addButtonToKeyboard];
}

#pragma -
#pragma Numeric keyboard done button

- ( void ) keyboardDoneClicked:(id)sender {
    [txtvannum resignFirstResponder];
    [txtmobnum resignFirstResponder];
//    [sender resignFirstResponder];
}

- ( void ) addButtonToKeyboard {
        // create custom button
//    if(keyButton){
    doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
        [doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
        [doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
    } else {
        [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
        [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
    }
    [doneButton addTarget:self action:@selector(keyboardDoneClicked:) forControlEvents:UIControlEventTouchUpInside];
        // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
            // keyboard found, add the button
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
            if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                [keyboard addSubview:doneButton];
        } else {
            if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                [keyboard addSubview:doneButton];
            }
        }

//    }
////    else{
////        return;}

}

`
I developed an app which consist of user to enter their details.There are 4 text fields in that.Two among those requires numeric type of keyboard.For that numeric keyboard I added the done button to resign after finished editing.But that done button is coming for all other type of keyboard also.How can add that done button oly to numeric keyboard so that it should hide for all other type.I am struggling in this.Please help.
Thank you.

A: For each UITextField use the function setReturnKeyType: which can attain values,
typedef enum {
   UIReturnKeyDefault,
   UIReturnKeyGo,
   UIReturnKeyGoogle,
   UIReturnKeyJoin,
   UIReturnKeyNext,
   UIReturnKeyRoute,
   UIReturnKeySearch,
   UIReturnKeySend,
   UIReturnKeyYahoo,
   UIReturnKeyDone,
   UIReturnKeyEmergencyCall,
} UIReturnKeyType;

And you have to set the key type for each text field separately.For the text field that you don't want the done button just set it as UIReturnKeyDefault.
 Hope this helps.

A: First of all, you have to set a notification to keep tracking keyboard's activity. To identify, which UITextField is being active, you have to set an unique tag to each.
In .h file >>

@interface myViewController : UIViewController
{
    UITextField *txtField1; // Allows Numeric input
    UITextField *txtField2; // Allows String input
    UITextField *txtField3; // Allows Numeric input
    UITextField *txtField4; // Allows String input
    UITextField *txtFieldTemp; // Temp textfield

    BOOL isReturned;
}

In .m file >>

- (void)viewDidLoad
{
    txtField1.tag = 0;
    txtField2.tag = 1;
    txtField3.tag = 2;
    txtField4.tag = 3;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UIKeyboardWillChangeFrameNotification:) name:UIKeyboardDidShowNotification object:nil];
}

- (void)UIKeyboardWillChangeFrameNotification:(NSNotification *)note
{
    if (txtFieldTemp.tag == 0 || txtFieldTemp.tag == 2)
    {
        [self addButtonToKeyboard];
    }
}

-(void) textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag == 0 || textField.tag == 2)
    {
        [self addButtonToKeyboard];
    }
    else
    {
        [self removeButtonFromKeyboard];
    }
    txtFieldTemp = textField;
}

- (void)removeButtonFromKeyboard
{
   // Remove Keyboard logic
}


text:
Q: optimize angular filter performance I am filtering a fairly small dataset but there is still some performance issues (UI thread freezing when filter is not concise).
    <input type="text" ng-model="vm.user" />
    <table class="tbl" ng-show="vm.user.length > 2">
        <tbody ng-repeat="p in vm.permissions | filter: {UserName: vm.user}:false">

the issue is only when there are a lot of records, so I've attempted to improve performance by hiding the whole thing when there are less than 3 characters entered in search.
unfortunately, even when the data-set is hidden it appears that angular is manipulating the dom (UI freezing as I type into the filter).
Is there a way to make it not do anything when there are less characters, and/or improve performance in other ways?

A: I would make 3 suggestions to improve performance:

*

*As New Dev said, use ng-if instead of ng-show to remove the whole node from the DOM, which will mean that no processing of directives on the removed nodes will occur at all. I tend to prefer ng-if in 99% of scenarios now, unless I know that the visibility of the option will toggle a lot and therefore modifying the class of an existing node is quicker than inserting and removing the same node over and over again.

*Use a track by in your ng-repeat expression. This means that Angular will re-use DOM nodes for items in the array that have the same matching value. e.g. if you have track by p.UserName (so long as UserName is 100% unique), if it encounters a record with the same username, it will use the same DOM node as before, rather than recreating a new one.

*Use ng-model-options to have a debounce on the filter input so that if a user is typing fast, not every keystroke will trigger a new filtering operation. You may need to experiment to find the correct timeout value that works for you in your target browsers.

I have created an example Plunkr that shows these techniques in action. When I tried it with 100,000 records in the list of "permissions" (really just dummy users in the example), it was still very fast in Chrome. Didn't test in other browsers, though.


text:
Q: Using Qt threads and passing large objects between threads. Am I just doing it wrong? I'm used to using boost_threads and hooking things together using thread safe queues and function calls that I roll myself.  However,  the signal and slots idiom of Qt seems really helpful for some things but not others.  For example,  for named pipes, it seems great for doing asynchronous communication that way.
That is until I have to pass the object I received over the named pipe to be translated and then send it off to another thread to translate the data and send it out.
The biggest issue I have is sending these messages back and forth through the
signals and slots mechanism or perhaps using QMetaObject::invokeMethod().  It seems like this would get sent out using a Queued connection and if I understand correctly it copies the object being passed instead of passing it by reference or pointer.
This seems like it can get really inefficient if a lot of this is going to happen.  In my case it will be.  Is there a different way I should be approaching this issue?
Is there a way to just insert an object into a queue by reference or pointer in a different thread?

A: If you're passing between processes then you have to copy the data (ie marshal it across the process boundaries) or put it some where common that both processes can access. You can usually do the latter with shared memory, being careful about ownership.

A: It looks like pointers can be passed to escape the copying that goes with passing by value.  I also found out that using boost::shared_ptr is recommended so that it will delete itself.  I hope this helps someone else.


text:
Q: Error When Activating Unyson Plugin in Wordpress Fatal Error does anyone know why when i activate unyson an error message appears like this
The plugin could not be activated because it triggered a fatal error.

Parse error: syntax error, unexpected ')' in /home/u4437453/public_html/bssys/wp-content/plugins/unyson/framework/core/components/backend.php on line 1111

I'm confused, where is the problem?
anyone can help me

A: Looks like there is a syntax error in the plug-in code.
I would contact the developer of the plug-in to ask for help. You can usually find information about how to report bugs and contact the developer on the plug-in's details page.


text:
Q: how to chinese character add md5 function before chinese Hi all I want add md5 to chinese character, but not working
ex: 你好,我是Jack!
to: df1fd9101108b40d26977a8d0bb9fd1e-你, ac2c8f13c6e60810197b19d683f5f184-好, 16815254531798dc21ee979d1d9c6675-我, 0a60ac8f02ccd2cf723f927284877851-是, Jack!
My code:
$data = "你好,我是Jack!";

$data = preg_replace('/(\p{Han}+)/u',md5('$1')-$1,$data);

echo $data;

A: Use preg_replace_callback().
$data = "你好,我是Jack!";

$data2 = preg_replace_callback(
  '/(\p{Han})/u',
   function($matches){return md5($matches[1])."-".$matches[1];},
  $data
);


text:
Q: Vim doesn't allow me to type in numbers I'm having difficulty using Vim. When I attempt to type in numbers it just adds a character about what I'm trying to type.

Here, I've pressed "2" and it moves up and adds an r. Number "1" adds q and moves up a line as well. I've been googling for solutions and am kind of lost at this point. Insert mode is enabled, as shown at the bottom.
Additionally, I've tried enabling and disabling number lock and using the number pad as well.
Number lock off -> number pad only responds with Home, End, Pg Up, Pg Dn.
Number lock on -> number pad responds the same as above.
I've tried hitting control, mac key, and alt in the hopes that one of them were toggled, but I still get the same issue after hitting them once.
Note: Using VNC Viewer to connect.
Inputs are set to enabled and to pass media keys and special keys directly to VNC server.

A: You can find some help (though not straightforward) here in wikia :
http://vim.wikia.com/wiki/PuTTY_numeric_keypad_mappings
at the bottom of the article, there is some comments related to VNC.
Hope it helps.

A: Do not use the numbers on the right hand side of the keyboard, instead use the ones above the letters.


text:
Q: DE : $\frac{\mathrm d^2(F)}{\mathrm dx^2} -S^2 \cdot (F) = K \cdot e^{-ax}$ I have this ODE that I need to solve and I am not sure where to begin:
$$\frac{d^2(F)}{dx^2} -S^2 \cdot (F) = K \cdot e^{-ax}$$
Does anyone know any techniques that I could use?

A: Hints:

*

*For the homogeneous, we have:

$$m^2 - s^2 = 0 \rightarrow m_{1,2} = \pm ~ s$$
This gives:
$$F_h(x) = c_1e^{-sx} + c_2 e^{sx}$$

*

*For the particular, using Undetermined Coefficients, we can choose:

$$F_p = w e^{-a x}$$
Substitute into the ODE and solve for $w$.


text:
Q: Cortex-M4 custom HardFault_Handler I'm in the process of writing a custom HardFault_Handler for the Cortex M4 -- but for an unknown reason, I am unable to step though any instructions in the handler.
When I break with gdb, I am stuck at the first instruction of the handler. n does not proceed to the next instruction, gdb just starts spinning again until I break. OpenOCD shows that I am hitting halting repeatedly, but it doesn't appear that any of the code in my exception handler is being executed... but every time I break, I am in the exception handler.
...
Info : halted: PC: 0x08000240
Info : halted: PC: 0x08000240
Info : halted: PC: 0x08000240
Info : halted: PC: 0x08000240
...

I know that if I break at main, I can step through the code (in C) up until the point I generate the exception and catch it in my custom handler. However, stepping through the instructions in the handler just puts be at the beginning of the handler.
Here's my handler:
.syntax unified
.thumb
.global HardFault_Handler

  .section  .text.HardFault_Handler,"ax",%progbits
HardFault_Handler:
  .size  HardFault_Handler, .-HardFault_Handler

Infinite_Loop:
  mov r0, #0x1
  mov r1, #0x2
  mov r2, #0x3
  b  Infinite_Loop

A: .thumb needs to be replaced by .thumb_func.
This directive ensures that the function pointer is a valid for the thumb mode. Thumb mode instructions have odd addresses, while arm mode instructions have even addresses. The directive will add 1 to the address of the function pointer (i.e. exception vector pointer).
Without this directive, the address of the pointer will be in arm mode (even address), which itself causes an exception. In other words, my exception was being preempted with an exception.
Add .thumb_func to explicitly identify this symbol as a thumb-mode function so the linker can do the right thing.
.syntax unified
.thumb_func
.global HardFault_Handler

  .section  .text.HardFault_Handler,"ax",%progbits
HardFault_Handler:
  .size  HardFault_Handler, .-HardFault_Handler

Infinite_Loop:
  mov r0, #0x1
  mov r1, #0x2
  mov r2, #0x3
  b  Infinite_Loop