text:
Q: Android Camera: Attempt to invoke virtual method Android Camera Parameters on android.hardware.Camera.getParameters()' on a null object reference I used my Fabric-service and found this error on most of the devices that are running my app.
Error was this:

Fatal Exception: java.lang.NullPointerException Attempt to invoke
  virtual method 'android.hardware.Camera$Parameters
  android.hardware.Camera.getParameters()' on a null object reference

Here's my code:
 public class CameraActivity extends Activity implements SurfaceHolder.Callback{

    android.hardware.Camera camera;
    int moi = 0;
    @InjectView(R.id.s)
    SurfaceView surfaceView;

    @InjectView(R.id.takeaphoto)
    ImageView imageView;
    SurfaceHolder surfaceHolder;
    private Camera.Face[] mFaces;

    // Draw rectangles and other fancy stuff:
    private FaceOverlayView mFaceView;
    private int mOrientation;
    private float x1,x2;
    static final int MIN_DISTANCE = 150;
    private int mOrientationCompensation;
    private OrientationEventListener mOrientationEventListener;

    // Let's keep track of the display rotation and orientation also:
    private int mDisplayRotation;
    private int mDisplayOrientation;

    Camera.PictureCallback callback;
    int cameraId = 0;
    Camera.ShutterCallback shutterCallback;

    private Camera.FaceDetectionListener faceDetectionListener = new Camera.FaceDetectionListener() {
        @Override
        public void onFaceDetection(Camera.Face[] faces, Camera camera) {
            Log.d("onFaceDetection", "Number of Faces:" + faces.length);
            // Update the view now!
            mFaceView.setFaces(faces);
        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Fabric.with(this, new Crashlytics());
        Fabric.with(this, new Answers());
        setContentView(R.layout.camera_activity);

        mFaceView = new FaceOverlayView(this);
        addContentView(mFaceView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        // Create and Start the OrientationListener:
        mOrientationEventListener = new SimpleOrientationEventListener(this);
        mOrientationEventListener.enable();

        SharedPreferences pap = this.getSharedPreferences(
                "AD1", Context.MODE_PRIVATE);
        boolean frr = pap.getBoolean("fr", false);

        if (!frr) {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Tip");
            builder.setMessage("Use the beautiful filters by swiping from right to left")
                    .setCancelable(true)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            SharedPreferences e = getApplicationContext().getSharedPreferences(
                                    "AD1", Context.MODE_PRIVATE);
                            SharedPreferences.Editor d = e.edit();
                            d.putBoolean("fr", true);
                            d.commit();

                        }

                    });

            AlertDialog alert = builder.create();
            alert.show();

        } else {

        }

        ButterKnife.inject(this);
        surfaceHolder=surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
cameraImage();
            }
        });
        callback = new android.hardware.Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
                FileOutputStream outputStream=null;
                File file_image = getDirc();

                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyymmddhhmms");
                String date = simpleDateFormat.format(new Date());
                String photo_file="PI_"+date+".jpg";
                String file_name = file_image.getAbsolutePath()+"/"+photo_file;
                File picfile=new File(file_name);

                try {

                    outputStream=new FileOutputStream(picfile);
                    outputStream.write(bytes);
                    outputStream.close();

                }catch (FileNotFoundException e){}
                catch (IOException ex){}
                finally {

                }
                refreshCamera();
                refreshGallery(picfile);

                try {
                    camera.stopPreview();
                }catch (Exception e){}

                try{

                    camera.setPreviewDisplay(surfaceHolder);
                    camera.startPreview();
                }catch (Exception e){}

            }

        };

        }

    private void refreshGallery(File file){
        Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));

    }

    public void refreshCamera(){

        if (surfaceHolder.getSurface() == null){

            return;

        }

    }

    private class SimpleOrientationEventListener extends OrientationEventListener {

        public SimpleOrientationEventListener(Context context) {
            super(context, SensorManager.SENSOR_DELAY_NORMAL);
        }

        @Override
        public void onOrientationChanged(int i) {
            // We keep the last known orientation. So if the user first orient
            // the camera then point the camera to floor or sky, we still have
            // the correct orientation.
            if (orientation == ORIENTATION_UNKNOWN) return;
            mOrientation = Util.roundOrientation(orientation, mOrientation);
            // When the screen is unlocked, display rotation may change. Always
            // calculate the up-to-date orientationCompensation.
            int orientationCompensation = mOrientation
                    + Util.getDisplayRotation(CameraActivity.this);
            if (mOrientationCompensation != orientationCompensation) {
                mOrientationCompensation = orientationCompensation;
                mFaceView.setOrientation(mOrientationCompensation);
            }
        }

    }

        private File getDirc(){

File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        return new File(dics ,"Camera");

    }

    public void cameraImage(){

        camera.takePicture(null , null ,callback);
       MediaPlayer mediaPlayer = MediaPlayer.create(this , R.raw.sound);
        mediaPlayer.start();

    }

    public void surfaceCreated(SurfaceHolder surfaceHolder ) {

try {
    camera = android.hardware.Camera.open();
}catch (RuntimeException ex){}
        android.hardware.Camera.Parameters parameters;
        parameters = camera.getParameters();
        camera.setFaceDetectionListener(faceDetectionListener);
        camera.startFaceDetection();
        parameters.setPreviewFrameRate(20);
        List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
        Camera.Size customSize = customSizes.get(0); //Added size
        parameters.setPreviewSize(customSize.width, customSize.height);
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(90);

        try {

            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();

        }catch (Exception e){

        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        refreshCamera();
        setDisplayOrientation();

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        camera.stopPreview();
        camera.release();
        camera=null;

    }

    public void frontCamera(View view) {

        camera.stopPreview();
        camera.release();
        camera=null;

        if (cameraId == 0){

            try {
                camera = android.hardware.Camera.open(1);
            }catch (RuntimeException ex){}
            android.hardware.Camera.Parameters parameters;
            camera.setFaceDetectionListener(faceDetectionListener);
            camera.startFaceDetection();
            parameters = camera.getParameters();
            parameters.setPreviewFrameRate(20);
            List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();

            Camera.Size customSize = customSizes.get(0); //Added size
            parameters.setPreviewSize(customSize.width, customSize.height);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);

            cameraId = 1;

            try {

                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();

            }catch (Exception e){

            }
        }

        else{

            try {
                camera = android.hardware.Camera.open();
            }catch (RuntimeException ex){}
            android.hardware.Camera.Parameters parameters;
            camera.setFaceDetectionListener(faceDetectionListener);
            camera.startFaceDetection();
            parameters = camera.getParameters();
            parameters.setPreviewFrameRate(20);
            List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();

            Camera.Size customSize = customSizes.get(0); //Added size
            parameters.setPreviewSize(customSize.width, customSize.height);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);

            cameraId = 0;

            try {

                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();

            }catch (Exception e){

            }

        }
        }

    private void setDisplayOrientation() {
        // Now set the display orientation:
        mDisplayRotation = Util.getDisplayRotation(CameraActivity.this);
        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, 0);

        camera.setDisplayOrientation(mDisplayOrientation);

        if (mFaceView != null) {
            mFaceView.setDisplayOrientation(mDisplayOrientation);
        }
    }

Here's my manifest:
  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.camera">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/pc"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SplashScreen"
            android:theme="@style/AppTheme"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CameraActivity"
      android:screenOrientation="portrait"
         >
         </activity>
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="e7ded6b46068e619fd1d96f6b9eeaac888fe83f5" />
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

A: Here is your problem. Your camera object is instantiated only if there is no RuntimeException. So, if this exception happens, camera == null;.
try {
    camera = android.hardware.Camera.open();
}catch (RuntimeException ex){}
// Here is your problem. Catching RuntimeException will make camera object null,
// so method 'getParameters();' won't work :)
        android.hardware.Camera.Parameters parameters;
        parameters = camera.getParameters();
        camera.setFaceDetectionListener(faceDetectionListener);
        camera.startFaceDetection();
        parameters.setPreviewFrameRate(20);
        List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
        Camera.Size customSize = customSizes.get(0); //Added size
        parameters.setPreviewSize(customSize.width, customSize.height);
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(90);

        try {

            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();

        }catch (Exception e){

        }

    }

A: Check the app in your device Settings, if the required permissions are given or not. In my case, this was the reason for Exception, that I had not given permissions from the Settings.
Hope it helps you.

A:   try {
        camera = android.hardware.Camera.open();
    }catch (RuntimeException ex){}

if(camera != null){
            android.hardware.Camera.Parameters parameters;
            parameters = camera.getParameters();
            camera.setFaceDetectionListener(faceDetectionListener);
            camera.startFaceDetection();
            parameters.setPreviewFrameRate(20);
            List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
            Camera.Size customSize = customSizes.get(0); //Added size
            parameters.setPreviewSize(customSize.width, customSize.height);
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);
}

    try {

        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();

    }catch (Exception e){

    }

}

After initializing the camera you can put a simple if condition where you can check if(camera != null){ // the code for parameter}


text:
Q: Two locations suggestion in Profile It would be good if the profile allowed both Current Location and then Origin. I don't want to be mistaken coming from another country nor I don't want also to mislead someone of my current location or where I stay for a long while.
In our profile view one of the fields is Location. In my case I am working overseas for four years now which makes me a foreign worker here. So, I put that as my location but I want also to put my origin or which exact country I came from.

A: Location is a free text field. Put in whatever you want. Like

Here / There
  Currently in the USA but from Switzerland

I am in the same position right now. I am from Germany but live in Argentina. Personally I put the Country of my current location in there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ActionBar item click to add item to ListView I have problem with adding new item through ActionBar item click. I got all the error below and the code is just beneath. If anyone would be so kind to tell me what stupid mistake I made I would be grateful.
LogCat:
08-26 19:17:57.767: E/AndroidRuntime(29108): FATAL EXCEPTION: main
08-26 19:17:57.767: E/AndroidRuntime(29108): Process: com.klangstudios.dailyachiever, PID: 29108
08-26 19:17:57.767: E/AndroidRuntime(29108): java.lang.NullPointerException
08-26 19:17:57.767: E/AndroidRuntime(29108):    at com.klangstudios.dailyachiever.Lista$StableArrayAdapter.getItemId(Lista.java:81)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.AbsListView.obtainView(AbsListView.java:2291)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.ListView.onMeasure(ListView.java:1175)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.View.measure(View.java:16540)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.View.measure(View.java:16540)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.View.measure(View.java:16540)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.View.measure(View.java:16540)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.View.measure(View.java:16540)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1942)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1132)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1321)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.Choreographer.doCallbacks(Choreographer.java:574)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.Choreographer.doFrame(Choreographer.java:544)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.os.Handler.handleCallback(Handler.java:733)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.os.Handler.dispatchMessage(Handler.java:95)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.os.Looper.loop(Looper.java:136)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at android.app.ActivityThread.main(ActivityThread.java:5086)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at java.lang.reflect.Method.invokeNative(Native Method)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at java.lang.reflect.Method.invoke(Method.java:515)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
08-26 19:17:57.767: E/AndroidRuntime(29108):    at dalvik.system.NativeStart.main(Native Method)

Just don't know why it won't work:
public class Lista extends Activity{

ArrayList<String> list;
ListView listview;
StableArrayAdapter adapter;

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

    listview = (ListView) findViewById(R.id.listView1);
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
        "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
        "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
        "Android", "iPhone", "WindowsMobile" };

    list = new ArrayList<String>();
    adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, list);
    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> parent, final View view,
          int position, long id) {
        final String item = (String) parent.getItemAtPosition(position);
        view.animate().setDuration(2000).alpha(0)
            .withEndAction(new Runnable() {
              @Override
              public void run() {
                list.remove(item);
                adapter.notifyDataSetChanged();
                view.setAlpha(1);
              }
            });
      }

    });

  }

  private class StableArrayAdapter extends ArrayAdapter<String> {

    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

    public StableArrayAdapter(Context context, int textViewResourceId,
        List<String> objects) {
      super(context, textViewResourceId, objects);
      for (int i = 0; i < objects.size(); ++i) {
        mIdMap.put(objects.get(i), i);
      }
    }

    @Override
    public long getItemId(int position) {
      String item = getItem(position);
      return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
      return true;
    }

  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu items for use in the action bar
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.menu, menu);
      return super.onCreateOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle presses on the action bar items
      switch (item.getItemId()) {
          case R.id.action_add:
              doThis();
              return true;
          default:
              return super.onOptionsItemSelected(item);
      }
  }

  public void doThis(){
      list.add("Abba");
      adapter.notifyDataSetChanged();
    }

}

A: return mIdMap.get(item);
change these line to
return position;

A: The problem is in your adapter. You create an index (mIdMap) in the constructor, but you are no updating it before to call adapter.notifyDataSetChanged(); Your code throws an exception in the getItemId() call.
A posible solution is to add this method to your adapter:
public void addToIdMap(String item) {
    // Add the new item to the map
    mIdMap.put(item, mIdMap.size());
    notifyDateSetChanged();
}

Then you can call it like:
list.add("Abba");
adapter.addToIdMap("Abba");

In cases like this I prefer to use BaseAdapter


text:
Q: How do I add my .h files if they are in different directory? #include <Dao/Dao.h>
#include <Cola/Cola.h>
int main(){return 0;}

I am trying to compile that code with this makefile:
DIR = -I/usr/include/cppconn -I/home/panda/Documents/eclipse-workspace/Computacion/Cola -I/home/panda/Documents/eclipse-workspace/Computacion/Dao
main: main.o Dao.o Cola.o Nodo.o
        $(CXX) -Wall $(DIR) -o main main.o Dao.o Cola.o Nodo.o -L/usr/lib -lmysqlcppconn

It works perfectly when I take Dao.h and Cola.h to the same directory the main file is in
Output of make:
g++    -c -o main.o main.cpp
main.cpp:2:21: fatal error: Dao/Dao.h: No such file or directory
compilation terminated.
<builtin>: recipe for target 'main.o' failed
make: *** [main.o] Error 1

A: Use this:
DIR = -I/usr/include/cppconn -I/home/panda/Documents/eclipse-workspace/Computacion

since your #include statements already specify Dao and Cola. So you need to add the parent directory of Dao and Cola in your build flags.

A: I had to add the directory paths to the object files because they are in a different directory than the makefile.
DIR = -I/usr/include/cppconn -I/home/panda/Documents/eclipse-workspace/Computacion
OBJS = main.o ./Dao/Dao.o ./Cola/Cola.o ./Cola/Nodo.o ./Persona/Persona.o
main: $(OBJS)
g++ -Wall $(DIR) $(OBJS) -o main -L/usr/lib -lmysqlcppconn


text:
Q: Changing Number of Products Per Row I found lots of discussion regarding the issue. And the major solution for the issue is adding the line <action method="setColumnCount"><columns>5</columns></action> at the catalog.xml. I tried this, by writing the following code at local.xml,
    <catalog_category_default>
        <reference name="product_list">
            <action method="setColumnCount"><columns>5</columns></action>
        </reference>
    </catalog_category_default>
    <catalog_category_layered>
        <reference name="product_list">
            <action method="setColumnCount"><columns>2</columns></action>
        </reference>
    </catalog_category_layered>

At app/design/frontend/mytheme/default/template/catalog/product/list.phtml , i have added the following code for checking the number of columns,
$_columnCount = $this->getColumnCount();
    var_dump($_columnCount);

It given int(5) at the main site. But the products per row is not changing. I am using 1column.phtml for category page.
catalog.xml,
 <catalog_category_layered translate="label">
        Catalog Category (Anchor)

       <reference name="left_first">

            <block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml">
                <block type="core/text_list" name="catalog.leftnav.state.renderers" as="state_renderers" />
            </block>
        </reference>

        <reference name="content">
            <block type="catalog/category_view" name="category.products" template="catalog/category/view.phtml">
                <block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
                    <block type="core/text_list" name="product_list.name.after" as="name.after" />
                    <block type="core/text_list" name="product_list.after" as="after" />

                    <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
                        <block type="page/html_pager" name="product_list_toolbar_pager"/>

                    </block>
                    <action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
                    <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
                    <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
                    <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
                    <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
                    <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>

                    <action method="setColumnCount"><count>4</count></action>
                </block>
            </block>
        </reference>
    </catalog_category_layered>

list.phtml:
<?php // Grid Mode ?>

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = 5; ?>

    <ul class="products-grid row products-grid-max-<?php echo $_columnCount; ?>-col">
        <?php $i=0; foreach ($_productCollection as $_product): ?>
            <?php $i++; /*if ($i++%$_columnCount==0): ?>
            <?php endif*/ ?>
            <li class="col-lg-4 col-md-4 col-sm-6 col-xs-6 col-mobile-12 item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">

                            <?php echo $helpLabels->getLabels($_product); //Product labels ?>
                            <?php //var_dump($_product); ?>
                             <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image quickview">
                                <img id="product-collection-image-<?php echo $_product->getId(); ?>" class="img-responsive" src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($width , $height); ?>" width="<?php echo $width ?>" height="<?php echo $height ?>"
                                     alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

                                <a title="<?php echo $this->__('Quick View') ?>" href="<?php echo $this->getUrl('magicshop/quickview/view') .'id/'.$_product->getId()?>" class="link-quickview"><?php //echo $this->__('Quick View') ?>

                                <?php if($_product->isSaleable()): ?>
                                    <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><?php echo $this->__('Add to Cart') ?></button>
                                <?php else: ?>

<?php echo $this->__('Out of stock') ?>

                                <?php endif; ?>

                                    <?php if ($this->helper('wishlist')->isAllow()) : ?>

<a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php //echo $this->__('Add to Wishlist') ?>

                                    <?php endif; ?>
                                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>

<a href="<?php echo $_compareUrl ?>" class="link-compare"><?php //echo $this->__('Add to Compare') ?>

                                    <?php endif; ?>

<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

                        <?php
                        // Provides extra blocks on which to hang some features for products in the list
                        // Features providing UI elements targeting this block will display directly below the product name
                        if ($this->getChild('name.after')) {
                            $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                            foreach ($_nameAfterChildren as $_nameAfterChildName) {
                                $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                                $_nameAfterChild->setProduct($_product);
                                echo $_nameAfterChild->toHtml();
                            }
                        }
                        ?>
                        <?php echo $this->getPriceHtml($_product, true) ?>

            <?php /*if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
            <?php endif*/ ?>
        <?php endforeach ?>

I hope someone will help on this issue,
Thanks

A: in list.phtml under grid use below mention code
<?php // Grid Mode ?>

    <?php $_collectionSize = $_productCollection->count() ?>
   <?php $_columnCount = 5; ?>

A: it worked for me go to
app/design/frontend/your theme/default/template/catalog/product/list.phtml
add
else
{
    $_columnCount = 3;
}

<?php // Grid Mode ?>

<?php $_collectionSize = $_productCollection->count() ?>

<?php $_columnCount = Mage::getStoreConfig('ovansport_cfg/general/Count_colunm_listing');
if($_GET['prorow']) {
    $_columnCount=$_GET['prorow'];
} else {
    $_columnCount = 3;
}


text:
Q: React Native - Improve cold start time The project I was working is to use react native to create an iOS app.
Following is the cold start time in iPhone 5S release build
Pre-main time: 0.52 seconds

App did launch to javascript did load time: 2.12 seconds

JS render time: 0.74 seconds

Total time: 3.34 seconds

The slowest part is to wait react library to load the js bundle (2.2MB). Is the loading time looks normal? How can I improve the js bundle loading time? Thanks so much.
Reducing the js bundle size can improve the time from Application did launch to javascript did load. For a new Hello World project, it only took 0.18-0.19 seconds (iPhone 5S).

A: Yes, the problem that you described really exist. As a possible solution you can use ram-bundle format, that metro bundler provides.
In this case you will not load the entire js-bundle - you will load only part, that you need at a startup (in a lot of application are a lot of places, which user may not even see, and this feature allow you load such parts, only when they are required). So you can simplify your entry point and load only small piece of your bundle.
You can look at react-native-bundle-splitter. This library well integrated with almost all popular navigation libraries and allows you to postpone a loading of specific routes. For example, if you have a login screen, you can load at start up only this screen, and all others load in background or start the loading of them, only when user can see them. And the startup time of your complex application will be almost equally as for "Hello world" application.

A: Whether the time ok is up to you and your app users only =)
Obviously, if reducing the js bundle size improves the time, you should do your best to get it done. There is several steps I guess can help you:

*

*first of all, DRY: doubling code do increase the size

*check for using npm packages, remove unused (also as unused inner modules)

*obfuscate and minify the bundle with third-party tools

Also it should be done to reduce initializing complexity

*

*check an asymptotic complexity of your algorithms - is can cause to time increasing

*remove unused variables, functions and data - it can be a reason of redundant memory usage

And I can just advice you also try to affect not only an actual time but also a time feeling. For example, use an animated splash screen


text:
Q: Is Spotify Android API audio delivered in raw PCM? I am wanting to write a Spotify Android plug-in to perform audio pre-processing prior to playback.
Judging by the documentation for com.spotify.sdk.android.player.AudioController.onAudioDataDelivered:

samples - 16-bit PCM data. The buffer contains sampleCount samples, whereby each sample contains the data for a single audio channel.

and the now deprecated libspotify int( * sp_session_callbacks::music_delivery):

[in]  frames  Points to raw PCM data as described by format

It appears that the Android onAudioDataDelivered call above would receive raw PCM data (non DRM encoded).
Could anyone confirm this is the case?

A: Yes it's raw PCM , you can hook into the PCM playback with the Android SDK.


text:
Q: SEDE query to find progress on Four Ayes hat? I've been working on a query to count the number of days a user's posts have had votes up, with no votes down on any day. But it seems like it's missing some posts. Users that have Four Ayes, do not seem to show up in this report.
Can someone tell me where I'm going wrong with this query?
WITH FourAyes (Id, DisplayName, Title, Up, Down, Created)
AS
(
    SELECT p.Id, u.DisplayName, p.Title,
       SUM(CASE WHEN v.VoteTypeId = 2 THEN 1 ELSE 0 END),
       SUM(CASE WHEN v.VoteTypeId = 3 THEN 1 ELSE 0 END),
       CONVERT(DATE, p.CreationDate)
    FROM Posts p
       JOIN Users u on u.Id = OwnerUserId
       JOIN Votes v on p.Id = v.PostId and v.VoteTypeId between 2 and 3
    WHERE u.DisplayName = '##Name##'
      AND p.CreationDate > '2022-12-14 21:00'
    GROUP BY p.id, u.DisplayName, p.Title, p.CreationDate
)
SELECT Id as [Post Link], DisplayName, Title, Up, Created
FROM FourAyes
WHERE Down = 0
ORDER BY Id

A: SEDE isn't accurate enough I guess, due to its weekly scheduled refresh on Sunday. Instead you could leverage the Stack Exchange API. Specially the users/posts endpoint with an appropriate filter. I've tried to mimic your query in the following stack snippet. Your userid and the site that we query are hard coded in the script. I leave it as an exercise for the reader to adapt and enhance the features when warranted.

var userid = 1244491;
var site = 'meta';
var host = 'https://api.stackexchange.com';
var url = `${host}/2.3/users/${userid}/posts?fromdate=1670976000&order=desc&sort=activity&site=${site}&filter=!)qxdRwDaP7)QKzhUN*sI`

function createLink(item) {
  var td = document.createElement('td');
  var a = document.createElement('a');
  a.href = item.link;
  a.textContent = item.link
  td.appendChild(a);
  return td;
}

function createUpvote(item) {
  var td = document.createElement('td');
  td.textContent = item.up_vote_count;
  return td;
}

function createDate(item) {
  var td = document.createElement('td');
  var date = new Date(item.creation_date *1000);
  td.textContent = date.getFullYear()+'-'+(date.getMonth()+1)+'-' + date.getDate()
  return td;
}

function createCard(item) {
  var tr = document.createElement('tr');

  tr.appendChild(createLink(item));
  tr.appendChild(createUpvote(item));
  tr.appendChild(createDate(item));

  return tr;
}

function append(elements) {
  var result = document.getElementById('result');
  for(var element of elements) {
     result.appendChild(element);
  }
}

fetch(url)
  .then(resp => resp.json())
  .then(json => json.items.filter( i => i.down_vote_count === 0))
  .then(items => items.map(i => createCard(i)))
  .then(elements => append(elements));

    link
    upvotes
    date


text:
Q: AQL to validate path to node We're required to have some AQL that validates a specific path to an entity. The current solution performs very poorly, due to needing to scan whole collections.
e.g. here we have 3 entity 'types': a, b, c (though they are all in a single collection) and specific edge collections between them and we want to establish whether or not there is a connection between _key "123" and _key "234" that goes exactly through a -> b -> c.

FOR a IN entities FILTER e._key == "123"
FOR b IN 1..1 OUTBOUND e edges_a_to_b
FOR c IN 1..1 INBOUND e_1 edges_c_to_b
FILTER e_2._key == "234"
...

This can fan out very quickly!
We have another solution, where we use SHORTEST PATH and specify the appropriate DIRECTION and edge collections which is much faster (>100times). But worry that this approach does not satisfy quite our general case... the order of the edges is not enforced, and we may have to go through the same edge collection more than once, which we cannot do with that syntax.
Is there another way, possibly involving paths in the traversal?
Thanks!
Dan.

A: If i understand correctly you always know the exact path that is required between your two vertices.
So to take your example a -> b -> c, a valid result will have:
path.vertices == [a, b, c]
So we can use this path to filter on it, which only works if you use a single traversal step instead of multiple ones.
So what we try to du is the following pattern:
FOR c,e, path IN <pathlength> <direction> <start> <edge-collections>
  FILTER path.vertices[0] == a // This needs to be formulated correctly
  FILTER path.vertices[1] == b // This needs to be formulated correctly
  FILTER path.vertices[2] == c // This needs to be formulated correctly
  LIMIT 1 // We only net exactly one path, so limit 1 is enough
  [...]

So with this hint is it possible to write the query in the following way:
FOR a IN entities
  FILTER a._key == "123"
  FOR c, e, path IN 2 OUTBOUND a edges_a_to_b, INBOUND edges_b_to_c
    FILTER path.vertices[1] == /* whatever identifies b e.g. vertices[1].type == "b" */
    FILTER path.vertices[2]._key == "234"
    LIMIT 1 /* This will stop as soon as the first match is found, so very important! */
    /* [...] */

This will allow the optimizer to apply the filter conditions as early as possible, und will (almost) use the same algorithm as the shortest path implementation.
The trick is to use one traversal instead of multiples to save internal overhead and allow for better optimization.
Also take into account that it might be better to search in the opposite direction:
e.g. instead of a -> b -> c check for c <- b <- a which might be faster.
This depends on the amount of edges per each node.
I assume a doctor has many surgeries, but a single patient most likely has only a small amount of surgeries so it is better to start at the patient and check backwards instead of starting at the doctor and check forwards.
Please let me know it this helps already, otherwise we can talk about more details and see if we can find some further optimizations.
Disclaimer: I am part of the Core-Dev team at ArangoDB


text:
Q: Spring Security filter always being invoked even for endpoints without security set I'm facing some problems with spring security and spring boot here when adding some custom filters.
In my main class I have:
@ComponentScan
@SpringBootApplication
@ImportResource("/applicationContext.xml")
public class Application {}

Also I removed the "spring-boot-starter-security" (I already tried with this dependency) dependency. I thought the problem was related to some automatic stuff from spring boot with spring security, so I tried to "disable" spring-security started by spring boot and configured security by myself, so I added expliclty the dependencies:
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-acl</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>

Then I have a filter which makes a custom authentication:
public class SSOProcessingFilter extends extends GenericFilterBean {}

Then in my applicationContext.xml I created a bean for this filter:
<bean id="ssoAuthenticationFilter" class="com.custom.security.filter.SSOProcessingFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
</bean>

My problem happens when I try to remove security from an endpoint, for example:
<security:http pattern="/api/v1/health" security="none"/>

Once I started the application, It invokes the SSOProcessingFilter every time just by declaring the bean in the applicationContext.xml
I need that once a given endpoint is marked to not have security. this SSOProcessingFilter does not execute.
Do you know why spring boot is always executing this filter even for endpoints without security?
Thanks in advance

A: Filters are applied according to their url patterns. By default subclasses of GenericFilterBean will have /* pattern. If you want to override this default behavior you have to register your filter manually with FilterRegistrationBean.
On the other hand you can allow your authentication filter be hit at each request and let Spring access decision makers do their job. In this case the simplest configuration might look like the following:
<bean id="ssoFilter" class="com.custom.security.filter.SSOProcessingFilter"/>
<bean id="ssoEntryPoint" class="com.custom.security.SSOEntryPoint"/>

<http use-expressions="true" entry-point-ref="ssoEntryPoint">
    <intercept-url pattern="/api/v1/health" access="permitAll()"/>
    <intercept-url pattern="/**" access="isAuthenticated() and hasRole('ROLE_USER')"/>
    <custom-filter ref="ssoFilter" after="BASIC_AUTH_FILTER"/>
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="user" password="secret" authorities="ROLE_USER"/>
        </user-service>
    </authentication-provider>
</authentication-manager>

SSOProcessingFilter will be invoked even if the user accesses /api/v1/health. As long as the request does not meet authentication requirements SSOProcessingFilter should ignore it and let it go throught the filter chain.


text:
Q: Site having issues on android I have http://strutmymutt.com/ for which normal signup and facebook login is not working on Android mobile phones. On the main splash page http://strutmymutt.com/, there is 2 buttons "connect with facebook" and "Use standard signup" but these are working fine everywhere, but not on Android
Please help

A: Worked fine on my 4.2.2 Android phone.  Are you using the emulator?  Do you have facebook installed on the emulator or device and an account that can access it?


text:
Q: How to return Completed status on RxJS Observable in Angular I've imported EmptyObservable like this:
import { EmptyObservable } from 'rxjs/observable/EmptyObservable'

I then assigned it to an object like this:
public user = { initCompleted: new EmptyObservable() }

Both lines validate in Visual Studio Code, the library appears to be found, and no warnings are shown. Based on that, I hope I am on the right path...
Now, when an API call I'm making is done and the results are assigned to a few values on the user object, I want to emit the Completed signal. How do I emit the Completed signal using the EmptyObservable in Angular 6, using RXJS 5.5.6?
I was able to make this work using Subject observer/observable by simply subscribing to user.InitCompleted and waiting for any value from user.initCompleted.next(somevalue), but I'm fairly certain this is not the best tool for the job.


text:
Q: How can I bypass nowsecure.nl via requests lib in python I would like too access nowsecure.nl with using the requests lib in python. But I don't want to use undetected_chromedriver.
i've came up with this as an example:
import os, time, requests
from undetected_chromedriver import v2 as uc

def clear():
    if os.name == "nt":
        os.system("cls")
    else:
        os.system("clear")

if __name__ == "__main__":
    clear()
    driver = uc.Chrome()
    driver.get("https://rblxwild.com")
    time.sleep(2.2)

    cf_clearance = driver.get_cookie("cf_clearance").get("value")
    __cf_bm = driver.get_cookie("__cf_bm").get("value")

    print(f"cf_clearance: {cf_clearance}")
    print(f"__cf_bm: {__cf_bm}")

    driver.quit()

    Headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "en-US,en;q=0.9",
        "Host": "rblxwild.com",
        "From": "https://rblxwild.com",
        "Sec-Ch-Ua": "\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\"",
        "Sec-Ch-Ua-Mobile": "?0",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "none",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
        "cookie": f"cf_clearance={cf_clearance}; __cf_bm={__cf_bm}",
    }

    Session = requests.Session()
    r = Session.post("https://rblxwild.com/crash", headers=Headers, cookies={"cf_clearance": cf_clearance, "__cf_bm": __cf_bm})
    print(r.status_code)

    os.abort()

How to bypass it via requests


text:
Q: finalize() method breaks mid-execution? Question
I have a URLClassLoader anonymous class. In it, I've overridden the finalize() method so that the object will automatically close itself when garbage collected:
protected void finalize() throws Throwable {
    close();
}

and I've overridden the close() method to print some information:
public void close() throws IOException {
    System.out.println("Closing...");
    super.close();
    System.out.println("Closed.");
}

Immediately after creating this object, I call System.gc() to destroy it. As expected, the finalize() method gets called, and then the close() method gets called, but I only see Closing... get printed to the console.
Why does execution never reach my second print statement?

Notes
The first thing that I suspected was happening was that super.close() was throwing an exception, and whatever prepares an object for garbage collection was swallowing the exception, so I tried catching any Throwable and printing it:
public void close() throws IOException {
    System.out.println("Closing...");
    try {
        super.close();
        System.out.println("Closed.");
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

But I got the same exact output as before: Closing.... The next thing I did was test what would happen if I closed the class loader manually, so I just called .close() on my class loader, immediately after constructing it, instead of running System.gc(); In this case, both of my print statements were run:
Closing...
Closed.


text:
Q: new Option() vs  Is there any difference between adding an option to a select via:
mySelect.options[mySelect.options.length] = new Option('val', 'key');

vs
$('#mySelect').append('<option value="key">val</option>');

Does one perform better? Do only certain browsers support new Option()? etc

A: new Option() is faster but may not be cross-browser (version) compatible.  The jQuery solution is better because one of the selling points of jQuery is to ensure cross-browser compatibility.  Also, whatever gain there is in efficiency is too insubstantial to care about.

A: new Option() is faster because it doesn't use external libraries (jQuery in your case)


text:
Q: NAND2Tetris VM Translator If the pointer to the next location in the stack is raved in Ram[SP]/[0], How do I instruct the computer in hack to open the location?
I have tried
@0
D=M
@D

but it isn't opening the address in stored in Ram[0]
How do I make it access the ram address stored in Ram[0]
Thank you

A: You indirect through a ram location using the A/M register.
@SP  // loads the A register with the value SP (SP predefined to 0)
A=M  // loads the A register with the contents of MEM[0] (the stack pointer)
D=M  // loads D with the contents of MEM[Stack]

@D would load the A register with the contents of the symbolic location D, which will get automatically assigned by the assembler. @D (address) and D (register) are not the same thing, and for that reason, using @D is not a good idea.


text:
Q: Wordpress post enumeration I am using wordpress as a quick fix for a blog for my site. I am using a short loop in an external page (i got the links to use the wordpress set-up correctly):
query_posts('p='.$thisPost); //$thisPost enumerates 1,2..etc up to a maximum number of posts

<?php
while (have_posts()): the_post(); ?>

<?php the_title(); ?>

<?php the_content(); ?>
<?php endwhile; ?>

The issue that in the database the wordpress would store post #2 as "p=6", which essentially screws up this setup.
How would I get a post number 2 ( or 3 or n ) from the start?

A: The database is not just storing the posts that you have created, it stores revisions of that post along with other post types, etc. all in this table.  So the post ids of the posts that we enter rarely go up one at a time.
The post ids themselves are not very relevant in the queries.  The specific queries are used to only show posts that have a certain criteria, such as category, post_type, date stored, etc.


text:
Q: Extended (JWT) OncePerRequestFilter cannot be invoked. because @Autowire is failing sothat this.Class is returning null I'm currently building a standard JwtAuthorizationFilter. I extend the OncePerRequestFilter class for this. Furthermore I have a JwtUtils class, which contains all JWT methods. For example, one method validates the JWT bearer token. However, I keep getting the error that this method (and all others) cannot be invoked because this.jwtUtils is null.
So bassicly I am trying to autowire the JwtUtils classe. But Spring is not giving any instance. Instead it is giving null
Thats my error message
Cannot invoke ... jwt.JwtUtils.validateJwtToken(String)" because "this.jwtUtils" is null

JwtAuthorizationFilter class (the error is throwing here)
@Slf4j
public class JwtAuthorizationFilter extends OncePerRequestFilter {

  @Autowired private JwtUtils jwtUtils;
  @Autowired private UserDetailsServiceImpl userDetailsService;

  @Override
  protected void doFilterInternal(
          HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    try {
      String jwt = JwtUtils.resolveToken(request);
      System.out.println("before if " + jwt);
      if (jwtUtils.validateJwtToken(jwt)) { // ERROR !
        String username = jwtUtils.getUserNameFromJwtToken(jwt);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken authentication =
            new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

        SecurityContextHolder.getContext().setAuthentication(authentication);
      }

    } catch (Exception e) {
      JwtAuthorizationFilter.log.error("Cannot set user authentication: {}", e.getMessage());
    }
    filterChain.doFilter(request, response);
  }
}

JwtUtils class
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component
public class JwtUtils {

  @Value("${ggg.app.jwtSecret}")
  private String jwtSecret;

  @Value("${ggg.app.jwtExpirationMs}")
  private long jwtExpirationMs;

  @Value("${ggg.app.jwtRefreshExpirationMs}")
  private long jwtRefreshExpirationMs;

  static String resolveToken(HttpServletRequest req) {
    String bearerToken = req.getHeader("Authorization");
    if (bearerToken != null && bearerToken.startsWith("Bearer ")) return bearerToken.substring(7);
    return null;
  }

  public String generateJwtAccessToken(String username) {
    return generateTokenFromUsername(username, jwtExpirationMs);
  }

  public String generateJwtRefreshToken(String username) {
    return generateTokenFromUsername(username, jwtRefreshExpirationMs);
  }

  private String generateTokenFromUsername(String username, Long expiration) {
    return Jwts.builder()
        .setSubject(username)
        .setIssuedAt(new Date())
        .setExpiration(new Date((new Date()).getTime() + expiration))
        .signWith(secretKey())
        .compact();
  }

  public String getUserNameFromJwtToken(String token) {
    return Jwts.parserBuilder()
        .setSigningKey(secretKey())
        .build()
        .parseClaimsJws(token)
        .getBody()
        .getSubject();
  }

  public boolean validateJwtToken(String token) {
    try {
      Jwts.parserBuilder().setSigningKey(secretKey()).build().parseClaimsJws(token);
      return true;
    } catch (SignatureException e) {
      JwtUtils.log.error("Invalid JWT signature: {}", e.getMessage());
    } catch (MalformedJwtException e) {
      JwtUtils.log.error("Invalid JWT token: {}", e.getMessage());
    } catch (ExpiredJwtException e) {
      JwtUtils.log.error("JWT token is expired: {}", e.getMessage());
    } catch (UnsupportedJwtException e) {
      JwtUtils.log.error("JWT token is unsupported: {}", e.getMessage());
    } catch (IllegalArgumentException e) {
      JwtUtils.log.error("JWT claims string is empty: {}", e.getMessage());
    }
    return false;
  }

  private SecretKey secretKey() {
    return Keys.hmacShaKeyFor(jwtSecret.getBytes());
  }
}

WebSecurityConfig
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired private UserDetailsServiceImpl userDetailsService;

  @Bean
  private static PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
  }

  @Bean
  private static JwtAuthorizationFilter authenticationJwtTokenFilter() {
    return new JwtAuthorizationFilter();
  }

  //  @Override
  //  public void configure(AuthenticationManagerBuilder authenticationManagerBuilder)
  //      throws Exception {
  //    authenticationManagerBuilder
  //        .userDetailsService(userDetailsService)
  //        .passwordEncoder(WebSecurityConfig.passwordEncoder());
  //  }

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    // Disable CSRF (cross site request forgery)
    http.cors()
        .and()
        .csrf()
        .disable()
        // No session will be created or used by spring security
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/api/v1/auth/**", "/confirm-account")
        .permitAll()
        .anyRequest()
        .authenticated();

    // Apply JWT
    http.addFilterBefore(
        WebSecurityConfig.authenticationJwtTokenFilter(),
        UsernamePasswordAuthenticationFilter.class);
  }
}

Problem solver ?
 @Bean
  public JwtAuthorizationFilter authenticationJwtTokenFilter() {
    return new JwtAuthorizationFilter();
  }

I found out that the private static JwtAuthorizationFilter
authenticationJwtTokenFilter() method is calling the issue. If i change that to a public method it is working, although passwordEncoder is privat static and is used in my auth service . Unfortunately it is my plugin which is causing that problem. It changes the code automatically. Does somebody know what to do ?
AuthService class
@Service
public class AuthService implements AuthServiceRepository {

  @Autowired private RoleRepository roleRepository;
  @Autowired private UserRepository userRepository;
  @Autowired private PasswordEncoder encoder;
  @Autowired private JwtUtils jwtUtils;
  @Autowired private AuthenticationManager authenticationManager;
  @Autowired private UserService userService;
  @Autowired private EmailService emailService;
  @Autowired private ConfirmationTokenRepository confirmationTokenRepository;

@Override
  public JwtResponse signUpUser(SignUpRequest signUpRequest, String siteURL)
      throws MessagingException, UnsupportedEncodingException {
    String accessToken = jwtUtils.generateJwtAccessToken(signUpRequest.getUsername());
    String refreshToken = jwtUtils.generateJwtRefreshToken(signUpRequest.getUsername());
    Set<Role> roles = SignUpRequest.getRoles(signUpRequest, roleRepository);
    AppUser user =
        new AppUser(
            signUpRequest.getUsername(),
            signUpRequest.getEmail(),
                encoder.encode(signUpRequest.getPassword()));
    user.setRoles(roles);

    user.setEnabled(false);
    AppUser newUser = userService.saveUser(user);
    ConfirmationToken confirmationToken = new ConfirmationToken(user);
    confirmationTokenRepository.save(confirmationToken);
    emailService.sendVerificationEmail(user, siteURL, confirmationToken.getConfirmationToken());
    List<String> userRoles =
        newUser.getRoles().stream().map(role -> role.getName().name()).collect(Collectors.toList());

    return new JwtResponse(
        accessToken,
        refreshToken,
        user.getId(),
        signUpRequest.getUsername(),
        signUpRequest.getEmail(),
        userRoles);
  } ... }

A: That's because JwtUtils and WebSecurityConfig are not registered as Spring Beans. Try to add a @Component annotation to the classes.
More about dependency injection in Spring Boot: https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.spring-beans-and-dependency-injection


text:
Q: How to Export data fields from .dbf to .sqlite table using php script How to export all data fields in database foxpro table (.dbf) to sqlite  table (.sqlite) using php script.
Thanks in advance

A: php has support for both, see the documentation for more details:

*

*dBase

*sqlite
I don't know if you actually have more specific issues, so this is as detailed as my answer can be. Please provide more details for a more specific answer.


text:
Q: Create AWS Resource Group where Tags do not equal some value I'm trying to create an AWS Resource Group that helps me locate non-standard resources. In my case, that's one of these two options:

*

*Resources missing an Environment tag

*Resources with a non-standard Environment tag value (e.g. Environment != Production AND Environment != Development)

A: It is possible to find the resources missing a tag. Use the Tag Editor to find the resources that are not missing an Environment tag.

Then click on View as resource group, give a name to the group and save.


text:
Q: Retrieve unique entries from DB using Eloquent Laravel 4 I am using Laravel-4 to build an application. I am trying to make the best use of Eloquent ORM. Currently I am displaying a list of db entries which all have a number of tags associated with them
 To the right I display a grid of all the tags however it is showing duplicate tags. I would only like to show unique tags
This is my code:

Tags

            @foreach(Tag::distinct()->get() as $tag)
                 {{ Tag::getAmount($tag->id) }}  {{$tag->name}}
            @endforeach

Does Eloquent provide a way of only retrieving distinct entries from the db?

A: Try using Tag::groupBy('field_name')->get()

Tags

            @foreach(Tag::groupBy('field_name')->get() as $tag)
                 {{ Tag::getAmount($tag->id) }}  {{$tag->name}}
            @endforeach

A: To use the distinct()-function you have either have a select() in your chain, or use a field as an argument in your get()-function. For example:
$tags = Tag::distinct()->get(array('field'));

or
$tags = Tag::select('field')->distinct()->get();

You could also instead use groupBy('field') if you don't want to supply field names:
$tags = Tag::groupBy('field')->get();


text:
Q: Change help message when select change I have a little symfony form with a select field inside.
$builder
    ->add('automaticPaymentMethod', EnumType::class, [
        'class' => AutomaticPaymentMethod::class,
        'horizontal' => false,
        'label_render' => false,
        'translation_domain' => 'global',
        'prefix_label_with_class' => true,
    ])
;

Working with this enum class
final class AutomaticPaymentMethod extends AbstractEnum
{
    const NONE = 'none';
    const CREDIT_CARD = 'card';
    const BANK_ACCOUNT = 'bank';
}

I'm trying to change the value of help_block` option with a translated message from my translation files, when the selected value change.
I tried with EventListener and EventSubscriber but this don't work when the select change.
How can I do this ? Should I use ajax to change this message or php is good enough ?
Thanks for your help.

A: To control the select field change you must to do by javascript, in other case, you must to load all the form, if i had to do this, i put the translations of the help block in data attributes in the select and show this based on the select value. For example:
<select>
  <option value="1" data-help-block="{{ 'help block 1'|trans() }}"/>
  <option value="2" data-help-block="{{ 'help block 2'|trans() }}"/>
</select>

And update the help block according the selected value


text:
Q: How to sort files files alphabetically rather than numerically in file manager With "ls" the following files are sorted as I want as:
026  046  048  08f  28f  46a

but in file manager (I have tried nautilus, nemo and pcmanfm) they are sorted as:
08f  026  28f  046  46a  048

At this article says you can affect sort order in file browser using:
export LC_COLLATE=C;   nemo&

But I tried this and the sort order is still the same - numerically not alphabetical.
Is there away of getting any file manager to sort as ls does by some option in preferences or by setting a variable such as LC_COLLATE?
-
Extra information on why files are sorted numerically for those interested :
At bugs.launchpad.net
the reason given for sorting numerically goes something like a user expects the following files to be ordered numerically like:
8     9   10   11  101

and not alphabetically like:
10  101   11    8    9

and where as I can see this point:

*

*If files are ordered alphabetically, then you simply need to pad files with a zero, to make them ordered numerically (easy to script using printf "%03d" ), but there is nothing you can pad files that are ordered numerically to order them alphabetically.

*It is not obvious how the files ordered numerically at the top of this post are sorted - I spent 30 mins creating various files and could not figure out how they were being sorted and had to resort to Google to work it out, where as it is a lot easier to workout that "numbered" files like 10,101,11,8,9 are ordered alphabetically.

*Even AFTER I knew files were ordered numerically it still took a while to understand, and hard to locate the files I wanted (I have over 70 files to look through) - point in case is the comment by "muru" who says they couldn't see how 08f comes before 026 numerically and they have a reputation of over 100,000, so is clearly very intelligent.  In contrast, when you know files are ordered alphabetically it is easy to understand how the "numbered" files are sorted and easy to locate them.
I don't mind the default being to sort numerically in a file browser as long as there is an option to change default to sort alphabetically, so surely there is a file manager that has this option or that uses "LC_COLLATE"


text:
Q: Not able to add Users to Site Collection in SharePoint 2013 I am having big issues in adding users to a site collection to giving them access.
Let me describe to you my problem:

*

*I have created a site collection and can set the site collection administrators.

*To even allow the site administrators access I have to set Everyone in the User Policy in Managed Web Application. If I change this, everyone is not able to access the site. Why it is this way, I do not know.

*User Profile Synchronization Service is set to Active Directory Import and ALL Services are running. I have left User Properties to default and thus deliberately have not changed them

*Leaving access to Everyone through User Policy, I can then log on to the site. Going to site settings, and then to Site Permissions, searching for a user to add to the site, returns nothing. There are no users coming up.

*However, in Central Administration I can see ALL my users from Active Directory.
So, can someone please if they can answer me the following questions:

*

*How do I ensure that I can see any user imported into SharePoint 2013 are visible in any Site Collection?

*How do I ensure that a Site Collection Administrator set during Site Collection creation can get access without having to set User Policy to Everyone, or is this the way?

A: Indeed this is not a programming question.
It might be useful to enable verbose level SharePoint ULS in central admin and see what authentication error or relevant info it catches when a AD user attempts to access the site you referred.

A: Be aware that there is no dependency between the UPS and security. You do not need a sync before you can add users.
What happens when you can't access? Do you get a 401 or a SharePoint message to say you don't have access?
I assume you have a farm account? Can it access the site collections after you have created them? Can you access the web objects via powershell? If so Can you test this:
$web = Get-SpWeb http://spsite
$web.ensureuser("domain\user")

Does the above throw an exception or return a userlogin and displayname?


text:
Q: How to use simple-peer with react-native-webrtc I'm trying to use react-native-webrtc in the constructor for simple peer
import wrtc from 'react-native-webrtc';

const peer = new SimplePeer({initiator: true, wrtc: wrtc});

the error I'm getting is
ExceptionsManager.js:179 Error: No WebRTC support: Not a supported browser

A: you have to import it like this

import {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
  MediaStreamTrack,
  mediaDevices,
  registerGlobals
} from 'react-native-webrtc';

const peer = new SimplePeer(
{initiator: true,
 wrtc: {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
  MediaStreamTrack,
  mediaDevices,
  registerGlobals
  },
});


text:
Q: ServiceStack with AngularJS: JSON Vulnerability Protection and XSRF The AngularJS documentation provides some recommendation to protect a web side against JSON Vulnerability and XSRF Attacks (https://docs.angularjs.org/api/ng/service/$http section "Security Considerations").
How can I configure the JSON serialize to prefix my JSON?
What is the best way to get a verifiable value for the "X-XSRF-TOKEN" token value and how to validate that for each request?

A: You can add a GlobalResponseFilter to prefix your JSON with:
this.GlobalResponseFilters.Add((req, res, dto) =>
{
    if (req.ResponseContentType.MatchesContentType(MimeTypes.Json)
        && !(dto is IHttpResult))
    {
        res.Write(")]}',\n");
    }
});

Which will write the recommended prefix before the serialized JSON response.
This will protect against JS Array vulnerability, an alternative approach would be to wrap array responses in a DTO, e.g:
return new Response { Results = Db.Select<Poco>() };

Which would serialize as a JSON object avoids the JS Array vulnerability.
I prefer returning object responses since it doesn't limit your JSON services to only work with appropriately configured JS Apps and object responses are more forward-compatible/future-proofed as you can later modify the service to return multiple return types without breaking compatibility with existing clients.
Any random string should make a good token, e.g. hex-encoded random bytes or just a new Guid.


text:
Q: An eigenvalue problem for positive semidefinite matrix Let  $  \begin{bmatrix}
A& B   \\ B^*  &C
\end{bmatrix}$ be positive semidefinite, $A,C$ are of size $n\times n$. Is it true that $$\quad \sum\limits_{i=1}^n\lambda_i\begin{bmatrix}
A& B   \\ B^*  &C
\end{bmatrix}\le \sum\limits_{i=1}^n\left(\lambda_i(A)+\lambda_i(C)\right)\quad? $$
Here, $\lambda_i(\cdot)$ means the $i$th largest eigenvalue of $\cdot\quad$

A: Since the sum of all eigenvalues is equal to the trace of a matrix, we can say the former actually equals the latter sum, so long as you change the indices of the left sum to run over all values from 1 to $2n$. If you're interested in keeping the indexing as it is, then the sum on the left will be smaller than or equal to what it would have been running over all eigenvalues (since all eigenvalues of a positive semi-definite matrix are nonnegative), thus your inequality is correct.

A: Note that, using your notation, $\quad \sum\limits_{i=1}^{2n}\lambda_i(\begin{bmatrix}
A& B   \\ B^*  &C
\end{bmatrix}) = \text{tr}( \begin{bmatrix}
A& B   \\ B^*  &C
\end{bmatrix}) = \text{tr} (A) + \text{tr} (C) = \sum\limits_{i=1}^n\left(\lambda_i(A)+\lambda_i(C)\right),$
so your inequality can actually be made stronger. But your inequality holds, since all the eigenvalues of a positive semidefinite matrix satisfy $\lambda_i \ge 0$, so if the sum on the LHS only goes up to $n$ it will of course be lessened.


text:
Q: .NET Web Service Using WEB CONFIG Settings Hard Coded Net TCP I wanted to confirm something.
Below is how I am spinning up a call to my WCF web service in my ASP.NET application.
var xml = "my xml string";
var ep = new EndpointAddress("http://myendpoint");
xml = new Proxy.ServiceClient(new NetTcpBinding(), ep).getNewXML(new Proxy.CallContext(), xml);

My web config looks similar to below. My question is, even though these settings are in the web config, the fact that my calls above are newing up the a service client and fresh New TCP binding everytime tell me that these settings aren't being referenced. Is this correct based on above?
 <system.serviceModel>
  <bindings>
   <netTcpBinding>
    <binding name="NetTcpBinding_SCSService" closeTimeout="00:01:00"
     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
     transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
     hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288"
     maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
      maxBytesPerRead="4096" maxNameTableCharCount="16384" />
     <reliableSession ordered="true" inactivityTimeout="00:10:00"
      enabled="false" />
     <security mode="Transport">
      <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
      <message clientCredentialType="Windows" />
     </security>
    </binding>
   </netTcpBinding>
  </bindings>
  <client>
   <endpoint address="net.tcp://myendpoint"
    binding="netTcpBinding" bindingConfiguration="NetTcpBinding_SCSService"
    contract="Proxy.Service" name="NetTcpBinding_SCSService">
    <identity>
     <userPrincipalName value="user@user.com" />
    </identity>
   </endpoint>
  </client>
 </system.serviceModel>

A: That's correct. In this case, you are not using the configuration settings found in the config file.
Proxies typically derive from the abstract class ClientBase<T> which provides several different ways to create an instance of a client proxy. Some of the constructors listed will use all of the config file while others will attempt to use the config file to fill in the information that has not been explicitly supplied in the constructor. There are even constructor overloads which do not use the configuration file at all which ClientBase<TChannel>(Binding, EndpointAddress) is one of them.
If you wanted to use what was in the application configuration file, you could use:
var client = new Proxy.ServiceClient("NetTcpBinding_SCSService");


text:
Q: Add an IBAction to a UIBarButton I programmatically created a UIBarButton and I want it to segue to another viewController. I tried it with the following code, and it gave me an error. (If you would like me to post the error I can.)
[btn addTarget:self action:@selector(myAction) forControlEvents:UIControlEventTouchDown];

A: Your method declaration doesn't match your @selector - Your method accepts a parameter (sender), so your selector is myAction:.  Your code should be
[btn addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchDown];

Also, your image load won't work on the device because the path isn't available - you will need to load it from the bundle.
And, I don't know what functionality you are looking for with the button, but if it is a "tap" you should use event UIControlEventTouchUpInside rather UIControlEventTouchDown

A: Please try to replace this line
[btn addTarget:self action:@selector(myAction) forControlEvents:UIControlEventTouchDown];

With that line
[btn addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchDown];


text:
Q: Sending JSON Data to MongDB via Mongoose I currently have a JSON object and I'm having trouble persisting it to a mongoDB database via mongoose. There are two main questions I have.

*

*Is my model setup correctly for the JSON object I have below? I've never used subdocuments before, so this is a first.

*I keep getting an error when I try to persist the data (error: "object is not a function").  What am I doing wrong?

All code is below.
Here is how I've setup mongoose.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/yjs');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'mongodb connection error:'));

var Schema = mongoose.Schema;

var resultsSchema = new Schema({
    jobtitle: String,
    company: String,
    city: String,
    state: String,
    country: String,
    formattedLocation: String,
    source: String,
    date: String,
    snippet: String,
    url: String,
    onmousedown: String,
    jobkey: String,
    sponsored: Boolean,
    expired: Boolean,
    indeedApply: Boolean,
    formattedLocationFull: String,
    formattedRelativeTime: String
});

var jobSchema = new Schema({
    version: Number,
    query: String,
    location: String,
    dupefilter: Boolean,
    highlight: Boolean,
    radius: Number,
    start: Number,
    end: Number,
    totalResults: Number,
    pageNumber: Number,
    results: [resultsSchema]

});

var Jobs = mongoose.model('Jobs', jobSchema);

module.exports = {
    Jobs: Jobs
}

This is my JSON object:
{
  version: 2,
  query: "javascript $19,900-$20,900",
  location: "New York, NY",
  dupefilter: true,
  highlight: true,
  radius: 25,
  start: 1,
  end: 3,
  totalResults: 3,
  pageNumber: 0,
  results: [
    {
      jobtitle: "Web Application Developer",
      company: "Sogeti",
      city: "New York",
      state: "NY",
      country: "US",
      formattedLocation: "New York, NY",
      source: "Sogeti",
      date: "Sat, 15 Nov 2014 08:50:24 GMT",
      snippet: "Roles/ Responsibility/ Qualifications: Position Location: Raritan, New Jersey Sogeti is a leading provider of technology and software testing, specializing...",
      url: "http://www.indeed.com/viewjob?jk=5c3af4fc30704f52&qd=PgQusJx_gGiiAmACeKxgepvuLa6C1I07uk43fDZ3DSq8GvDGPvLAOvUmXryxs9bezoA6A_gJOaAYR60u2fV5hFgosDLOUjUrxWWMfxXcFW0txtBb9O5egndMhGuvOU46RMGL25yEMtQuUuTH37UmVA&indpubnum=9222093808317380&atk=19g75527l0np13ao",
      onmousedown: "indeed_clk(this, '2276');",
      jobkey: "5c3af4fc30704f52",
      sponsored: false,
      expired: false,
      indeedApply: false,
      formattedLocationFull: "New York, NY",
      formattedRelativeTime: "30+ days ago"
    },
    {
      jobtitle: "Interactive Designer – New York",
      company: "Unruly Ltd",
      city: "New York",
      state: "NY",
      country: "US",
      formattedLocation: "New York, NY",
      source: "Unruly Ltd",
      date: "Fri, 28 Nov 2014 00:05:17 GMT",
      snippet: "WANTED: Positioned at the intersect of the three fastest-growing trends in digital advertising – programmatic, video and mobile – Unruly is a high-growth tech",
      url: "http://www.indeed.com/viewjob?jk=98f978c3e33061d1&qd=PgQusJx_gGiiAmACeKxgepvuLa6C1I07uk43fDZ3DSq8GvDGPvLAOvUmXryxs9bezoA6A_gJOaAYR60u2fV5hFgosDLOUjUrxWWMfxXcFW0txtBb9O5egndMhGuvOU46RMGL25yEMtQuUuTH37UmVA&indpubnum=9222093808317380&atk=19g75527l0np13ao",
      onmousedown: "indeed_clk(this, '2276');",
      jobkey: "98f978c3e33061d1",
      sponsored: false,
      expired: false,
      indeedApply: true,
      formattedLocationFull: "New York, NY",
      formattedRelativeTime: "30+ days ago"
    },
    {
      jobtitle: "Java Angular JS Developer",
      company: "UST Global",
      city: "Edison",
      state: "NJ",
      country: "US",
      formattedLocation: "Edison, NJ",
      source: "Dice",
      date: "Wed, 18 Feb 2015 14:06:16 GMT",
      snippet: "Rakesh.Sasidharanust-global.com <b>Javascript</b>, Angular JS, JQuery, Ext. Java Angular JS Developer 5 years experience in Java and web development Should have...",
      url: "http://www.indeed.com/viewjob?jk=f347ca5dc7439231&qd=PgQusJx_gGiiAmACeKxgepvuLa6C1I07uk43fDZ3DSq8GvDGPvLAOvUmXryxs9bezoA6A_gJOaAYR60u2fV5hFgosDLOUjUrxWWMfxXcFW0txtBb9O5egndMhGuvOU46RMGL25yEMtQuUuTH37UmVA&indpubnum=9222093808317380&atk=19g75527l0np13ao",
      onmousedown: "indeed_clk(this, '2276');",
      jobkey: "f347ca5dc7439231",
      sponsored: false,
      expired: false,
      indeedApply: false,
      formattedLocationFull: "Edison, NJ 08817",
      formattedRelativeTime: "22 days ago"
    }
  ]
}

How I'm trying to persist data:
var job = new Jobs(json_object);

Jobs.create(json_object, function (err, job) {
    if (err) return handleError(err);

    return job();
});

Any guidance would be greatly appreciated!  And sorry about the formatting of the JSON object, I can't get it to stay as code when I change the formatting. It's basically an object, with one of the key values being an array of objects.

A:   models.Jobs.create(json_object, function (err) {
        if (err) {return handleError(err);

        } else {
            console.log('data collected')
        }

    })

The above code fixed the issue.  Also seems like the subdocuments are working correctly. I completely glanced over what the module I was requiring.


text:
Q: Create two matrices from one dataset in R I'm new in R so my question is probably trivial. I would like to make a matrix x1i of 50 random vectors (from matrix x) with condition [,27]==0. For example: in my x matrix I have 70 vectors where [,27]==0 and I would like to randomly select 50 of them.
x<-matrixData #100 rows and 27 columns

xi<-x[x[,27]==0,]

x1i<-xi[sample(1:50),]

Is that ok? Now I would just like to create another matrix x2 from the remaining (50) vectors/rows that were not in x1i.
So simply x minus x1i.
Everything I try, I get

Error in xj[i] : invalid subscript type 'list'

Any help is greatly appreciated!

A: Try this solution:
sample<-sample(which(x[,27]==0),50)

x[sample,] #50 rows sample
x[-sample,] #other rows

Starting from your x matrix a sample (variable sample) composed by 50 rows based on the condition which(x[,27]==0) is extracted. Using -sample you are able to extract the rest of the matrix.


text:
Q: Display Tables on Tabs I have two tables containing different sets of data.  I want the tables to be displayed on separate tabs. My code works perfectly when I display just one table, but whenever I try to display both the tables values are no longer displayed, just the various titles.  Any help is much appreciated.  Below is my code.  I use the Lahman database and DT package.
server.R:
library(shiny)
library(ggplot2)

# Define a server for the Shiny app
shinyServer(function(input, output) {

 # Filter data based on selections
output$table <- DT::renderDataTable(DT::datatable({
data <- Pitching
if (input$yearID != "All") {
  data <- data[data$yearID == input$yearID,]
}
if (input$lgID != "All") {
  data <- data[data$lgID == input$lgID,]
}
if (input$teamID != "All") {
  data <- data[data$teamID == input$teamID,]
}
data
}))

output$table2 <- DT::renderDataTable(DT::datatable({
data <- Batting
if (input$yearID != "All") {
  data <- data[data$yearID == input$yearID,]
}
if (input$lgID != "All") {
  data <- data[data$lgID == input$lgID,]
}
if (input$teamID != "All") {
  data <- data[data$teamID == input$teamID,]
}
data
}))

})

ui.R:
library(shiny)

# Load the ggplot2 package which provides
# the 'mpg' dataset.
library(ggplot2)

# Define the overall UI
shinyUI(
  fluidPage(
   titlePanel("Pitching"),

   # Create a new Row in the UI for selectInputs
   fluidRow(
    column(4,
         selectInput("yearID",
                     "Year:",
                     c("All",
                       unique(as.integer(Pitching$yearID))))
  ),
  column(4,
         selectInput("lgID",
                     "League:",
                     c("All",
                       unique(as.character(Pitching$lgID))))
  ),
  column(4,
         selectInput("teamID",
                     "Team:",
                     c("All",
                       unique(as.character(Pitching$teamID)))))
),

# Create a new row for the table.
fluidRow(
  DT::dataTableOutput("table")

),

fluidPage(
  titlePanel("Batting"),

  # Create a new Row in the UI for selectInputs
  fluidRow(
    column(4,
           selectInput("yearID",
                       "Year:",
                       c("All",
                         unique(as.integer(Batting$yearID))))
    ),
    column(4,
           selectInput("lgID",
                       "League:",
                       c("All",
                         unique(as.character(Batting$lgID))))
    ),
    column(4,
           selectInput("teamID",
                       "Team:",
                       c("All",
                         unique(as.character(Batting$teamID)))))
  ),

  # Create a new row for the table.
  fluidRow(
    DT::dataTableOutput("table2")

  ),

  mainPanel(
    tabsetPanel(type = "tabs",
    tabPanel("Pitching",tableOutput("table")),
    tabPanel("Batting", tableOutput("table2"))
  )
)
 )
  ))

A: It seems like you are calling the tables twice (one in DT::dataTableOutput(), and again in tableOutput()). The table names (table and table2) are given IDs, which in valid HTML syntax can only be called once. You are calling them twice, which might be the reason why your tables are not showing up. Why do you need to call them twice?

A: As Bogdan mentions you are attempting to render your tables twice in the UI. This appears to be your main issue.
You are most the way there, however your double call to render the table twice makes me think you're wanting the pitching to be on one tab and the batting to be on another.
See the updated ui.R file below:
library(shiny)

# Load the ggplot2 package which provides
# the 'mpg' dataset.
library(ggplot2)

# Define the overall UI
shinyUI(
  fluidPage(
    mainPanel(
        tabsetPanel(type = "tabs",
                    tabPanel("Pitching",
    titlePanel("Pitching"),

    # Create a new Row in the UI for selectInputs
    fluidRow(
      column(4,selectInput("yearID","Year:",
                         c("All", unique(as.integer(Pitching$yearID))))
      ),
      column(4,selectInput("lgID","League:",
                         c("All",unique(as.character(Pitching$lgID))))
      ),
      column(4,selectInput("teamID","Team:",
                         c("All",unique(as.character(Pitching$teamID)))))
    ),

    # Create a new row for the table.
    fluidRow(
      DT::dataTableOutput("table")

    )),
    tabPanel("Batting",
      titlePanel("Batting"),

      # Create a new Row in the UI for selectInputs
      fluidRow(
        column(4,selectInput("yearID","Year:",
                           c("All",unique(as.integer(Batting$yearID))))
        ),
        column(4,selectInput("lgID","League:",
                           c("All",unique(as.character(Batting$lgID))))
        ),
        column(4,selectInput("teamID","Team:",
                           c("All",unique(as.character(Batting$teamID)))))
      ),

      # Create a new row for the table.
      fluidRow(
        DT::dataTableOutput("table2")
      )
      )
    )
  )))


text:
Q: Magento table rates and multiple stores? I am trying to make my table rates work with my multi store setup. I have 2 stores (not only store views) for the same installation and I want table rates for that.
I tried with the built in table rates and I also tried with http://www.magentocommerce.com/magento-connect/webshopapps-matrixrate-1-multiple-table-rates-extension.html.
The problem is, this only seems to work for my first store, the second store always tells me that there is no shipping available in the OPC.
I checked the tables shipping_tablerate and shipping_matrixrate (this one comes from the extension) and both have the website_id column which is 1 (my first store) for me. I tried changing from 1 to 3 (thats the id of my other store), did not help.
This is the content for the extensions file:
Land,Region/Staat,Stadt,"Zip/Postal Code From","Zip/Postal Code To","Gewicht From","Gewicht To",Versandkosten,"Delivery Type"
DEU,*,,,,1.1000,2.0000,4.4000,Versand
DEU,*,,,,2.1000,5.0000,6.9900,Versand
DEU,*,,,,0.2000,1.0000,3.9500,Versand
DEU,*,,,,0.0000,0.1000,6.9900,Versand

How can I make this work for my second store as well?
Thanks!

A: you just need to import csv for all websites.
No changes in code.


text:
Q: confusing coordinate system on storyboard xcode? I'm trying to make my image view that i put in Xcode right at 0, 0 top right corner with 320 460 so it spans over entire screen, in the size inspector i made sure to have the origin with the red arrows right at the top left so its the right coordinate thing, but for some reason when i put the image view in the exact center its telling me that the center is 20x 160 y
why is it doing this, when i click on my view its saying the center is 0x 0y the way is supposed to be, this is making me mad

A: Im not sure what you mean by "when i put the image view in the exact center", but regardless if you use the size inspector, and set the origin to (0,0) with a size of (320,460), it will span the entire view.
Beyond that, the view you are loading the image view into needs to be origined at (0,0) and with a size of (320,460).
It sounds like the views you are putting the image view into are not positioned correctly, as the coordinate system is in relation to the parent view.


text:
Q: Applying kernel function to input data before giving it to algorithm I have gene expression data, I do dimensionality reduction and clustering with self organizing maps, but self organizing maps do not perform well with my data.
I want to map my data to feature space using different kernel functions and then give this data as input to self organizing maps to compare their performance.
My input data is of dimension $m\times n$, and upon applying a given kernel it becomes a square matrix, which I don't want to.
How can I map my data to feature space without changing dimension of my input matrix?

A: In general, kernels are not interpretable in the original feature space. The m by m gram/covariance matrix computed in the problem statement is the explicit mapping of the kernel function.
Each element represents the i,j distance between points i,j in the original feature space. This operation does not have an inverse to the original feature space. Each feature in kernel space represents the distance to each observation in your original space.
Finding a point in the original feature space is geometrically equivalent to triangulation in the basis function of your kernel. For an RBF kernel this is finding the point of intersection for m circles of radius given by the weight of the kernel feature, where each circle has an origin at the mth observation.
Depending on the goal of the analysis, k-means cluster centers might suffice.

A: Most of the kernels (assuming you mean kernel trick as in SVM) used are of an infinite dimension, you will have trouble storing them in our puny not-really-a-turning-machine-no-infinite-memory computers.
You will need to use an approximate version of the feature vectors, such as those obtained using Nystrome's method or Random Fourier Features.


text:
Q: Autofac with FluentValidation in MVC2 I'm getting a 'not registered error' during execution in the ValidatorFactory.CreateInstance call. It appears the type being sent into the method is correct.
My registration code:
...
builder.RegisterAssemblyTypes(assembly).Where(t => t.Name.EndsWith("Validator")).As<IValidator>();
builder.Register(d => _containerProvider).As<IContainerProvider>();
builder.Register(d => new ValidatorFactory(_containerProvider.ApplicationContainer.Resolve<IContainerProvider>())).As<IValidatorFactory>();

_containerProvider = new ContainerProvider(builder.Build());

My ValidatorFactory code:
public class ValidatorFactory : ValidatorFactoryBase {
    private readonly IContainerProvider _containerProvider;

    public ValidatorFactory(IContainerProvider containerProvider) {
        _containerProvider = containerProvider;
    }

    public override IValidator CreateInstance(Type validatorType) {
        return _containerProvider.ApplicationContainer.Resolve<IValidator>(validatorType);
    }
}

My view model and validator code:
[Validator(typeof(EmployeeViewModelValidator))]
public class EmployeeViewModel {
    public EmployeeViewModel() {}
    public EmployeeViewModel(string firstName) {
        FirstName = firstName;
    }

    public string FirstName { get; private set; }
}

public class EmployeeViewModelValidator : AbstractValidator<EmployeeViewModel> {
    public EmployeeViewModelValidator() {
        RuleFor(x => x.FirstName)
            .NotEmpty();
    }
}

My best guess is that I'm registering the validators wrong.

A: To resolve from multiple classes that implement IValidator, the autofac documentation shows a couple of techniques.  I don't think you can use assembly scanning with these methods; you'll have register the validators individually.
By Name
builder.RegisterType<EmployeeViewModelValidator>().Named<IValidator>("employee");

var r = container.Resolve<IValidator>("employee");

By Key
The documentation shows an enumeration being used as a key, but you could use the type as the key, which would let you call Resolve using the validatorType being passed to you in the CreateInstance method.
builder.RegisterType<EmployeeViewModelValidator>().Keyed<IValidator>(typeof(EmployeeViewModelValidator));

var r = container.Resolve<IValidator>(validatorType);

Note:  The documentation is for version 2.3 of Autofac.  I'm using 2.2.4, which is why the method names above vary from the documentation.
Hope this helps.

A: The other answer by @adrift is a nice clean approach. Just to add some notes, this also works with the IIndex<K,V> relationship type, which Autofac provides automatically, e.g.:
public class ValidatorFactory : ValidatorFactoryBase {
    readonly IIndex<Type, IValidator> _validators;

    public ValidatorFactory(IIndex<Type, IValidator> validators) {
        _validators = validators;
    }

    public override IValidator CreateInstance(Type validatorType) {
        return _validators[validatorType];
    }
}

Important note: don't use IContainerProvider and ApplicationContainer in a component—instead use IComponentContext or IIndex<K,V> as above. This will help prevent lifetime issues (your example associates validators with the application rather than the request lifetime.)

A: Current Registration Code:
builder.RegisterType<EmployeeViewModelValidator>().Keyed<IValidator>(typeof(EmployeeViewModel));
builder.RegisterType<ValidatorFactory>().As<IValidatorFactory>();

_containerProvider = new ContainerProvider(builder.Build());

Current ValidatorFactory:
public class ValidatorFactory : ValidatorFactoryBase {
    readonly IIndex<Type, IValidator> _validators;

    public ValidatorFactory(IIndex<Type, IValidator> validators) {
        _validators = validators;
    }

    public override IValidator CreateInstance(Type validatorType) {
        return _validators[validatorType];
    }
}

Same error inside CreateInstance:
The requested service 'FluentValidation.IValidator`1[.EmployeeViewModel] (FluentValidation.IValidator)' has not been registered.


text:
Q: Spacing between two barButtons in Navigation Bar-ios iOS
I have three right bar buttons items in my navigation Bar.
I want to change the default spacing between them to zero, so that all the buttons stick to each other?

A: You can try adding a spacer (UIBarButtonSystemItemFixedSpace) with a negative value. See this answer for more details.
Another approach could be using a custom item with a smaller size than its content then allowing drawing outside out of its bounds using UIView.clipToBounds property.


text:
Q: HttpClient on GAE I'm really curious as how JIQL admin demo was able to run on Appengine cloud (appspot.com)
Whereas where I tried to port the available sources like the Guestbook and the Jqladmin app I get this error:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.HttpException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:176)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 44 more

However, there is a running JiqlAdmin that runs on top of GAE and I have tried and was able to execute a SQL query:
http://jiqladmin.appspot.com/Jiqladmin.html
Just wondering what went wrong in my app.

A: Error seems obvious, you should add Apache commons Http client as dependency. Try putting that in your war/WEB_INF/lib or add it as dependency in Eclipse.


text:
Q: What are the Golden Chests for and where are the Moon ones? I found a Golden Chest on the Moon. Is it just for simple loot? Are there others on the moon? How many are there?

A: Golden Chests just contain loot, yes. It's also worth noting that they scale on the area, not your level. So it's best to find them asap. You also are given an item for finding all the golden chests on a single planet. I know that you get a Sparrow from Earth and an Emblem from the Moon.
There's a few on each of the planets in-game at the moment. There are 5 on the moon
1 - Found during the The World's Grave mission inside the cave full of cocoons.
2 - Head to the mission marker located in the large yellow building. Proceed until you find the green gas pit. Look nearby for a rock formation and orange lights.
3 - Another in The World's Grave. When defending your Ghost search a nearby room with a little pool of water
4 - Inside the Temple of Crota during the Chamber of Night mission.
5 - The Summoning Pits Strike mission. After the final boss fight walk to the edge of the room and drop down onto a small platform
I'm affiliated with Gamers Heroes and we have a guide on the topic should you need more direction: Destiny Gold Chests Moon