text:
Q: How are our brains and we "wired" in this TEDxTysons talk? Would you help to get the meaning of "Wired " in this context please :

And something I think we're going to be hearing more about in the near
  future is that there's a fundamental mismatch between the way our brains are wired and this behavior of exposing yourself to stimuli with intermittent rewards throughout all of your waking hours.
It's one thing to spend a couple of hours at a slot machine in Las
  Vegas, but if you bring one with you, and you pull that handle all day long,
  from when you wake up to when you go to bed: we're not wired from it.
— Dr Cal Newport at TEDxTysons

A: In this context, the word wired is used to compare the human brain to a piece of electrical equipment. A mixer, for example, is wired to rotate a blade when you push a button. It may have different speeds, but it can't change its basic function. A mixer won't dry your laundry, no matter what button you push.
To a certain extent, we can change the functioning of our own brains. We can learn new tasks and new attitudes. What we can't change is the way we respond to basic stimuli, such as light and heat. Using a smart phone, in the way Newport describes it, involves a series of responses from us, tied to a series of rewards. It's a form of addiction, which is a deliberate misuse of our wiring. We need to earn our rewards, that is, our brains expect us to do work that corresponds to the value of the reward. That's how we are wired.


text:
Q: Android Java: bitmap resize define height and width auto I setImageBitmap from URL to imageview. I want to define only the height, and I want that the app would set the width automatically, proportionally.
This is my code:
URL imageURL = new URL("url");
HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
image_projet.setImageBitmap(bitmap);

A: float aspect = bitmap.getWidth() / (float) bitmap.getHeight()
int newWidth = newHeight * aspect;

You yourself can calculate new width.

A: I am still a beginner in Android. I am open for criticism. But here is my answer. The first answer was right. Here's an example of how I applied it on TextView.
TextView name = (TextView)findViewById(R.id.name);
//this is where I got my bitmap. Not complete. This is inside AsyncTask
byte[] decodedString = Base64.decode(getBase64(jsonResult), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
/////

//here is His Code
int newHeight = 300; //I added this
float aspect = bitmap.getWidth() / (float) bitmap.getHeight() ;
float newWidth = newHeight * aspect;

//Now apply the it
name.setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(getResources(),Bitmap.createScaledBitmap(bitmap,(int)newWidth,newHeight,true)), null, null);

Anyway, if you find it hard to understand, here is the complete source code
MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends Activity {

    private ProgressDialog pd;
    String jsonResult="";
    TextView name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView)findViewById(R.id.name);
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context
                .CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo!=null && networkInfo.isConnected()){
            JasonReadTask jasonReadTask = new JasonReadTask();
            String url = "http://192.168.42.164/red_bank/android_connector/get_by_id.php?q=1"; //replace this URL accordingly
            jasonReadTask.execute(url);
        }
        else{
            Toast.makeText(this,"Not Connected", Toast.LENGTH_LONG).show();
        }

    }

    private class JasonReadTask extends AsyncTask<String, Void, String>{
        @Override
        protected void onPreExecute(){
            pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("Please wait");
            pd.setIndeterminate(false);
            pd.setCancelable(false);
            pd.show();
        }
        @Override
        protected String doInBackground(String... params){
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(params[0]);
            try{
                HttpResponse httpResponse = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(httpResponse.getEntity().getContent()).toString();
            } catch (IOException e){
                Log.e("doInBackground", "IOException: " + e.getMessage());
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result){
             pd.dismiss();
            byte[] decodedString = Base64.decode(getBase64(jsonResult), Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            float aspect = decodedByte.getWidth() / (float) decodedByte.getHeight() ;
            float newWidth = 300 * aspect;
            name.setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(getResources(),Bitmap
                            .createScaledBitmap(decodedByte,(int)newWidth,300,false)), null, null);
        }
    }

    /*
     * Converts InputStream to String builder
     * for conversion to String.
     */
    private StringBuilder inputStreamToString(InputStream is){
        String rLine = "";
        //Converts Buffered data to String
        StringBuilder stringBuilder=new StringBuilder();
        //Reads the JSON data line by line
        BufferedReader rd=new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine=rd.readLine()) != null) {
                stringBuilder.append(rLine); //each line is appended into one file
            }
        }
        catch (IOException e) {
            Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return stringBuilder;
    }

    /*
     * Get the base64 encoded image
     * and return it for Bitmap to ImageView Conversion
     */
    private String getBase64(String result){
        String base64="";
        try{
            JSONObject jsonObject = new JSONObject(result); //Get the Entire Object
            JSONArray jsonArray = jsonObject.optJSONArray("accounts"); //Interpret the Object
            // into array
            JSONObject jasonData = jsonArray.getJSONObject(0); //Get specific row
            base64 = jasonData.optString("profile"); //getSpecific data
            name.setText(jasonData.optString("full_name"));
        } catch(JSONException e){
            e.getMessage();
            Log.e("getBase64", "JSONException: " + e.getMessage());
        }
        return  base64;
    }

}

This is the layout
<!--activity_main.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:text="Not Connected"
            android:id="@+id/name" android:layout_gravity="center_horizontal" android:textSize="24sp" />
</LinearLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: integration Facebook sign-in , Google+ sign-in in Android app I tried knowledge base before asking this question but I didn't find anything relevant.
I am building a native app in Android platform. I want users of this app to be able to login using their Facebook or Google login details. I have main activity in my app called StartingPoint.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner.*;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook.*;
import com.facebook.android.FacebookError;
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.*;
import com.google.android.gms.plus.PlusClient;

@SuppressWarnings("deprecation")
public class StartingPoint extends Activity
implements  View.OnClickListener, ConnectionCallbacks, OnConnectionFailedListener{

    private static final String TAG = "StartingPoint";
    private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

    private ProgressDialog mConnectionProgressDialog;
    private PlusClient mPlusClient;
    private ConnectionResult mConnectionResult;

    public static String APP_ID = "**************";
    // Instance of Facebook Class
     private Facebook facebook = new Facebook(APP_ID);
     private AsyncFacebookRunner mAsyncRunner;
     String FILENAME = "AndroidSSO_data";
     private SharedPreferences mPrefs;

     TextView signup;
    //Buttons
     Button btnfacebook, google;

     @SuppressWarnings("deprecation")
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPlusClient = new PlusClient.Builder(this, this, this)
        .setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
        .build();
         // Progress bar to be displayed if the connection failure is not resolved.
        mConnectionProgressDialog = new ProgressDialog(this);
        mConnectionProgressDialog.setMessage("Signing in...");
        setContentView(R.layout.login);
        signup = (TextView) findViewById(R.id.textView5);
        btnfacebook = (Button) findViewById(R.id.loginfb);
        google = (Button) findViewById(R.id.loging);
        google.setOnClickListener(this);
        mAsyncRunner = new AsyncFacebookRunner(facebook);

         btnfacebook.setOnClickListener(new View.OnClickListener() {

               @Override
               public void onClick(View v) {
                Log.d("Image Button", "button Clicked");
                loginToFacebook();

               }
              });
        /*google.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                WebView myWebView = (WebView) findViewById(R.id.webview);
                myWebView.loadUrl("http://www.aristoslabs.com");
                // AlertDialog alertDialog = new
                // AlertDialog.Builder(StartingPoint.this).create();
                // alertDialog.setTitle("Welcome to Colletor");
                // alertDialog.setMessage("We will be back soon");
                // alertDialog.show();
            }
        });*/
    }
     @Override
        protected void onStart() {
            super.onStart();
            mPlusClient.connect();
        }

     @Override
        protected void onStop() {
            super.onStop();
            mPlusClient.disconnect();
        }
     @Override
        public void onConnectionFailed(ConnectionResult result) {
          if (mConnectionProgressDialog.isShowing()) {
            // The user clicked the sign-in button already. Start to resolve
            // connection errors. Wait until onConnected() to dismiss the
            // connection dialog.
            if (result.hasResolution()) {
              try {
                       result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
               } catch (SendIntentException e) {
                       mPlusClient.connect();
               }
            }
          }
          // Save the result and resolve the connection failure upon a user click.
          mConnectionResult = result;
        }

        protected void onActivityResult1(int requestCode, int responseCode, Intent intent) {
            if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
                mConnectionResult = null;
                mPlusClient.connect();
            }
        }

        @Override
        public void onConnected(Bundle connectionHint) {
            String accountName = mPlusClient.getAccountName();
            Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
        }
        @Override
        public void onDisconnected() {
            Log.d(TAG, "disconnected");
        }

     /**
      * Function to login into facebook
      * */
     @SuppressWarnings("deprecation")
     public void loginToFacebook() {

      mPrefs = getPreferences(MODE_PRIVATE);
      String access_token = mPrefs.getString("access_token", null);
      long expires = mPrefs.getLong("access_expires", 0);

      if (access_token != null) {
       facebook.setAccessToken(access_token);
       Intent i = new Intent();
        i.setClass(StartingPoint.this, Settings.class);
        startActivity(i);
       /* *********************************************** */
        btnfacebook.setVisibility(View.INVISIBLE);

       // Making get profile button visible
      // btnFbGetProfile.setVisibility(View.VISIBLE);

       // Making post to wall visible
       //btnPostToWall.setVisibility(View.VISIBLE);

       // Making show access tokens button visible
       //btnShowAccessTokens.setVisibility(View.VISIBLE);

       Log.d("FB Sessions", "" + facebook.isSessionValid());
      }

      if (expires != 0) {
       facebook.setAccessExpires(expires);
      }

      if (!facebook.isSessionValid()) {
       facebook.authorize(this,
         new String[] { "email", "publish_stream" },
         new DialogListener() {

          @Override
          public void onCancel() {
           // Function to handle cancel event
          }

          @Override
          public void onComplete(Bundle values) {
           // Function to handle complete event
           // Edit Preferences and update facebook acess_token
           SharedPreferences.Editor editor = mPrefs.edit();
           editor.putString("access_token",
             facebook.getAccessToken());
           editor.putLong("access_expires",
             facebook.getAccessExpires());
           editor.commit();
                   Intent i = new Intent();
            i.setClass(StartingPoint.this, Settings.class);
            startActivity(i);

           // Making Login button invisible
          // btnfacebook.setVisibility(View.INVISIBLE);

           // Making logout Button visible
           //btnFbGetProfile.setVisibility(View.VISIBLE);

           // Making post to wall visible
           //btnPostToWall.setVisibility(View.VISIBLE);

           // Making show access tokens button visible
           //btnShowAccessTokens.setVisibility(View.VISIBLE);
          }

          @Override
          public void onError(DialogError error) {
           // Function to handle error

          }

          @Override
          public void onFacebookError(FacebookError fberror) {
           // Function to handle Facebook errors

          }

         });
      }
     }

     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      facebook.authorizeCallback(requestCode, resultCode, data);
     }
    /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.starting_point, menu);
        return true;
    }*/
     @Override
     public void onClick(View view) {
         if (view.getId() == R.id.loging && !mPlusClient.isConnected()) {
             if (mConnectionResult == null) {
                 mConnectionProgressDialog.show();
             } else {
                 try {
                     mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
                 } catch (SendIntentException e) {
                     // Try connecting again.
                     mConnectionResult = null;
                     mPlusClient.connect();
                 }
             }
         }
     }
}

When I run my application basically my app is getting crashed. Following log report I get in my logcat
09-18 18:22:52.750: D/libEGL(20862): loaded /system/lib/egl/libEGL_mali.so
09-18 18:22:52.760: D/libEGL(20862): loaded /system/lib/egl/libGLESv1_CM_mali.so
09-18 18:22:52.765: D/libEGL(20862): loaded /system/lib/egl/libGLESv2_mali.so
09-18 18:22:52.770: D/(20862): Device driver API match
09-18 18:22:52.770: D/(20862): Device driver API version: 10
09-18 18:22:52.770: D/(20862): User space API version: 10
09-18 18:22:52.770: D/(20862): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
09-18 18:22:52.810: D/OpenGLRenderer(20862): Enabling debug mode 0
09-18 18:22:52.865: D/dalvikvm(20862): GC_CONCURRENT freed 149K, 8% free 12371K/13319K, paused 21ms+1ms, total 52ms
09-18 18:22:53.710: D/AndroidRuntime(20862): Shutting down VM
09-18 18:22:53.710: W/dalvikvm(20862): threadid=1: thread exiting with uncaught exception (group=0x411452a0)
09-18 18:22:53.725: E/AndroidRuntime(20862): FATAL EXCEPTION: main
09-18 18:22:53.725: E/AndroidRuntime(20862): java.lang.SecurityException: Missing android.permission.GET_ACCOUNTS
09-18 18:22:53.725: E/AndroidRuntime(20862):    at android.os.Parcel.readException(Parcel.java:1425)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at android.os.Parcel.readException(Parcel.java:1379)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.ej$a$a.getAccountName(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.ek.getAccountName(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.plus.PlusClient.getAccountName(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at        StartingPoint.onConnected(StartingPoint.java:136)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.u.v(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.u$f.a(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.u$f.a(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.u$b.A(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.google.android.gms.internal.u$a.handleMessage(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at android.os.Looper.loop(Looper.java:137)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at android.app.ActivityThread.main(ActivityThread.java:4898)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at java.lang.reflect.Method.invokeNative(Native Method)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at java.lang.reflect.Method.invoke(Method.java:511)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-18 18:22:53.725: E/AndroidRuntime(20862):    at dalvik.system.NativeStart.main(Native Method)
09-18 18:23:03.805: I/Process(20862): Sending signal. PID: 20862 SIG: 9

I know that there something in this code which not correct but I am not able to figure it out.
Please let me know.
Thanks in advance

A: Inside <manifest> and </manifest> put this node:
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>

A: This is your clue.
    09-18 18:22:53.725: E/AndroidRuntime(20862):
java.lang.SecurityException: Missing android.permission.GET_ACCOUNTS

You need to add this permission to your manifest.


text:
Q: Xampp Tomcat doesn't start return code: -1073741510 I'm new using Xampp but I have serous trouble finding what's the issue with tomcat is. I've changed ports of apache (4430, 8080) and mysql (3306).
I've also changed the port for tomcat from 8080 to 8020, 8082 ... but none of them seem to work. I've always get this message from Control Panel

Tomcat Started/Stopped with errors,return code: -1073741510

11:41:02  [Tomcat]  Make sure you have Java JDK or JRE installed and the required ports are free
11:41:02  [Tomcat]  Check the "/xampp/tomcat/logs" folder for more information

Also when I stop the process I've recently get this other message:

Port 8080 in use by "C:\xampp\apache\bin\httpd.exe"!
11:53:38  [Tomcat]  Tomcat WILL NOT start without the configured ports free!
11:53:38  [Tomcat]  You need to uninstall/disable/reconfigure the blocking application
11:53:38  [Tomcat]  or reconfigure Tomcat and the Control Panel to listen on a different port

I've also add what the Control panel displays, I'm really confused because I don't know what the problem could be. I've downloaded the last version of JDK and it doesn't work
enter image description here
Windows 10 xampp v7
I've also add info about the current status in the server.xml file
enter image description here

A: This is the answer to how to fix this problem.


text:
Q: How to use reflected tables with DeclarativeMeta interface? http://docs.sqlalchemy.org/en/latest/core/reflection.html
Written in that page, it's possible to get 'Table' object with reflection.
messages = Table('messages', meta, autoload=True, autoload_with=engine)

However, I don't know how to use it in declarative way.
I want to write some codes like
s.query(messages).all()
s.add(messages(sender='a', receiver='b', body='hello'))
s.commit()

, as if messages is the class defined in declarative way.
I think that there should be a class method which returns what I want.
Does anyone know?

A: You can use reflection with declarative models in a couple ways with just SQLAlchemy. You can pass a Table instance to a declarative model using the __table__ property (as opposed to __tablename__ which is more usual if you don't already have a Table instance.) Or, you can use the DeferredReflection mixin which handles this for you and is, I think, somewhat more convenient.
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import DeferredReflection
from sqlalchemy import create_engine
Base = declarative_base()

class Messages(DeferredReflection, Base):
    __tablename__ = 'messages'

engine = create_engine( ... )
DeferredReflection.prepare(engine)

# make session etc...


text:
Q: Need comment about my WordPress solution to show sticky post in home (with category link as title instead of post link) I thinks I should share share this solutions  with all..
I am adding a solution for showing only sticky posts in index.php and the link to go to category page(not post page) with The Loop and adding classes dynamically to the posts so that its easy to write css for them.
Add the code in index.

                    <?php
                while(have_posts()) {
                    the_post();
                    if ( is_sticky()) {
                        $postid = get_the_ID();
                         global $post;
                         $post_slug=$post->post_name;
                        ?>

                    <div  id="<?php echo $postid.'csscid'.$post_slug?>" class="content-block col-xs-12">

<?php echo get_the_category_list(', '); ?>

<?php echo wp_trim_words(get_the_content(), 11); ?>

<?php the_tags(); ?>

            <?php }
        }?>


text:
Q: Hover div, show other div

    <asp:HyperLink ID="hlHemenBasla" runat="server">Deneyim Paylaş</asp:HyperLink>

I have two divs on my website.
While I am hovering on div#quickstart, div#visiblepanel should be visible; at other times, it should not be.
I found some code on the internet, but I "couldn't run none".

A: First, make sure you're NOT self closing your

NOT


text:
Q: Unable to start AKKA application inside docker container I am attempting to start an akka application inside a docker container.
Following is a snippet from the application.conf
    akka.persistence.journal.plugin = "akka.persistence.journal.leveldb"
    akka.persistence.snapshot-store.plugin = "akka.persistence.snapshot-store.local"
    akka.persistence.journal.leveldb.native = true
    akka.persistence.snapshot-store.local.dir = "data/snapshots"
    akka.persistence.journal.leveldb.dir = "data/journal"

logingestordev          | java.lang.UnsatisfiedLinkError: Could not load library. Reasons: [no leveldbjni64-1.8 in java.library.path, no leveldbjni-1.8 in java.library.path, no leveldbjni in java.library.path, Permission denied]
logingestordev          |   at org.fusesource.hawtjni.runtime.Library.doLoad(Library.java:182)
logingestordev          |   at org.fusesource.hawtjni.runtime.Library.load(Library.java:140)
logingestordev          |   at org.fusesource.leveldbjni.JniDBFactory.(JniDBFactory.java:48)
logingestordev          |   at akka.persistence.journal.leveldb.LeveldbStore$class.leveldbFactory(LeveldbStore.scala:52)
logingestordev          |   at akka.persistence.journal.leveldb.LeveldbJournal.leveldbFactory(LeveldbJournal.scala:23)
logingestordev          |   at akka.persistence.journal.leveldb.LeveldbStore$class.preStart(LeveldbStore.scala:178)
logingestordev          |   at akka.persistence.journal.leveldb.LeveldbJournal.preStart(LeveldbJournal.scala:23)
logingestordev          |   at akka.actor.Actor$class.aroundPreStart(Actor.scala:522)
logingestordev          |   at akka.persistence.journal.leveldb.LeveldbJournal.aroundPreStart(LeveldbJournal.scala:23)
logingestordev          |   at akka.actor.ActorCell.create(ActorCell.scala:591)
logingestordev          |   at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:462)
I am not running this application as the 'root' user, inside the docker container. Inside the DockerFile, I also have the following lines of code, to run it as a particular user
    RUN useradd -ms /bin/bash portal-admin
    USER portal-admin
    WORKDIR /home/portal-admin
    RUN chown portal-admin /home/portal-admin

This is on a 'centos:6.9' image.


text:
Q: how to convert a tflite fp32 model to int8 directly? I have already had a tflite model, like 'model.TFLITE', and now I want to convert it to int8. Is there any convert funcs or tools to implement it? (tf.lite.TFLiteConverter only has from_savemodel,from_keras,from_func)
(tf.lite.TFLiteConverter only has from_savemodel,from_keras,from_func)


text:
Q: Hibernate: Overriding Field Optionality in Subclass Is there a way, using Hibernate or JPA annotations, to override the optionality of a field in a subclass? Take the following example:
Parent Class
This is a base class that defines a number of common fields. For the example below, I am just showing a single field that I want to override in a few sub classes. In the @MappedSuperclass, this field is required (doesn't allow null).
@MappedSuperclass
public abstract class GenericLog {
  protected String sessionId;

  @Basic(optional = false)
  @Column(name = FIELD__SESSION_ID__COLUMN, length = 50)
  public String getSessionId() {
    return sessionId;
  }

  public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
  }
}

Child Class
This is a subclass. It has the same sessionId field defined in the parent class, the only difference is that the field should allow nulls in this class.
@Entity
@Table(name = LogError.TABLE_NAME)
@Cache(usage = CacheConcurrencyStrategy.NONE)
public class LogError extends GenericLog {
  @Basic(optional = true)
  @Column(name = FIELD__SESSION_ID__COLUMN, length = 50)
  @Override
  public String getSessionId() {
    return super.getSessionId();
  }

  @Override
  public void setSessionId(String sessionId) {
    super.setSessionId(sessionId);
  }
}

I tried using the @AttributeOverride annotation, but that didn't work, even specifying the nullable property.
P.S. I'm using Hibernate 4.1.9 (JPA 2.0 annotations).

A: I think there's some non-documented interaction between @Basic and @Column that prevent the effect of @AttributeOverride.
Remove the @Basic and move the annotation to the field level instead of method level did the trick for me:
Here is my setup:
@MappedSuperclass
public abstract class GenericLog {

  @Column(name = "sessionId", length = 50, nullable = false)
  protected String sessionId;

  // getter setter here
}

@Entity
@Table(name = "child")
@AttributeOverride(column = @Column(name = "sessionId", length = 50, nullable = true), name = "sessionId")
public class ChildEntity extends SuperClass {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // getter setter here
}

@Entity
@Table(name = "child2")
public class ChildEntity2 extends SuperClass {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // Getter setter here
}

Here's the result:


text:
Q: Scripting SSIS Packages to run remotely with PowerShell I am trying to run some SSIS Packages installed on a database remotely, I do have access to the database and can see the SSISDB and its Catalog.  The problem I have been having is how best to execute one of the packages in the Project I have in the catalog.
I know DTExec is an option if I use invoke-command but don't want to do that if it's possible, at times there may be multiple connections and I have seen crashes on certain boxes with multiple executions of DTExec.
I have tried getting the execute script from the package and putting that in PowerShell and using that as a SQL Query, my long term fear with this method is if the Packages change then I need to keep track of that.
The simplest solution I would like to have is execute the package just by name, if I need to update the name that's simpler than an entire SQL script for each package.  Is this simpler solution possible and what would be the best method to do it?  So far I have had no luck running this as an execute with SMO.  What I have tried is something like:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$SMOserver = New-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $Server

#This sets the connection to mixed-mode authentication
$SMOserver.ConnectionContext.LoginSecure=$true

$query = @" this is where my execute SQL goes from the SSIS catalog "@

$db2 = New-Object ('Microsoft.SqlServer.Management.Smo.Database')
$db2 = $SMOserver.Databases[$database]
Write-Host "My Query: $query"
$results2 = $db2.ExecuteNonQuery($query)
Write-Host "Results: " $results2

Although when I run this I often just get a return, with no values.

A: Ended up getting around this by using sqlcmd and making the individual tasks into Jobs, then using sqlcmd to execute the jobs.
So with a Username and Password used:

$jobOutput = sqlcmd -S $server -U $username -P $password -Q "EXEC msdb.dbo.sp_start_job @job_name=N'$jobName'"

This allowed access and provided me some output on the results,


text:
Q: In pylint is there a way to locally disable a warning and then undo the previous suppression without explicitly giving a list? I am aware of the FAQ entry for PyLint which states that:

4.2 Is there a way to disable a message for a particular module only?
Yes, you can disable or enable (globally disabled) messages at the
  module level by adding the corresponding option in a comment at the
  top of the file:
# pylint: disable=wildcard-import, method-hidden
# pylint: enable=too-many-lines

However, how can I locally suppress a message and then simply restore the previous state, prior to suppression. I don't want to have to repeat myself when restoring the previous state. Is there a way to achieve this?
A shortcoming of the way PyLint handles this appears to be that if I disable a particular message some-message globally (e.g. command line or pylintrc) and then I have the following Python code segment:
# pylint: disable=some-message
foo, bar, baz = 0, 1, 2
# ... the code that creates the warning
# pylint: enable=some-message

the documentation suggests that the first line would not have any effect (i.e. the already disabled message would remain disabled) while the last line would undo not just the local effect of the first line - whether it was benign or not due to global settings - but would also undo the command line option or pylintrc setting.
What I am looking for is a functionality similar to that in MS Visual C++ for warnings:
#pragma warning(push) /* save current state of warning settings */
#pragma warning(disable:somewarning)
/* warning occurs in code here */
#pragma warning(pop)  /* restore previous state of warning settings */

an more concise alternative is:
#pragma warning(disable:somewarning)
/* warning occurs in code here */
#pragma warning(default:somewarning)

Does either functionality exist in PyLint?

A: There is no such functionnality in pylint. You may suggest it on its tracker though: https://bitbucket.org/logilab/pylint/issues


text:
Q: Weird "assembly not referenced" error when trying to call a valid method overload I'm using method overloading in Assembly A:
public static int GetPersonId(EntityDataContext context, string name)
{
    var id = from ... in context... where ... select ...;
    return id.First();
}

public static int GetPersonId(SqlConnection connection, string name)
{
    using (var context = new EntityDataContext(connection, false))
    {
            return GetPersonId(context, name);
    }
}

When I try to call the second overload from Assembly B, VS produces the following compile-time error:

The type 'System.Data.Entity.DbContext' is defined in an assembly that
is not referenced. You must add a reference to assembly
'EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=...'.

Assembly B references Assembly A. Entity Framework is referenced only in Assembly A as Assembly B doesn't use it. The call from Assembly B looks like this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    var id = AssemblyA.GetPersonId(connection, name);
    // compiler error
}

What I don't understand is that the error goes away if I change the method signature in Assembly A to e.g.:
public static int GetPersonId(SqlConnection connection, string name, bool empty)

and change the call to:
var id = AssemblyA.GetPersonId(connection, name, true); // no error

Why is my code not compiling in the first case? It doesn't seem to be related to Entity Framework as the error indicates. I have always thought that C# allows method overloading where method signatures differ only in parameter types. E.g. I can run the following code without problems as expected:
static void DoStuff(int a, int b) { ... }
static void DoStuff(int a, float b) { ... }

DoStuff(10, 5);
DoStuff(10, 5.0f);

So why am I getting the error in my situation despite the apparently legal overloads?
Note that from Assembly B I have no problems calling other methods that internally use EntityDataContext, the only difference is that these methods don't have overloads.

Background
EntityDataContext inherits EF's DbContext:
public partial class EntityDataContext : DbContext
{
    public EntityDataContext() : base("name=EntityDataContext") { }

    public EntityDataContext(DbConnection connection, bool contextOwnsConnection) : base(connection, contextOwnsConnection)
    {

    }
}

I'm using .NET 4.0 with EF 6 code first to an existing database with some custom ctor overloads added.

A: The C# standard specifies that overload resolution (section 7.5.3) is performed by comparing each matching signature to determine which is a better fit. It doesn't say what happens when a reference is missing, so we must infer that it still needs to compare those unreferenced types.
In your case, the compiler needs a reference to EntityDataContext to be able to compare the two overloads. Your call matches the signature exactly so in theory you shouldn't need this, but the standard doesn't specify any such short-circuit behavior.


text:
Q: how to apply the func for textfield underline code to all text fields I want to reuse the code for all the text field in my screen there is the function i have written for a single textfield out of all how do I apply it to all the text field how to customise it so that only single code will work for all: code is Here:
func textfieldborder()
{
    let border = CALayer()
    let width = CGFloat(1.0)
    border.borderColor = UIColor.darkGray.cgColor
    border.frame = CGRect(x: CGFloat(0), y: textname.frame.size.height - width, width:  textname.frame.size.width, height: textname.frame.size.height)

    border.borderWidth = width
    textname.layer.addSublayer(border)
    textname.layer.masksToBounds = true

}

A: You should make your function accept a parameter of type UITextField.
func textfieldborder(_ textField: UITextField) {
    let border = CALayer()
    let width = CGFloat(1.0)
    border.borderColor = UIColor.darkGray.cgColor
    border.frame = CGRect(x: CGFloat(0), y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)

    border.borderWidth = width
    textField.layer.addSublayer(border) // note that you are setting properties of textField the parameter now!
    textField.layer.masksToBounds = true
}

You can call this method on all the text fields you want a border on:
textfieldBorder(textname)
textfieldBorder(textFoo)
textfieldBorder(textBar)


text:
Q: How to capture parent class 'this' in a child object getter in ES6 or later? Here is a simple JavaScript code:
class Test {
  constructor(val) {
    this._value = val;
    this.child = {
      get value() { return this._value; },
      getValue: () => { return this._value; }
    };
  }
}

let o = new Test(1);
console.log(o.child.value);
console.log(o.child.getValue());

The output:
undefined
1

In the child object child, I want to make the getter get value() to produce the same value as the lambda getValue(), i.e. to capture the parent's this properly and produce 1 rather than undefined.
Is there an elegant way of doing it within the class? Or should I use the lambda and give up on the getter?
I could probably do this:
    this.child = {
      parent: this,
      get value() { return this.parent._value; },
    };

However I don't want to expose child.parent, only child.value.

A: Answering to myself, it can simply be done by capturing this inside constructor:
class Test {
  constructor(val) {
    const self = this;
    this._value = val;
    this.child = {
      get value() { return self._value; }
    };
  }
}

A: The value and child are defined in the constructor, and value should be private, and accessed only via child. You can set value as a normal variable in the closure, and access it via the child getter and setter:

class Test {
  constructor(val) {
    let value = val;
    this.child = {
      get value() { return value; },
      set value(v) { value = v; },
    };
  }
}

let o = new Test(1);
console.log(o.child.value);
o.child.value = 5;
console.log(o.child.value);

If you need the value inside Test, you can always access it via the child:

class Test {
  constructor(val) {
    let value = val;
    this.child = {
      get value() { return value; },
      set value(v) { value = v; },
    };
  }

  get value() {
    return this.child.value;
  }

  set value(v) {
    this.child.value = v;
  }
}

let o = new Test(1);
console.log(o.value);
o.value = 5;
console.log(o.value);


text:
Q: DELETE statement in MySQL doesnt take the table name correct I have a database called broodjes-service, whenever i run this query in it:
DELETE FROM order_items WHERE order_id = 42

I get this error:
#1146 Table 'broodjes-service.i' doesn't exist

While i'm sure this table exists, with this table structure:

Problem
I'm trying to delete a row from a table named order_items, but it takes the table name i for some reason.
Questions

*

*Why is it taking the table name i

*How can I make it so that my query will actually a row from that specific table?

I do have triggers for the table order_items
This one is for when deleting something:

UPDATE orders o
   INNER JOIN (SELECT i.order_id id, SUM(i.quantity * p.price) total_price
      FROM `orders-items` i

   INNER JOIN products p ON p.id = i.products_id
      AND i.order_id = old.order_id) t ON t.id = o.id

SET o.total_price = t.total_price

Insert trigger

INNER JOIN (SELECT i.order_id id, SUM(i.quantity * p.price) total_price
FROM `orders-items` i

INNER JOIN products p ON p.id = i.products_id AND i.order_id = new.order_id) t ON t.id = o.id

SET o.total_price = t.total_price

Update trigger

UPDATE orders o INNER JOIN (SELECT i.order_id id, SUM(i.quantity * p.price) total_price FROM `orders-items` i INNER JOIN products p ON p.id = i.products_id AND i.order_id = new.order_id) t ON t.id = o.id SET o.total_price = t.total_price

A: DELETE FROM `broodjes-service`.order_items
WHERE order_id = 42

If you use alias names then like this
DELETE i
FROM `broodjes-service`.order_items i
WHERE order_id = 42

Don't mix db names and alias names
DELETE `broodjes-service`.i
FROM `broodjes-service`.order_items i
WHERE order_id = 42

A: Try:
Use broodjes-service;
DELETE FROM order_items WHERE order_id = 42


text:
Q: Finding the best real value for $C$. Consider the recurrence $f_{n+1}=f_n + \ln(f_n)$ with $f_0=2$.
Also consider differential equations of type $g(0)=2$ and $\dfrac{d g}{d x}=\ln(g(x)- C \cdot \ln(g(x)))$. Lets call the solution depending on the real value $C$ as follows : $g_C(x)$.
It has been shown by Did here
An issue with approximations of a recurrence sequence
that the recurrence $f(x)$ lies between $g_1(x)$ and $g_0(x)$. So my question is what is the best value for $0<C<1$ such that $g_C(x)$ is as close to f as can be for large $x$ ?


text:
Q: Reading the last row or the row having the latest value in csv file I have a python script which takes input from a admin.csv file. I want to read the latest entry in the admin.csv file, which is on the last line. Kindly help me out. My csv file is below.
Input_IP    Skip_Frames Save_Video  Id_Display
192.168.1.97    100             True    False
191.168.43.97   91              False   True
191.168.43.97   1               True    True
191.168.4.61    11              False   False
191.135.4.12    99              True    True

A: One simple way if you are using pandas is
import pandas as pd

df = pd.read_csv('filename.csv')
df.iloc[-1]

A: The csv reader is a generator, you can convert that to a list. You can get the last data in the last line with the following code sample:
import csv

with open('test.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=' ')
    print(list(csv_reader)[-1][-1])


text:
Q: Compile errors using std::bind in gcc 4.7 I am having a lot of trouble using std::bind in various places of my code. Sometimes it works, sometimes it doesn't, so I assume I am doing something fundamentally wrong.
As far as I understand, the following basic use of std::bind should work fine:
#include <functional>

int foo(int a, int b){ return a+b; }

int main(){

    using namespace std::placeholders;

    // works
    auto bar_auto=std::bind(foo,1,_2);

    // compile error
    std::function<int(int)> bar_fun=std::bind(foo,1,_2);

    int quux=1;
    // compile error
    std::function<int(int)> bar_fun_lvalue=std::bind(foo,quux,_2);

}

Surely the type of bar_auto is std::function<int(int)> (type of foo with 1 int argument bound), so why does bar_fun fail to compile? I included bar_fun_lvalue because some googling showed me that rvalues used to be problematic. but this didn't fix anything.
It resembles this bug, but that's so old I don't expect it to be relevant.
gcc's output is not particularly enlightening:

In file included from bindnew.cpp:1:0:
  /usr/include/c++/4.7/functional: In instantiation of 'static _Res
  std::_Function_handler<_Res(_ArgTypes ...), _Functor>::_M_invoke(const
  std::_Any_data&, _ArgTypes ...) [with _Res = int; _Functor =
  std::_Bind))(int, int)>; _ArgTypes =
  {int}]': /usr/include/c++/4.7/functional:2298:6:   required from
  'std::function<_Res(_ArgTypes ...)>::function(_Functor, typename
  std::enable_if<(! std::is_integral<_Functor>::value),
  std::function<_Res(_ArgTypes ...)>::_Useless>::type) [with _Functor =
  std::_Bind))(int, int)>; _Res = int;
  _ArgTypes = {int}; typename std::enable_if<(! std::is_integral<_Functor>::value), std::function<_Res(_ArgTypes
  ...)>::_Useless>::type = std::function::_Useless]'
  bindnew.cpp:15:52:   required from here
  /usr/include/c++/4.7/functional:1912:40: error: no match for call to
  '(std::_Bind))(int, int)>) (int)'
  /usr/include/c++/4.7/functional:1140:11: note: candidates are:
  /usr/include/c++/4.7/functional:1211:2: note: template _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) [with _Args = {_Args ...}; _Result =
  _Result; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder<2>}] /usr/include/c++/4.7/functional:1211:2: note:
  template argument deduction/substitution failed:
  /usr/include/c++/4.7/functional:1206:35: error: cannot convert
  'std::_No_tuple_element' to 'int' in argument passing
  /usr/include/c++/4.7/functional:1225:2: note: template _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const [with _Args = {_Args ...};
  _Result = _Result; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder<2>}] /usr/include/c++/4.7/functional:1225:2: note:
  template argument deduction/substitution failed:
  /usr/include/c++/4.7/functional:1219:35: error: cannot convert
  'std::_No_tuple_element' to 'int' in argument passing
  /usr/include/c++/4.7/functional:1239:2: note: template _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) volatile [with _Args = {_Args ...};
  _Result = _Result; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder<2>}] /usr/include/c++/4.7/functional:1239:2: note:
  template argument deduction/substitution failed:
  /usr/include/c++/4.7/functional:1233:35: error: cannot convert
  'std::_No_tuple_element' to 'int' in argument passing
  /usr/include/c++/4.7/functional:1253:2: note: template _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const volatile [with _Args = {_Args
  ...}; _Result = _Result; _Functor = int (*)(int, int); _Bound_args =
  {int, std::_Placeholder<2>}] /usr/include/c++/4.7/functional:1253:2:
  note:   template argument deduction/substitution failed:
  /usr/include/c++/4.7/functional:1247:35: error: cannot convert
  'std::_No_tuple_element' to 'int' in argument passing

A: The placeholder position objects (e.g. when you use _2) is not the position of the argument in the function you call, but a placeholder for the argument in the created callable object. Instead always start with _1 and increase.
So:
auto bar_auto=std::bind(foo,1,_1);

etc.

This means you can switch the arguments in the object created by std::bind by simply doing like
auto bar_auto=std::bind(foo,_2,_1);

When you "call" the bar_auto object, the first argument will be the second argument to foo, and the second argument in the call will be the first argument to foo.

A: The _2 placeholder means to use second argument of the returned functor. Therefore the type of
std::bind(foo,1,_2)

is not std::function<int(int)> but
std::function<int(unspecified_type, int)>

To get std::function<int(int)>, use
std::bind(foo, 1, _1)
//                ^^


text:
Q: A failure occurred while executing com.android.build.gradle.internal.tasks.workers$actionfacade See the Console for details When I try build Android application. I got some error about R8.
I used to be able to build successfully, but at some point I started getting errors.

Configure project :launcher
WARNING: The option 'android.enableR8' is deprecated and should not be used anymore.

I googled android.enableR8 and it only worked for people developing apps in Android Studio.
My project currently uses PUN 2 to enable multiplayer, and Firebase for the database.

Also, the error continues below;

注意:D:\UnityProjects(ProjectName)\Temp\gradleOut\unityLibrary\src\main\java\com\unity3d\player\UnityPlayerActivity.javaは非推奨のAPIを使用またはオーバーライドしています。
注意:詳細は、-Xlint:deprecationオプションを指定して再コンパイルしてください。

It says UnityPlayerActivity.java uses a deprecated API, and check details by using -Xlint:deprecation option.
I don't know what -Xlint:deprecation is, and I don't remember changing the Unity Playern settings.
Is this a Unity bug? Or is it a bug in IL2CPP?

A: I don't know the cause yet, and I haven't solved it fundamentally, but I found that the problem was in Firebase.
I deleted all the Firebase related folders and the build worked.


text:
Q: How to find JAR name by using taglib URI I have URI name on my JSP and I need to find in which jar its using for example On my JSP Page I have following URI
<%@ taglib uri="http://xmlns.oracle.com/adf/faces/rich" prefix="af"%>

and I need to find out which jar its referring I almost perform all kind of search operation.

A: Install WinRAR. It is able to search in multiple compressed files in arbitrary folders. Open WinRAR, navigate to the /lib folder where all your JARs are and hit F3. Choose to search in all files and provide the search keyword http://xmlns.oracle.com/adf/faces/rich.

A: To do that, you have to search all JAR files in your classpath. Inside each JAR, look for a .tld file inside the META-INF directory, which contains the uri you're looking for.
In other words: look for a .tld file, containing the string http://xmlns.oracle.com/adf/faces/rich, in all JARs in your classpath.

A: If you are using Tomcat, try
<%=tldLocationsCache.getLocation("http://xmlns.oracle.com/adf/faces/rich")
.getJarResource().getJarFile().getName() %>


text:
Q: Show that $E\left[\sum_{n=1}^\infty \mathrm{1}_{A_n}\right]= \sum_{n=1}^\infty P(A_n)$ without using Fubini or Beppo-levi? Show that $E\left\{\sum_{n=1}^\infty \mathrm{1}_{A_n}\right\}= \sum_{n=1}^\infty P(A_n)$ where $(A_n)_{n \ge 0}$ is any sequence of events without using Fubini theorem or the  Beppo-levi.
This is problem 5.19 in Chapter 5 of Probability essentials and the aforementioned tools are developed only later in Chapter 9 of the book. Do I have to replicate the proof of the Beppo-levi for this particular case or is there a better way to show this using elementary methods and without any heavy machinery.
Thanks


text:
Q: How to make a simple auto-updating client (windows service)? How to make a simple auto-updating client (windows service)?
Note: Am using .NET 2.0 client and .NET 4.0 IIS web server.
I thought that I would have a main startup .exe (Step 1 and 1.5) and a separate class (DLL) to be called after the update process for the rest of the work so the 'worker' DLL could be overwritten in the update procedure.
Is this the best way to make an auto-update client?
All steps below are run at every timer interval and at at windows service / program startup.

*

*Close then open web service connection
1.5 Auto update client if web service version is newer in a transaction (download zipped binary file to update the client Program folder - usually just the "worker" dll file.)

*Login to web method to get SecurityToken to be used for future web method calls

*Upload local MessageLog (ideally before and after all processes)

*Get client settings

*Do main work processes (worker class)

*Upload Local MessageLog

*Logout web method

*Close web service connection

Other Notes:
a. Client is only upgraded if that installation has a web server setting allowing them to receive updates, and their app version needs an update (compare version #'s).
b. Everything is over SSL.
c. I will secure the entire web service in addition to requiring a security token per web method (security token expires after 60 minutes or less).
d. The client config file is strongly encrypted (login creds to entire web service and for the specific installation)
e. I probably should download a MD5 sum of the app update binary file to ensure I have the correct file to install.  Does .NET implement MD5 in a standard way for Windows and on Mono framework for a Mac?
f. This custom program is not freely available on the web but only for some clients.

A: Is there a problem using ClickOnce? It is built into the .NET Framework and can be configured from Visual Studio.


text:
Q: Rails UJS link_to :remote does AJAX GET and normal  GET EDIT:
In addition to the helpful comments below, two excellent articles by Steve Schwartz explain everything clearly:

*

*http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

*http://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/
Rails 3.2.2 / jquery-rails 2.0.1 (uses jquery 1.7.1)
I have link which sends an AJAX request to add additional file upload fields to a form.  Everything page-related works correctly - the new form field HTML fragment is retrieved from the server and appended to a div inside the form.
However,
The server receives two GET requests. One is the AJAX request ; the other appears to be the "normal" anchor element GET.  I expected the "normal" GET would be stopped by Rails UJS.
Am I supposed to disable the normal link action myself?  Can someone please explain what I have misunderstood, and what I should be doing instead [to prevent the second request]?
I've seen this question: Rails 3 UJS - controller gets called twice by link_to :remote.  Accordingly, I tried changing the asset pipeline compilation config.assets.debug = false, but it had no effect.  Moreover, this is not a double-AJAX GET request, so I think it's a different issue.
Thanks for any help!
Server log snippet:
Started GET "/files/new?asset_number=2" for 127.0.0.1 at 2012-03-23 15:23:27 +0100

Started GET "/files/new" for 127.0.0.1 at 2012-03-23 15:23:27 +0100

Browser HTML:
Add another file

View:
<%= link_to 'Add another file', new_file_path, :remote   => true,
                                               :update   => 'files',
                                               :position => 'after',
                                               :id       => 'add_another_file' %>

Controller's coffeescript:
$( ->
  $('a#add_another_file').click( ->
    url = '/files/new?asset_number=' + $('#files input').length
    $.get(url, ((data) -> $('#files').append(data)), 'html')))

A: If you're adding a click event to a#add_another_file , then you don't need to use :remote => true , because you're making the Ajax request manually.
Also, the click event should prevent the default action from occurring. This can be accomplished by adding event.preventDefault(); to the beginning of the click event's callback. Note that the callback needs to accept the event argument.

A: If you want to use the :remote => true option, you should remove the custom click event that you've added. This is because the :remote => true option tells the *jquery_ujs* library to hijack clicks on a#add_another_file. Thus, you needn't make your own HTTP request.
Next, to dictate what's done with the response, bind to the various events that will occur on a#add_another_file, such as success and error.
Here's the full list of Ajax events that you can bind to.

A: It's actually pretty simple, your remote link_to is sending one request (without params) and you've added a click event on that link to send another one (with params).
You should simplify your link_to as:
<%= link_to 'Add another file', new_file_path, :id => 'add_another_file' %>
Then in your click event you should return false so it doesn't follow the url.
It looks like you're using a lot of unnecessary parentheses in your coffeescript.
$ ->
  $('a#add_another_file').click ->
    url = '/files/new?asset_number=' + $('#files input').length
    $.get url, ((data) -> $('#files').append(data)), 'html'


text:
Q: How is the approximation $\sqrt{k+1} - \sqrt{k}\approx \frac{1}{2\sqrt{k}}$ done? How is the approximation $\sqrt{k+1} - \sqrt{k}\approx \frac{1}{2\sqrt{k}}$ done? (suppose $k$ is an integer)
Is this a Taylor expansion?
(P.S. I asked this on Physics Stack Exchange because I encountered this in a physics textbook and I think approximations like this are probably only done in physics/engineering instead of mathematics)

A: This approximation is valid for large $k\gg 1$.
Consider the small quantity $\frac{1}{k}\ll 1$. Then, by the binomial expansion:
$$\sqrt{1+\frac{1}{k}}-1=\left(1+\frac{1}{2k}+\mathcal{O}\left(\frac{1}{k}\right)^2\right)-1\approx\frac{1}{2k}$$
Multiplying both sides by $\sqrt{k}$, we have the desired result.

A: One can see this by simply rationalising the numerator:
$$(\sqrt{k+1}-\sqrt{k})\times\dfrac{\sqrt{k+1}+\sqrt{k}}{\sqrt{k+1}+\sqrt{k}}=\dfrac{1}{\sqrt{k+1}+\sqrt{k}}~ \approx \dfrac{1}{2\sqrt{k}}$$
Since $\sqrt{k+1} \approx \sqrt{k}$ for sufficiently large $k$.

A: You can also use derivatives to obtain this approximation: $$f(x) = \sqrt x \rightarrow f'(x) = \frac{1}{2\sqrt x}$$
$$f(x+\delta x) - f(x) \approx f'(x).\delta x$$
$$f(x+1) - f(x) \approx \frac{1}{2\sqrt x}.1$$
$$ \sqrt {x+1} - \sqrt x \approx \frac{1}{2\sqrt x}$$
provided $x \gg 1$
Hope this helps.

A: If you apply Lagrange's theorem to $f(x)=\sqrt{x}$ in the interval $[k,k+1]$, you get
$$
f(k+1)-f(k)=f'(\xi) (k+1-k),\quad \xi \in (k,k+1)
$$
i.e.,
$$
\sqrt{k+1}-\sqrt{k} = \frac{1}{2\sqrt{\xi}},\quad \xi \in (k,k+1)
$$
From this relation, you deduce that
$$
\frac{1}{2\sqrt{k+1}} \leq \sqrt{k+1}-\sqrt{k}\leq \frac{1}{2\sqrt{k}}.
$$
This inequality holds for all $k\ge 1$, large or small.


text:
Q: What is the easiest way to get a Kafka cluster in Kubernetes? I'm writing a Flink application on Kubernetes which reads and writes to Kafka, so I need a Kafka cluster for testing purposes. I just want to find the easiest way to have a Kafka cluster running in Kubernetes, it could be just a single node cluster, performance is not a concern.

A: You can definitely check https://strimzi.io/ , it is a Kubernetes Kafka Operator
check this out: https://strimzi.io/quickstarts/minikube/

A: I think the best option is to use Helm to deploy and use charts already tested and supported by big companies and the community.
I can highlight two of them:
1 - confluentinc/cp-helm-charts

The Confluent Platform Helm charts enable you to deploy Confluent
  Platform services on Kubernetes for development, test, and proof of
  concept environments.

Although this chart is in developer preview  (not supported for production use), the Kafka stack is pretty stable, well documented and supported by the Confluent Operator. By default, some commercially licensed components are used, so make sure to tweak the settings to use the community licensed ones.
2 - bitnami/kafka

This chart bootstraps a Kafka deployment on a Kubernetes cluster using
  the Helm package manager.
Bitnami charts can be used with Kubeapps for deployment and management
  of Helm Charts in clusters. This Helm chart has been tested on top of
  Bitnami Kubernetes Production Runtime (BKPR). Deploy BKPR to get
  automated TLS certificates, logging and monitoring for your
  applications.


text:
Q: Getting this xampp error message when trying to run only a certain file on local site I'm using an XAMPP Apache server and every time I go onto this specific page on my local/test site it comes up with this error message:

503 Service Unavailable error message

Things I've done to try and fix the issue:

*

*I've tried restarting apache

*I've restarted xampp

*I created a new branch from a fully functioning master branch

*I restarted my pc

Here is what comes out of my error.log file:
[Fri Nov 05 13:12:43.393672 2021] [proxy:error] [pid 2632:tid 1860] (OS 10061)No connection could be made because the target machine actively refused it.  : AH00957: AJP: attempt to connect to 127.0.0.1:8009 (127.0.0.1) failed
[Fri Nov 05 13:12:43.395690 2021] [proxy_ajp:error] [pid 2632:tid 1860] [client 127.0.0.1:50520] AH00896: failed to make connection to backend: 127.0.0.1

Let me know if there are any more details that need to be provided.


text:
Q: How do I refer to a nested object in .find method? I'm writing app in node.js. In the Order model I have a "userData" object that has an "email" element. How do I refer to "email" when using the find method?
order model:
const orderSchema = new Schema({
    userData: { // <--- email is in the userData
        firstname: String,
        email: String // <--- I want this
    },
    items: {}
});
module.exports = mongoose.model('order', orderSchema, 'orders');

use of the order:
router.put('/user-orders', (req, res) => {
  const data = req.body;

  Order.find({ userData.email: data.email }, (error, order) => { // <--- it doesn't work
    if (error) {
      console.log(error);
    } else {
      return res.json({ order });
    }
  })
})

A:

router.put('/user-orders', (req, res) => {
  const data = req.body;

  Order.find({ "userData.email": data.email }, (error, order) => { // <--- it doesn't work
    if (error) {
      console.log(error);
    } else {
      return res.json({ order });
    }
  })
})

You are missing some quotes for the keys. It needs to be "userData.email".


text:
Q: osm2pgsql can reimport with multi-geometry once imported full OSM data without starting from zero? Well, I executed the osm2pgsql command without the -G param which is intended to do a multi geometry search: https://osm2pgsql.org/doc/manual.html#geometry-processing
But I already did: sudo -u postgres osm2pgsql -s -C16G --flat-nodes=/tmp/osm-cache.bin --number-processes=8 /osmpbf/planet.osm.pbf -d osm
Can I do something else in order to create multi geometry relations without starting from scratch?

A: Kind of. The easiest way is to run the import again, but one option would be to find the cases in the polygon table where there are multiple rows with the same ID, and use PostGIS to turn this into a MULTIPOLYGON.
You could generate a new table with these geometries with
CREATE TABLE planet_osm_polygon_merged AS
SELECT
    osm_id, amenity, -- ... add the rest of columns in your style file
    ST_Collect(way), SUM(way_area)
FROM planet_osm_polygon
WHERE osm_id < 0
GROUP BY osm_id, amenity --, ... add the rest of columns in your style file
HAVING COUNT(*) > 1

You can then inspect the results in the table, delete the rows from the existing planet_osm_polygon table that are in the planet_osm_polygon_merged table, and insert the rows from the planet_osm_polygon_merged to the planet_osm_polygon table.
I note that you did a --slim import without --drop, so you've created a database you can keep up to date with diffs. Be sure to stop updates while doing this process. If you don't plan to do updates, I recommend dropping the planet_osm_rels, planet_osm_ways and planet_osm_nodes tables to save space and using --drop next time you import.
Overall, I do not recommend this method, but instead recommend reimporting with the correct options as documented in the style you are using, and suggesting to the style that they use lua transforms or the flex backend instead of the dated osm2pgsql "C transforms".


text:
Q: Ajax success function doesn't react on response I have made a Photo upload system but got a issue now:
Here the Ajax part:
$(document).ready(function(){
        $("#upload").click(function(e){
            var formData = new FormData(this);
            e.preventDefault();
            e.stopPropagation();
            $.ajax({
                type: "POST",
                url: "../system/avatar_system.php",
                data:formData,
                cache:false,
                contentType: false,
                processData: false,
                success: function(data){
                    if(data == "upload_ok"){
                        location.reload();
                    }
                },
                error: function(){
                }
            });
        });
});

here the html:

        <form id="avatar_form" enctype="multipart/form-data" method="post" action="../system/avatar_system.php">
            <input type="file" accept="image/*" id="file" name="file" class="select_file">
            Bild auswählen
            <input id="upload" type="submit" value="Bild ändern" class="upload_file">
        </form>

and here the avatar_system.php:
if(isset($_FILES['file'])){
$dirpath = "../users/". $username ."/avataruploads/";
if(!is_dir($dirpath)){
    if(!mkdir($dirpath, 0777, true)){
        $error =  error_get_last();
        echo "Failed creating Folder";
        exit();
    }
}

$file = $_FILES['file'];

$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];

$fileExplode = explode('.', $fileName);
$fileExt = strtolower(end($fileExplode));

$allowed = array('jpg', 'jpeg', 'png', 'gif');
if(in_array($fileExt, $allowed)){
    if($fileError === 0){
        if($fileSize < 32768000){
            $fileNewName = uniqid('', true) . '.' . $fileExt;
            $filepath = $dirpath . $fileNewName;
            move_uploaded_file($fileTmpName, $filepath);
            $sql = "UPDATE users SET avatar = '$filepath' WHERE username = '$username'";
            mysqli_query($conn, $sql);
            mysqli_close($conn);
            echo "upload_ok";
            exit();
        }else{
            echo "This file is to big";
            exit();
        }
    }else{
        echo "There was an Error";
        exit();
    }
}else{
    echo "Not allowed Extension";
    exit();
}
}

I want that the site reloads if the response is 'upload_ok', but I get a new blank page with the message 'upload_ok'.
Or maybe it should not reload the page but just change the avatar immediately.
How is this possible?

A: As you see in error text

TypeError: Argument 1 ('form') to the FormData constructor must be an instance of HTMLFormElement

you pass to FormData not <form> but <input[type=submit]>.
So, you should pass a <form>. The simplest way is
var formData = new FormData(this.form);

This is possible because inputs of a form always have property form, in which there's a <form>, that input belongs to.

A: You should change
$("#upload").click(

to
$('#avatar_form').submit(

As mentioned by u_mulder this is bound to the button instead of the form. Also it is a good practice to use the submit event instead of button clicks because you can also submit a form but pressing enter in an input field.


text:
Q: Bounds for $\sum_{t=1}^Tn_t(s_t)^{-\alpha}\mu(s_t)$ where $n_t(s) = \sum_{1 \le t' \le t} 1_{\{s_{t'}=s\}}$ for $s \in [k]$ and $\mu \in \Delta_k$ Disclaimer: I'm not certain this is the right venue for this post, but I'll give it a try...
So trying prove some bounds in my ongoing work in theoretical reinforcement learning, I encountered the need to devise and proof the following small theorem.

[A small Theorem] Consider $T \ge 1$ runs of an experiment with $k \ge 1$ possible outcomes, only one of which
  can be the observed on each run. For each run $t$, let $s_t \in \{1,\ldots,k\}$
  be observed outcome. For each possible outcome $s \in \{1,\ldots,k\}$, let $n_t(s):=\sum_{t' \le t}
1_{\{s_{t'} = s\}}$ be the total number of observations of $s$ in the first $t$
  runs of the experiment. Finally, let $\mu \in \Delta_k$ be any prior
  distribution on the outcomes, and let $\alpha \in (0, 1]$. Define
  $E_{T}:=\sum_{t=1}^T n_t(s_t)^{-\alpha}\mu(s_t)$. We have the bound
  \begin{eqnarray}
E_{T}
  \le \begin{cases}\frac{1}{1-\alpha}\left(\|\mu\|_{\frac{1}{\alpha}}T^{1-\alpha}-\alpha
    \right) = \mathcal
    O\left(T^{1-\alpha}\right), &\mbox{
      if }0 < \alpha < 1,\\ \log(T)+ 1=\mathcal O(\log(T)),&\mbox{ if }\alpha =
    1.\end{cases}
\end{eqnarray}

Indeed, let $f_\alpha(x) := x^{-\alpha}$, a continuous function with anti-derivative $F_\alpha(x) :=
(1-\alpha)^{-1}x^{1-\alpha}$ if $0 < \alpha < 1$ and $g_1(x):=\log(x)$.
My proof (only sketched here for brevity) of this result is based on the pigeon-hole principle
\begin{eqnarray}
  \begin{split}
    E_{T} &:=\sum_{t=1}^Tf_\alpha(n_t(s_t))\mu(s_t)=\sum_{t=1}^T\sum_{s=1}^k
    f_\alpha(n_t(s))\mu(s)1_{\{s_t=s\}}
    =\sum_{s=1}^k\mu(s)\sum_{t=1}^Tf_\alpha(n_t(s))1_{\{s_t=s\}}\\
    &= \sum_{s=1}^k\mu(s)\sum_{n=1}^{n_T(s)} f_\alpha(n) \le 1-F_\alpha(1) +
\sum_{s=1}^k F_\alpha(n_T(s))\mu(s),
  \end{split}
  \label{eq:ph}
\end{eqnarray}
where

*

*where in the last equality, we have used the trick: $\{n_t(s) \mid s_t=s\} = \{1,2,\ldots,n_T(s)\}$, and

*the last inequality derives from an elementary inequality relating a sum and an integral.
I then apply Hoelder's inequality on the 2nd sum: $\sum_{s=1}^k F_\alpha(n_T(s))\mu(s) \le \|F_\alpha \circ n_T\|_{\frac{1}{1-\alpha}}\|\mu\|_{\frac{1}{\alpha}}$.
Question

*

*Are there general tools (transforms, general inequalities, techniques, etc.) for handling quantities like $E_{T}:=\sum_{t=1}^T n_t(s_t)^{-\alpha}\mu(s_t)$ defined in the above theorem ?

*Do the above above bounds on $E_T$ look right ? Are they alarmly off ?
Any kind of feedback, input, etc. will be really appreciated. Thanks.


text:
Q: mustache js - Can't access array value using tables I am having a problem with Mustache.js accessing to the values of a json array and I need some help.
The problem is when I want to access to the values using a table. It always shows [object Object], when it should show the array content.
Below is a working and a non-working example:
<!DOCTYPE html>

Works but not what I need:

{{#numbers}} {{.}} {{/numbers}}

Doesn't work:

        {{#numbers}}  {{.}} 	 {{/numbers}}

Output is:
Works but not what I need:
1 2 3
Doesn't work:
[object Object]

Is there any way to solve this problem or to print the object attributes using mustache.js?
The issue was already asked in their issue system, no replies yet:
https://github.com/janl/mustache.js/issues/295
Thanks,
Mariano.

A: Finally, this is what I did.
Replaced the div element template, to a script element:
from
 to

Works but not what I need:

{{#numbers}} {{.}} {{/numbers}}

Doesn't work:

        {{#numbers}} {{{th}}} {{/numbers}}

A: I spent a lot of time debugging this.
The problem is $('#template').html(). It returns broken HTML because table markup is malformed (stuff outside  is rendered outside the table by browser)
That is why changing to


text:
Q: Div tag Scrolling to bottom I have gone through all related questions. But didn't find any answer.
My question is i have scrollable div tag, a chat window, in which images can be dropped as well. I have span tag at the end of every message so using this code the div tag scrolls properly to the bottom.
var EndChat = $(myid);
var chat_target = EndChat.find('span').last();
EndChat.scrollTo(chat_target, 1000);

But When i append Image after resizing it, It doesn't get to the bottom. It stop at 1/4th of the image.
And when the chat loads in the beginning, if there are many images, the scrolling stops even more far from the bottom. Please Help

A: Why don't you scroll to the bottom of the chat using:
EndChat.scrollTop(EndChat[0].scrollHeight);

It works: http://jsfiddle.net/shawn31313/mb6JA/

A: In order to make sure the images have loaded before scrolling, attach an event to the load, something like this:
$('.chat img').on('load', function() {
    var chat_target = EndChat.find('span').last();
    EndChat.scrollTo(chat_target, 1000);
});

If I'm not mistaken, whenever an image in .chat is loaded, it'll trigger the scroll to the footer. You could modify it as necessary :)


text:
Q: Stop objects from being deallocated even when it has strong pointers to it I have an array of employee objects. Whenever I print them using NSLog(), the array gets logged but it starts to deallocate the employee objects though I have not assigned the objects to nil.
Here is my Employee.h :
@interface : Employee:NSObject
{
NSMutableArray *assetsarray;
}
@property int ID;

-(void)dealloc;
-(NSString *)description;

Employee.m :
@synthesize ID;

    -(void)dealloc
    {
    NSLog(@"Deallocating Employee %i" , self.ID);
    }

    -(NSString *)description
    {
    return [NSString stringWithFormat:@"Employee %i" , self.ID];
    }

Here is my main.m : (Please ignore the comments)
 int main(int argc, const char * argv[])
{

          @autoreleasepool {

                    NSMutableArray *employeesarray = [NSMutableArray array];
//                    NSMutableArray *assetsarray = [NSMutableArray array];

                    for (int i = 1; i < 11; i++) {

                              Employee *emp = [[Employee alloc]init];

                              [emp setID:i];

                              [employeesarray addObject:emp];

                    }

//
//                    for (int j = 1; j<11; j++) {
//
//
//                              Asset *ass = [[Asset alloc]init];
//
//                              ass.label = [NSString stringWithFormat:@"Laptop %i" , j];
//                              ass.resaleValue = j*18;
//
//                              [assetsarray addObject:ass];
//
//                              int index = arc4random() % [employeesarray count];
//
//
//                              [[employeesarray objectAtIndex:index] addAssetsObject:ass];
//
//
//                    }

                    NSLog(@"%@" , employeesarray);

          }
    return 0;
}

Here is the output :
2014-03-18 20:45:16.456 Employee[2112:303] (
    "Employee 1",
    "Employee 2",
    "Employee 3",
    "Employee 4",
    "Employee 5",
    "Employee 6",
    "Employee 7",
    "Employee 8",
    "Employee 9",
    "Employee 10"
)
2014-03-18 20:45:16.458 Employee[2112:303] Deallocating Employee 1
2014-03-18 20:45:16.458 Employee[2112:303] Deallocating Employee 2
2014-03-18 20:45:16.458 Employee[2112:303] Deallocating Employee 3
2014-03-18 20:45:16.459 Employee[2112:303] Deallocating Employee 4
2014-03-18 20:45:16.459 Employee[2112:303] Deallocating Employee 5
2014-03-18 20:45:16.459 Employee[2112:303] Deallocating Employee 6
2014-03-18 20:45:16.460 Employee[2112:303] Deallocating Employee 7
2014-03-18 20:45:16.460 Employee[2112:303] Deallocating Employee 8
2014-03-18 20:45:16.460 Employee[2112:303] Deallocating Employee 9
2014-03-18 20:45:16.460 Employee[2112:303] Deallocating Employee 10
Program ended with exit code: 0

A: The behaviour you see is normal. The array deallocates its elements because it is deallocated itself at the end of the block. Did you expect the objects to be never deallocated?


text:
Q: Yii framework with dropzone js I have an add product page with the image upload function.
This snippet is in my view file.

                <?php if ($modelProductitem->imagepath != '') { ?>

                    <div class="col-xs-6 col-md-4 oc-thumbs col-xs-offset-4" data-product-id="<?php echo $modelProductitem->productid; ?>">

                            <img src="<?php echo Octopus::getImagePathProductsWeb ().'/'.$productId.'/'.$modelProductitem->imagepath; ?>" title="<?php echo $modelProductitem->imagepath; ?>">

                <?php } ?>

                   x

in my JS
productDropzone = new Dropzone ('#frm-add-product', {

        url: '<?php echo Yii::app()->getBaseUrl (true); ?>/product/uploadProductImage',
        acceptedFiles: '.png, .PNG, .jpeg, .JPEG, .jpg, .JPG',
        autoProcessQueue: false,
        addRemoveLinks: true,
        uploadMultiple: true,
        previewsContainer: '.oc-dropzone-previews',
        clickable: '.drop-file',

        init: function() {
            this.on ('complete', function (file) {
                if (productDropzone.getUploadingFiles ().length === 0 && productDropzone.getQueuedFiles ().length === 0) {

                }
            });
        }
    });

In my ProductController , I have this function :-
public function actionUploadProductImage () {
        echo "test"; print_r($_POST);
die();
    }

However after clicking on submit there's no error on the dropzone js. The page is just redirected as usual, as though it didn't go through the "actionUploadProductImage" at all.
Can anyone help? Thank you

A:
The image files are getting from $_FILES but you are using $_POST

public function actionUploadProductImage () {
    $ds          = DIRECTORY_SEPARATOR;  //1
    $storeFolder = 'uploads';   //2

    if (!empty($_FILES)) {
        $tempFile = $_FILES['file']['tmp_name'];          //3

        $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4

        $targetFile =  $targetPath. $_FILES['file']['name'];  //5

        move_uploaded_file($tempFile,$targetFile); //6

    }
}


text:
Q: Method names for event handlers S100 The Sonar rule csharpsquid:S100 (Method name should comply with a naming convention) is thrown also for event handlers that are generated by Visual Studio, something like:
protected void Page_Load(object sender, EventArgs e)
{
    DoIt();
}

Is it possible to ignore this rule for event handlers as they are auto-generated?

A: We have already changed the default Regex for this rule to allow underscores. The next version of the C# plugin will use that. Until then you can change the Regex yourself to ^[A-Z][a-zA-Z0-9_]*[a-zA-Z0-9]$.


text:
Q: Why are images are not load by a compiled nodejs application? After creating an application using the MEAN stack, I am trying to compile it using the pkg package https://www.npmjs.com/package/pkg.
The application works fine, the HTML and CSS files are rendered, the connection with the database and my APIs are working correctly but images cannot be loaded.
NB: images are in the same folder as HTML and CSS files.
First of all, here is how my app is structured:
my-app
    |__ app-server
    |            |__ index.js
    |            |__ package.json
    |            |__ lib
    |            |__ all the other files and directories
    |
    |__ app-client
                 |__dist
                 |     |__app
                 |           |__ index.html
                 |           |__ style.css
                 |           |__ assets/images
                 |           |__ othermain.js files
                 |
                 |__ all the other files and directories

Second, here is how my application work:

*

*My Angular application is built using ng build into the app-client/dist/app directory and it is rendered from my Nodejs server.

*All the images SRC and HREF in my angular application are set to paths like this:

src="assets/images/my-image.svg"

*

*From the index.js file in the Node.js server I am serving static files (images, CSS, HTML files) from the built angular app using this snippet of code:

// enable static files
app.use(express.static(path.join(__dirname, '../app-client/dist/app')));

*

*And rendering my HTML file like this:

// routes
app.get('/', (req, res)=>{
    res.sendFile(path.join(process.env.BASE_PATH, '../app-client/dist/app/index.html'));
});

*

*I transpiled my Nodejs server using babel into the lib folder

*I packaged my app using pkg with this configuration from the package.json file:

{
  // other configs

 "bin": {
    "app": "index.js"
  },
  "pkg": {
    "scripts": [
      "lib/**/*.js"
    ],
    "assets": [
      "other assets",
      "../app-client/dist/app/*"
    ]
  }

  // other configs
}

NB: the application works perfectly locally using the angular as a built application.
Can anyone help me please, to find the problem and correct it?


text:
Q: Making a dataframe out of a condition on one of the columns; need to know the right syntax I've got a big dataframe where in the fifth column are date/time stamps, and I want to filter by the condition of the fifth and sixth character being "01" (so as to get the month of January).
My first attempt at the right syntax was
df_b_january=df_b.loc[df_b[4][4:6]=="01"]

Where df_b is the big dataframe, and df_b_january is a smaller dataframe consisting only of those rows of the first dataframe such that the substring of the fifth column with the index range given is "01". And yeah, I get that this is too memory-intensive a way to do it, but right now I'm just hoping to master the correct syntax for this, assuming it can be done in one line. It gives an error message at the moment, but presumably if it were a condition referring to the whole string that would be all right. Is there a way to do it in just one line?


text:
Q: Which should I choose for an iPhone game: HTML5 or OpenGL ES? I am interested in developing IPhone game and am confused whether to choose HTML5 way to do it using Phonegap or using OpenGL ES.
I have developed HTML5 based games but I have never used OpenGL. This is very basic games and requires some great lighting. It's rocket flare game where rocket comes down to earth flaring.

A: If you have already programmed a game in HTML5, you should know whether this approach is ok for you or have some limitations. Big benefit is you don't have to develop the game for each platform, and this is a big plus.
On the other hand, using OpenGL ES will give you access to all the potentiality of hardware acceleration has they are available on iOS and possibly improve your frame rate. But you have a steeper learning curve and this is not exactly a multi-platform approach.
In any case, if you are interested in giving a try to OpenGL, I would suggest looking into one of the frameworks that are available out there to make you life easier, both as far as ease of use (programming) in concerned and portability.
One great framework is cocos2d, including one of the two major physics libraries it supports, chipmunk and Box2d.
Another framework you could look into is Cinder, and a third one is openFrameworks, depending on your game overall feature set.
I have worked mostly with cocos2d, and IMO this is the best option if you want to build a game; the other two frameworks, that I have only investigated about, offer a better integration of different technologies, like audio, video, besides OpenGL. As far as I know, none offers an IDE allowing you to define your scene or sprites. Anyway, for cocos2d there are several tools that make easier to manage texture atlas, tilemaps, or define the shapes of your sprites (e.g., for collision detection).
The only framework I know of that also sports an IDE is Unity3d, but this has a cost.


text:
Q: A linear operator and Stone-Cech compactification I am reading the following article
Jean-Pierre Gossez. "On the range of a coercive maximal monotone operator in a
nonreflexive Banach space". In: Proc. Amer. Math. Soc. 35 (1972), pp. 88–92
in which the following linear operator $A:\ell_1(\mathbb{N})\to\ell_\infty(\mathbb{N})$ is defined by
$$
(Ax)_n:=-\sum_{k<n}x_{k}+\sum_{k>n}x_{k}=\sum_{k\in\mathbb{N}}x_{k}\alpha(k,n),\ x=(x_{k})_{k\in\mathbb{N}}\in\ell_{1},\ n\in\mathbb{N},
$$
where $\alpha(k,n)=\left\{ \begin{array}{lll}
-1, & \mathrm{if} & k<n\\
0, & \mathrm{if} & k=n\\
1, & \mathrm{if} & k>n
\end{array}\right.$
, $k,n\in\mathbb{N}$.
Also, the adjoint of $A$  is considered $A^*:\ell_{\infty}^{*}\to\ell_{\infty}$ which is given by $\langle y,A^{*}\mu\rangle=\langle\mu,Ay\rangle$, for $y\in\ell_{1}$, $\mu\in\ell_{\infty}^{*}$, where $\langle\cdot,\cdot\rangle$ is the natural duality formed by a Banach space $X$ with its topological dual $X^*$, $\langle x,x^*\rangle:=x^*(x)$.
The author says "It is easy to verify that"
$$
\langle\mu,-A^{*}\mu\rangle=(\mu(\beta\mathbb{N}\smallsetminus\mathbb{N}))^{2}.\hspace{3cm}(\star)
$$
Here $\beta\mathbb{N}$ is the Stone-Cech compactification of $\mathbb{N}$, $\ell_{\infty}^{*}$ is identified with $M(\beta\mathbb{N})$ the space of finite Borel measures on $\beta\mathbb{N}$, and $\mu(\beta\mathbb{N}\smallsetminus\mathbb{N})$ denotes the measure of the set $\beta\mathbb{N}\smallsetminus\mathbb{N}$. I am mainly interested in the proof of ($\star$).
I tried getting ($\star$) by finding the expression of $A^*$ as follows.
Every $x\in\ell_\infty$ is uniquely extended to (identified with) $\beta x\in C(\beta\mathbb{N})$ while $C(\beta\mathbb{N})^*$ is identified with $\ell^*_\infty$ via Riesz's Representation Theorem as follows: every $\mu\in C(\beta\mathbb{N})^*$ is a finite Borel measure (on $\beta\mathbb{N}$) such that $\mu(f)=\int f d\mu$, for $f\in C(\beta\mathbb{N})$.
I wonder whether for $\mu\in \ell^*_\infty$, $x\in\ell_\infty$, $\mu(x)=\sum_{n\in\mathbb{N}}x_n \mu(\{n\})$, where $\mu(\{n\}$ denoted the measure of the set $\{n\}$?
Any other way to approach ($\star$)?

A: As for your second question

I wonder whether for $\mu\in \ell^*_\infty$, $x\in\ell_\infty$, $\mu(x)=\sum_{n\in\mathbb{N}}x_n \mu(\{n\})$, where $\mu(\{n\}$ denoted the measure of the set $\{n\}$?

The answer is no, not every measure on $\beta \mathbb N$ is discrete. For example, take a continuous surjection $f\colon \beta \mathbb N\to [0,1]$. Then $\mu(A) = m(f[A])$ ($A$ is a Borel subset of $\beta \mathbb N$), where $m$ is the Lebesgue measure, is an atomless measure so it cannot have the form you specified.
Compact spaces on which every measure is discrete (in particular, of the form you specified) are precisely the scattered spaces. (This was noted by W. Rudin in the 1950s.)
Every measure $\mu$ however naturally decomposes into
$$\langle \mu ,f \rangle = \sum_{n=1}^\infty f_n \mu(\{n\}) + \int_{\beta N\setminus N} (\beta f)\,{\rm} d\mu\quad (f\in \ell_\infty)$$
so the first step is to show that the former summand always vanishes for $\langle \mu, -A^*\mu\rangle$.


text:
Q: Show that if $P(B|A) =1$ then $P(A^C|B^C)=1$ I want to show that if $P(B|A) =1$ then $P(A^C|B^C)=1$ where A and B are events with probabilities not equal to 0 or 1. The question comes from Blitzstein's Introduction to Probability (Chapter 2, question 17(a)) and, as a hint, notes that Bayes' rule and the Law of Total Probability should be applied. I thought the most direct way would be as follows:
\begin{align*}
    P(A^C|B^C) = 1 -P(A|B^C) && \text{Definition of complement}\\
    P(A^C|B^C) = 1 - \bigg(\dfrac{P(B^C|A)P(A)}{P(B^C)}\bigg) && \text{Bayes' rule}\\
    P(A^C|B^C) = 1 - \bigg(\dfrac{(1-P(B|A))P(A)}{P(B^C)}\bigg) && \text{Definition of complement}\\
    P(A^C|B^C) = 1 - \bigg(\dfrac{(0)P(A)}{P(B^C)}\bigg) && \text{Using P(B|A) = 1}\\
\end{align*}
And thus, $P(A^C|B^C) = 1$. However, since I didn't at all use the Law of Total Probability as the question hinted at, I'm not confident whether this is another way of performing this proof or if I've done something wrong here. I would really appreciate any assistance in pointing out if I did something wrong.

A:
However, since I didn't at all use the Law of Total Probability as the question hinted at,

By Law of Total Probability: $\mathsf P((A\cup A^{\small\complement})\mid B^{\small\complement})=\mathsf P(A\mid B^{\small\complement}) +\mathsf P(A^{\small\complement}\mid B^{\small\complement})\\~\,\therefore~~~~\mathsf P(A^{\small\complement}\mid B^{\small\complement})=1-\mathsf P(A\mid B^{\small\complement})$
Which you used.

A: The following answer is wrong, but is being left in (i.e. not deleted) as an interesting example of me going off the rails.
Alternative:
In general, when $R,S$ are both events with probability strictly between $0$ and $1$, exclusive, then $p(R|S) = 1$ is logically equivalent to $(S \implies R).$
Edit
Thanks to TonyK for indicating that this is wrong.  His counter example is $X$ has a uniform distribution on $(0,1)$, with $S$ representing the event that $X \geq (1/2)$ and $R$ representing the event that $X > (1/2)$.
This shows the danger of my relying on intuition without formal training in Probability.  Thus, the analysis below is invalid.

Therefore:
$p(B|A) = 1 \implies [A \implies B] \implies [B^c \implies A^c] \implies $
$p\left(A^c|B^c\right) = 1.$


text:
Q: Get data from Ajax Get Request in CherryPy for login session I'm doing an authentication for an web app in which I have the following flow:
After the Login, a POST is sent calling login method and if login successful redirects to /user
@cherrypy.expose
    def login(self, username=None, password=None):

        cursor.execute("""SELECT * FROM Users WHERE username=? and password=?""", (username, password))

        result = cursor.fetchone()

        if result == None:
            sessions[username] = None
            raise cherrypy.HTTPRedirect('/')
        else:
            username = result[0]
            sessions[username] = uuid4()

            # Redirects to user page
            raise cherrypy.HTTPRedirect('/user/')

Then the /user page is loaded and in the client side this code is executed:
$(document).ready(function() {
        let username = sessionStorage.getItem('username');
        var myObject = { "username": username};

        $.get("/user/auth", JSON.stringify(myObject),
        function(res) {
            console.log(res);
        });
});

How to get the username here from the GET call to return the approriate access token?
    @cherrypy.expose
    def auth(self):
        # get username and if login was successful return access token
        res = {"authentication": "Ok", "token": uuid4()}

        cherrypy.response.headers["Content-Type"] = "application/json"
        return json.dumps(res).encode('utf8')

A: Send the information as a parameter (no need to stringify the js object):
$(document).ready(function() {
        let username = sessionStorage.getItem('username');
        var myObject = { "username": username};

        $.get("/user/auth", myObject,
        function(res) {
            console.log(res);
        });
});

Receive the parameter in your method:
@cherrypy.expose
def auth(self, username):
    # get username and if login was successful return access token
    res = {"authentication": "Ok", "token": uuid4()}
    cherrypy.response.headers["Content-Type"] = "application/json"
    return json.dumps(res).encode('utf8')

Or better using cherrypy.tools.json_out (no need to directly convert to json or set the content type):
@cherrypy.expose
@cherrypy.tools.json_out()
def auth(self, username):
    # get username and if login was successful return access token
    return {"authentication": "Ok", "token": uuid4()}


text:
Q: Looking for the cheapest way to use std::wstring with NSLog I have a library which uses wstring extensively. I need to output changes and external data using NSLog Is there a simple way (not too expensive) to output the wstring using an intermediate function.
Converting each wstring to NSString using va_list is the only way I can think of right now.

Edit: More precisions. I have a multi platform lib. I added a logging macro MYLog.

Edit
I have to call my MYLog from C++ and I don't have access to Objective-C at that point. So the problem is that I can't convert the std::wstring before I do the call to MYLog.

Through MYLog I would like to be able to use NSLog or an intermediate like follows:
MYLog("Received %ls(%d) from user %ls %ls cp: %ls /nRAW:/t%ls",
       &d.name, d.id, &d.user.firstName, &d.user.lastName,
       &d.caption, &d.rawText);

Here (originally from here) I found this nice addition to NSString:
@interface NSString (cppstring_additions)
+(NSString*) stringWithwstring:(const std::wstring&)string;
+(NSString*) stringWithstring:(const std::string&)string;
-(std::wstring) getwstring;
-(std::string) getstring;
@end

@implementation NSString (cppstring_additions)

#if TARGET_RT_BIG_ENDIAN
const NSStringEncoding kEncoding_wchar_t = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32BE);
#else
const NSStringEncoding kEncoding_wchar_t = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32LE);
#endif

+(NSString*) stringWithwstring:(const std::wstring&)ws
{
    char* data = (char*)ws.data();
    unsigned size = ws.size() * sizeof(wchar_t);

    NSString* result = [[NSString alloc] initWithBytes:data length:size encoding:kEncoding_wchar_t];
    return result;
}

+(NSString*) stringWithstring:(const std::string&)s
{
    NSString* result = [[NSString alloc] initWithUTF8String:s.c_str()];
    return result;
}

-(std::wstring) getwstring
{
    NSData* asData = [self dataUsingEncoding:kEncoding_wchar_t];
    return std::wstring((wchar_t*)[asData bytes], [asData length] / sizeof(wchar_t));
}

-(std::string) getstring
{
    return [self UTF8String];
}

@end

All I could think of without wasting too much time (of mine) was to create an intermediate function called by my MYLog:
#define LAD(data) [logString appendFormat:[NSString stringWithFormat:@"%%%@", c], data]
#define LAP(type) LAD(va_arg(listPointer, type))

void MyLogImplementation(NSString* message, ...)
{
NSMutableString* logString = [[NSMutableString alloc] init];

    va_list listPointer;
    va_start(listPointer, message);

NSArray* lmc = [message componentsSeparatedByString:@"%"];

int counter = 0;
//NSLog(@"there are %d components in %@.", [lmc count], message);
BOOL ignoreNext = NO;
for (NSString* c in lmc)
{
    //NSLog(@"Testing %@", c);

    if (ignoreNext)
    {
        [logString appendFormat:@"%%%@", c];
        ignoreNext = NO;
    }
    if (0 == [c length])
    {
        ignoreNext = !ignoreNext;
    }
    else if (0 == counter && '%' != [message characterAtIndex:0] )
    {
        [logString appendFormat:@"%@", c];
    }
    else
    {
        switch ([c characterAtIndex:0])
        {
            case 'd':
            case 'i':
                LAP(int);
                break;

            case 'X':
            case 'x':
                LAP(int);
                break;

            case '@':
                LAP(NSObject*);
                break;

            case 'f':
                LAP(double);
                break;

            case 'c':
                LAP(char);
                break;

            case 'l':
                switch ([c characterAtIndex:1])
            {
                case 's':
                {
                    std::wstring* str = va_arg(listPointer, std::wstring*);
                    NSString* nstr = [NSString stringWithwstring:str];

                    [logString appendFormat:@"%@", nstr];

                    [nstr release];
                    if (2 < [c length])
                    {
                        [logString appendString:[c substringFromIndex:2]];
                    }
                }
                    break;
            }
                break;
            default:
                [logString appendFormat:[NSString stringWithFormat:@"%%%@", c]];

        }
    }
    ++counter;
}

    NSLog(@"%@", logString);
[logString release];
    va_end(listPointer);
}

But this - it seems to me - is very inefficient. Is there a better way to achieve what i'm doing? I know I could simply transform this to:
NSLog(@"Received %@(%d) from user %@ %@ cp: %@ /nRAW:/t%@",
       [NSString stringWithwstring:d.name], d.id,
       [NSString stringWithwstring:d.user.firstName],
       [NSString stringWithwstring:d.user.lastName],
       [NSString stringWithwstring:d.caption],
       [NSString stringWithwstring:d.rawText]);

And the problem would be solved. But I would loose the multiplaform advantage... I guess.

A: You could convert to an NSString and log that. This is a NSString category taken from here. Don't know how well it works but it looks sensible...
@interface NSString (wstring_additions)
+(NSString*) stringWithwstring:(const std::wstring&)string;
-(std::wstring) getwstring;
@end

@implementation NSString (wstring_additions)

#if TARGET_RT_BIG_ENDIAN
const NSStringEncoding kEncoding_wchar_t =
CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32BE);
#else
const NSStringEncoding kEncoding_wchar_t =
CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32LE);
#endif

+(NSString*) stringWithwstring:(const std::wstring&)ws
{
    char* data = (char*)ws.data();
    unsigned size = ws.size() * sizeof(wchar_t);

    NSString* result = [[[NSString alloc] initWithBytes:data length:size encoding:kEncoding_wchar_t] autorelease];
    return result;
}

-(std::wstring) getwstring
{
    NSData* asData = [self dataUsingEncoding:kEncoding_wchar_t];
    return std::wstring((wchar_t*)[asData bytes], [asData length] / sizeof(wchar_t));
}

@end

A: Perhaps if you convert it to a CFStringRef using CoreFoundation and then pass that to either CFLog(..) or cast it to NSString* (toll free bridged) and use NSLog(...)
CFStrings are in CoreFoundation which is a C level API and so should be callable from non objc land.
<CoreFoundation/CFString.h> contains CFStringCreateWithBytes(...) or perhaps CFStringCreateWithCString(...) and passing in the appropriate CFStringEncoding