Q:

Why do we still need generated code?

I have seen alot of frameworks that generate stub applications, like Ruby on Rails for example, where most of the code is used for business domain logic, but why do we have generated code still. Wouldn't a library be better?

A:

There are both justified and unjustified cases of code generation. However proper code generation can result to the following benefits:

Optimal runtime code -- libraries process stuff during runtime, whereas you can eliminate a lot of runtime machinery by analyzing the codes structure during generation.
The elimination of bugs introduced doing repetitive work.
Better understanding of your code, generation generally leads to higher level "model"; where the model is used to represents what needs to be generated.
Reduction in LOC -- thousands of lines can leads to millions of lines of output code.

A:

A library will consist of common functions or classes that may be used as is in many applications. These frameworks do include libraries of code.
The generated code takes care of the scaffolding that you will need to write yourself regardless. Since most of it is pretty standard, it can be generated and the intention is you modify the pieces that you wish to.


Q:

Qgis2threejs "disk object"

First of all, I'm completely new to qgis2threejs.
During a field trip I've measured strike/dip for some cracks in the bedrock and mapped the positions, and now I'm trying to show the results as a disk with the strike and dip for each point.
My data looks something like this (added as a delimited layer):
Point, Strike, Dip, Point, Easting, Northing, Height
1, 220, 30 NE, 1, 392430, 7302787, 9.2
...
...
When selecting "Object Type: Disk" for the point layer I can apparently choose the column with the "Dip" and "Dip direction", but there is only 4 possibilities: Fixed value, "Easting", "Northing", "Height"
Is something wrong with my data format? How do I get to choose the "Dip"-column for the dip?

A:

Your Dip column is not a number. Remove the 'NE' and other text from the data and it should appear as a selectable column.


Q:

Symmetric groups

Find $\sigma$ in $S_5$ that fulfills:
$$\sigma(12)(34)=\sigma^{-1}(13)(45)$$
Can anyone help with that? i've tried to multiply by $\sigma^{-1}$ from the right side but it doesn't seem to lead anywhere

A:

You need $\sigma^2=(13)(45)(12)(34)=(12354)$
Clearly $\sigma$ must be a $5$-cycle also, so we get $\sigma=\sigma^6=(12354)^3=(15243)$


Q:

Does Release call on an Interface ensure that the COM Component is distroyed

i am working on a issue where i see an intermittent crashes happening at the customer site, while code review, i found that we have written that some code in the destructor to free memory etc.  but my question is when does this destruct-or gets called.
does it get called when the client call's Release on the interface. or how do we free resources consumed by an interface or when are we supposed to free those resources.
i know when the call to Relase returns "0" the COM calls the DllcanGetUnloadNow and it the dll is unloaded , what about freeing memory?
can anyone clarify
regards
tom

A:

Typically the implementing object's destructor is called from Release if the reference count has reached zero. That is something that is performed by the implementing object's implementation of Release.
So, a typical implementation of Release looks like this:
IFACEMETHODIMP_(ULONG) Release()
{
    ULONG cRef = InterlockedDecrement(&_cRef);

    if (!cRef)
        delete this;
    return cRef;
}


Q:

onTouchListener on FrameLayout: close it when clicked outside

I'm finding difficult to implement a probably simply feature.
I've a FrameLayout containing a dropdown menu (like the one in WhatsApp, popping up when you click on the Attachment icon).
I want to close it when I click outside of said FrameLayout.
I'm trying to implement it using an onTouch event, with no luck.

My code:
public class MainActivity extends AppCompatActivity {

private LinearLayout mRevealView;
private FrameLayout mRevealFrame;

...

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    mRevealView = (LinearLayout) findViewById(R.id.rows);
    mRevealFrame = (FrameLayout) findViewById(R.id.reveal_frame);

    ...

}

// This method is called when I click on the right menu icon.
public void fuelTypes() {
    // Looking for X and Y coordinates.
    int cx = (mRevealView.getLeft() + mRevealView.getRight());
    int cy = (mRevealView.getTop());

    // Looking for radius when icon is tapped for showing layout.
    int startRadius = 0;
    int endRadius = Math.max(mRevealView.getWidth(), mRevealView.getHeight());

    // Performing circular reveal when icon will be tapped.
    Animator animator = ViewAnimationUtils.createCircularReveal(mRevealView, cx, cy, startRadius, endRadius);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setDuration(400);

    // Reverse animation to find radius when icon is tapped again for hiding layout.
    // The starting radius will be the radius or the extent to which circular reveal animation is to be shown.
    int reverseStartRadius = Math.max(mRevealView.getWidth(), mRevealView.getHeight());

    // End - radius will be zero.
    int reverseEndRadius = 0;

    // Performing circular reveal for reverse animation.
    Animator animate = ViewAnimationUtils.createCircularReveal(mRevealView, cx, cy, reverseStartRadius, reverseEndRadius);

    if (hidden) {
        // To show the layout when the icon is tapped.
        mRevealView.setVisibility(View.VISIBLE);
        mRevealFrame.setVisibility(View.VISIBLE);
        animator.start();
        hidden = false;
    } else {
        mRevealView.setVisibility(View.VISIBLE);
        mRevealFrame.setVisibility(View.VISIBLE);

        // To hide layout on animation end.
        animate.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mRevealView.setVisibility(View.INVISIBLE);
                mRevealFrame.setVisibility(View.INVISIBLE);
                hidden = true;
            }

        });

        animate.start();
    }

    mRevealFrame.setOnTouchListener(new FrameLayout.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            Log.d("MOTION_EVENT", "getAction(): " + motionEvent.getAction());

            switch (motionEvent.getAction()) {

                case MotionEvent.ACTION_UP:
                    Log.d("REVEAL_FRAME", "motion event: " + "ACTION_UP");
                    fuelTypes();
                    return true;

            }

            return true;
        }
    });

}

The first Log.d() is working, showing that the listener is triggered.
Still, the method is not going inside the switch: I've already tried a lot of flags, with no luck.
I've read about onInterceptTouchEvent and onTouchEvent, but I don't know how to use them instead of the OnTouchListener.
Thank you for any help.

A:

Your layout :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_layout"       // give id here
tools:context="com.myfuel.MainActivity">

<include layout="@layout/activity_main"/>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/reveal_frame"
    android:layout_marginTop="?attr/actionBarSize">

    // EVERYTHING INSIDE THIS WILL BE AS IT IS

</FrameLayout>

</FrameLayout>

Your Activity
public class MainActivity extends AppCompatActivity {

private LinearLayout mRevealView;
private FrameLayout mRevealFrame;
private FrameLayout mMainLayout;
...

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    mRevealView = (LinearLayout) findViewById(R.id.rows);
    mRevealFrame = (FrameLayout) findViewById(R.id.reveal_frame);
    mMainLayout = (FrameLayout) findViewById(R.id.main_layout);

    mMainLayout.setOnTouchListener(new FrameLayout.OnTouchListener()
    {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            Log.d("MOTION_EVENT", "getAction(): " + motionEvent.getAction());

                    //Things changed here

                    if(!hidden)
                       fuelTypes();

            return false;
        }
    });
    ...

}

As your mRevealFrame does not define the whole FrameLayout of your activity we can not use that for closing mRevealView. See i have defined mMainLayout which covers the WHOLE layout it will work now.
Try it and let me know if there is still a problem.


Q:

C++ unordered map error

I'm trying to declare an unordered map into my program in which I will map them to tokens in another file.
I need a method which returns the Token type found in Token.h (which is an enum class)
What is confusing me is that, since I want to return the mapped Tokens from the unordered_map to the enum class, what should be the return type of the method? Also, it is stating that
error: 'unordered_map' does not name a type
I am rather new to C++ and am still finding it a bit hard in this case how I should declare methods. I've read that the unordered map should be declared INSIDE a method, but since I want the value returned by the map, which should be the return type?

I tried this
 Test 1
Token Lexer::getTokenType()
{
   unordered_map<string,Token> tokenType;

}

This outputs these errors:

 Test 2  I tried this
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <wctype.h>
#include <map>

#include "lexer.h"

using namespace std;

long Row, Col, Offset;

unordered_map<string, Token> ProtectedWords
{

}

OR
unordered_map<string, Token>::Lexer::getTokenType()
{
}

still yielded the same
Its error:
I know these do sound stupid, but would you mind explain to me please? As in the tutorial I followed many are, yes, called inside a method, but even that did not work

A:

You need to include <unordered_map>.
You'll also need to enable C++11 support, if you haven't already done so: for GCC, make sure the compiler arguments include -std=c++11 (or c++0x if you're using an old compiler).


Q:

Devise/OmniAuth/Twitter - OAuth::Unauthorized (401)

I'm trying to set up a Twitter login using Devise/OmniAuth, following the latest RailsCast for this.  I've registered the Twitter developer app, using the callback url of: myiphere:port/users/auth/twitter.
I've followed everything to the T on the RailsCast, but each time I click the Sign In With Twitter link, I immediately get OAuth::Unauthorized 401 Unauthorized on the myiphere:port/users/auth/twitter page.
I think I've defined the key correctly using export TWITTER_CONSUMER_KEY=MYKEYINSERTEDHERE export TWITTWR_CONSUMER_SECRET=MYSECRETINSERTEDHERE rails server.  I've tried most every solution I can find on the internet, all to no avail.  Almost all of the answers are for returning back to their site once logged in, I can't get to any kind of Twitter screen, just the 401 error on the /users/auth/twitter page.

A:

I had this same issue; in my case, I had the API keys set up correctly, but had not set a callback URL in the Twitter setup at https://dev.twitter.com/apps/, under the "Settings" tab.
Oddly, it doesn't appear that the callback URL needs to point anywhere useful; Twitter apparently just uses its existence as a signal of some sort.
The debugging information provided by omniauth-twitter leaves something to be desired.

A:

I got it to work by removing the brackets and ENV from the initializer DEVISE.RB:
config.omniauth :twitter, "APP_ID", "APP_SECRET"

my callback specified in DEV Twitter settings:
http://www.mysite.com/users/auth/twitter/callback

In routes.rb
devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}

My LogIn link:
<%= link_to "Log in with Twitter", user_omniauth_authorize_path(:twitter) %>


Q:

proxmox KVM routed network with multiple public IPs

I have a dedicated hosting with hetzner.
Additionally i have bought a 6IP subnet.
My main IP is: 148.111.111.200
My main subnet is: 255.255.255.224
My additional IPs are 148.222.222.1 to 148.222.222.6.
My usage scenario is as follows:
Several instances will have public facing IPs (webservers, etc)
All instances will have a second nic setup for internal LAN, so I can have mysql server, memcached, etc on private network locked from outside.
Webserver will be online on 148.222.222.1 and will have a second NIC with ip 10.10.10.10
Currently, i have setup the internal lan. All the instances can connect and ping one another via internal IP (10.10.10.X), but my webserver cannot reach the internet.
I cannot use bridged mode, since hetzner does not allow multiple MACs on same external ip, so I have to use routing mode.
Here is my /etc/network/interfaces file for the host:
# network interface settings
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static

    address  148.111.111.200
    netmask  255.255.255.255
    pointopoint 148.111.111.193
    gateway  148.111.111.193
    broadcast  148.111.111.223
    post-up echo 1 > /proc/sys/net/ipv4/conf/eth0/proxy_arp
#commentedout
    #up route add -net 148.111.111.192 netmask 255.255.255.224 gw 148.111.111.193 eth0

    # default route to access subnet

auto vmbr0
iface vmbr0 inet static

    address  148.111.111.200
    netmask  255.255.255.255
    bridge_ports none
    bridge_stp off
    bridge_fd 0

    up ip route add 148.222.222.1/32 dev vmbr0
    up ip route add 148.222.222.2/32 dev vmbr0

auto vmbr1
iface vmbr1 inet static

    address 10.10.10.1
    netmask 255.255.255.0
    bridge_ports none
    bridge_stp off
    bridge_fd 0

    post-up echo 1 > /proc/sys/net/ipv4/ip_forward
    post-up   iptables -t nat -A POSTROUTING -s '10.10.10.0/24' -o eth0 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s '10.10.10.0/24' -o eth0 -j MASQUERADE

auto vmbr2
iface vmbr2 inet static

    address  148.222.222.1
    netmask  255.255.255.248
    bridge_ports none
    bridge_stp off
    bridge_fd 0

And here is my kvm interfaces file:
auto eth0
iface eth0 inet static
    address 148.222.222.1
    netmask 255.255.255.255
    pointopoint 148.111.111.200
    gateway 148.111.111.200
    dns-nameservers 8.8.8.8 8.8.4.4

auto eth1
    address 10.10.10.12
    netmask 255.255.255.0
    network 10.10.10.0
    broadcast 10.10.10.255

Currently, KVM instances can ping oneanother, but nothing else works
Host can ping instances, but nothing else
And i cannot get internet access on my instances.
What do I need to change in my configuration in order for this to work.
P.S. NIC type is set to virtio in proxmox

A:

I solved the problem by using the following config:
auto eth0
iface eth0 inet static
    address  148.111.111.200
    netmask  255.255.255.255
    pointopoint 148.111.111.193
    gateway  148.111.111.193
    broadcast  148.111.111.193

# default route to access subnet

auto vmbr0
iface vmbr0 inet static
    address  148.111.111.200
    netmask  255.255.255.255
    bridge_ports none
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

    #subnet
    up ip route add 148.222.222.0/32 dev vmbr0
    up ip route add 148.222.222.1/32 dev vmbr0
    up ip route add 148.222.222.2/32 dev vmbr0
    up ip route add 148.222.222.3/32 dev vmbr0
    up ip route add 148.222.222.4/32 dev vmbr0
    up ip route add 148.222.222.5/32 dev vmbr0
    up ip route add 148.222.222.6/32 dev vmbr0
    up ip route add 148.222.222.7/32 dev vmbr0

auto vmbr1
iface vmbr1 inet static
    address 10.10.10.1
    netmask 255.255.255.0
    bridge_ports none
    bridge_stp off
    bridge_fd 0

    post-up echo 1 > /proc/sys/net/ipv4/ip_forward
    post-up   iptables -t nat -A POSTROUTING -s '10.10.10.0/24' -o eth0 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s '10.10.10.0/24' -o eth0 -j MASQUERADE

On your client machines you need to define one ore two network interfaces

One for VMBR0 (public facing IP)
One for VMBR1 (private IP - 10.10.10.X)

Sample config for ubuntu
/etc/network/interfaces
#vmbr0
auto eth0
iface eth0 inet static
  address 148.222.222.1
  netmask 255.255.255.255
  pointopoint 148.111.111.200
  gateway 148.111.111.200 #public IP for the proxmox node
  dns-nameservers 8.8.8.8 8.8.4.4

#vmbr1
auto eth1
iface eth1 inet static
  address 10.10.10.20
  netmask 255.255.255.0
  network 10.10.10.0
  broadcast 10.10.10.255


Q:

What kinds of effects can modify a die roll?

After you roll a d20, there are some effects that can modify the result before the calculation is made. Is this a complete list?

If you don't like the roll (before you know success or failure), throw it away and roll it again
If you don't like the roll (after you know the result), throw it away and roll it again
Roll it again and take the better result (oath of enmity)
Roll it again and take the worse result (various curses)
replace a die roll with one you rolled before (dice of auspicious fortune)
add a number to the die roll (heroic effort, adept's insight)

And I think these only apply to a damage roll:

Brutal

if it's N or below, re-roll until it's N+1 or above

if it's N or below, throw away the old roll and re-roll once, taking the result no matter what
if it's N or below, change to N+1
if it's the maximum value, roll again once and take the sum
if it's the maximum value, roll again, take the sum, and repeat if it's maximum value (vorpal/explosive)

A:

Don't know if you count these into one or more of your bullet points, but...

Add another die roll to the die roll (Memory of a Thousand Lifetimes[DDI]).
Replace the die roll with a fixed number (Climatic Crescendo[DDI], if you consider the critical hit a natural 20, which could be a bit over-reading it).


Q:

Best (safest) way to store database credentials for AJAX

In the past I have stored database credentials (username, password) in another file (outside of the web directory) and included this in a PHP page to make connections with the database.  Since I have started doing a lot of database interaction via AJAX, I have to change how I do this, since the AJAX script cannot include a script outside the web directory.
In order to deal with AJAX database connections, I need a good secure way to get the username and password data to the AJAX script.  What is the best (secure and handy) way to do this?  If i simply put my database credentials file in the web directory, what permissions to give it?  Is this a good/bad idea?
Thanks a lot!
** EDIT **
Apparently there is not problem including files outside of web root directory, I was mistaken.  Thanks very much, this probably changes things for me... :-/
** EDIT 2 **
Indeed that changed everything for me, I was able to include the database config file which i was using in all the pages (which resided outside the web root), so this is great!

A:

if you are not opposed to changing things up a little bit, I think you should use your backend to interface with the database, and just use your ajax to hit those interfaces to the DB. that way you dont have to ever "Store db creds" client side
OR if you absolutely must save client side, you should figure out a way to reduce your access to a hashed / salted key that you save in a session cookie or something


Q:

Not able to fetch location using GPS

I'm trying to make a simple app to show my location coordinates. When I emulate the code ( nexus 6.0 , it works). However, when I use a real device via usb debugging (my htc 10), nothing appears when I press the button to show my coordinates. Any idea why? This is my code:
    //Location
    textView = (TextView) findViewById(R.id.textView);
    button2 = (Button) findViewById(R.id.button2);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
            System.out.println(location.getLongitude());
            System.out.println(location.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
    };

    configure_button();

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case 10:
            configure_button();
            break;
        default:
            break;
    }
}

void configure_button() {
    // first check for permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
                    , 10);
        }
        return;
    }
    // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    });
}

I have this added in my manifest:
  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />

A:

You should declare the button2 click listener in oncreate as there is return statement in configure_button() method.
Just declare it right after declaring ids.
  textView = (TextView) findViewById(R.id.textView);
    button2 = (Button) findViewById(R.id.button2);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    });
   //rest of the code


Q:

Predicting from inferred parameters in pymc3

I am trying to understand this from a non-Bayesian background.
In linear regression or blackbox machine learning tools the work flow is something like the following.

Get data
Prepare data
Model data (learn from it [or part of it, the training set])
Test model (usually on the test set)
If model is good according to some metric, goto 6, else
investigate and revise work.
Model is good enough; use it to predict/classify, etc.

So let's say I use pymc3 to try to understand the relationship between advertising expenditure and revenue from goods sold. If all stages from 1 to 5 go well, then in frequentest statistics used in R and machine learning packages such as scikit-learn, I only need to pass new unseen data to the learned model and invoke the predict method. This will usually print out a predicted value of Y (revenue from goods sold), given some unseen value(s) of X (advertising expenditure), with some confidence intervals or some other margin of error still being taken into account.
How would one go about doing that in pymc3? If I end up with many slopes and many betas then which should I use for predicting? And wouldn't taking the mean of all slopes and all betas to use be like throwing away a lot of otherwise useful learned knowledge?
I find if difficult to understand how sampling from the posterior can help in this. One can imagine bosses who need to be told about an expected revenue from goods sold Y figure given some advertising expenditure X amount, with some confidence and error margins. Aside from plotting, I don't know how sampling from posterior can be incorporated into a management report and make it useful for cash flow planning by interested parties.
I know some of us are spoiled coming from R and maybe scikit-learn, but wouldn't it be nice if there was a predict method that dealt with this matter in a more uniform and standardized way?
Thanks

A:

One way of taking into account the uncertainty in parameters when making predictions with a model is to use the posterior predictive distribution. This distribution tells you the probability of a new observation, conditioned on the data that you used to constrain the model parameters. If the revenue is Y, the advertising expenditure is X, the model parameters are theta and the data used to constrain the model are X', then you can write

The left hand side is the probability of attaining revenue Y given an expenditure X, and the data used to constrain the model X'. This is the posterior predictive distribution of your model, and should be used when making predictions. p(Y | X, theta) is the probability of revenue Y given some set of model parameters theta and the expenditure X. p(theta | X') is the posterior distribution on the model parameters given the data that you used to constrain the model.
When using software like pymc3, you obtain samples from p(theta | X'). You can use these to do the integral above in a Monte-Carlo fashion. If you have N samples from the posterior in your MCMC chain, then you can do the sum

in other words, you compute p(Y | X, theta_n) for every set of parameters in your MCMC, and then take the average (note that this isnt the same as `taking the mean of all slopes and all betas' as you mentioned in your question, because you are computing the average of a pdf rather than the parameters themselves). In practice this should be easy to code, you just need to implement the function p(Y | X, theta) and then plug in your posterior parameter samples, then take the mean at the end. This gives you the fairest representation of your model prediction given your MCMC sampling.


Q:

ControllerAdvice for Kotlin

I want to create ControllerAdvice for validation exception and I'm using Webflux, Kotlin and jackson-module-kotlin.
I've tried to do it with traditional code as following :
  @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleValidationExceptions(
            ex: MethodArgumentNotValidException): Map<String, String?>? {
        val errors: MutableMap<String, String?> = HashMap()
        ex.bindingResult.allErrors.forEach(Consumer { error: ObjectError ->
            val fieldName = (error as FieldError).field
            val errorMessage = error.getDefaultMessage()
            errors[fieldName] = errorMessage
        })
        return errors
    }

but it doesn't work properly and the default response is :
{
    "timestamp": "2020-07-25T10:19:00.023+00:00",
    "path": "/boarding/subscribeUserWithSoloWorkspace",
    "status": 400,
    "error": "Bad Request",
    "message": "Failed to read HTTP message",
    "requestId": "62f1e90a-1",
    "trace": "org.springframework.core.codec.DecodingException: JSON decoding error: Instantiation of [simple type, class co.ashiyane.flare.domains.User] value failed for JSON property mobileNumber due to missing (therefore NULL) value for creator parameter mobileNumber which is a non-nullable type; nested exception is com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class co.ashiyane.flare.domains.User] value failed for JSON property mobileNumber due to missing (therefore NULL) value for creator parameter mobileNumber which is a non-nullable type\n at [Source: (io.netty.buffer.ByteBufInputStream); line: 4, column: 5] (through reference chain: co.ashiyane.flare.domains.supdomains.UserAndWorkspace[\"user\"]->co.ashiyane.flare.domains.User[\"mobileNumber\"])\n\tat org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:215)\n\tat org.springframework.http.codec.json.AbstractJackson2Decoder.decode(AbstractJackson2Decoder.java:173)\n\tat org.springframework.http.codec.json.AbstractJackson2Decoder.lambda$decodeToMono$1(AbstractJackson2Decoder.java:159)\n\tat reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:118)\n\tat reactor.core.publisher.FluxContextStart$ContextStartSubscriber.onNext(FluxContextStart.java:96)\n\tat reactor.core.publisher.FluxMapFuseable$MapFuseableConditionalSubscriber.onNext(FluxMapFuseable.java:287)\n\tat reactor.core.publisher.FluxFilterFuseable$FilterFuseableConditionalSubscriber.onNext(FluxFilterFuseable.java:330)\n\tat reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)\n\tat reactor.core.publisher.MonoCollect$CollectSubscriber.onComplete(MonoCollect.java:152)\n\tat reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:136)\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.onComplete(FluxPeek.java:252)\n\tat reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:136)\n\tat reactor.netty.channel.FluxReceive.terminateReceiver(FluxReceive.java:427)\n\tat reactor.netty.channel.FluxReceive.drainReceiver(FluxReceive.java:210)\n\tat reactor.netty.channel.FluxReceive.request(FluxReceive.java:121)\n\tat reactor.core.publisher.FluxMap$MapSubscriber.request(FluxMap.java:155)\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.request(FluxPeek.java:130)\n\tat reactor.core.publisher.FluxMap$MapSubscriber.request(FluxMap.java:155)\n\tat reactor.core.publisher.MonoCollect$CollectSubscriber.onSubscribe(MonoCollect.java:112)\n\tat reactor.core.publisher.FluxMap$MapSubscriber.onSubscribe(FluxMap.java:86)\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.onSubscribe(FluxPeek.java:163)\n\tat reactor.core.publisher.FluxMap$MapSubscriber.onSubscribe(FluxMap.java:86)\n\tat reactor.netty.channel.FluxReceive.startReceiver(FluxReceive.java:300)\n\tat reactor.netty.channel.FluxReceive.lambda$subscribe$2(FluxReceive.java:138)\n\tat io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)\n\tat io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)\n\tat io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:384)\n\tat io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\n\tat io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\n\tat io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\n\tat java.base/java.lang.Thread.run(Thread.java:832)\nCaused by: com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class co.ashiyane.flare.domains.User] value failed for JSON property mobileNumber due to missing (therefore NULL) value for creator parameter mobileNumber which is a non-nullable type\n at [Source: (io.netty.buffer.ByteBufInputStream); line: 4, column: 5] (through reference chain: co.ashiyane.flare.domains.supdomains.UserAndWorkspace[\"user\"]->co.ashiyane.flare.domains.User[\"mobileNumber\"])\n\tat com.fasterxml.jackson.module.kotlin.KotlinValueInstantiator.createFromObjectWith(KotlinValueInstantiator.kt:112)\n\tat com.fasterxml.jackson.databind.deser.impl.PropertyBasedCreator.build(PropertyBasedCreator.java:202)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:490)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1310)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:331)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164)\n\tat com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:542)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:535)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:419)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1310)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:331)\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164)\n\tat com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:2057)\n\tat com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1431)\n\tat org.springframework.http.codec.json.AbstractJackson2Decoder.decode(AbstractJackson2Decoder.java:168)\n\t... 29 more\n"
}

In the message, there are some other exceptions like DecodingException and MissingKotlinParameterException, but I could't handle them too!

A:

I've resolved this issue with following ControllerAdvice:
    @ExceptionHandler(value = [ServerWebInputException::class])
    @ResponseBody
    fun onException(exception: ServerWebInputException): Mono<ResponseEntity<ClientAcknowledgement>> {
        val parameterName = (exception.rootCause as MissingKotlinParameterException).parameter.name // id
        val parameterType = (exception.rootCause as MissingKotlinParameterException).parameter.type // ObjectId
        val fieldName = (exception.rootCause as MissingKotlinParameterException).path[0].fieldName // in User part
        return Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ClientAcknowledgement("there is a missing parameter in your request, check your request body." +
                        " detail : missing $parameterName ($parameterType) type in $fieldName")))
    }


Q:

tsql user-defined functions

Is it possible to call a user-defined function in TSQL without the scoping qualifier. I want to call
select myfunc(var)

and not
select dbo.myfunc(var)
select myschema.myfunc(var)

It's possible in every other DB that I've ever worked with (7 others) it has to be possible in tsql too.
If I'm signed into my DB/schema I don't have to qualify a table reference... i can do
select * from mytable

without the qualifier... why aren't function calls orthogonal to this?

A:

From Executing User-Defined Functions (Database Engine) on MSDN:

...Scalar-valued functions must be
  invoked by using at least the two-part
  name of the function...

The writing between the lines here is that the schema name is not required for table-valued UDFs, but I have not personally tested this.


Q:

Conservation of energy in a multiverse

When I was studying about classical mechanics, I learned about Hamiltonian mechanics. In a example problem, we saw that in a system of just one capacitor, energy seemed to flow in and out and the conservation of energy law was violated. This was because in the example, the entire electrical circuit was not taken into account, which flowed energy in and out of the capacitor system. Therefore, I thought, if the universe was part of a multiverse, wouldn't a similar situation happen? Wouldn't the conservation of energy law not apply in our universe?

A:

In most multiverse theories the worlds are effectively separated. Also, our particular world seems to be one that may well have a total mass/energy of zero.


Q:

matrix product with numpy.dot()

I am trying to calculate the product:
tA*M*B
where A, B are two vectors and M is a squared matrix, tA is the transposed A. The result should be a number.
Numpy has the dot() function that multiplies arrays and matrix: is there a way I can use it to calculate my product in a single blow?
I am using python 2.6

A:

How about:
import numpy

#Generate Random Data
M = numpy.random.normal(0,1,9).reshape(3,3)
A = numpy.random.normal(0,1,3)
B = numpy.random.normal(0,1,3)

#The Operation
numpy.dot(A, numpy.dot(M,B) )


Q:

How can I speed up a web-application? (Avoid rebuilding a structure.)

After having successfully build a static data structure (see here), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out), this turns out to be too time-consuming, as the file is rather large.
Any ideas how I can easily speed up this thing? Splitting the file into multiple files? Or a program running on the server? (How difficult is this to implement?)
Thanks for your help!

A:

You can dump it in a memory cache (such as memcached).
This method has the advantage of cache key invalidation. When underlying data changes you can invalidate your cached data.
EDIT
Here's the python implementation of memcached: python-memcached. Thanks NicDumZ.

A:

If you can rebuild your Python runtime with the patches offered in the Unladen Swallow project, you should see speedups of 40% to 150% in pickling, 36% to 56% in unpickling, according to their benchmarks; maybe that might help.

A:

My suggestion would be not to rely on having an object structure. Instead have a byte array (or mmap'd file etc) which you can do random access operations on and implement the cross-referencing using pointers inside that structure.
True, it will introduce the concept of pointers to your code, but it will mean that you don't need to unpickle it each time the handler process starts up, and it will also use a lot less memory (as there won't be the overhead of python objects).
As your database is going to be fixed during the lifetime of a handler process (I imagine), you won't need to worry about concurrent modifications or locking etc.
Even if you did what you suggest, you shouldn't have to rebuild it on every user request, just keep an instance in memory in your worker process(es), which means it won't take too long to build as you only build it when a new worker process starts.


Q:

.NET inter-process "events"

I have multiple instances of the same application running. The user ask can click "Quit" on each instance to shut it down.
I would like to add the choice to "Quit All Instances", which will raise some kid of "event" that notifies all instances of the application that they should close. I don't need to transport any data along with this event.
What's the best (and preferably simplest) way to do this in Windows using C#/.NET?

A:

Send the good'ol WM_CLOSE to all instances...
Process[] processes = Process.GetProcesses();
string thisProcess = Process.GetCurrentProcess().MainModule.FileName;
string thisProcessName = Process.GetCurrentProcess().ProcessName;
foreach (Process process in processes)
{
   // Compare process name, this will weed out most processes
   if (thisProcessName.CompareTo(process.ProcessName) != 0) continue;
   // Check the file name of the processes main module
   if (thisProcess.CompareTo(process.MainModule.FileName) != 0) continue;
   if (Process.GetCurrentProcess().Id == process.Id)
   {
     // We don't want to commit suicide
     continue;
   }
   // Tell the other instance to die
   Win32.SendMessage(process.MainWindowHandle, Win32.WM_CLOSE, 0, 0);
}


Q:

How do I delete a song from iCloud?

I updated to iTunes 11.0.2 very recently, and I'm fairly certain this version specifically brought a change of wording regarding deleting songs from iCloud, and I'm curious if there's changed functionality to match.

After perusing Apple's support documentation, it seems I was correct:

I intend to replace the current version of this song, and figured the easiest way to ensure everything updates would be to delete the song from iCloud and my Library, and then import the new version.
Now that the functionality of deleting songs has changed, how do I delete the song from both my local library and iCloud as well?

A:

This seems to be fixed in 11.0.4:


Q:

How can I scan a string for numbers to adjust the font size in an iOS app?

I'm off to a good start. But I would like to make this code more dynamic.
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
UIFont *font = [UIFont systemFontOfSize:10.0f];
UIFont *smallFont = [UIFont systemFontOfSize:9.0f];

[attString beginEditing];
[attString addAttribute:NSFontAttributeName value:(font) range:NSMakeRange(0, string.length - 2)];

[attString addAttribute:NSFontAttributeName value:(smallFont) range:NSMakeRange(string.length - 1, 1)];

Say I have the following String:
@"C3OC2OH4"
I would like to adjust the font size of the numbers only to fulfill a chemistry application. How can I scan the above string, and create a series of custom ranges to plug into my function above, which adjusts the font size?

A:

You can enumerate the characters and apply the attributes like this.
NSString * string = @"C3OC2OH4";

NSMutableAttributedString * attributedString = [NSMutableAttributedString new];

NSDictionary * subscriptAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:10.0],
                                       NSBaselineOffsetAttributeName : @(-5.0)};

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByComposedCharacterSequences
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {

                            NSCharacterSet * letterCharacterSet = [NSCharacterSet letterCharacterSet];

                            if ([substring rangeOfCharacterFromSet:letterCharacterSet].location != NSNotFound)
                                [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:substring]];
                            else
                                [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:substring attributes:subscriptAttributes]];

                        }];

In this case substring is each character and is appended without any change if it is a letter. If it is a number we change the font size and shift the baseline. Change them according to your need.
Good luck.


Q:

Ajax Load data from remote file with specific ID

I am stuck In an issue. Need some help from great people like you.
I have created a small like system here.
I have a HTML file having Some Data with Different IDs.
Here you can see my remote.html File codes.
314
214
19
124
114

Now I have one File index.php
In which I have a
I want to get the Data from Remote.HTML With Different ID
For Example. 214 will show on Index.php file like 214 and so on for all IDs on Remote.html
Here is Ajax Code i am using
$.ajax({
    url: 'update_record.php',

    success: function(data) {
                    data=$(data).find('#15');
        $('#output').html(data);

     }
    });

But it is not showing me anything there.
Please help me

A:

Try with this code.
  function data(){
        $.ajax({
            url: 'update_record.php',

            success: function(data) {
                var fval = $($.parseHTML(data)).filter("#15")
                $('#output').html(fval);

             }
            });
       setTimeout(function(){data();},5000);
    }
data();


Q:

Check if these vectors form a basis

I am having trouble trying to solve this problem:
Check that the following vectors are bases and find the dimension of the vector space they are basis for

$S_1 = (1,0,...,0),(0,1,...,0),...,(0,0,...,1) \in K^n$
I do not know how can I put these vectors in row echelon form since I don't know how many they are or all their components.
$S_2 = 1,x,x^2,...,x^n\subset K^n$ [x]=“Polynomials of degree less than or equal to n”
How do i put these in row echelon form?

Thank you in advance.

A:

Your first set of vectors contains $n$ vectors, where the $k$th one has zeros everywhere except in coordinate number $k$. For instance if $n=3$ we have $(1, 0, 0)$ and $(0,1,0)$ and $(0,0,1)$.
If you just write them in a matrix in the order they come, it is already in row echelon form. You just need to verify that it is a basis, which should be quite easy regardless of your preferred method of doing so.
Your second set of vectors seems ill-defined; what is $x$ and how does it give a $n$-dimensional vector?
Assuming that $x$ is an element of $K$, and the vectors you want are $(1,0,0,...)$, $(0,x,0,...)$, $(0,0,x^2,...)$ et cetera it should be almost exactly the same as the previous one.
And btw, to get it to be in $K^n$, you have to stop at $x^{n-1}$ since you included $1=x^0$.
edit:
With the new information, I interpret the second question as us being given a $K$-vector space $W$ spanned by the elements $1,x,x^2,...,x^n$.
It is indeed a $K$-vector space, with addition of two vectors in the usual sense, and multiplication of vectors with scalars (elements of $K$) also defined in the usual way.
To see the dimension, you just have to realise that $1,x,...,x^n$ are all linearly independent elements, and that their span is $n+1$-dimensional.


Q:

How to collect a variable length relationship's properties

I can obtain the properties from all the relationships that satisfy a simple pattern (length of 1) such as:
MATCH ()-[r:RELATIONSHIP]->() RETURN collect(r.id)

But cannot obtain the properties of variable length relationships such as:
MATCH ()-[r:RELATIONSHIP*]->() RETURN collect(r.id)

Any help will be appreciated.

Error message is: Neo.ClientError.Statement.SyntaxError: Type
  mismatch: expected Any, Map, Node, Relationship, Point, Duration,
  Date, Time, LocalTime, LocalDateTime or DateTime but was
  List

A:

In a simple pattern (fixed length 1) variable  r is only one relationship, but in the case of variable length patterns, the variable r is a list of relationships.
Your first query is correct but in the second query, you are trying to get id property from List instead of getting it from a particular relationship.
You can modify your query to get properties from the list as follows:
MATCH ()-[r:RELATED_TO*2]->()
UNWIND  r as rel
RETURN COLLECT(DISTINCT id(rel))

Above pattern(Binding relationships to a list in a variable length pattern is deprecated) is deprecated and will be removed in future versions.
The recommended way is to bind the whole path to a variable, then extract the relationships:
MATCH path=()-[:RELATED_TO*2]->()
UNWIND relationships(path) AS  rel
RETURN COLLECT(DISTINCT id(rel))


Q:

Coefficients of the vectors in a tensor product

The postulate says that if we want to build the compound state of two sub-systems, we just take the tensor product $\otimes$ of the respective state vectors. This means that if one of the vectors has an overall phase $e^{i \phi}$, that can be interpreted either as the phase of any of the two vectors in the subspaces, or of the compound one, and this can be easily seen "in the formulas" when using the bracket notation $e^{i\phi}(|\psi\rangle\otimes|\zeta\rangle)=|\psi\rangle\otimes(e^{i\phi}|\zeta\rangle)=(e^{i\phi}|\psi\rangle)\otimes|\zeta\rangle$, or even more directly if we use the matrix representation.
This seems a technicality, as usually we just elide the overall phase because it's not measurable. But, I came across this quantum computation problem.
Consider the "phase estimation" algorithm presented in Quantum Computation and Quantum Information, Nielsen & Chuang, II edition, page 221 (also Wikipedia). Consider only a part of the circuit described: a qubit register $|t\rangle$ controls (i.e., activates or inhibits) the application of an operator $U$ to a second qubit register, which is initially in the state $|u\rangle$. This $|u\rangle$ happens to be an eigenvector of $U$, so $U|u\rangle=e^{i\phi}|u\rangle$. Now, the algorithm starts by setting $|t\rangle = 0$ and then applying an Hadamard transform, $|0\rangle \rightarrow H|0\rangle = \frac{1}{\sqrt{2}}(|0\rangle+|1\rangle)$, and then let it do the job on the second register. The output is $|tu\rangle_{final}=\frac{1}{\sqrt{2}}(|0\rangle+e^{i\phi}|1\rangle)|u\rangle$, for the aforementioned tensor product rule. At the end, we do some operations on $|t\rangle$ and we measure it getting some information on the phase $e^{i\phi}$, completely ignoring the state of $|u\rangle$ (which N&C regard as unchanged, since the phase somehow "passed" to the register $|t\rangle$).
I can't fit together these two facts: $|t\rangle$ is supposed to be "controlling" the transform on $|u\rangle$, so it should not change at all; yet, thanks to the tensor product and its "permeability" to numeric factors, I can just shuttle around the $e^{i\phi}$ phase, and decide to measure it (somehow) on the first register, instead of the second, where my intuition would tell me that it resides. Most importantly, as I said initially, putting the phase here and there seems natural, possible in the formulas and completely arbitrary, so I don't see why I shouldn't let the phase stay "attached" to $|u\rangle$ and then get... basically nothing useful for my quantum algorithm.
How can I get out of this apparent contradiction? Is this a clever trick set into the very core rules of quantum mechanics, to encode the fact that in two interacting systems there can't really be one spectator (or controller) and one affected (controlled)?

A:

|t⟩ is supposed to be "controlling" the transform on |u⟩, so it should not change at all;

In this case, the use of the terminology "control" and "target" derived from classical computer science is a little confusing. Your intuition here may be helped here by realising that there is no way in general to split the operation $U$ into parts that act on the two qubits separately$^{\ast}$. In general, $U$ acts non-trivially on the joint state of the qubit pair, so there is no reason to expect that the control qubit should be left unchanged.

I don't see why I shouldn't let the phase stay "attached" to |u⟩ and then get... basically nothing useful for my quantum algorithm.

If you write your output state like $$|0\rangle |u\rangle + e^{i\phi}|1\rangle|u\rangle,$$
it becomes clear that the phase is not "attached" to either of the individual qubits: control or target. Rather the phase is attached to one branch of the wavefunction, i.e. just one of the pair of two-qubit states that appears in the superposition. Namely, the phase appears in the branch where the control qubit was in the state $|1\rangle$, thus applying a phase shift to that part of the global wavefunction. The lesson here is that one cannot usually think of quantum states of many-particle systems as being associated to one particle or another. As Lev Vaidman niftily wrote: "the quantum wavefunction describes all systems together."
$^{\ast}$ However this situation, as described in the OP's question, could also arise from the unitary $U = V \otimes I$, where $I$ is the identity on the target qubit and $V$ acts on the control qubit as
$$V|0\rangle = |0\rangle \qquad V|1\rangle = e^{i\phi}|1\rangle.$$
So actually $U$ must act non-trivially at least on the control qubit, perhaps surprisingly.


Q:

PowerShell Pipeline iteration

I often write functions that need to accept pipelines like:
function Invoke-ExchangeHubChecks
{
    [cmdletbinding()]
    param
    (
        [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [object[]]$oServersToTest,
        [int]$QueueWarnThreshold = 50,
        [int]$QueueFailThreshold = 100

    )
    begin
    {
        $oHubTests = @()
        $c=0
    }
    Process
    {
        $c++
        $Server = $oServersToTest[0]

        $oHubTests += [pscustomobject]@{
            Identity = $server.Identity
            Queue = "blah"
            Count = $c
        }
    }
    end
    {
        $oHubTests
    }
}
    end
    {
        $oHubTests
    }
}

I often see code snippets with a foreach inside the process block. My understanding is that the process block replaces the need for the foreach block (in most cases).
I need to add a "filter" to the input object "$oServersToTest". I have used "where-object" to create the filter:
$Server = $oServersToTest[0] | Where-Object {$_.IsHub}

However, as it iterates over the collection, it is adding objects that don't match the where clause to the custom object, proved by $c:
Output:
Identity    Queue Count
--------    ----- -----
Server01    blah      1
Server02    blah      2
Server03    blah      3
Server04    blah      4
Server05    blah      5
            blah      6
            blah      7
Server06    blah      8
Server07    blah      9
Server08    blah     10
Server09    blah     11
Server10    blah     12
            blah     13
            blah     14

Is this an example where I must use a foreach inside the process block:
Process
{
    $c++
    #$Server = $oServersToTest[0] | Where-Object{$_.IsHubServer}
    $TestResult = @()
    $oServersToTest | Where-Object {$_.IsHubServer} | Foreach-object{
        $TestResult += [pscustomobject]@{
            Identity = $_.Identity
            Queue = "blah"
            Count = $c
        }
    }

    $oHubTests += $TestResult
}
End
{
    $oHubTests
}

Which works, but why does this work and not the other way? To me, it's doing twice the work.
(Powershell 5.0)
TIA

A:

I would use a foreach() loop inside the process block.
As Jeff Zeitlin points out, this also lets you support processing of collections with named parameters and pipelining alike.
The reason for using foreach() over ForEach-Object is three-fold:

Performance:
When the input collection is already in memory (which it is in both cases), the overhead from implicit parameter binding will make ForEach-Object slower than foreach()
Readability:
IMO, having a named variable (like $Server) makes the script more readable and you avoid confusion with nested ForEach-Object or Where-Object clauses inside the loop
Functionality:
With a plain ol' foreach(), you get fast flow control options like break and continue for free.

process {
    $oHubTests += foreach($server in $oServersToTest |Where-Object {$_.IsHubServer}){
        $c++
        [pscustomobject]@{
            Identity = $server.Identity
            Queue = "blah"
            Count = $c
        }
    }
}

If the only thing your cmdlet does is take the input and construct corresponding [pscustomobject]'s, then I would cut out the $oHubTests part completely, and just output the objects as they flow through:
function Invoke-ExchangeHubChecks
{
    [CmdletBinding()]
    param
    (
        [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [object[]]$oServersToTest,
        [int]$QueueWarnThreshold = 50,
        [int]$QueueFailThreshold = 100

    )
    begin {
        $c=0
    }
    process {
        foreach($server in $oServersToTest |Where-Object {$_.IsHubServer}){
            $c++
            [pscustomobject]@{
                Identity = $server.Identity
                Queue = "blah"
                Count = $c
            }
        }
    }
}


Q:

MPI asynchronous broadcast from unknown source

I have a C-project that has n numbers of processors working on a kind of tree search. At any given time of the program, any of these processes may find something of interest and want to send this to all other processors asynchronously.
How can I listen for new messages on the other processes without having to loop through all possible senders each loop iteration?
I have read other questions about this, for example this one (MPI - Asynchronous Broadcast/Gather), however, all I've seen so far either doesn't handle unpredictable senders or loops through each possible sender, which I don't really fancy.
EDIT for clarification:
Sending the found value to a root rank and distributing it from there is out of the option. Zulan's answer would work, if I did not have that condition, so for others this might be of help.
In my case it can (and most definitely will) happen that different ranks find something they need to share multiple times (which means that race conditions could also occur).

A:

After a lot of trial and error (and other feedback) I found that the most performant solution uses asynchronous broadcasts.
My first approach was inspired by Petru's answer using multiple non blocking MPI_Isend() calls to distribute data and only one single MPI_Irecv() call (with any source) to periodically receive data. This approach turned out to be quite slow, since the non blocking MPI_ISend() calls have to be checked by the sender with MPI_Test() on every single MPI_Request handle that is created.
The reason for that is, that asynchronous operations aren't truly asynchronous in the sense that they work in the background, but rather have to be checked periodically.
In my case the problem also presents the possibility that new solutions can (and will) be found multiple times, which resulted in a lot of management issues with existing, open MPI_Request handles, which had to be waited for or managed otherwise.
My second approach was using a central communicator as proposed by Zulan. This approach was very quick when there weren't many messages, but the root rank got clogged up when there were many found solutions at the same time, making it very slow in special cases. Most importantly the root rank was not as fast as the others anymore (which was to be expected), which resulted in an overall slower program in my case.
My third and final approach was using multiple non blocking MPI_Ibcast() calls, one for every possible rank that could send a message. For example that would mean that in a case with 3 different ranks that

rank 0 has two open MPI_Ibcasts with root 1 and 2
rank 1 has two open MPI_Ibcasts with root 0 and 2
rank 2 has two open MPI_Ibcasts with root 0 and 1

When a rank then finds a solution, it posts the last necessary MPI_Ibcast with itself as the root. At first this may seem similar to approach one, however, in this case the sender always only has to monitor a single request handle (the one from the final MPI_Ibcast) and check it periodically with MPI_Test(). The other ranks always have the same amount of open broadcasts (namely the world's size minus 1), which can be stored in an array and checked with MPI_Testany().
The difficulty with this approach is, however, that each open broadcast must operate on it's own communicator, essentially needing as many communicators as there are ranks.
So, my findings are that the second approach is acceptable sometimes, making it a quick and viable option, when there are not a lot of messages. It was the easiest to handle and implement. The third approach was faster under heavier load and also made my program termination very easy, since there always is a known amount of open connections at all time. It was the hardest and longest to implement and used up a bit more memory than the other implementations. (I don't know the reason for this, but it seems to have something to do with the broadcast's buffer management and possibly the additional communicators.)
Lastly I cannot stress enough that the first approach seems easy at first, however when you really want to keep track of every single request, then it is hard to manage and slow as well, unfortunately.


Q:

Probability involving three cards

There are three bags, with two cards in each bag having $1$ and $2$ on those two cards. What is the probability when withdrawing one card from each bag that the sum of card values is $5$?
I found an answer is $3/8$, but I think I didn't understand how to solve...

A:

There are $8$ ways to pull the cards in total. Of these $3$ give us the answer we want:
$$122, 212, 221$$
So the probability of pulling $5$ is:
$$P(\text{total is 5})=\frac38$$


Q:

golang unmarshal complex json

I have the following JSON blob, and I'm trying to decode it into Go.
["contig", "32", {"a":[33,41,35], "b":[44,34,42]}]

I believe that I have to model the data structure of the JSON.  I tried using a struct called Line:
package main

import (
"encoding/json"
"fmt"
)

type Line struct {
    Contig string
    Base   string
    PopMap map[string][]int
}

func main() {
    j := []byte(`["contig", "32", {"a":[33,41,35], "b":[44,34,42]}]`)
    var dat Line
    err := json.Unmarshal(j, &dat)
    fmt.Println(dat)
    fmt.Println(err)
}

I got the following error:
{  map[]}
json: cannot unmarshal array into Go value of type main.Line

What am I doing wrong?
Link to sandbox for trying out code

A:

The JSON input you specified is an array of different types, so as it is, you can't unmarshal it into a struct, but only into a slice of different types: []interface{}.
in := `["contig", "32", {"a":[33,41,35], "b":[44,34,42]}]`

var arr []interface{}
if err := json.Unmarshal([]byte(in), &arr); err != nil {
    panic(err)
}
fmt.Println(arr)

Output:
[contig 32 map[a:[33 41 35] b:[44 34 42]]]

Filling the struct
Good, you now have the values, just not in the struct you want them to be. You can use type assertion to obtain the types you want:
l := Line{PopMap: map[string][]int{}}
l.Contig = arr[0].(string)
l.Base = arr[1].(string)

m := arr[2].(map[string]interface{})
for k, v := range m {
    nums := v.([]interface{})
    pops := make([]int, len(nums))
    for i, val := range nums {
        pops[i] = int(val.(float64))
    }
    l.PopMap[k] = pops
}

fmt.Printf("%+v", l)

Output (try it on the Go Playground):
{Contig:contig Base:32 PopMap:map[a:[33 41 35] b:[44 34 42]]}

Some notes:
The "internal" arrays of the values of "a" and "b" are unmarshaled into values of type []interface{} which you cannot simply convert to []int or []float64 hence the for loops to iterate over them and use type assertion on each of their elements. Also note that the json package unmarshals the numbers into values of type float64 and not int (because not just integers can be in the JSON text so float64 is used which can accommodate both).
Also note that the success of type assertions are not checked in the above example. If the unmarshaled array has less than 3 elements, or any of the type assertion fails, a runtime panic occurs.
Using recover()
You can add a defer function which calls recover() to catch this panic (try it on the Go Playground):
defer func() {
    if r := recover(); r != nil {
        fmt.Println("Failed to unmarshal")
    }
}()

l := Line{PopMap: map[string][]int{}}
// ...and here comes the code that uses type assertions
// and stores values into...

Code with checks
Or you can add checks for the type assertions. The type assertion has a special form v, ok = x.(T) which when used never panics, but rather if the type assertion doesn't hold, ok will be false (and will be true if type assertion holds).
Try it on the Go Playground:
if len(arr) < 3 {
    return
}
var ok bool
l := Line{PopMap: map[string][]int{}}
if l.Contig, ok = arr[0].(string); !ok {
    return
}
if l.Base, ok = arr[1].(string); !ok {
    return
}
if m, ok := arr[2].(map[string]interface{}); !ok {
    return
} else {
    for k, v := range m {
        var nums []interface{}
        if nums, ok = v.([]interface{}); !ok {
            return
        }
        pops := make([]int, len(nums))
        for i, val := range nums {
            if f, ok := val.(float64); !ok {
                return
            } else {
                pops[i] = int(f)
            }
        }
        l.PopMap[k] = pops
    }
}

fmt.Printf("%+v", l)


Q:

Change path in Joomla from localhost

I have joomla install on IIS with a domain that's not registered yet, so we are still using the IP address..
So whenever you go "home" or do some actions in the admin panel it keeps trying to go back to localhost - how do I change it - or do I need to wait for the domain to come on...
The website is here btw - http://12.148.212.142/

A:

I fixed it - had to change the settings for "live_site" in configuration.php


Q:

Can a JPA entity have multiple OneToMany associations?

Adding two OneToMany associations to my entity class seems not to work. It works fine if I remove one of them.
@Entity
@Table(name = "school")
public class School {

    private List<Teacher> teachers;
    private List<Student> students;

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER)
    public List<Teacher> getTeachers()
        return this.teachers;
    }
    public void setTeachers(List<Teacher> teachers) {
         this.teachers = teachers;
    }

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER)
    public List<Student> getStudents()
        return this.students;
    }
    public void setStudents(List<Student> teachers) {
         this.students = students;
    }
}

Then in Teacher and Student I have the correct ManyToOne annotations
@Entity
@Table(name = "teacher")
public class Teacher {
    private School school;

    @ManyToOne
    @JoinColumn(name = "school_id")
    public School getSchool() {
        return this.school;
    }
    public void setSchool(School school) {
        this.school = school;
    }
}

@Entity
@Table(name = "student")
public class Student {
    private School school;

    @ManyToOne
    @JoinColumn(name = "school_id")
    public School getSchool() {
        return this.school;
    }
    public void setSchool(School school) {
        this.school = school;
    }
}

I also have id fields with the correct annotations (@Id, @GeneratedValue)
So to me it seems like I cannot have more than one @OneToMany in the same class. Is this correct?

A:

Why FetchType.EAGER is a bad idea
You can have multiple one-to-many associations, as long as only one is EAGER.
But, even if you can use Set instead of List to bypass this MultipleBagFetchException, it's not a good thing to do because you'll end up with a Cartesian Product.
Avoiding the Cartesian Product
The best thing to do is to NOT use EAGER at all. You should use LAZY for all associations and eager fetch multiple many-to-one and one-to-one associations and at most one one-to-many association using the JOIN FETCH JPQL directive.
If you want to fetch multiple one-to-many associations, you can use the Hibernate.initialize(proxy) method for the 2nd or 3rd association.
Fetching multiple parents along with multiple child collections
However, if you have a collection of parent entities that need to load multiple child associations, then you can use JOIN FETCH for the first collection since, if you try to eagerly fetch multiple child collections, then you'll end up with a Cartesian Product.
SO, assuming you wanted to fetch multiple Post parent entities along with their comments and tags collections, you can fetch the comments in the first query:
List<Post> _posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.id between :minId and :maxId ", Post.class)
.setParameter("minId", 1L)
.setParameter("maxId", 50L)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();

And, for the second tags collection, you can issue the following secondary query:
_posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.tags t " +
    "where p in :posts ", Post.class)
.setParameter("posts", _posts)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();

How does this work?
The first query fetches the Post entities which are attached to the current EntityManager. The comments collection is fetched for each Post entity, but the tags collection is represented by a Proxy.
The second query will fetch the tags, but since Hibernate already cached the Post entities, it will just replace the tags Proxy collections with the actual tags entries fetched from the database.

Check out this article for more details about this trick.


Q:

How to debug MySQL "You have an error in your SQL syntax error"

This is the error
Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1

This is my query
$sql = 'INSERT INTO list '.
   '(bond_amount,bond,prize,prize_amount,draw,draw_date,held_at) '.
   'VALUES ( "bonds", "bonds", prize, p_amount, draw, d_date, held,)';

A:

current_date is a reserved word in mysql.  You should avoid it, but if you really want to use it, you must quote it (in back-quotes).

A:

You can not use current_date as column name. It is a reserve words of mysql.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

A:

try
INSERT INTO staff_service (customer_id,workorder_no,service_date,`current_date`)
VALUES (2,021,'3112-21-1',CURDATE())


Q:

SQL Server Row_Count with Reset

I have 6 columns:
Date, Account, Side, Symbol, Currency, Reset Flag (0 Yes, 1 No)

I want to row count over partition by but reset the row count whenever a 0 appears in Reset Flag column. The first 5 columns are not unique but their combination forms a unique set of columns.
Please help me with this !
Every other solution I've researched doesn't work for some reason :/

A:

This is a gaps and islands style problem. Without any sample data or desired results...
Using two row_number() to identify groups by reset flag, and another in the outer query to number the rows by ResetFlag and the grp created in the inner query.
Change the order of date, Account, Side, Symbol, Currency to whichever order of those columns you want to number the rows by; keep them in the same order for each of the three row_number()s.
/* ----- */
select
    date
  , Account
  , Side
  , Symbol
  , Currency
  , ResetFlag
  , rn = case when ResetFlag = 0 then 0
         else row_number() over (
            partition by ResetFlag, grp
            order by date, Account, Side, Symbol, Currency)
         end
from (
  select *
    , grp = row_number() over (order by date, Account, Side, Symbol, Currency)
          - row_number() over (
              partition by ResetFlag
              order by date, Account, Side, Symbol, Currency)
  from t
  ) s
order by date, Account, Side, Symbol, Currency

rextester demo: http://rextester.com/VLCO32635
returns:
+------------+---------+------+--------+----------+-----------+----+
|    date    | Account | Side | Symbol | Currency | ResetFlag | rn |
+------------+---------+------+--------+----------+-----------+----+
| 2017-01-01 |       7 |    2 |      3 | 7,0000   |         1 |  1 |
| 2017-01-02 |       8 |    9 |      9 | 6,0000   |         1 |  2 |
| 2017-01-03 |       4 |    1 |      5 | 6,0000   |         1 |  3 |
| 2017-01-04 |       5 |    4 |      8 | 5,0000   |         0 |  0 |
| 2017-01-05 |       2 |    1 |      3 | 1,0000   |         1 |  1 |
| 2017-01-06 |       8 |    0 |      2 | 0,0000   |         0 |  0 |
| 2017-01-07 |       0 |    3 |      8 | 9,0000   |         1 |  1 |
| 2017-01-08 |       0 |    3 |      1 | 3,0000   |         1 |  2 |
+------------+---------+------+--------+----------+-----------+----+


Q:

Setting a DataRow item to null

I have a text file that I read into a data table and then perform a bulk insert into a SQL Server table. It's quite fast and it works great when all the imported values are treated as strings (dates, strings, ints, etc are all imported into string fields).
Now that I have the concept worked out, I'm going back to assign real datatypes in the database and my code. The database has the correct types assigned to the fields. I'm working on the code now.
I'm having a problem with dates. As I mentioned, everything is a string and gets converted to the correct type. In the following code, I want to test if the string value representing a date is null or whitespace. If it isn't null, then use the existing value. Otherwise, set it to null.
row[i] = !string.IsNullOrWhiteSpace(data[i]) ? data[i] : DBNull.Value;

I tried using null but get an error telling me to use DBNull instead. When I use DBNull, I get a message telling me there is no implicit conversion between string and System.DBNull.
The columns in the datatable have datatypes specified (in this case, DataType = Type.GetType("System.DateTime") ) and I set AllowDBNull = true for this column
How do I handle this?
Thanks!

A:

The problem is because of the operation you are using.  Since DBNull.Value is not a string, you can't use the conditional operator.  This is because, from the conditional operator docs:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Try doing this:
if (!string.IsNullOrWhiteSpace(data[i]))
    row[i] = data[i];
else
    row[i] = DBNull.Value;

This bypasses the conversion requirements for both sides to be the same.  Alternatively, you can cast both to a System.Object explicitly, and still use the conditional operator.

A:

You need to cast them both to objects like so:
row[i] = !string.IsNullOrWhiteSpace(data[i]) ? (object)data[i] : (object)DBNull.Value;


Q:

C Logical Operators Query

In C Logical AND operator if both the operands are non-zero then only condition becomes true.
Then why
printf(">>>>>>>>>%d\n", ((4 == 0) && (5 != 6) || (6 != 7)));

is printing
>>>>>>>>>1

A:

Take a look at operators' precedence.
logical && has higher priority than logical ||.
Therefore the condition becomes:
((4 == 0) && (5 != 6)) || (6 != 7)

which is
(false && true) || true

which is
false || true

which is
true

A:

Here
printf(">>>>>>>>>%d\n", ((4 == 0) && (5 != 6) || (6 != 7)));

(4 == 0) && (5 != 6) will evaluate to false, and then you will have
printf(">>>>>>>>>%d\n", (0 || (6 != 7)));

and since 6 != 7 then it will be
printf(">>>>>>>>>%d\n", 1);

maybe you wanted to try this
printf(">>>>>>>>>%d\n", (4 == 0) && ((5 != 6) || (6 != 7)));

read about operators precedence.


Q:

Migrating SQL CLR project from VS2008 to VS2010 - deploy fails

I have a solution with a SQL CLR project in VS2008. The solution / project was converted to VS2010 and now the deploy no longer works.
I get the following type of erros:

Beginning deployment of assembly MyProjectDatabaseCode.dll to server DEVPN-004 : MyProject
    The following error might appear if you deploy a SQL CLR project that was built for a version of the .NET Framework that is incompatible with the target instance of SQL Server: "Deploy error SQL01268: CREATE ASSEMBLY for assembly failed because assembly failed verification". To resolve this issue, open the properties for the project, and change the .NET Framework version.
  C:\inetpub\wwwroot\VS2010_MyProjectSolution\DatabaseCode\bin\Release\MyProjectDatabaseCode.dll : Deploy error : Plan verification encountered errors; deployment cannot continue.
  C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TeamData\Microsoft.Data.Schema.SqlClr.targets(96,5): Deploy error TSD00561: This deployment may encounter errors during execution because changes to [dbo].[Column1] are blocked by [dbo].[Table1].[Column1]'s dependency in the target database.

I verified and the project is targeted against .NET 3.5. We have predeployscript.sql and postdeployscript.sql files that are supposed to be run. It appears like they are not being run by VS2010. What could be causing the issue?

A:

We ended up contacting Microsoft and they reproduced our issue as a known bug. They offered a workaround by retargeting the assembly to .NET 2.0, but that didn't work in our scenario either.
It seems that the only way forward until the fix is to create a brand new SQL CLR project in 2010 and add all the files to it by hand.


Q:

Hibernate MacBook on 10-ish % power instead of 0/1% when running on battery?

Yeah, I know my battery is probably hosed, but every time I reach 5%, my MacBook shuts down, as it expects the battery to be able to run down to 1% before hibernating.
However I would like it to hibernate and not shutdown, when I run out of power, so is it possible to make my MacBook hibernate at like 5-10%?
My MacBook is over 2 years old and I'm not going to buy a new battery. The battery only lasts 1-2 hours.
I have tried calibrating the battery, resetting the SMC etc., without any noticeable effect.

A:

http://www.jinx.de/SmartSleep.html will let you control it via GUI. The app is $6 on his website or $4 on the Mac App Store.

(Note: I have no idea how this app ever got approved for the Mac App Store, but it appears that Apple is stone-walling the developer on approving a Lion-compatible update. This seems to be Apple's passive-aggressive way of getting apps out of the Mac App Store after they were approved: they don't want to upset people by yanking the app, so they just won't approve an update and eventually it either breaks and the developer pulls the app because they are getting so many support requests, or people just stop buying it. When the sandboxing rules hit in November, we may see apps start disappearing from the Mac App Store. All of which is to say that if I was going to buy this app, I'd buy it through his website even though it's $2 more. There's a demo available, although the "request a trial" button didn't work for me, I assume it's a temporary glitch that the developer can fix. It also appears that Mac App Store customers can download the version from his website and use that, so if those $2 are really important to you, I guess you could try that.)

If you'd rather spend time than money, http://tidbits.com/article/9115 has a script that might help.


Q:

Javascript/Jquery validating decimal input on keyup

I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using.
input numbers max length 999.999
-
my result after .  (point) 3 number it is goog. but 99999.999
I need 999.999,222.222,22.01 ->
max length +++.+++
this my code
<input type="text" id="spinEdit2" class="aSpinEdit" />

<script type="text/javascript">
var txt = document.getElementById('spinEdit2');
    txt.addEventListener('keyup', myFunc);

    function myFunc(e) {
        var val = this.value;

        var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?|[0-9])/g;
            val = re1.exec(val);
            //console.log(val);
            if (val) {
                this.value = val[0];
            } else {
                this.value = "";
            }

    }
</script>

Thanks

A:

How about
/^([0-9]{1,3}(?:\.[0-9]{0,3})?)/g

In case you want the details: the {1,3} means the preceding thing can happen from 1 to 3 times. The (?:) is a non-captured group -- it's a grouping of the following symbols, but it doesn't capture to any variables like $1.


Q:

D3, dates on the x axis, data the width of a date

I am visualizing data by date.  I want something a bit like this:

The point is that I want to draw rectangles that are the width of the days. Here's how I draw rectangles:
svg.selectAll(".my_class")
.data(my_data)
.enter()
.append("rect")
.attr({
    "width": function(d) { return x_scale.rangeBand(); },
    "height": function(d) { return h_scale(d.end - d.start); },
    "x": function(d) { return x_scale(new Date(d.date)); },
    "y": function(d) { return y_scale(d.end); },
    "class": function(d) { return d.device; }
});

The problem is that in order to get the right width, I ended up declaring my x_scale thus
d3.scale.ordinal()
.domain(my_data.map(function (d) { return new Date(d.date); }))
.rangeRoundBands([0, image_width]);

when I surely should have used d3.time.scale() instead.  (Note the non-gaps after 2, 7, and 12 Feb.)  The problem is that I don't see a way to specify the rectangle widths using d3.time.scale().
A work-around is to generate zero-height rectangles on the back end for every day in the period.  This isn't that hideous, but I feel I should be able to do better.  In addition, I'd lose niceties like .ticks(d3.time.weeks, 1) and have to spin them myself.
Any pointers?

A:

In the end, the simplest solution I found was to use an ordinal scale and provide (sometimes empty) elements for each date in the range.


Q:

logitech t650 tap to click still not registering?

I upgraded my firmware as suggested in this reddit link, but I still can't seem to trigger left clicks or right clicks via tapping. Its driving me crazy now as I still need to thumb press the physical click to make the touchpad somewhat usable.
Any thoughts on how I could diagnose what the problem is?

A:

Seems I needed to update the firmware twice... the correct version is 38.
Tap to click works now


Q:

Split a large string into multiple substrings containing 'n' number of words via python

Source text: United States Declaration of Independence
How can one split the above source text into a number of sub-strings, containing an 'n' number of words?
I use split(' ') to extract each word, however I do not know how to do this with multiple words in one operation.
I could run through the list of words that I have, and create another by gluing together words in the first list (whilst adding spaces). However my method isn't very pythonic.

A:

text = """
When in the course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the Laws of Nature and of Nature?s God entitle them, a decent Respect to the Opinions of Mankind requires that they should declare the causes which impel them to the Separation.

We hold these Truths to be self-evident, that all Men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the pursuit of Happiness?-That to secure these Rights, Governments are instituted among Men, deriving their just Powers from the Consent of the Governed, that whenever any Form of Government becomes destructive of these Ends, it is the Right of the People to alter or abolish it, and to institute a new Government, laying its Foundation on such Principles, and organizing its Powers in such Form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient Causes; and accordingly all Experience hath shewn, that Mankind are more disposed to suffer, while Evils are sufferable, than to right themselves by abolishing the Forms to which they are accustomed. But when a long Train of Abuses and Usurpations, pursuing invariably the same Object, evinces a Design to reduce them under absolute Despotism, it is their Right, it is their Duty, to throw off such Government, and to provide new Guards for their future Security. Such has been the patient Sufferance of these Colonies; and such is now the Necessity which constrains them to alter their former Systems of Government. The History of the Present King of Great-Britain is a History of repeated Injuries and Usurpations, all having in direct Object the Establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid World.
"""

words = text.split()
subs = []
n = 4
for i in range(0, len(words), n):
    subs.append(" ".join(words[i:i+n]))
print subs[:10]

prints:
['When in the course', 'of human Events, it', 'becomes necessary for one', 'People to dissolve the', 'Political Bands which have', 'connected them with another,', 'and to assume among', 'the Powers of the', 'Earth, the separate and', 'equal Station to which']

or, as a list comprehension:
subs = [" ".join(words[i:i+n]) for i in range(0, len(words), n)]

A:

You're trying to create n-grams? Here's how I do it, using the NLTK.
punct = re.compile(r'^[^A-Za-z0-9]+|[^a-zA-Z0-9]+$')
is_word=re.compile(r'[a-z]', re.IGNORECASE)
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
word_tokenizer=nltk.tokenize.punkt.PunktWordTokenizer()

def get_words(sentence):
    return [punct.sub('',word) for word in word_tokenizer.tokenize(sentence) if is_word.search(word)]

def ngrams(text, n):
    for sentence in sentence_tokenizer.tokenize(text.lower()):
        words = get_words(sentence)
        for i in range(len(words)-(n-1)):
            yield(' '.join(words[i:i+n]))

Then
for ngram in ngrams(sometext, 3):
    print ngram


Q:

Django: How to save mxGraph, so when user refreshes the graph stays? (asynchronous)

I convert the current mxGraph the user creates into XML which is stored in the database (ajax.js). I return this in my views as a JSONResponse to my ajax request (views.py).
The data stored in the database saves, as I have checked in the Django administration page and the xml gets updated per save button.
This is all working fine, however the issue is that when I refresh the page the graph created does not stay on the page.
ajax.js
var button = mxUtils.button('Save', function()
            {
                //var url = "{%url'login'%}"
                //var url = "{% url 'myapp:productdetail' %}";
                //location.href = '/saveData/'
                var encoder = new mxCodec();
                var node = encoder.encode(graph.getModel());
                var xml = mxUtils.getPrettyXml(node);
                var csrftoken = getCookie('csrftoken');

                $.ajax({

                    type: "POST",
                    url: "/saveData/",
                    data: { "xml": xml},
                    headers:{
                        "X-CSRFToken": csrftoken
                    },
                    success: function(data){
                        //console.log("data" + data[0])
                        //console.log(graph)
                        //var xmlDoc = data[0]

                        var xmlDoc = mxUtils.parseXml(data[0]);
                        //var xmlDoc = mxUtils.load("/saveData/").getXml();
                        //console.log("xmlDoc " + xmlDoc)
                        var node = xmlDoc.documentElement;
                        //console.log("node " + node)
                        var dec = new mxCodec(node.ownerDocument);
                        //console.log("dec " + dec)
                        //console.log("graph model " + graph.getModel())
                        dec.decode(node, graph.getModel());

                    }
                });

views.py
def saveData(request, user):
if request.method == "POST":
#Get user profile
    member = Member.objects.get(username=user)
#Get XML data once user presses save
#xmlData = request.POST['xml']
    member.data = request.POST['xml']
    member.save()
    print(member.data)
    response = JsonResponse([
        member.data
    ], safe = False);
    #return render(request, 'fastcookapp/index.html', {"xmlData": member.data})
    return HttpResponse(response, content_type="application/json")

return HttpResponse('POST is not used')

models.py
class Member(User):
data = models.TextField(null=True)

def __str__(self):
    return self.username

P.S I have no clue why my JS is not coming in colour, I have added the javascript tag and it's not working... sorry in advance

A:

I had to create an Ajax GET request and decode the mxGraph as done above.


Q:

Tensorflow/Keras - how to expose relations between categories?

I have data which is labelled with 5 categories.
Each category represent the same event of different intensity in physical world.
The importance of that fact is that category 5 is basically must stronger version of the same event as category 1 (eg earthquake).
Can someone please offer an idea how to make this knowledge available to the model (TF/Keras) ?

A:

One-Hot Encoding is common for multi-class classification problems. In your case, a category 3 event label would be encoded as [0, 0, 1, 0, 0]. You would create a model with a dense output layer with softmax activations, then to get a prediction you would take the argmax of the output layer to get the category.
If you are asking how you can embody the fact that all of your categories are variations of the same class, you may want to look into Embedding Layers. Basically an embedding layer converts a categorical (sparse) vector into a dense vector, and allows that conversion to be a learnable parameter of the model. It allows the model to group similar classes together in vector space. It's commonly used in language modelling for grouping similar words together. For example, Woman, Lady, Queen would be closer together in the embedding vector than Man, Lord, King. In your case, class 1,2,3 may be closer together than 4,5 and an embedding layer would allow your model to learn that.


Q:

file.cpp from windows to linux

I have a file.cpp which as an file.h included. This works on windows. Is there a easy way to change the code to be compiled on linux or do I have to rewrite all of it.
Thanks in advance.

A:

Some Pointers towards Porting Code to different OS:

Check all the system headers included in the file. If there are OS specific headers, put them under OS specific macros and add different header files appropriate to Linux OS
Check all the system function calls and replace them.
Check if there are any compiler specific macros or code present and change it.
Check if the data types used are supported in all OS.


Q:

Why and how were the Mongols able to invade Russia successfully?

https://en.wikipedia.org/wiki/Mongol_invasion_of_Rus%27

The campaign was heralded by the Battle of the Kalka River in 1223,
  which resulted in a Mongol victory over the forces of several Rus'
  principalities. The Mongols nevertheless retreated. A full-scale
  invasion of Rus' by Batu Khan followed, from 1237 to 1240. The
  invasion was ended by the Mongol succession process upon the death of
  Ögedei Khan. All Russian states were forced to submit to Mongol rule
  and became part of the Golden Horde empire, some of which lasted until
  1480.

Mongol invaders of Russia enjoyed a level of success never experienced by the Europeans. Why is that?

A:

The mongols, when at their best, were unified and powerful. At the time, Russian city-states and kingships had little to no unity, and as the mongols were the top dogs of their time, they easily dispatched the little true resistance they were given.
Plus, much of Russian land is plateau. The mongols were given a big boost with this as their horses and archers achieved maximum results under these conditions.
Mongols were also very self-sufficient and never lost troops easily. There have been (true) stories on how one scouting party sent by Genghis Khan nearly annihilated all of Eastern Europe and West Asia. They could survive in near intolerable conditions like Russia and Mongolia due to generations of living off the barren land. They also picked up new troops nearly everywhere they went as the Khans were very tolerant of caste and religion, as long as one also worshiped the Khan. Many great Mongolian troops and generals were farmed of conquered villages and states.
In hindsight, it may be confusing to some people seeing Russia as the big power it is today, but Russia was just groups of weak states at that time.

A:

Just a couple of thoughts.

Rus' internal weakness Due to disunity Russian feodal states were not capable to form a grand alliance.
Kievan Rus vs Russian Empire Rus had no such territory or human resources as Russia had. Napoleon seized far bigger piece than mongols did but still was too far from the true success.
Military superiority At the very least, in the 13th century mongol army was the most mobile one. That helped them not only to conquer Russian states but also to control them efficiently.
Political and administrative management Mongol conquests could be compared with Arab conquests. That was not just "robbery". They created new administrative system which included both "conquered" and "free" Russian states.


Q:

How to install PyQt4 with Python 3.6.4 (Error: Make sure you have a working Qt qmake on your PATH. )

I am having real trouble with installing PyQt4 package. I have read many documentations about this but still have not figured it out. So my first question is when I download the PyQt4 zip fail, where I have to extract it?
I have tried to extract it to the \Lib\site-packages and then from there run a PS and use the command "python configure-ng.py" then it gives me an error "Error: Make sure you have a working Qt qmake on your PATH." Although I have the QT software installed.
I found that there is two qmake folders in my system. One located "Qt\Tools\QtCreator\share\qtcreator\templates\wizards\projects" and the other located "Qt\Tools\Preview\Qt Creator 4.5.0 rc1\share\qtcreator\templates\wizards\projects". I also tried to copy the "qmake" folder to the directory where the PyQt4 files are, but still nothing.
UPDATE: So I gave up trying to install with the configure-ng.py fail and started to try adding the package with configure.py. And then first I got an error "No module named 'sipconfig'".
I found over the internet that it is caused, cause SIP is not installed and you need to installid like this . Then I encountered a error "make is not recognized as an internal or external command python" So I installed MinGW C compiler. Now I f I run it C:\PATH\main.exe I get an error:
PS G:\Programmeerimine\uus\Lib\site-packages\PyQt4_gpl_win-4.12.1\sip 4.19.7> C:\MinGW\bin\make.exe
make[1]: Entering directory 'G:/Programmeerimine/uus/Lib/site-packages/PyQt4_gpl_win-4.12.1/sip-4.19.7/sipgen'
gcc -c -O2 -Wall -DNDEBUG -DUNICODE -DQT_LARGEFILE_SUPPORT -I. -o main.o main.c
gcc: error: CreateProcess: No such file or directory
Makefile:29: recipe for target 'main.o' failed
make[1]: *** [main.o] Error 1
make[1]: Leaving directory 'G:/Programmeerimine/uus/Lib/site-
packages/PyQt4_gpl_win-4.12.1/sip-4.19.7/sipgen'
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 2

A:

So I got help form another forum. The solution is described here


Q:

Django: How to Like an Object with Ajax

Here's my View,
class ObjLike(RedirectView):
def get_redirect_url(self, *args, **kwargs):
    id = self.kwargs.get('id')
    obj = get_object_or_404(Data, id=id)
    user = self.request.user
    if user.is_authenticated():
        if user in obj.likes.all():
            obj.likes.remove(user)
        else:
            obj.likes.add(user)

So after this view how can I redirect user to the same page?
I used "return redirect(request.META['HTTP_REFERER'])" but it gives an error "name 'request' is not defined"
I can't use the get absolute URL method, i'm using this view at several places.
So, how can I do that?

A:

to like an object with ajax calls do this
first in html we want to make a like button:
<button id="like">Like!</button>

the add a script that contain the ajax:
<script>
$(document).ready(function() {
$("#like").click(function(event){
        $.ajax({
             type:"POST",
             url:"{% url 'like' Obj.id %}",
             success: function(data){
                 confirm("liked")

             }
        });
        return false;
   });

});
</script>

the we add the like url to the urlpatterns list:
url(r'like/obj/(?P<pk>[0-9]+)/', views.like, name="like"),

adding the view :
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def like(request, pk)
    obj = Obj.objects.get(id=pk)
    obj.likes += 1
    obj.save()
    return HttpResponse("liked")

Note: you can customize the like view to check if user liked already


Q:

Create MS Excel Sheet

How can I create an MS Excel sheet and download it from a Moonlight/Silverlight app? Regards Lennie
Basically I want to run a report in the Siverlight client and allow the user to download the MS Excel report.

A:

I had to do this previously, its pretty time consuming but you can write it to a XML file on the client side.
A good place to start is to create a new excel sheet save it as an XML file and then you can work out which bits need to change and then work out a way to write the correct information to the XML file.
Although as I said it will take a fair bit of time!!
Edit-
Just found this for you to take a look at-
http://www.rshelby.com/post/creating-excel-worksheet-from-silverlight.aspx


Q:

Modify a sub-part of a sub-list only

I have this list:
a = {{{0, 0}, {1, 7}, {2, 0}, {3, 2}, {4, 7}}, {{0, 0}, {1, 0}, {2, 1}, {3, 2}, {4, 7}}}

and I'd like to transform it to this:
a = {{{0, 0}, {1, 7}, {2, Na}, {3, 2}, {4, 7}}, {{0, 0}, {1, Na}, {2, 1}, {3, 2}, {4, 7}}}

ie I'd like to replace every 0 by Na except in the first sub-sub-list of each sub-list.
All I can come up with is:
Part[#, 2 ;; All, All] & /@ a  /. 0 -> Na

and it works I get
{{{1, 7}, {2, Na}, {3, 2}, {4, 7}}, {{1, Na}, {2, 1}, {3, 2}, {4, 7}}}

but the modification is not attributed to a.
How can I do that?

A:

This will work if all your first elements of the sub-lists are of the form {0,0}
a = a /. {{x_?Positive, 0} :> {x, Na}};
a

{{{0, 0}, {1, 7}, {2, Na}, {3, 2}, {4, 7}}, {{0, 0}, {1, Na}, {2,
     1}, {3, 2}, {4, 7}}}