text:
Q: File.separator and "/" work differently in a runnable jar Context
I have detected a strange behaviour of File.separator when used in a piece of code compiled as a runnable jar.
For context, I have a database that is supported by xml. The program then interacts with that database, parsing the whole document at the start, creating the objects, modifying them, and then updating the xml file when the program ends.
The actual contents and/or file type are actually irrelevant, but I have included a simple Hello World txt as an example. Either way, the file is read as an InputStream by the database (the only difference is that I'm parsing the actual xml from the that InputStream).
MWE
Database.java
import java.io.File;
import java.io.InputStream;

public class Database {
    public InputStream getInputStreamDependentSeparator(String fileName) {
        return getClass().getResourceAsStream("/resources/" + fileName);
    }

    public InputStream getInputStreamIndependentSeparator(String fileName) {
        return getClass().getResourceAsStream("/resources" + File.separator + fileName);
    }
}

Main.java
import java.io.InputStream;

public class Main {
    public static void main(String[] args) {
        Database db = new Database();

        InputStream is1 = db.getInputStreamDependentSeparator("HelloWorld.txt");

        InputStream is2 = db.getInputStreamIndependentSeparator("HelloWorld.txt");

        System.out.println(is1.toString());
        System.out.println(is2.toString());
    }
}

HelloWorld.txt
Hello World!

Problem description

*

*is1 uses / to separate directories, while is2 uses File.separator

*Running through the IDE (Eclipse), neither statement results in an exception, and produce the following output:

java.io.BufferedInputStream@5305068a
java.io.BufferedInputStream@1f32e575

*

*Compiling the code as a runnable jar (in Eclipse, right-clicking on the project, left-clicking on Export, and then following the prompts for a runnable jar), and running from the command line results in a NullPointerException thrown by is2. This is the following output:

java -jar fileSeparator.jar
sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@85ede7b
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.toString()" because "is2" is null
        at Main.main(Main.java:12)

*

*Note that the System.out.println(); statement is not meant to actually give the content of the HelloWorld.txt file, just to check if the InputStream is valid or trigger an exception otherwise

Questions

*

*Quoting directly from Oracle: EDIT: As Erwin Bolwidt pointed out, this was regarding the atg and is not applicable to jdk. Sorry for not noticing this.

When specifying values for file properties, Nucleus translates the forward slash (/) to the file separator for your platform (for example, Windows uses a backslash (\) as a file separator).

*

*This means that both File.separator and / should provide identical results. However, the MWE shows that the former is not working when running the jar, while the latter works both in the IDE and from the jar. Is this a bug? Or am I missing something, and this is the actual intended behaviour?

*I have been using File.separator since, according to this post, it is the safest way to ensure future platform compatibility. Whether this is a bug or an actual intended behaviour, how should I fix the issue? (I could just use the /, but then again I'd lose platform independency...)


text:
Q: Dropbox Python API - Upload function Let's say that I upload a text file to Dropbox via Python API.
If I constantly append 1Mb of data per day and sync it, in the Day 10 will Dropbox upload all the 10Mb and replace the old file or just 1Mb and extend to the 9Mb file that have left?

A: If you're uploading a file to Dropbox using the Dropbox Python SDK, e.g., with the files_upload method, the entire file contents has to be uploaded with every upload. The Dropbox API doesn't offer a way to just append to existing files, but I'll pass this along as a feature request.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not deserialize instance of my package out of START_ARRAY token I'm m currently having trouble connecting to my webservice on android.I use jackson-core/databind/annotation-2.2.4 and Spring RESTWebService. If I access the URL from browser I can see the JSON response: (server return List\Shop\ looks like:)
[{"id":1,"product_tmpl_id":1,"message_last_post":null,"ean13":null,"default_code":null,"name_template":"Service","image_variant":null,"active":true,"create_uid":1,"create_date":1463633587963,"write_date":1463633587963,"write_uid":1}]

From a Client endpoint (Android application) I receive this error message:
06-14 15:18:34.702 14597-14639/? E/MainActivity: Could not read JSON: Can not deserialize instance of stpi.com.rest.Products out of START_ARRAY token
at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41da0398; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of stpi.com.rest.Products out of START_ARRAY token
at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41da0398; line: 1, column: 1]
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of stpi.com.rest.Products out of START_ARRAY token
at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41da0398; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of stpi.com.rest.Products out of START_ARRAY token
at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41da0398; line: 1, column: 1]
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
at stpi.com.rest.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:83)
at stpi.com.rest.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:76)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of stpi.com.rest.Products out of START_ARRAY token
at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41da0398; line: 1, column: 1]
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:691)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:685)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1215)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:126)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2993)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
... 13 more
06-14 15:18:34.707 14597-14597/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: stpi.com.rest, PID: 14597
java.lang.NullPointerException
at stpi.com.rest.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:96)
at stpi.com.rest.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:76)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)

My main activity in android app:
package stpi.com.rest;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        new HttpRequestTask().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            new HttpRequestTask().execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.content_main, container, false);
            return rootView;
        }
    }

    private class HttpRequestTask extends AsyncTask<Void, Void, Products> {
        @Override
        protected Products doInBackground(Void... params) {
            try {
                final String url = "http://164.164.36.11:443/seis/productController/getProduct";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                Products greeting = restTemplate.getForObject(url, Products.class);
                return greeting;
            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Products greeting) {
            TextView greetingIdText = (TextView) findViewById(R.id.id_value);
            TextView greetingContentText = (TextView) findViewById(R.id.content_value);
            greetingIdText.setText(greeting.getId());
            greetingContentText.setText(greeting.getname_template());
            greetingContentText.setText(greeting.getproduct_tmpl_id());
            greetingContentText.setText(greeting.getmessage_last_post());
            greetingContentText.setText(greeting.getean13());
            greetingContentText.setText(greeting.getdefault_code());
            greetingContentText.setText(greeting.getimage_variant());
            greetingContentText.setText(greeting.getactive());
            greetingContentText.setText(greeting.getcreate_uid());
            greetingContentText.setText(greeting.getcreate_date());
            greetingContentText.setText(greeting.getwrite_date());
            greetingContentText.setText(greeting.getwrite_uid());
        }

    }

}

This is the Other class Product where I Add the id,rest variables and getters.
package stpi.com.rest;

/**
 * Created by Admin on 6/14/2016.
 */
public class Products {

    private String id;
    private String name_template;
    private String product_tmpl_id;
    private String message_last_post;
    private String ean13;
    private String default_code;
    private String image_variant;
    private String active;
    private String create_uid;
    private String create_date;
    private String write_date;
    private String write_uid;

    public String getId() {
        return this.id;
    }

    public String getname_template() {
        return this.name_template;
    }

    public String getproduct_tmpl_id() {
        return this.product_tmpl_id;
    }

    public String getmessage_last_post() {
        return this.message_last_post;
    }

    public String getean13() {
        return this.ean13;
    }

    public String getdefault_code() {
        return this.default_code;
    }

    public String getimage_variant() {
        return this.image_variant;
    }
    public String getactive() {
        return this.active;
    }

    public String getcreate_uid() {
        return this.create_uid;
    }

    public String getcreate_date() {
        return this.create_date;
    }

    public String getwrite_date() {
        return this.write_date;
    }

    public String getwrite_uid() {
        return this.write_uid;
    }

}

Can anyone help me to solve this issue?

A: As we are getting object collection to get single object I had used Product[] and it worked correctly.
private class HttpRequestTask extends AsyncTask<Void, Void, Products> {
        Products[] greeting;
        @Override
        protected Products doInBackground(Void... params) {
            try {
                final String url = "http://164.164.36.11:443/seis/productController/getProduct";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                greeting = restTemplate.getForObject(url, Products[].class);

                return greeting[0];
            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Products greeting) {
            TextView greetingIdText = (TextView) findViewById(R.id.id_value);
            TextView greetingContentText = (TextView) findViewById(R.id.content_value);
            Log.i("post exe active", greeting.getname_template());
            greetingIdText.setText(greeting.getId());
            greetingContentText.setText(greeting.getname_template());


text:
Q: "The type or namespace name 'HttpApplication' could not be found" error in .Net6 Recently I upgrade my .net 4.8 web project to .net 6. Post upgrade I am getting below error from Global.asax.cs page
public class MvcApplication : HttpApplication

CS0246    The type or namespace name 'HttpApplication' could not be found (are you missing a using directive or an assembly reference?)   ~project path\Global.asax.cs
I have tried few possible way to fix this issue, but no luck
It seems like issue is with System.Web namespace in .Net 6. I am getting maximum error because of System.Web namespace
What I can see in .net 6.0 only one class is present in System.Web that is "HttpUtility". Refer this https://learn.microsoft.com/en-us/dotnet/api/system.web?view=net-6.0
But for System.Web in .Net Framework 4.8 many class was there. Refer this.  https://learn.microsoft.com/en-us/dotnet/api/system.web?view=netframework-4.8
Can anyone please help me to understand the issue or any possible way or namespace we can use to fix this

A: It seems you have an ASP.NET application.
ASP.NET is a framework that runs under .NET Framework only.
It is not compatible with .NET 6.0 (or any .NET Core and later versions).
A new framework replaces ASP.NET for .NET (.NET Core): ASP.NET Core.
ASP.NET Core is a redesign of ASP.NET.
While both framework share some common concepts, they are different frameworks. This page list the differences between the two frameworks.
Some extensive changes might be needed in order to convert an ASP.NET project to an ASP.NET Core project.
As pointed out by @NPras, a migration guide is issued by Microsoft to provide guidance in such a task.


text:
Q: Why is ng-checked firing twice on page load I have the following code, and it seems as though ng-checked is firing my simple alert method twice when the page loads.

(function() {
  'use strict';

  angular.module('app', ['common.ajax']);
  angular.module('common.ajax', []);

  angular
    .module('app')
    .controller('loginCtrl', controller);

  controller.$inject = ['$scope', 'ajaxFactory'];

  function controller($scope, ajaxFactory) {
    $scope.alertme = activate;

    function activate() {
      ajaxFactory.getData();
    }
  }

  angular
    .module('common.ajax')
    .factory('ajaxFactory', factory);

  factory.$inject = ['$http'];

  function factory($http) {
    var service = {
      getData: getData
    };

    return service;

    function getData() {
      alert("click me");
    }
  }
})();
<script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>

<body ng-app="app" ng-controller="loginCtrl">
  <input type="checkbox" ng-checked="alertme()" ng-model="tester" />
</body>

I am just starting out on my Angular journey so any info on why this is happening would be great as I cannot seem to find anything in particular online.

A: I think you ment to use ng-click not ng-checked.
Look at the documentation: https://docs.angularjs.org/api/ng/directive/ngChecked
ngChecked is meant to be a boolean parameter, not a function.

Sets the checked attribute on the element, if the expression inside ngChecked is truthy.

A: ngChecked can take a function as a param so long that function return a truthy or falsy value like so:
const isGreaterThanOne = x => x > 1;

<body ng-app="app" ng-controller="loginCtrl">
    <input type="checkbox" ng-checked="isGreaterThanOne(2)" ng-model="tester" />
</body>


text:
Q: Resizing a allocatable array I am trying to allocate an array and want to resize the array ie., grow the array size as and when required in the program.
My sample code looks like this
program main
implicit none
integer, allocatable, dimension(:)::test1
integer i, c1, c2
c1=10
c2=5
allocate(test1(1:c1))
!  I basically want to do this
!allocate(test1(c1+1:c2))
end program main

How do I do this?


text:
Q: Python: Plotly 3D Surface Plot I am having a tough time drawing the Plotly 3d surface plot. I have a big data frame of 4000 rows and three columns. I did ask questions here and got some answers. When I try them, it takes hours for the code to run yet I see no plot. I want to confirm what I am doing is right. Because I am new to the surface plots.
My code:
import plotly.graph_objects as go
import plotly.graph_objs
import plotly
df =
index     x           y           z
0        10.2        40.5        70.5
1        30.5        30.2       570.5
.
.
4000     100.5       201.5      470.5

df['z']= [df['z'].tolist for x in df.index]
df =
index     x           y           z
0        10.2        40.5       [70.5,570.5,..,470.5]
1        30.5        30.2       [70.5,570.5,..,470.5]
.
.
4000     100.5       201.5      [70.5,570.5,..,470.5]

    zdata = [df['z'].tolist()]*len(df)
    plotly.offline.plot({"data":[go.Surface(x=df['x'].values,
                                            y=df['y'].values,
                                            z = df['z'].values)],
    "layout":plotly.graph_objs.Layout(title='Some data', autosize=False,
                      width=600, height=600,
                    scene = dict(xaxis_title='x',
                    yaxis_title='y',
                    zaxis_title='z'),
                      margin=dict(l=10, r=10, b=10, t=10))})

I would be grateful to have somebody clarify me that what I am doing to generate a surface plot is correct?

A: Here is a simple / stripped down example of a 3D surface plot to hopefully get you going.
The key message here is: Don't over complicate it.  This same logic should be fine on a DataFrame with 4000+ rows. (Granted, it'll plot ~16M data points, so it'll take a bit of time).
The key point to remember is that z must be a 2d array of the shape [x.shape[0], y.shape[0]]. Essentially meaning, if x and y are of length 10, then z must be of the shape: [10, 10].
As I don't have your complete dataset, I've synthesised the data - hope that's OK for illustration purposes.  Additionally, I've stuck with numpy for simplicity, keeping in mind that a numpy array is essentially a DataFrame column.
Simple example:
import numpy as np
from plotly.offline import plot

n = 10
x = np.arange(n)
y = x
z = np.tile(x**2, [n, 1])

data = [{'x': x,
         'y': y,
         'z': z,
         'type': 'surface'}]

plot({'data': data}, filename='/path/to/graph.html')

Output:

Something a little more fun:
n = 360
x = np.arange(n)
y = x
v = np.tile([np.sin(i*(np.pi/180)) for i in range(n)], [n, 1]).T
z = (v.T[0]*v)

data = [{'x': x,
         'y': y,
         'z': z,
         'type': 'surface'}]

plot({'data': data}, filename='/path/to/graph.html')

You'll note the plotting logic is identical.
Output:

A: When you use go.Surface, z should be a 2-dimensional matrix, and x and y should be unique values of x_axis and y_axis. This code prepares DataFrame values for using go.Surface.
x_data = df['x'].values
y_data = df['y'].values
z_data = df['z'].values

x = np.unique(x_data)
x_min = np.min(x)
y = np.unique(y_data)
y_min = np.min(y)

# Set default value of np.Nan for z matrix
z = np.empty((x.shape[0], y.shape[0]))
z[:] = np.NaN
for i in range(len(z_data)):
    z[x_data[i] - x_min, y_data[i] - y_min] = z_data[i]
z=z.transpose()

fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])
fig.show()


text:
Q: Multithreading CQRS with NServiceBus I am currently investigating using NServiceBus to solve the following problem. I just want to make sure that I am not going down the rabbit hole with this.
I have a solution based on a CQRS architecture. Essentially I have a series of commands being delivered to an endpoint via NServiceBus, I perform some processing to alter the state of the aggregate root, then fire off a series of events to notify the rest of the system of the changes.
The problem I have is that this all works great on one thread where I do not need to worry about locking down any given aggregate root while I alter the state.
We are getting to the point where one thread is not going to cut it and I need to start looking into using multiple worker threads/processes to process the messages.
There is a natural task break down based on the fact that I can process multiple aggregate roots at the same time, however I cannot process more than one message for the same aggregate root at the same time, as this will cause high contention due to the speed that the messages are being received.
I am trying to avoid the situation where I would need to lock a specific aggregate root id and instead assign an aggregate root to a queue/thread/process which will ensure that all messages from the same aggregate root are processed synchronously.
I am using a Pub/Sub model with NServiceBus to publish out the events. The problem as far as  I see it is that these events would need to be published from the same endpoint, even though the processing of that message may be delegated to another. i.e. I need to trick the system into thinking that the message was published from "MyDomainQueue" when in fact the message was processed on "MyDomainQueue-Worker1".
My plan is to create a custom distributor which will allow the main endpoint to delegate the processing of messages to worker endpoints. The distributor would allocate a queue to any give aggregate root in a round robin fashion. The main endpoint would send commands to these workers, the processing would take place, and the worker would reply with a list of events. The main endpoint would then publish the events back onto the bus.
I am looking for some feedback regarding this approach. It feels like I am working a bit to hard to get this to work and I just want to check if any one else has dealt with a similar problem. Perhaps NServiceBus is the wrong tool for the job, or perhaps my approach is just wrong. Any and all feedback is welcome.
Thanks,
PS - I also have concerns around the amount of configuration which will be required for the solution described above.

A: With regard to publishing events from different endpoints, I think you're getting a little too caught up in the concept of an event being published from one service. That's true only in the logical sense - one event should be fully owned by one logical service, however a logical service can be made up of many endpoints.
An event is not really published from a queue. When you think of the queue that an event is published from, what you really are talking about is the input queue where you send subscription requests for that event.
So, you can have multiple endpoints all publishing the same event, as long as the subscription requests for that event all go to the same place.
This is commonly the case, for instance, in a bulk vs. priority scenario, where you have two endpoints handling the same command (and then publishing the same event) except one is bulk with a long SLA, and the other has a much shorter SLA - maybe it's a big customer, or the command is coming from an actual human user waiting for a response. QueueA and PriorityQueueA both process the same command and publish the same event, but QueueA handles the subscriptions, so both processes "publish from" QueueA.
That said, have you tried just letting multiple threads access the aggregate roots? Even with some contention, you may find that with a small number of retries it may not be as contentious as you might think. I have some fairly contentious processes in production with NServiceBus and although I see the occasional evidence of contention as an exception in the log, with 5 retries I never have any of those progress to the error queue.
-- More recently, the second-level retries feature has been added which further decreases the chance of a message ending up in the error queue.
If there is that much contention, another strategy might be to maintain an in-memory list of aggregate roots currently being operated on, and then if a message comes in that should be "locked out" just call Bus.HandleCurrentMessageLater() to stick that message back on the end of the queue.


text:
Q: Json policy for allowing SetInstanceProtection I've used the following inline json policy to allow distinct IAM users to call SetDesiredCapacity:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "autoscaling:SetDesiredCapacity",
            "Resource": [
                "arn:aws:autoscaling:${region}:${userid}:autoScalingGroup:*:autoScalingGroupName/*-${username}-*"
            ]
        }
    ]
}

Each user has one autoscaling group of machines assigned to them with a name like ${companyname}-${username}-${machinetype}. After filling in the correct userid, username and region, the above inline json policy appears to work and users can call SetDesiredCapacity.
I'd like to allow users to set instance protection state on some of the instances in this autoscaling group also. For that, I tried creating this rule:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "autoscaling:SetInstanceProtection",
            "Resource": [
                "arn:aws:autoscaling:${region}:${userid}:autoScalingGroup:*:autoScalingGroupName/*-${username}-*"
            ]
        }
    ]
}

However, after adding this inline json policy to the IAM user's permissions, he still gets a "An error occurred while changing the termination protection setting of this instance". What do I need to change to this inline json policy so the user can modify instance protection state on autoscaling group instances?


text:
Q: Errno::ENOENT: No such file or directory @ rb_sysopen I am doing a project with Ruby on Rails, trying to build an E-commerce grocery shop and so have created some data to work without of my db/seed.rb file.
I created a CSV file which contains information like product, SKU, category, a site name, price, etc. and then put the following code into my seed.rb file:
require 'csv'
CSV.foreach(Rails.root.join("db/seeds_data/Store.csv"), headers: true) do |row|
  Store.find_or_create_by(upc: row[0], article_name: row[1], product_category_name: row[2],
  super_product_category_name: row[3], category_code: row[4], category_name: row[5],
  trading_area_name: row[6], ranged_articles_tw: row[7], site_name: row[8], price: row[9])
end

I then try to run, rails db:seed, and it returns this error:
Errno::ENOENT: No such file or directory @ rb_sysopen - /home/ec2-user/environment/grocerystore/db/seeds_data/store.csv
/home/ec2-user/environment/grocerystore/db/seeds.rb:2:in `<main>'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
/usr/local/rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
bin/rails:4:in `<main>'


text:
Q: Move an image to the position of a DIV using jQuery 1.3.x I have a number of small images that I display that are the size of an icon (32x32).  I want to animate them from their current position on the page to the x,y of a DIV anytime someone clicks on any of the images.  What is the best route to do this using jQuery?

A: If I understand the question correctly, then you can change the css properties to that of the image.  I.e. contain the images within the div and move the div to the location of the clicked icon.
$("#divname").css({'width' : '32', 'height' : '32' , 'left' : 'IMAGELEFT', 'top' : 'IMAGETOP'});

Assuming I understand the question.
EDIT:
To move the image to the div:
$("#image").click(function(){
  $(".block").animate({'left': 'DIVPOSITION', 'top', 'DIVPOSITION'}, 'slow', function() {
 $("#div").html("<img src=\"THEIMAGE\">");
   });
 );
});

A: It looks like there are already some jquery plugins that do what you're looking for.
From the link, CJ Object Scaler should be able to make sure that your images fit within the specified size.  JQUERY IMAGE MAGNIFY handles animation and transparency with images.

A: Ok just from the top of my head, you can use the offset() function to get the x and y coordinates of both the image and the div you want the image to move to. offset().left and offset().right.
Then I also think you'll need to make sure the image is positioned absolutely for this to work correctly. Then just use the animate() function on the image element and add the new x and y position in the animate() function, to make the image go there.
Go to docs.jquery.com and read up on the parameters the animate() function need.
I'll try and come up with code examples if you're struggling.


text:
Q: Attempting to add QLayout "" to QWidget "", which already has a layout i got a error when i want to add QWidget to QGridLayout.
i'm new with PyQt, previously i create a simple GUI without using Class, but now i want to try create a simple gui using class in python although it's make me confuse,  but i got this error
QLayout: Attempting to add QLayout "" to QWidget "", which already has a layout
QLayout::addChildLayout: layout "" already has a parent

this is my previously work without class
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyClass(object):
    def __init__(self, device_type=None, ip=None, username=None, password=None, secret=None, command=None):
        self.device_type = device_type
        self.ip = ip
        self.username = username
        self.password = password
        self.secret = secret
        self.command = command

device_list = []
#ip_list = []

def addDevice():
    device_type = str(cb_device_list.currentText())
    ip = le_ip.text()
    username = le_username.text()
    password = le_password.text()
    secret = le_enable.text()
    command = 'show tech'
    device_list.append(MyClass(device_type, ip, username, password, secret, command))
    #ip_list.append(ip)
    combobox_ip_list.addItem(ip)# Add Ip to ComboBox

    for list in device_list:
        print(list.device_type)

##################################
app = QApplication(sys.argv)
QApplication.processEvents()
app.setStyle('cleanlooks')
window = QWidget()
window.setWindowTitle("Network Automation")
############################# Input IP

# Device Type
lb_device_list = QLabel(window)
lb_device_list.setText('Device Type')
cb_device_list = QComboBox(window)
cb_device_list.addItem('cisco_ios')
cb_device_list.addItem('cisco_s300')

lb_ip = QLabel(window)
bt = QPushButton(window)
btadd = QPushButton(window)

# Ip Device
lb_ip.setText('IP Address')
le_ip = QLineEdit(window)
le_ip.setText('')
le_ip.setPlaceholderText('Input Device IP')
le_ip.setFixedWidth(150)

# username
lb_username = QLabel(window)
le_username = QLineEdit(window)
lb_username.setText('Username')
le_username.setText('')
le_username.setPlaceholderText('Input Username')
le_username.setFixedWidth(150)

# password
lb_password = QLabel(window)
le_password = QLineEdit(window)
lb_password.setText('Password')
le_password.setText('')
le_password.setPlaceholderText('Input Password')
le_password.setFixedWidth(150)

# Privilage Password
lb_enable = QLabel(window)
lb_enable.setText('Privilege Mode Password')
le_enable = QLineEdit(window)
le_enable.setText('')
le_enable.setPlaceholderText('Input Enable Password')
le_enable.setFixedWidth(150)

bt.setText('Generate')
bt.setFixedWidth(70)

btadd.setText('Add')

line = QFrame(window)
line.setFrameShape(QFrame.VLine)
line.setFrameShadow(QFrame.Sunken)
line.setLineWidth(3)

########################### Layout Ip Device List

lb3 = QLabel(window)
lb3.setText('IP Device List')
combobox_ip_list = QComboBox(window)
combobox_ip_list.setFixedWidth(170)
#combobox_ip_list.addItems(ip_list)

############################## SubLayout and Layout
hblayout = QHBoxLayout()
hblayout.addWidget(bt)
hblayout.addWidget(btadd)

sublayout = QVBoxLayout()
sublayout.addWidget(lb_device_list)
sublayout.addWidget(cb_device_list)
sublayout.addWidget(lb_ip)
sublayout.addWidget(le_ip)
sublayout.addWidget(lb_username)
sublayout.addWidget(le_username)
sublayout.addWidget(lb_password)
sublayout.addWidget(le_password)
sublayout.addWidget(lb_enable)
sublayout.addWidget(le_enable)
sublayout.addLayout(hblayout)

sublayout2 = QVBoxLayout()
sublayout2.addWidget(lb3)
sublayout2.addWidget(combobox_ip_list)
sublayout2.addStretch(1)

layout = QGridLayout(window)
layout.addLayout(sublayout,0,0)
layout.addWidget(line,0,1)
layout.addLayout(sublayout2,0,2)

btadd.clicked.connect(addDevice)

window.show()
sys.exit(app.exec_())

Now using Class (error)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Window(QMainWindow,QWidget):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('Network Automation')
        self.window = QWidget(self)
        self.lb_device_list = QLabel('Device Type',self.window)
        self.cb_device_list = QComboBox(self.window)
        self.cb_device_list.addItem('cisco_ios')
        self.cb_device_list.addItem('cisco_s300')

        self.vbox = QVBoxLayout(self.window)
        self.vbox.addWidget(self.lb_device_list)
        self.vbox.addWidget(self.cb_device_list)

        self.layout = QGridLayout(self.window)
        self.layout.addLayout(self.vbox,0,0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myapp = Window()
    myapp.show()
    sys.exit(app.exec_())

i need to create simple gui like my previously work using class

A: Placing some_layout(some_widget) is similar to some_widget.setLayout(some_layout), so in each layout you are adding it to self.window.
In addition MainWindow already has a default layout since it has certain default widget like a QStatusBar and a QMenubar so you should not add it that way, you should add it to the centralWidget, in your case it could be self.window.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Window(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        widget = QWidget(self)
        self.setCentralWidget(widget)
        self.setWindowTitle('Network Automation')
        self.lb_device_list = QLabel('Device Type')
        self.cb_device_list = QComboBox()
        self.cb_device_list.addItem('cisco_ios')
        self.cb_device_list.addItem('cisco_s300')

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.lb_device_list)
        self.vbox.addWidget(self.cb_device_list)

        self.layout = QGridLayout()
        self.layout.addLayout(self.vbox,0,0)
        widget.setLayout(self.layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myapp = Window()
    myapp.show()
    sys.exit(app.exec_())

Another observation, you should not inherit from QMainWindow and QWidget at a time since QMainWindow inherits from QWidget, it is unnecessary
Another option is to implement a class that inherits from QWidget, not from QMainWindow.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle('Network Automation')
        self.lb_device_list = QLabel('Device Type')
        self.cb_device_list = QComboBox()
        self.cb_device_list.addItem('cisco_ios')
        self.cb_device_list.addItem('cisco_s300')

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.lb_device_list)
        self.vbox.addWidget(self.cb_device_list)

        self.layout = QGridLayout()
        self.layout.addLayout(self.vbox,0,0)
        self.setLayout(self.layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myapp = Window()
    myapp.show()
    sys.exit(app.exec_())

I've also converted your implemented code into a class that inherits from QWidget:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.device_list = []
        self.setWindowTitle("Network Automation")
        ############################# Input IP

        # Device Type
        lb_device_list = QLabel(self)
        lb_device_list.setText('Device Type')
        self.cb_device_list = QComboBox(self)
        self.cb_device_list.addItem('cisco_ios')
        self.cb_device_list.addItem('cisco_s300')

        lb_ip = QLabel(self)
        bt = QPushButton(self)
        btadd = QPushButton(self)

        # Ip Device
        lb_ip.setText('IP Address')
        self.le_ip = QLineEdit(self)
        self.le_ip.setText('')
        self.le_ip.setPlaceholderText('Input Device IP')
        self.le_ip.setFixedWidth(150)

        # username
        lb_username = QLabel(self)
        self.le_username = QLineEdit(self)
        lb_username.setText('Username')
        self.le_username.setText('')
        self.le_username.setPlaceholderText('Input Username')
        self.le_username.setFixedWidth(150)

        # password
        lb_password = QLabel(self)
        self.le_password = QLineEdit(self)
        lb_password.setText('Password')
        self.le_password.setText('')
        self.le_password.setPlaceholderText('Input Password')
        self.le_password.setFixedWidth(150)

        # Privilage Password
        lb_enable = QLabel(self)
        lb_enable.setText('Privilege Mode Password')
        self.le_enable = QLineEdit(self)
        self.le_enable.setText('')
        self.le_enable.setPlaceholderText('Input Enable Password')
        self.le_enable.setFixedWidth(150)

        bt.setText('Generate')
        bt.setFixedWidth(70)

        btadd.setText('Add')

        line = QFrame(self)
        line.setFrameShape(QFrame.VLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setLineWidth(3)

        ########################### Layout Ip Device List

        lb3 = QLabel(self)
        lb3.setText('IP Device List')
        self.combobox_ip_list = QComboBox(self)
        self.combobox_ip_list.setFixedWidth(170)
        #combobox_ip_list.addItems(ip_list)

        ############################## SubLayout and Layout
        hblayout = QHBoxLayout()
        hblayout.addWidget(bt)
        hblayout.addWidget(btadd)

        sublayout = QVBoxLayout()
        sublayout.addWidget(lb_device_list)
        sublayout.addWidget(self.cb_device_list)
        sublayout.addWidget(lb_ip)
        sublayout.addWidget(self.le_ip)
        sublayout.addWidget(lb_username)
        sublayout.addWidget(self.le_username)
        sublayout.addWidget(lb_password)
        sublayout.addWidget(self.le_password)
        sublayout.addWidget(lb_enable)
        sublayout.addWidget(self.le_enable)
        sublayout.addLayout(hblayout)

        sublayout2 = QVBoxLayout()
        sublayout2.addWidget(lb3)
        sublayout2.addWidget(self.combobox_ip_list)
        sublayout2.addStretch(1)

        layout = QGridLayout(self)
        layout.addLayout(sublayout,0,0)
        layout.addWidget(line,0,1)
        layout.addLayout(sublayout2,0,2)

        btadd.clicked.connect(self.addDevice)

    def addDevice(self):
        device_type = str(self.cb_device_list.currentText())
        ip = self.le_ip.text()
        username = self.le_username.text()
        password = self.le_password.text()
        secret = self.le_enable.text()
        command = 'show tech'
        self.device_list.append(MyClass(device_type, ip, username, password, secret, command))
        #ip_list.append(ip)
        self.combobox_ip_list.addItem(ip)# Add Ip to ComboBox

        for list in self.device_list:
            print(list.device_type)

class MyClass(object):
    def __init__(self, device_type=None, ip=None, username=None, password=None, secret=None, command=None):
        self.device_type = device_type
        self.ip = ip
        self.username = username
        self.password = password
        self.secret = secret
        self.command = command
#ip_list = []

##################################
app = QApplication(sys.argv)
QApplication.processEvents()
app.setStyle('cleanlooks')
window = Widget()
window.show()
sys.exit(app.exec_())


text:
Q: Symmetric Regular Matrix, Matrix Norm I have solved an exercise and would like to know if my solution is correct.
The Exercise
$\kappa_p(A) :=\|A\|_p\|A^{-1}\|_p, 1 \leq p \leq \infty, A \in \mathbb R^{n \times n}$
Show that for a symmetric regular, but not necessarily
positive definite matrix $A \in \mathbb R^{n \times n}$ it holds that:
$\kappa_2(A) = \frac{|\lambda|_{max}(A)}{|\lambda|_{min}(A)}$
where $|\lambda|_{max}$ is the absolute value of the eigenvalue with biggest absolute value and $|\lambda|_{min}$ with the smallest.
My solution
If A $\in \mathbb R^{n \times n}$ is a symmetric regular matrix, there is an orthonormal
base in $\mathbb R^n$ where A has a diagonal representation
A = diag$(\lambda_1,...,\lambda_n)$
with eigenvalues arranged according to
$|\lambda_1| \leq .... \leq |\lambda_n|$
Hence $|\lambda_1| = |\lambda|_{min}(A)$ and $|\lambda_n| = |\lambda|_{max}(A)$.
Naturally we obtain
$\|A\|_2 = max_{\|x\|_2 = 1} \|Ax\|_2 = |\lambda|_{max}(A)$
Note that since A is regular, then $\lambda_k \neq 0 $ for k=1,..,n. Moreover within the same base $A^{-1}$ has also a diagonal representation: $A^{-1}$ = diag$(\frac{1}{\lambda_1},...,\frac{1}{\lambda_n})$. Hence the statement above is true since $\|A^{-1}\|_2 = \frac{1}{|\lambda|_{min}(A)}$

A: It looks good! It's even better if you could elaborate on the reason why $\max_{\|x\|_2 = 1} \|Ax\|_2 = |\lambda|_{\max}(A)$. (The orthogonality of the basis plays an important role here.)


text:
Q: Webpack doesn't compile my javascript file due to Regexp I'm working on a Symfony 4 project using Webpack Encore. Using yarn encore dev, I get this error :
ERROR  Failed to compile with 2 errors                                 11:45:38

These dependencies were not found:

* core-js/modules/es.regexp.exec in ./assets/js/poteauxskip.js
* core-js/modules/es.string.match in ./assets/js/poteauxskip.js

To install them, you can run: npm install --save core-js/modules/es.regexp.exec core-js/modules/es.string.match

And the Regexp expression doesn't work. I tried to install as they say, but it's the beginning of all sorts of problems. But mainly, it doesn't solves the main problem, which is: why doesn't this work? I see no reason to import anything in my javascript file to use Regexp, I found no mention of this in my whole research for a solution.
poteauxskip.js file :
const $ = require('jquery');

$(".tableau").addClass("d-none");

$(".serie").change(function(){
    updateTableaux();
});

function updateTableaux() {
    var serie1 = $("select#serie1").val() == '?' ? '[0-9A-F]' : $("select#serie1").val();
    var serie2 = $("select#serie2").val() == '?' ? '[0-9A-F]' : $("select#serie2").val();
    var serie3 = $("select#serie3").val() == '?' ? '[0-9A-F]' : $("select#serie3").val();
    var serie4 = $("select#serie4").val() == '?' ? '[0-9A-F]' : $("select#serie4").val();
    var serie5 = $("select#serie5").val() == '?' ? '[0-9A-F]' : $("select#serie5").val();
    var serie6 = $("select#serie6").val() == '?' ? '[0-9A-F]' : $("select#serie6").val();

    var regex = new Regexp("/" + serie1 + serie2 + serie3 + serie4 + serie5 + serie6 + "$/");

    alert("12".match(regex));
}

The alert works if I test it for something else. The other variables also work if I use it without any Regexp. Actually, the new Regexp() or the string.match() are enough to get a compilation error.
package.json :
{
  "devDependencies": {
    "@symfony/webpack-encore": "^0.27.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper": "^1.0.1",
    "popper.js": "^1.15.0",
    "sass-loader": "^7.0.1",
    "webpack-notifier": "^1.6.0"
  },
  "name": "hyperbolic-world",
  "version": "2.0.0",
  "description": "Pour favoriser l'immersion dans un espace hyperbolique.",
  "main": "index.js",
  "author": "Julien Busset",
  "license": "CC-BY-4.0",
  "directories": {
    "test": "tests"
  }
}

webpack.config.js :
var Encore = require('@symfony/webpack-encore');

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Add 1 entry for each "page" of your app
     * (including one that's included on every page - e.g. "app")
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if you JavaScript imports CSS.
     */
    .addEntry('app', './assets/js/app.js')
    .addEntry('poteauxskip', './assets/js/poteauxskip.js')
    //.addEntry('page1', './assets/js/page1.js')
    //.addEntry('page2', './assets/js/page2.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // enables @babel/preset-env polyfills
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })

    // enables Sass/SCSS support
    .enableSassLoader()
    //.addStyleEntry('global', './assets/scss/global.scss')

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes()

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()

    // uncomment if you use API Platform Admin (composer req api-admin)
    //.enableReactPreset()
    //.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();

A: Problem solved by adding core-js with yarn add core-js --dev.


text:
Q: What'll change about maven extensions according to this line in apache doc? I found this note in the Maven's documentation:

You can add elements to this classloader by extensions. These are loaded into the same place as ${maven.home}/lib and hence are available to the Maven core and all plugins for the current project and subsequent projects (in future, we plan to remove it from subsequent projects).

I couldn't understand what they mean by "subsequent projects" here. As far as I understand, extensions are enhancements to lifecycle phases of Maven and are not project specific. So it makes sense to work for all the Maven projects.
Question: Can anyone explain what this statement means "in future, we plan to remove it from subsequent projects"

A: First an extensions can be extensions of a life cycle but not need to. You can implement an extensions also as an EventSpy for example.
This documentation is related to the Core Classloader which is available within such extensions and makes it also possible to enhance it via an extensions. This classloader contains those files from ${maven.home}/lib which is not a good idea and not necessary. It would be better having only the Maven Plugin API there and it's instances which are currently used and not more...
There existing some extensions like Wagon which are using to make a transport in special cases possible which could be project specific.
Starting with Maven 3.3.1 the core extensions mechanism has been improved to make loading project specific extensions more simpler which means they are located into ${maven.projectBasedir}/.mvn/extensions.xml file and also being loading from an repository. Before 3.3.1 you need to do that manually via mvn -Dmaven.ext.class.path=extension.jar.


text:
Q: Save as .PARQUET file in Logic App workflow How can I save the output file from Run query and list results in a .PARQUET file format.
This is my current workflow.

My Logic App is working, But the file .parquet created are not valid every time I view it on Apache Parquet Viewer
Can someone help me on this matter. Thank you!
Output:

A: I see that you are trying to add .parquet to the csv file you are receiving but that's not how it will be converted to parquet file.
One of the workarounds that you can try is to get the csv file and then add Azure function which can convert into parquet file and then adding the azure function to logic app.
Here is the function that worked for me:
BlobServiceClient blobServiceClient = new BlobServiceClient("<YOUR CONNECTION STRING>");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("<YOUR CONTAINER NAME>");
BlobClient blobClient = containerClient.GetBlobClient("sample.csv");

//Download the blob
Stream file = File.OpenWrite(@"C:\Users\<USER NAME>\source\repos\ParquetConsoleApp\ParquetConsoleApp\bin\Debug\netcoreapp3.1\" + blobClient.Name);
await blobClient.DownloadToAsync(file);
Console.WriteLine("Download completed!");
file.Close();

//Read the downloaded blob
Stream file1 = new FileStream(blobClient.Name, FileMode.Open);
Console.WriteLine(file1.ReadToEnd());
file1.Close();

//Convert to parquet
ChoParquetRecordConfiguration csv = new ChoParquetRecordConfiguration();
using (var r = new ChoCSVReader(@"C:\Users\<USER NAME>\source\repos\ParquetConsoleApp\ParquetConsoleApp\bin\Debug\netcoreapp3.1\" + blobClient.Name))
{
        using (var w = new ChoParquetWriter(@"C:\Users\<USER NAME>\source\repos\ParquetConsoleApp\ParquetConsoleApp\bin\Debug\netcoreapp3.1\convertedParquet.parquet"))
        {
            w.Write(r);
            w.Close();
         }
}

after this step you can publish to your azure function and add the Azure function connector to your logic app
You can skip the first 2 steps (i.e.. Read and Download the blob) and get the blob directly from logic app and send it to your azure function and follow the same method as above. The generated parquet file will be in this path.
C:\Users\<USERNAME>\source\repos\ParquetConsoleApp\ParquetConsoleApp\bin\Debug\netcoreapp3.1\convertedParquet.parquet

Here convertedParquet.parquet is the name of the parquet file. Now you can read the converted parquet file in Apache Parquet reader.
Here is the output


text:
Q: Foreign key fields different databases. Django Is that possible to have model with foreign key fields on different databases?
example:
class MultiBDModel(models.Model):
    db1_user = models.ForeignKey(User) # here suppose to be foreign key on `db1`
    db2_user = models.ForeignKey(User) # and here on `db2`

maybe copy somehow User. Apply for it custom manager. Which returns query set with using='db1'
in settings.py:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'db1',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    },

    'website': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'db2',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.              # Set to empty string for default. Not used with sqlite3.
    }
}

A: No. As written by @ignacio-vazquez-abrams, one model must have all fields in the same database.

BUT
As an alternative, you could use a proxy model to link between models from two different databases.
Aim
One model should provide the fields from db1 and db2 at the same time
General trick

*

*You have the model ContactMessage from db1, that we will name legacy_db. We suppose you don't want to touch to this model since it comes from another project.

*Create a proxy model ProxyContactMessage, it has the same attributes than ContactMessage.

*Use a database router to tell Django where to look in legacy_db for ProxyContactMessage objects.

*Add a new model ExtendedContactMessage with the fields you would like to add. Declare a OneToOneField with ProxyContactMessage. This data will be saved to your db2 django_db.

*Your proxy model cannot hold the new fields since it's abstract, but it can have methods that ask the related ExtendedContactMessage object (if any). Add the callables you want.

Example
In your legacy_app/models.py, the model on db1 legacy_db is:
class ContactMessage(models.Model):
    subject = models.CharField(max_length=255)
    message = models.TextField()
    created_at = models.DateTimeField()
    created_by = models.CharField(max_length=255)

    class Meta:
        managed = False
        db_table = 'contact_message'

    def __unicode__(self):
        return self.subject

Therefore you create in myapp/models.py:
class ProxyContactMessage(ContactMessage):
    class Meta:
        proxy = True
        verbose_name = 'Contact message'
        verbose_name_plural = 'Contact messages'

    def add_extension(self):
        e = ExtendedContactMessage(contact_message=self)
        e.save()
        return e

    def mark_as_processed(self):
        try:
            e = self.extendedcontactmessage
        except ExtendedContactMessage.DoesNotExist:
            e = self.add_extension()
        e.mark_as_processed()

    def processed(self):
        return self.extendedcontactmessage.processed

    def processed_at(self):
        return self.extendedcontactmessage.processed_at

class ExtendedContactMessage(models.Model):
    contact_message = models.OneToOneField(ProxyContactMessage)
    processed = models.BooleanField(default=False, editable=False)
    processed_at = models.DateTimeField(null=True, default=None, editable=False)

    def mark_as_processed(self):
        self.processed = True
        self.processed_at = timezone.now()
        self.save()

Note that only the non abstract model ExtendedContactMessage will be saved in db2, since ProxyContactMessage is abstract.
In settings.py, set DATABASE_ROUTERS with the class
class LegacyRouter(object):
    """
    A router to control all database operations on models in the
    legacy database.
    """
    def db_for_read(self, model, **hints):
        if model.__name__ == 'ProxyContactMessage':
            return 'legacy_db'
        return None
    def db_for_write(self, model, **hints):
        """
        Attempts to write in legacy DB for ContactMessage.
        """
        if model.__name__ == 'ProxyContactMessage':
            return 'legacy_db'
        return None

Your default router sends everything to db2.
Finally you may have an admin class like:
def mark_as_processed(modeladmin, request, queryset):
    for obj in queryset:
        obj.mark_as_processed()
mark_as_processed.short_description = "Mark as processed"

class ProxyContactMessageAdmin(admin.ModelAdmin):
    list_display = (
        'subject',
        'message',
        'created_at',
        'created_by',
        'processed',
        'processed_at',
    )
    actions = (mark_as_processed,)
admin.site.register(ProxyContactMessage, ProxyContactMessageAdmin)

Related:
Use a router for the proxy class
"Hack" the app_name in Meta
Catch the queryset

A: No. The ORM cannot do anything the database engine isn't capable of.


text:
Q: Importing table into database (DB2) I have a table which contains an XML type column. I make export for this table using IXF format. when I tried to make import for this table, it gives me error saying you may use File Type Modifier (FORCECREATE) or You should use db2look tool to extract information from the table then make Insert.
I do not know how to use File Type Modifier (FORCECREATE)? Can anyone expalin?
What is db2look tool? where can I find this tool? How to use it? I searched alot but no website talks about those tools!

A: What you wrote could have several possible causes. Without the concrete error message it's hard to find the exact problem. On this page you find several problems that require the use of FORCECREATE: Link
With that you might be able to correct the cause and don't need to use FORCECREATE or DB2LOOK.

Import with FORCECREATE:
The modifier is just an parameter for the import-command:
db2 import from <file> of ixf modified by forcecreate replace_create into <tab>

You can get an short reference for the import-command in the commandline:
db2 ? import

Or read the details in IBMs very comprehensive online docmentation

DB2LOOK-Tool:
The db2look-tool ist part of db2 (at least in v.9.5 on windows). Just enter db2look in commandline, if it is installed you get short parameter overview. Again, the IBM online documentation would provide you with detailed information.


text:
Q: Bootstrap modal show error I'm using bootstrap for my website design and angular to communicate with the server.
The problem I am having is that whenever I try to open a bootstrap modal I get this error:

Uncaught Error: Syntax error, unrecognized expression: [name=]

This is the button tag:
<button type="button" class="btn btn-primary" ng-click="post()">Register</button>

And the angular scope:
$scope.registerAction = function() {
  $('#registerModal').modal('show')
}

What is strange is that if I open a browser console and enter
$('#registerModal').modal('show');
It works


text:
Q: "EXCEPTION: Unexpected directive value 'undefined' on the View of component" in nested components I have two AngularJS 2.0 components:
Comment :
import {Component, Injectable, View, Input} from 'angular2/core';
import {Comments} from './comments.component';

@Injectable()

@Component({
    selector: 'comment'
})

@View({
    templateUrl: 'res/templates/components/comment.component.html',
    directives: [Comments]
})

export class Comment {
    @Input() comment;
    @Input() commentable = false;
}

Comments :
import {Component, Injectable, View, Input} from 'angular2/core';
import {CommentsService} from './../services/comments.service';
import {RouteParams} from 'angular2/router';
import {Comment} from './Comment.component';

@Injectable()

@Component({
    selector: 'comments',
    providers: [CommentsService]
})

@View({
    templateUrl: 'res/templates/components/comments.component.html',
    directives: [Comment]
})

export class Comments {
    @Input() ID;
    public comments;
    public commentsService: CommentsService;
    public routeParams: RouteParams;

    constructor (routeParams: RouteParams, commentsService: CommentsService) {
        var self = this;

        self.routeParams = routeParams;
        self.commentsService = commentsService;
    }

    ngOnInit()   {
        var self = this;

        if (self.ID !== undefined)
            self.comments = self.commentsService.comments[self.ID];
        else if (self.routeParams.params['id'] !== undefined)
            self.comments = self.commentsService.comments[self.routeParams.params['id']];
        else
            self.comments = undefined;
    }
}

comment.template :

{{comment.author.name}} {{comment.author.surname}}

{{comment.publication | date:"MM/dd/yy"}}

{{comment.body}}

    <comments *ngIf="commentable" [ID]="comment.ID"></comments>

comments.template :

    <comment *ngFor="#comment of comments" [comment]="comment" [commentable]="true"></commento>

In Comments' template I have an Angular Loop that prints multiple Comment components. In Comment's template I have an Angular ngIf that, if var commentable is true, prints a Comments component. When I run it I get:
EXCEPTION: Unexpected directive value 'undefined' on the View of component 'Comment'

A: I often get this error when I've imported something that doesn't exist. Usually this means there's a misspelling in my import or something of the same nature.
For instance I get this error when I try to import:
import {Comment} from './Comment.component';

When I actually mean:
import {CommentComponent} from './Comment.component';

A: There is a way to solve the circular dependency problem.
import {forwardRef} from 'angular2/core';
import {Comment} from './Comment.component';

...
directives: [forwardRef(() => Comment)]
})

I have tried this with 2.0.0-beta.10 and it works fine. See comment by tlancina in this issue report on github for more information.

A: A circular TypeScript import dependency can cause this. (I just ran into this)
For me:

*

*A is the parent component, and imports and exports B, C, D. for convenience.

*A tries to render B

*B imports C from A and tries to render C.
As soon as I add C to the directives block of B, I get that error (whether it is in B's template or not.) Really, since A depends on B, the minute I import anything from A into B's block I get

Unexpected directive value 'undefined'

@Eirc Martinez is right and you'll have to find a way around that circular dependency.

A: I got a problem something like that. Although this is case sensitive problem. Finally solve this.
courses.component.ts
import {Component} from 'angular2/core'

@Component({
selector: 'courses',
template: '
Courses
'
})

export class coursesComponent{

}

The mistake is coursesCompomnent class should be CoursesCompomnent. Just C is capital letter.
app.component.ts
import { Component } from 'angular2/core';
import{CoursesComponent} from './courses.component';

@Component({
selector: 'my-app',
template: '
Hello Angular
<courses></courses>',
directives: [CoursesComponent]
})
export class AppComponent {

}

https://github.com/angular/angular/issues/7526


text:
Q: failed to reinstall apache2 and php I'm a newbie and I messed up with a server trying to reinstall apache2 and php, I did extensive searches inside this forum and in the interwebs but no solution for similar problems helped me.
At the moment my web server downloads files instead of opening the web pages so i'm trying to clean up my php installation, I think I messed up my package list or php installation.
apt-get install php5
    # apt-get install php5Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 php5 : Depends: libapache2-mod-php5 (>= 5.3.10-1ubuntu3.25) but it is not going to be installed or
                 libapache2-mod-php5filter (>= 5.3.10-1ubuntu3.25) but it is not going to be installed or
                 php5-cgi (>= 5.3.10-1ubuntu3.25) but it is not going to be installed or
                 php5-fpm (>= 5.3.10-1ubuntu3.25) but it is not going to be installed
        Depends: php5-common (>= 5.3.10-1ubuntu3.25) but it is not going to be installed
 php5.6-fpm : Depends: php5.6-common (= 5.6.26-1+deb.sury.org~precise+1) but 5.6.26-2+deb.sury.org~precise+1 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

apt-get install php
# apt-get install phpReading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 php : Depends: php7.0 but it is not going to be installed
 php5.6-fpm : Depends: php5.6-common (= 5.6.26-1+deb.sury.org~precise+1) but 5.6.26-2+deb.sury.org~precise+1 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

apt-get -f install
# apt-get -f installReading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following extra packages will be installed:
  php5.6-fpm
Suggested packages:
  php-pear
The following packages will be upgraded:
  php5.6-fpm
1 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.
1 not fully installed or removed.
Need to get 0 B/1569 kB of archives.
After this operation, 0 B of additional disk space will be used.
Do you want to continue [Y/n]? Y
dpkg: dependency problems prevent configuration of php5.6-fpm:
 php5.6-fpm depends on php5.6-common (= 5.6.26-1+deb.sury.org~precise+1); however:
  Version of php5.6-common on system is 5.6.26-2+deb.sury.org~precise+1.
dpkg: error processing php5.6-fpm (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                       Errors were encountered while processing:
 php5.6-fpm
E: Sub-process /usr/bin/dpkg returned an error code (1)

any help will be appreciated.
SOLUTION:
sudo dpkg --remove --force-depends php5.6*
sudo apt-get autoclean
sudo apt-get install php php5.6

looks like the problem is solved, I'm not 100% sure because my web server still doesn't interpret php but I'm not getting those pesky installation errors anymore.

A: Open terminal and type
  sudo dpkg --configure -a

If it doesn't help then do this
  sudo apt autoremove <packagename>

If this doesn't help then you
Need an internet connection.Type in terminal
  sudo apt-get autoclean

remove sources.list file.and create new sources.list...
sudo rm /etc/apt/sources.list

Then, type in
sudo software-properties-gtk

This will open software-properties-gtk and a newsources.list will be created automatically.
Then change the server to US or to any other server of your choice. You must enable repositories from the new dialog in order to create new sources.list.
Tick all the boxes then click on Revert then click close.
Need to restore default repositories
 sudo apt-get update && sudo apt-get dist-upgrade -y

(it is good practice to backup this file before installing to recover if such things happen)
Now install anything!
UPDATE :
 sudo apt-get autoclean
 sudo dpkg --remove --force-depends   *put here all the things which are listed in ur Depends: *
  sudo apt-get install -f

Update 2:
Create a dummy initscript to fool dpkg:(use nano/gedit/vim)
 sudo nano /etc/init.d/php5.6-fpm

Enter the following:
 #!/bin/bash
  exit 0

Save the file, set execution permission (sudo chmod 755 /etc/init.d/php5.6-fpm) and try to sudo apt-get remove php5.6-fpm again.
Dot this for all packages.


text:
Q: Nodejs http-proxy server crash on socket.io connection I have issue on my Nodejs proxy server with socket hang up error.
Server crashes when refreshing browser on 'app.example.com'. Connection working as it should be and page is loading correctly.
I'm using http, http-proxy, cluster, domain, express, socket.io node modules.
I added code below to prevent crash, but it made every request really slow.
process.on('uncaughtException', err => { console.log('Uncaught Exception', err)}

What I'm doing wrong to have this issue? I tried to add connection check on socket.io and express.io and also to proxy server with domain module without any help.
Here is some pages I readed
http://www.clock.co.uk/blog/preventing-http-raise-hangup-error-on-destroyed-socket-write-from-crashing-your-nodejs-server
How to debug a socket hang up error in NodeJS?
Socket.IO server hangs up
"Error: socket hang up" with Express
What can cause this issue?
proxy_server.js
const http = require('http'),
      httpProxy = require('http-proxy'),
      domain = require('domain'),
      cluster = require('cluster'),
      numCpus = require('os').cpus().length

if(cluster.isMaster) {
    for(let i = 0;i < numCpus;i++) {
        cluster.fork()
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} closed at ${new Date()}\nRestarting`)
        cluster.fork()
    })
} else {

    const server = http.createServer((req, res) => {
        let host = req.headers.host

        let reqd = domain.create()
        reqd.add(req)
        reqd.add(res)

        // On error dispose of the domain
        reqd.on('error', err => {
            console.log('Error', err, req.url)
            reqd.dispose()
        })

        let proxy = new httpProxy.createProxy({
            target: 'localhost'
        })

        let subdomain = host.split('.')[0]
        switch(subdomain) {
            case 'app':
                proxy.web(req, res, { target: 'http://localhost:3010' }, err => {  } )
                break
            default:
                proxy.web(req, res, { target: 'http://localhost:3000' }, err => {  } )
                break
        }
    }

    server.listen(80)
    server.on('upgrade', (req, socket, head) => {
        proxy.ws(req, socket, head)
    })
}

app.js
const express = require('express'),
      app = express()
      io = require('socket.io')(app),

app.use((req, res, next) => {
    req.socket.on('error', () => {
        console.log('Error on req socket')
    })
    res.socket.on('error', () => {
        console.log('Error on res socket')
    })
    next()
})

... my application configs ...

io.on('connection', socket => {
    if(socket.connected)
        socket.emit('connected', { response: { success: true } })
})

app.listen(3010)

client.js
$(document).ready(() => {
    let socket = io.connect('app.example.com')

    socket.on('connected', () => { console.log('✓ Socket connected!') }
    socket.on('disconnect', () => { console.log(' Socket disconnected!') }
    socket.on('error', (err) => { console.log(' Socket error!\n', err) }
}

These happen everytime when I refresh page on app.example.com, page loading normally and socket.io connection works normally, but somehow it crashes my proxyserver and cluster fork it up again.
Client console.log
✓ Socket connected!

WebSocket connection to 'ws://app.example.com/socket.io/?EIO=3&transport=websocket&sid=sRs29QgeORgPFiIKAAAC' failed: Connection closed before receiving a handshake response

Proxy service crash
Error: socket hang up
    at createHangUpError (_http_client.js:250:15)
    at Socket.socketOnEnd (_http_client.js:342:23)
    at emitNone (events.js:91:20)
    at Socket.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:926:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

Worker 2208 closed at Wed May 11 2016 18:08:39 GMT+0300 (EEST)
Restarting
Worker 7153 started succesfully

A: ✓ Found and fixed the problem
I removed this part, and socket hang up error was gone!!
server.on('upgrade', (req, socket, head) => {
    proxy.ws(req, socket, head)
})

This was documented on https://github.com/nodejitsu/node-http-proxy nodejitsu github page and I tried that node-http-proxy but changed back to http-proxy module, but forgot to remove that part out. Finally it's working.
//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
   proxy.ws(req, socket, head);
});


text:
Q: Is there any equivalent of XAMPP for Pylons? I'd like to get started with Pylons, to be used on a Windows machine as a local web server. Is there any equivalent of e.g. XAMPP for Pylons that would set up everything with one installer?
Edit: I've just discovered the Pylons web server. Could I use this to serve pages to computers on a LAN?

A: One thing that you could do is use mod_wsgi with XAMPP. Unfortunately I am not aware of any installers for that combination.
You almost never want to use the web server built into the framework, but Pylons uses Paste, which is quite a bit more capable than most stock web servers so that could be an acceptable alternative if you don't need httpd.

A: pylons can be installed using easy_install or unzipping the tarball and running "python setup.py install" (like any python package).
the great google god machine says it's possible to run a wsgi app under IIS(shudder),
other than that, once you have your pylons application written, consider running it as a windows service


text:
Q: Are important features or noise model agnostic? I want to select important features of a given dataset which contains a lot of noisy features. My question is general: If I select features, by let's say Recursive feature elimination or L1 penalty using one algorithm, does that separate noise from important features once and for all? Basically, would it be right approach to train a new model with features selected from a different algorithm or same algorithm with different hyperparameters?

A: Short Answer: Yes and no, depending on what you mean by 'important'.
Long Answer: Let's consider using features $X := (x_1, \dots, x_d) \in \mathcal{X}$ to predict target $y \in \mathcal{Y}$. For instance $\mathcal{Y} = \{0, 1\}$ for some binary classification problems and $\mathcal{Y} \subset \mathbb{R}$ for single-output regression problems.
There are three related but different notions you might want to consider.

*

*Feature Importance: A score that quantifies how important a feature is to a specific model for generating predictions/decisions. One such score is the Mean Absolute SHAP values. As a reminder, SHAP values are Shapley values computed using as the characteristic function $S \to v(S)=f_S(x_S)$ the actual model decision made by a model trained with features in the coalition $S$. We take the absolute value because it can be negative but any deviation from $0$ is a sign of 'importance/significance' and we take the mean because it depends on specific feature values whereas we want a property/characteristic of a feature (not a specific value thereof).

*Feature Usefulness: A score that quantifies the contribution of a feature to the performance of a specific model. One possible implementation is (a score proportional to) Shapley values using as the characteristic function $S \to v(S)$ the (cross-validated) performance of the specific model using features $x_S$ in the coalition.

*Feature Potential: A score that quantifies the intrinsic worth of a feature in a set of features for predicting your target $y$. One possible implementation is (a score proportional to) Shapley values using as the characteristic function $S \to v(S)$ the mutual information $I(y; x_S)$ between the target $y$ and the set of features $x_S$ in the coalition. Note that the mutual information $I(y; x_S)$ is tightly related to the highest performance you may achieve consistently using features $x_S$ to predict $y$ (no matter what model you use). See https://arxiv.org/abs/2107.08066 for more details.
Feature importance and feature usefulness are (obviously) model-specific, while feature potential is not!
In general, because a feature is important does not make it useful! Feature importance has nothing to do with model performance; they don't even depend on the target $y$!
If you pick a random model, you can compute feature importance for any feature and some can be much bigger than others. It does not make features with high importance scores more useful than features with low importance score!
By the way, for this reason and many others, you should never use Recursive Feature Elimination for feature selection. See this blog post for more details on why you should not use RFE: https://blog.kxy.ai/why-you-should-stop-using-recursive-feature-elimination/.
In general, because a feature is useful for one model does not make it useful for another! In other words, using one model to select features that you will then use in another model can be disastrous as already noted by @Sycorax.
When selecting features, you want to keep features that are useful to the specific type of models you are training, not features that are important or have potential. Checkout this page for some robust feature selection alternatives in Python: https://blog.kxy.ai/tag/feature-selection/.
Finally, the only reason you could consider a feature noise is if its feature potential is 0.
When a feature has 0 feature potential, you can conclude that it cannot help you predict the target $y$, no matter which model you use, when it is used either by itself or in conjunction with a subset of other features in $X$.
For instance, when you use Shapley values with the mutual information as the characteristic function, the feature potential score of feature $x_i$ reads:
$$P_X(x_i) \propto \sum_{S} \left[I(y; x_S \cup \{x_i\})- I(y; x_S)\right] = \sum_{S} I(y; x_i | x_S),$$
where the sum is over all feature subsets of $X$ that do not contain $x_i$.
Note that $I(y; x_S \cup \{x_i\}) \geq I(y; x_S)$, so $P_X(x_i)=0$ if and only if $I(y; x_S \cup \{x_i\}) = I(y; x_S)$ for any possible subset of $X$.
In particular, if you take $S=\emptyset$ the empty set, you get $I(y; x_i)=0$, which implies $y$ and $x_i$ are statistically (unconditionally) independent (a.k.a you cannot predict $y$ using $x_i$ by itself).
Also, $I(y; x_i | x_S)=0$ for all subset $x_S$ of $X$ implies that, if a feature has zero potential, then it is statistically independent from the target $y$ conditional on any subset of other features in the candidate vector $X$.
From an ML/stats standpoint, for a feature $x_i$ to be worth using in a supervised learning problem, it ought to be statistical dependent to the target $y$ either unconditionally, or conditional on some other features you are using. If this is not the case, the feature has no potential (usefulness).
However, the notion of feature potential is tied to the candidate set $X$ you are using. $x_i$ might very well have $0$ potential with respect to a candidate set, but some potential with respect to another.
Example: If $P_X(x_i)=0$ and $I(y; x_i|x_{S^*}) > 0$ then $P_{X \cup S^*} = I(y; x_i|x_{S^*}) > 0$. In plain english, in this example, while $x_i$ cannot be helpful to predict $y$ when used either by itself or in conjunction with some features in vector $X$, you can however do better when predicting $y$ with feature $x_i$ and features $x_{S^*} \not\subset X$ compared to using only features $x_{S^*}$.


text:
Q: Youtube PHP API: Verify a youtube username matches up with authentication token I have a web application where I'm having the user log into youtube to authorize my web application to access their account.  However, I need their youtube user name to actually list their uploaded videos, and I want to ensure that the youtube username they provide matches up with the account they used to authorize with.  In other words, I only want the user to be able to share videos that they've uploaded, and not someone else's. Is there a way to do this?
I had done this before with C# .Net with the following code:
YouTubeRequestSettings yt_settings = new YouTubeRequestSettings(<devID name>, devKey, auth);
YouTubeRequest yt_request = new YouTubeRequest(yt_settings);

Uri uri = new Uri("http://gdata.youtube.com/feeds/api/users/default/uploads/?start-index=1&max-results=1");
Feed<Video> videoFeed = yt_request.Get<Video>(uri);
string uploader = "";
if (videoFeed.Entries.Count() > 0)
    uploader = videoFeed.Entries.ElementAt(0).Uploader;

But when I try something similar with php I get what appears to be a standard feed:
    $yt = new Zend_Gdata_YouTube($http_client,<devID name>,null,$_yt_dev_key);
$feed_url = urlencode("http://gdata.youtube.com/feeds/api/users/default/uploads/?start-index=1&max-results=1");
$videoFeed = $yt->getVideoFeed();
if(count($videoFeed) > 0)
{
    $videoEntry = $videoFeed[0];
    echo var_dump($videoEntry);
}

Anyone have any idea if I'm doing something wrong?
------------------ UPDATE ----------------------
I have the solution to getting youtube video feed for the user in the authenticated session.  $videoFeed = $yt->getuserFeed("default");
Though, I'm still looking at how to get the uploader name from this so that I can perform further video listings directly from javascript (like I had done with my old C#/Asp .Net web app).
----------- A RATHER ROUGH SOLUTION ------------
Well, this isn't exactly an elegant solution, but it's what I have working.
The following will extract the youtube username from a VideoEntry object...
$videoFeed = $yt->getuserUploads("default");
if(count($videoFeed) > 0)
{
    $videoEntry = $videoFeed[0];
    $v_dump = var_export($videoEntry, true);
    $check_for = "http://gdata.youtube.com/feeds/api/users/";
    $pos = strpos($v_dump,$check_for);
    $start_pos = $pos + strlen($check_for);
    $user_name = "";
    for($i = $start_pos; $i < strlen($v_dump); $i++)
    {
        if(($v_dump[$i] == '/') or ($v_dump[$i] == '?'))
            break;
        $user_name .= $v_dump[$i];
    }
    echo $user_name;
}

Basically, I'm parsing through the entire video entry variable string representation for the first generic part of the feed url, then getting the next token in the url which is the username.  In other words, I'm locating this url in the var dump and parsing the username out:
http://gdata.youtube.com/feeds/api/users/<username>/uploads

If anyone can find a better and cleaner way to do it, that'd be awesome.  Parsing a large string like this seems to be a very dirty way of doing this.

A: See http://code.google.com/apis/youtube/2.0/developers_guide_php.html#Enabling_user_interaction
It says,
Note: Using the string default instead of a username retrieves the profile of the currently authenticated user.

So you can get all the user data about the currently authenticated user using this.
Hope it helps!

A: Try this:
$user = $yt->getUserProfile('default');
$username = $user->getUserName();


text:
Q: periodically check for updates while app on foreground I have been looking here on Stackoverflow and googling for a correct approach, but could not find one. I guess I won't be the only one with this issue.
I have an app that periodically checks for updated data on the server. There is a file with a timestamp which should be checked. When it has changed, it will download the new data (xml-file).
At the moment, I start a handler, for testing I just print a toast:
Handler h;
Runnable r = new Runnable() {
    @Override
    public void run() {
        Toast.makeText(MyActivity.this, "YEEEEEP!",
                Toast.LENGTH_LONG).show();
        h.postDelayed(this, 5000);
    }
};

Then in the onCreate():
h = new Handler();
h.post(r);

in the onDestroy() I remove the runnables, so the handler stops when the user presses back in this Activity to exit the app.
It works OK, it keeps showing the toast while in other activities, but when the user presses the 'home' button, the app of course keeps running! What I want is, that the check for updates is only running when the user believes the app is running.
Did anyone tackle this issue before?
If there is a better way to do this via a service, any suggestions would be welcome. But I think there is no difference in the issue when using a service.

A: Use Broadcast receiver to check the updates. app in foreground mode.
Try with this.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, WordService.class);
    context.startService(service);
  }
}

Gothrough this to get more details about broadcast receiver.
http://developer.android.com/reference/android/content/BroadcastReceiver.html
example. http://www.compiletimeerror.com/2013/03/android-broadcast-receiver-in-detail.html


text:
Q: which mongodb-connection (admin or user) use to interact with the database I'm developing a c#-webservice which will provide some methods for the client to interact with the mongodb.
My question is: should I use the
--> admin-user to read/write from/to the database and take care of the authorization my self
 or
-->should I create a connection with the current logged-in user and let the mongodb take care of the user-authorization?
I'm asking because for some user-actions I need to query the user-database (where only the admin has right to read/write) before I can execute the method where user-rights are enough.
Tobias

A: The short answer is: Take care of the authentication yourself inside your application.
The medium length answer is: That's mostly based on your opinion, and it's a question you need to answer  regardless of you database solution.
The long answer is: There are 4 different authentication mechanisms supported by MongoDB:

*

*MONGODB-CR - An internal challenge-response MongoDB mechanism.

*x.509 Certificate (new in v2.6).

*Kerberos (only on MongoDB Enterprise).

*LDAP Proxy Authority (only on MongoDB Enterprise for Linux).

I assume you run windows, which uses Kerberos for authentication. I also assume that you don't have the MongoDB Enterprise subscription because it costs 3X the basic subscription. If those assumptions are correct, you can't really use the windows authentication of the logged-on user to access the DB. That means that you must handle authentication yourself.
I recommend using certificates. It's quite easy if your environment supports it, it ins't specific to MongoDB, and it's very secure.


text:
Q: No mapping found for HTTP request with URI [/HelloWeb/WEB-INF/jsp/hello.jsp] I tried to to load a simple example of spring mvc with a simple jsp but failed with the following error: No mapping found for HTTP request with URI [/HelloWeb/WEB-INF/jsp/hello.jsp]
I'm using Spring 3.2.2.
I really appreciate your help here.
I tried several thing but still it seems that I can not map my jsp page in the controller.
web.xml looks like that:
<web-app id="WebApp_ID" version="2.4"
               xmlns="http://java.sun.com/xml/ns/j2ee"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>

  <servlet>
    <servlet-name>HelloWeb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>*.jsp</url-pattern>
  </servlet-mapping>
</web-app>

HelloWeb-servlet.xml looks like that:
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation=" http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:component-scan base-package="com.tutorial.spring" />

  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>
</beans>

HelloControll.class looks like that:
package com.tutorial.spring;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController {
  @RequestMapping(method= RequestMethod.GET)
  public String printHello(ModelMap modelMap) {
    modelMap.addAttribute("message", "Hello Spring MVC Framework!");

    return "hello";
  }
}

A: Correct URL to hit your printHello handler method is
/HelloWeb/hello.jsp

A: I figured it out. foolish mistake.
I named my jsp "Hello.jsp" with capital 'H' and returned in my controller 'hello' with lower case.
Just changed my jsp page to be "hello.jsp".
thanks for your help.

A: Modify web.xml like this
  <servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

Try to access /YourAppName/hello. Then Spring-MVC will trigger the method printHello() . Then return the jsp view in /WEB-INF/jsp/.

A: The dispatcher servlet have to map the correct main route:
<servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

A: move jsp file to right place as defined in servlet
/WEB-INF/jsp/

A: The correct URL is http://localhost:8080/hello, without "/HelloWeb"


text:
Q: How can i move a Horizontal Stack upwards in Swift UI I am new to Swift UI a small help will be appreciated a lot.
Right now my app design looks as shown below in image
this is image please see it
the code for my app is as shown below
var body: some View {
    VStack(){
        ZStack {
            VStack(){

                HStack(){
                    Text("All Savings Bank Accounts")
                        .font(.title2)
                        .frame( alignment: .top)
                    Button("+") {
                        isSavingsFundsAlertsPresented = true
                    }.font(.title2)
                    .frame(alignment: .top)
                }
                Spacer()
                List(allBankAccountFunds){
                    aRow in TableRowSavingsAccount(Account: aRow)
                }
            }
            AlertView(isShown: $isSavingsFundsAlertsPresented, Name: $SavingAccountName, Amount: $SavingAccountAmount, title: "Add Savings Account", placeholder: "Name of Account", buttonText: "Add Account") {
                if(SavingAccountName != ""){
                    let newAccount = SavingsAccount(context: context);
                    newAccount.accountName = SavingAccountName;
                    newAccount.accountBalance = Double(SavingAccountAmount) ?? 0;

                    do{
                        try context.save()
                    }catch{
                        print(error)
                    }
                }
                    //after the alert has ended closure of on Done function
            }
        }
        ZStack {
            VStack{

even though i included spacer() in between HStack and List, still Hstack is way low,
All i want to achieve is to somehow reduce the space between Text("All savings bank account") and top notch.
if i try to ignoreallsafeEdges() the Hstack completely disappears.
I am new to swiftUI , any help will be highly appreciated.

A: If you present this View inside NavigationView, default NavigationBar appears.
If you add
.navigationBarTitle("")
.navigationBarHidden(true)

to VStack which below body, NavigationBar will be hidden.


text:
Q: CodeIgniter Display MySQL Count View

<?php echo $wonCount; ?>

Controller
$this->load->model('coupon_model');
$data['wonCount'] = $this->coupon_model->wonCount();
$this->loadPage('dashboard', $data);

Model
public function wonCount() {

    return $this->db->query("SELECT COUNT(status) FROM coupon WHERE status = 'won'");
}

Error :
Severity: Notice
Message: Undefined variable: wonCount
How can I display count?

A: you need to send a query result (you can use row() in case you only expect one row to be returned, like in your example) back to the controller and use an alias in your query:
so write in your model something like:
$query = $this->db->query("SELECT COUNT(status) as my_count FROM coupon WHERE status = 'won'");
return ($query->num_rows() ) ?$query->row()->my_count:false;

now, with your code example in controller and view, the variable $wonCount will echo out in your view correctly
more on Generating Query Result Rows here