text:
Q: What does the corner-asterisk mean in the Extensions sidebar? In the Extensions Sidebar, some of my installed extensions are marked in their upper-left corner with an asterisk.  No amount of searching has enlightened me as to what this means.
Screenshot of Extensions Sidebar showing some entries marked with an asterisk
Possibilities I've eliminated
Recommended?
After all, all the extensions in the RECOMMENDED section have this asterisk.
However, aside from the silliness of recommending an extension I already have installed, it turns out that only some of these marked extensions carry the byline "This extension is recommended based on..." when I open them.
In need of update?
If this is the case, I cannot locate any means of updating any of these extensions individually.  I assume my extensions auto-update.
Highly rated?
No, my marked extensions do not consistently have more stars or more downloads than my unmarked extensions.

A: I do think those are recommended extensions despite what you say in your question.  Why?  Because if you click the Gear icon and select Ignore Recommendation the asterisk goes away.  And that extension will no longer appear in your @recommnded workspace filter.


text:
Q: Relationships in back-end forum OctoberCMS i'm trying to create back-end Relationships (be more specific one to one type) with partly success, if I'm inserting information throw php-my-admin information show up, but when i try to enter information throw OctoberCMS back-end form, then information is recorded just in first major table, but not in second.
So I have two tables (first one, major)randman_random_rooms with fields [id, view, places, cleaned] and  randman_random_room_description with fields [id, description, room2_id] in my room2s.php model i have
public $hasOne = [
   'roomdescription' => [
       '\Randman\Random\Models\RoomDescription',
       'key' => 'rooms2_id',
       'otherKey' => 'id'
   ],
];

and in model rooms2 columns.yaml
roomdescription:
   label: 'description'
   relation: roomdescription
   select: decription
   type: text

and finally in my rooms2 fields.yaml
 roomdescription:
    label: description
    span: auto
    oc.commentPosition: ''
    type: number

so what am i missing here?

A: Please take a look for roomdescription type: "number". It is relation not a number. You probably should change roomdescription type to: "relation" and use Relation Widget. Or if you want put exact id number use proper id field name. For further debug you can use trace_log() function that will put sql queries to your log file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Something goes wrong with my startAt and endAt search data in range, its show all my data inside of firebase so i write a code for searching some range of data in my realtime firebase and when i did that, the data that shown up its not only in range, but all data that i have in firebase is out to my cardview(fragment)
this is my main code that work for searching data
public class SearchListView extends AppCompatActivity {

    private RecyclerView recView;
    MyAdapter adapter;

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

        String tanggalawal = getIntent ( ).getStringExtra ("tanggalawal");
        String tanggalakhir = getIntent ( ).getStringExtra ("tanggalakhir");

        DatabaseReference db = FirebaseDatabase.getInstance().getReference();
        DatabaseReference pendingRef = db.child("Users").child("Pending");

        Query queryByKey = pendingRef.orderByKey()
                .startAt("*" + tanggalawal)
                .endAt("*"+ tanggalakhir + "\uf8ff");

        recView = (RecyclerView)findViewById (R.id.recview);
        recView.setLayoutManager (new LinearLayoutManager (this));

        FirebaseRecyclerOptions<Model> options =
                new FirebaseRecyclerOptions.Builder<Model>()
                        .setQuery(queryByKey, Model.class)
                        .build();

        adapter = new MyAdapter (options);
        recView.setAdapter (adapter);

    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }

}

and my firebase look like this
Firebase Database
and this is my adapter code
public class MyAdapter extends FirebaseRecyclerAdapter <Model,MyAdapter.myViewHolder>{

    public MyAdapter(@NonNull FirebaseRecyclerOptions<Model> options) {
        super (options);
    }

    @Override
    protected void onBindViewHolder(@NonNull myViewHolder myViewHolder, int i, @NonNull Model model) {
        myViewHolder.currentDate.setText (model.getCurrentDate ());
        myViewHolder.fullName.setText (model.getFullName ());
        myViewHolder.currentDateandTime.setText (model.getCurrentDateandTime ());
    }

    @NonNull
    @Override
    public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from (parent.getContext ()).inflate (R.layout.item,parent,false);
        return new myViewHolder (view);
    }

    class myViewHolder extends RecyclerView.ViewHolder{
        TextView currentDate, fullName, currentDateandTime;
        public myViewHolder(@NonNull View itemView) {
            super (itemView);
            currentDate = (TextView)itemView.findViewById (R.id.tvTanggalPengajuan);
            fullName = (TextView)itemView.findViewById (R.id.tvNama);
            currentDateandTime = (TextView)itemView.findViewById (R.id.tvNomorkontrak);
        }
    }
    public interface OnNoteListener{

        void OnNoteListener(int position);

    }

}

i've following this method using "*" that look like this, but still failed
Search firebase realtime database base on 6 digit in front of the child data, i want to query data between two numbers (dates)


text:
Q: I need to install DYMO software for labelwriter 450, but i can't... any help? i can't find how to install and use the labelwriter 450 and it's urgent. i print for my job 50 to 100 labels per week.
i don't know what to do, i just went to ubuntu from windows 8.1.1.
I tried with wine but still doesn't work.

A: You need to get the correct drivers for CUPS, the Linux printing system.
As far as I can tell, you can download them here:
https://dymo.custhelp.com/app/answers/detail/a_id/101/~/dymo-drivers-and-downloads#lw_linux

A: The answer by Grzegorz kinda works, but there is an issue in the official DYMO sources which prevents it from building on the latest version of CUPS. I found a patch on this Ubuntu forum post which contains the fix for it.
The post's instructions were:
git clone https://aur.archlinux.org/dymo-cups-drivers.git

Then copy that files inside the folder of driver, and finally:
* patch -Np1 -i cups-ppd-header.patch
* ./configure
* make
* sudo make install

Basically, several files are missing this line, which makes it impossible to build:
#include <cups/ppd.h>

I made the change against the official version 1.4.0.5 copy of the source and put it in a repository for others to use:
https://github.com/Kyle-Falconer/DYMO-SDK-for-Linux

A: To install Dymo 450 LabelWriter on Debian Systems - Ubuntu, Raspibian, you might need first:  (helped me to compile drivers, advice from : http://ubuntuforums.org/showthread.php?t=1502581 )
sudo apt-get install libcups2-dev libcupsimage2-dev gcc g++

Then you want to do install dymo linux sdk (both links work at 2016-05-14):

*

*http://www.dymo.com/en-US/dymo-label-sdk-and-cups-drivers-for-linux-dymo-label-sdk-cups-linux-p--1

*http://var.dymo.com/US/resources/sdk/linux/
Then you unpack it, compile and install driver:
./configure
make
sudo make install

Later I've added driver via cups web interface like any other driver, choosing right ppd file. (example project : https://www.hmazter.com/2013/05/raspberry-pi-printer-server-for-labelwriter and another: https://gist.github.com/gwpl/6d6c1457b4d1f6b778917a2f7c3c57fd ).
Finally, I share via network Dymo 450 LabelWriter(s) attached to Ubuntu and Raspibian with other Linuxes (including Archlinux) and I've found that to make printing via network (e.g. ipp:// and ipps:// ) to work, I need to schedule printing (of pdf, png, whatever) add -o raw to lpr command. You will see example of -o raw in https://gist.github.com/gwpl/6d6c1457b4d1f6b778917a2f7c3c57fd and https://askubuntu.com/a/748035/31300 .
Finally references for installing and using Dymo 450 under Linux:

*

*https://www.hmazter.com/2013/05/raspberry-pi-printer-server-for-labelwriter

*https://ubuntuforums.org/showthread.php?t=861781&page=6

*http://www.taklischris.info/varietas/use-your-dymo-printer-on-ubuntu

A: 14.04 and later
Open the terminal and type:
sudo apt install printer-driver-dymo

A: Just FYI: If you need a label printer, do not buy a DYMO from this point in time onwards.
I have contacted their customer support and although not properly mentioned on their website, they have stopped supporting Linux as of this point in time.


text:
Q: Trying to put a map in a fragment activity In my Android app I am showing a Google Maps map inside a class that extends Fragment.
At the moment, only the map is shown, but I am not able to obtain the map from the SupportFragmentManager.
What I have done is adapting the MapActivity that comes within Android Studio to my app.
Here is my code:
public class Tab2 extends Fragment {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private double latitud_del_hotel, longitud_del_hotel;
    private String nombre_del_hotel;
    private GoogleMap map;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_2, container, false);
        //setUpMapIfNeeded();
        return v;
    }

    @Override
    public void onActivityCreated(Bundle state) {
        super.onActivityCreated(state);
        setUpMapIfNeeded();

    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

}

I am getting an exception: java.lang.NullPointerException
            at com.solinpromex.elpasojuarezexperience.Tab2.setUpMapIfNeeded
I have tried calling method setUpMapIfNeeded() from both methods: onCreateView and onActivityCreated. Both cases throw the exception.
If I remove setUpMapIfNeeded() then the map is shown, but I want to add map objects.
Any help is welcome..
EDIT
Complete exception log from logcat:
09-16 00:34:09.614  13999-13999/com.solinpromex.elpasojuarezexperience E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.solinpromex.elpasojuarezexperience, PID: 13999
    java.lang.NullPointerException
            at com.solinpromex.elpasojuarezexperience.Tab2.setUpMapIfNeeded(Tab2.java:66)
            at com.solinpromex.elpasojuarezexperience.Tab2.onActivityCreated(Tab2.java:57)
            at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1797)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:979)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
            at android.view.View.measure(View.java:16857)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1334)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1532)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1211)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6282)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
            at android.view.Choreographer.doCallbacks(Choreographer.java:591)
            at android.view.Choreographer.doFrame(Choreographer.java:560)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
            at android.os.Handler.handleCallback(Handler.java:808)
            at android.os.Handler.dispatchMessage(Handler.java:103)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
            at dalvik.system.NativeStart.main(Native Method)

EDIT 2
Layout file tab_2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.google.android.gms.maps.MapFragment"
            android:id="@+id/map"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true" />
    </LinearLayout>
</RelativeLayout>

A: If you use the latest GooglePlayServices you can use the getMapAsync function which will automatically initializes the maps system and the view.
Also use a MapView in the layout
This is how I added the map in fragment.
public class MapFragment extends Fragment implements OnMapReadyCallback {

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            view = inflater.inflate(R.layout.fragment_tab_fragment1, container, false);

            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            SupportMapFragment fragment = new SupportMapFragment();
            transaction.add(R.id.mapView, fragment);
            transaction.commit();

            fragment.getMapAsync(this);

            return view;
        }

   @Override
   public void onMapReady(GoogleMap map) {
      //map is ready
      map.addMarker(...
 }
}

in xml
<com.google.android.gms.maps.MapView
    android:id="@+id/mapView"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

To use the latest GooglePlayService put this in gradle
compile 'com.google.android.gms:play-services:8.3.0'

A: Follow this code.Hope this might help.Make the changes where ever necessary according to your requirement.I think you are adding this map view as a fragment in a tab view.
    public class DealsCloseBy extends Fragment {

    SupportMapFragment mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.fragment_deals_close_by, container, false);
        mMapView = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume();// needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        googleMap = mMapView.getMap();
        // latitude and longitude
        double latitude = 13.0294278;
        double longitude =80.24667829999999;

        // create marker
        MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_pin));

        // Changing marker icon
        // marker.icon(BitmapDescriptorFactory
        // .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

        // adding marker
        googleMap.addMarker(marker);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(13.0294278, 80.24667829999999)).zoom(12).build();
        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

        // Perform any camera updates here
        return v;
    }
}

In xml file,in place of map fragment,use:-
    <fragment
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    class="com.google.android.gms.maps.SupportMapFragment"/>


text:
Q: C program received signal SIGSEGV, Segmentation fault at matrix-multiplication? Yes, I've read through the questions like this, but none of them proved useful in my problem. My program has a problem with a function that has been working perfectly in another one.

Program received signal SIGSEGV, Segmentation fault. _int_malloc (av=0x7ffff7dd8e40, bytes=32) at malloc.c:4703 4703    malloc.c: No such file or directory.

That's the error I recieve.
And here is my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void endl()
{
  printf("\n\n");
}

void loadVector(FILE *infile, double *vector, int col)
{
  int i;
  for(i=0;i<col;i++)
  {
    fscanf(infile,"%lf",&vector[i]);
  }
  printf("vector read...\n");
}

void printVec(double *vect, int run)
{
  int k;
  for(k=0;k<run;k++)
  {
   printf("%.2f ",vect[k]);
  }
}

double* duplic(double* matr, double *vect, double *sol,  int col, int  row)
{
  int k, l;
  for(k=0;k<row;k++)
  {
    for(l=0;l<col;l++)
    {
      sol[k] += matr[col*k+l] * vect[l];
    }
  }
  return sol;
}

int main(int argc, char **argv)
{
  endl();
  printf("=== ===");
  endl();

  if(argc!=3)
  {
    perror("not enough arguments");
    endl();
    return 1;
  }

  char ins[300];
  char *cut;
  int row=0, col=0, rnr = 1, index = 0;
  double temp;
  double *mat = NULL;
  double *vec = NULL;
  double *res = NULL;

  FILE *in;
  in = fopen(argv[1], "r");

  while(fgets(ins,sizeof(ins),in) != NULL)
  {
      col = 0;
      cut = strtok(ins," ");
      while(cut != NULL)
      {
        col++;
        sscanf(cut,"%lf",&temp);
        if(mat==NULL)
         {
            mat = malloc(sizeof(temp));
            *mat = temp;
         }
         else
         {
            rnr ++;
            mat = realloc(mat,sizeof(mat)*rnr);
            index = rnr - 1;
            *(mat+index)=temp;
         }
        cut = strtok(NULL," ");
    }
    row ++;
 }

fclose(in);

printf("Matrix read...");
endl();

printf("Printing matrix: ");
endl();

int i, j;
for(i=0;i<row;i++)
{
   for(j=0;j<col;j++)
   {
      printf("%.2f ",mat[col*i+j]);
   }
   printf("\n");
}
endl();

// printf("rows: %i\tcols: %i\n",row,col);

vec = malloc(sizeof(col));

FILE *inv;
inv = fopen(argv[2],"r");
loadVector(inv,vec,col);

endl();
printVec(vec,col);
endl();

res = malloc(sizeof(row));
res = duplic(mat,vec,res,col,row);

printf("Solution-vector calculated...");
endl();
printf("\nSolution vector:");
endl();

printVec(res,row);

endl();

free(mat);
free(vec);
free(res);
fclose(inv);

printf("Exitting\n");
return 0;
}

The program is a matrix - vector multiplication one, which reads an unknown sized matrix and a matching vector (also, if you can offer a better way to read a random-length line with a better code, I'd be happy).
The problem comes at the multiplication code - though it should be working, as it is with another program I wrote where the size is fix.
So it reads the matrix and vector nicely, then gives the segfault.
Any thoughts?

A: You write sizeof(col), but col is an integer, which means your vec array will always be allocated sizeof(int) bytes of memory (which is typically 4 bytes but will depend on your architecture). If you want a double array with col number of doubles, you want to use malloc(sizeof(double) * col) to allocate the right amount of bytes.
I suspect the same issue is occurring for your res array. It might work in some cases where the space after the space you allocated is still available for write, in which case the computer doesn't complain, since malloc'ed memory is all in the heap. However, if it so happens that you try to write to a protected or reserved section of memory after the malloc'ed block (which is too small), the OS will throw a SegFault.


text:
Q: GCP Pub/Sub priority queue I have pub/sub topics, a pull subscriptions and a data pipelines that pull messages using python and NodeJS implementation of the GCP pub/sub library.
I have an endless regular streaming workload and ad-hoc workloads. I want to prioritize the ad-hoc workloads immediately when needed.
How do I do that?
Creating an additional pub/sub topic for each pipeline seems like a wrong solution. There must be another way to prioritize ad-hoc workloads.

A: There is no way to prioritize particular messages. I think the right way is to create a separate topic.

A: As mentioned in this stackoverflow thread, Pub/Sub does not provide any mechanism to prioritise a message. Moreover this feature would come into picture if the subscribers are not able to keep up with the publishing rate which is resulting in high backlog messages. If subscribers are keeping up and processing and acking messages quickly, then the notion of "priority" messages isn't really necessary.

If a backlog is being built up and some messages needs to be processed
with higher priority, then you can consider creating a different
"high-priority" topic and subscription. The subscribers subscribe to
this subscription as well as the "normal" subscription and prioritize
processing messages from the "high-priority" subscription whenever
they arrive.


text:
Q: Check if  has attribute or Not I have input value of HTML text with html tags inside this value like below
jsFiddle
HTML
<input type="hidden" value="<!DOCTYPE html>...Content..." id="ampHtml" />

Attempted Script:
var __amp_content = $("#ampHtml").val();
var __attr = jQuery(__amp_content).find('html').attr('amp4email');
if (typeof __attr !== 'undefined' && __attr !== false) {
    alert('Fail');
} else {
    alert('Success...');
}

How can I show alert based on:

*

*if html has amp4email show alert as Success

*Else show alert as Fail

A: It looks like jQuery is including only the contents of the  tag after parsing, which in this case is only a text node. The info you want isn't in the resulting object.
One option would be to use DOMParser instead. There's no need for a big library like jQuery for something like this anyway.

const ampContent = document.querySelector('#ampHtml').value;
const doc = new DOMParser().parseFromString(ampContent, 'text/html');
const attribute = doc.documentElement.getAttribute('amp4email');
console.log('Has attribute:', attribute !== null);
<input type="hidden" value="<!DOCTYPE html>...Content..." id="ampHtml" />


text:
Q: embedded jetty cannot access jsp servlet in deployment While my embedded jetty application runs fine in eclipse it isnt serving up a JSP as a servlet in my deployment.  Jetty doesnt return an error but rather it simply displays the contents of my webapp dir.  I can access other servlets but not console.jsp which is set as my welcome file in the web.xml.
My code for setting up the embedded server and the web.xml are below...
    Server server;

    WebAppContext webappContext = new WebAppContext();
    webappContext.setContextPath("/indexers");
    webappContext.setWar(IndexerWebApp.class.getResource("/webapp").toExternalForm());

    server.setHandler(webappContext);

web.xml......
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
    http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name>Indexer Control Console</display-name>

<welcome-file-list>
    <welcome-file>console.jsp</welcome-file>
</welcome-file-list>

<!-- Servlets -->
<servlet>
    <servlet-name>launchTask</servlet-name>
    <servlet-class>com.hp.it.kmcs.suggest.index.web.servlets.LaunchTask</servlet-class>
</servlet>

<servlet>
    <servlet-name>taskStatus</servlet-name>
    <servlet-class>com.hp.it.kmcs.suggest.index.web.servlets.GetTaskStatus</servlet-class>
</servlet>

<servlet>
    <servlet-name>rescheduleTask</servlet-name>
    <servlet-class>com.hp.it.kmcs.suggest.index.web.servlets.RescheduleTask</servlet-class>
</servlet>

<!-- Servlet mappings -->
<servlet-mapping>
    <servlet-name>launchTask</servlet-name>
    <url-pattern>/launchTask</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>taskStatus</servlet-name>
    <url-pattern>/taskStatus</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>rescheduleTask</servlet-name>
    <url-pattern>/rescheduleTask</url-pattern>
</servlet-mapping>


text:
Q: mapr windows client not working I am trying to install mapr  windows client. I have followed all the steps outlined in the mapr windows client installation. I have copied the ssl_truststore file from our cluster into the C:\opt\mapr\conf folder and ran the configure.bat file. It ran without any errors and  I even verified the C:\opt\mapr\conf\mapr-clusters.conf with updated cluster name and CLDB nodes.
But however when i run the following command by changing to folder c:\opt\mapr\hadoop\hadoop-2.7.0\bin
hadoop fs -ls /
I get the following error
18/01/19 14:05:07 ERROR cldbutils.CLDBRpcCommonUtils: Exception during init
java.lang.UnsatisfiedLinkError: com.mapr.security.JNISecurity.SetClusterOption(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
at com.mapr.security.JNISecurity.SetClusterOption(Native Method)
at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.init(CLDBRpcCommonUtils.java:163)
at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<init>(CLDBRpcCommonUtils.java:73)
at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<clinit>(CLDBRpcCommonUtils.java:63)
at org.apache.hadoop.conf.CoreDefaultProperties.<clinit>(CoreDefaultProperties.java:69)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2147)
at org.apache.hadoop.conf.Configuration.getProperties(Configuration.java:2362)
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:2579)
at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:2531)
at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:2444)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:1156)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:1128)
at org.apache.hadoop.conf.Configuration.setBoolean(Configuration.java:1464)
at org.apache.hadoop.util.GenericOptionsParser.processGeneralOptions(GenericOptionsParser.java:321)
at org.apache.hadoop.util.GenericOptionsParser.parseGeneralOptions(GenericOptionsParser.java:487)
at org.apache.hadoop.util.GenericOptionsParser.<init>(GenericOptionsParser.java:170)
at org.apache.hadoop.util.GenericOptionsParser.<init>(GenericOptionsParser.java:153)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:64)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
at org.apache.hadoop.fs.FsShell.main(FsShell.java:340)
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.mapr.security.JNISecurity.SetParsingDone()V
at com.mapr.security.JNISecurity.SetParsingDone(Native Method)
at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.init(CLDBRpcCommonUtils.java:231)
at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<init>(CLDBRpcCommonUtils.java:73)
at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<clinit>(CLDBRpcCommonUtils.java:63)
at org.apache.hadoop.conf.CoreDefaultProperties.<clinit>(CoreDefaultProperties.java:69)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2147)
at org.apache.hadoop.conf.Configuration.getProperties(Configuration.java:2362)
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:2579)
at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:2531)
at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:2444)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:1156)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:1128)
at org.apache.hadoop.conf.Configuration.setBoolean(Configuration.java:1464)
at org.apache.hadoop.util.GenericOptionsParser.processGeneralOptions(GenericOptionsParser.java:321)
at org.apache.hadoop.util.GenericOptionsParser.parseGeneralOptions(GenericOptionsParser.java:487)
at org.apache.hadoop.util.GenericOptionsParser.<init>(GenericOptionsParser.java:170)
at org.apache.hadoop.util.GenericOptionsParser.<init>(GenericOptionsParser.java:153)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:64)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
at org.apache.hadoop.fs.FsShell.main(FsShell.java:340)

We use java 8 and windows 7.
I am stuck with this issue for a while. I tried all the possible options but was not successful. Any help is greatly appreciated.

A: These are steps :
1.      Install Mapr applications

*Configure MapR client
   /opt/mapr/server/configure.sh -N poc2.cibdatahub.com -c -C (Ur cluster name)

*Upload the missing jar from MapR cluster node to Edge node under:
    /opt/mapr/hadoop/hadoop-2.7.0/share/hadoop/yarn/

*Create a local mapr account if you don't have one:
         Example: useradd mapr
         Passwd mapr

*Set environment for user mapr
su mapr
vi ~/.bashrc
 #append line below
export HADOOP_HOME=/opt/mapr/hadoop/hadoop-2.7.0
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export LD_LIBRARY_PATH=$HADOOP_COMMON_LIB_NATIVE_DIR
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib/native"
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
#HIVE home directory configuration
export HIVE_HOME=/opt/mapr/hive/hive-2.1
export PATH="$PATH:$HIVE_HOME/bin"
export HADOOP_USER_NAME="USERname"

# load environment
source ~/.bashrc

*Edit /opt/mapr/spark/spark-2.1.0/conf/spark-defaults.conf by adding
 spark.yarn.archive                 maprfs:///apps/spark/jars/spark-jars.zip

*Verify the cluster setting
/opt/mapr/conf/mapr-clusters.conf has option secure=false

*Test
 hadoop fs -Dfs.mapr.trace -ls

Please try these options.


text:
Q: jQuery carousel slide animation I am working on jQuery carousel. Here is my code:

  // CAROUSEL
  $('#left-arrow').click(previousSlide);
  $('#right-arrow').click(nextSlide);

function nextSlide() {
    var $currentSlide = $('#carousel .slide-image:first');
    var width = $currentSlide.width();
    var $lastSlide = $('#carousel .slide-image:last')
    $currentSlide.animate({ 'margin-left': -width }, 1000, function() {
        $currentSlide.remove().css({ 'margin-left': '0px' });
        $lastSlide.after($currentSlide);
    });
  }

  function previousSlide() {
    var $currentSlide = $('#carousel .slide-image:first');
   var width = $currentSlide.width();
    var $last = $('#carousel .slide-image:last');
    $last.remove().css({ 'margin-left': -width });
    $currentSlide.before($last);
    $last.animate({ 'margin-left': '0px' }, 1000);
  }
/* CAROUSEL */
#slide1 {
  background-color: red;
}

#slide2 {
  background-color: blue;
}

#slide3 {
  background-color: magenta;
}

#carousel {
  overflow: hidden;
  white-space: nowrap;
  position: relative;
  width: 100vw;
  height: 75vh;
}

.slide-image {
  width: 100vw;
  height: 75vh;
  background-position: center;
  background-size: cover;
  display: inline-block;
}

.arrow {
  width: 2%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

#right-arrow {
  right: 30px;
}

#left-arrow {
  left: 30px;
}

L

R

The problem is that it is acting differently for left and right side. If you click left side multiple times, it will just move the slider number of times, according on the number of clicks at once. If you however click multiple times on the right side, it will always move only once. That is because the current slide is being pushed before the last slide and there is no slide yet. However I would like it to act the same as the left side so it should be able to move multiple times.
How could I achieve that behaviour?

A: Try stoping the current animation and move to next slide.
You can use a variable like nextAnimation to check if the animation is still playing.

// CAROUSEL
  $('#left-arrow').click(previousSlide);
  $('#right-arrow').click(nextSlide);

  var nextAnimation = false;

function nextSlide() {
    var $currentSlide = $('#carousel .slide-image:first');
    var width = $currentSlide.width();
    var $lastSlide = $('#carousel .slide-image:last');
    if(nextAnimation) {
      $currentSlide.stop();
      $currentSlide.remove().css({ 'margin-left': '0px' });
      $lastSlide.after($currentSlide);
      $currentSlide = $('#carousel .slide-image:first');
      width = $currentSlide.width();
      $lastSlide = $('#carousel .slide-image:last');
    }
    nextAnimation = true;
    $currentSlide.animate({ 'margin-left': -width }, 1000, function() {
        $currentSlide.remove().css({ 'margin-left': '0px' });
        $lastSlide.after($currentSlide);
        nextAnimation = false;
    });
  }

  function previousSlide() {
    var $currentSlide = $('#carousel .slide-image:first');
   var width = $currentSlide.width();
    var $last = $('#carousel .slide-image:last');
    $last.remove().css({ 'margin-left': -width });
    $currentSlide.before($last);
    $last.animate({ 'margin-left': '0px' }, 1000);
  }
/* CAROUSEL */
#slide1 {
  background-color: red;
}

#slide2 {
  background-color: blue;
}

#slide3 {
  background-color: magenta;
}

#carousel {
  overflow: hidden;
  white-space: nowrap;
  position: relative;
  width: 100vw;
  height: 75vh;
}

.slide-image {
  width: 100vw;
  height: 75vh;
  background-position: center;
  background-size: cover;
  display: inline-block;
}

.arrow {
  width: 2%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

#right-arrow {
  right: 30px;
}

#left-arrow {
  left: 30px;
}

L

R

1

2

3


text:
Q: Calculating different between numbers in array(Assembly, Irvine) I'm trying to calculate the gaps between the numbers. For that purpose I'm using 2 arrays. So everything works fine except output and strange symbols that appears after the numbers.
first number-number in array at this moment, 2nd-different between elements, 3d- 2nd that already moved to the second array.
Output:
1 2 2 /3 44/722/9one/
2
From where this symbols? What cause it? Wrong register? And why in the first loop 'gap'(array) has right numbers,but when I go through this array later it has just 2 and wired symbol?
INCLUDE Irvine32.inc

.data
array byte 1,3,7,9
gap byte ?
blank byte ' '
ph byte "Done",0

.code
main PROC
        mov eax,0
        mov ecx,lengthof array
        mov esi, offset array
        mov edi,offset gap
         arr:

         mov al,[esi]
         call writedec; here

         .if ecx==1
         mov edx,offset ph
         call writestring
         .else
         mov al,blank
         call writechar

            mov al,[esi+1]
            sub al,[esi]

            call writedec; here

            mov [edi],al

            ;check block
            mov al,blank
            call writechar
            mov al,[edi] ; here
            call writedec
            mov al,blank
            call writechar

             inc esi
             inc edi
           .endif

           mov al,'/'
         call writechar

         loop arr

        call crlf

         mov eax,0
         mov ecx,lengthof gap
         mov esi,offset gap

         go:

         mov al,[esi]
         call writedec
         mov al,blank
         call writechar
         inc esi
         loop go

         exit

main ENDP

myexit proc

              call waitmsg
              ret
      myexit endp

end main

Thank you!

A: Gotcha! the variable gap was wrong initialize.
This is the right initialization gap byte lengthof array-1 dup(?)


text:
Q: How to count lengths from an arraylist I have been stuck on this one assignment and I don't really know how to make sense of it. What I have to do is to create a method 'lengths' that gets a list of Strings variables as a Parameter which then returns an arraylist that contains the lengths of the Strings.
The output should look like as following:
The lengths of the Strings: [5, 3, 10, 27]
import java.util.ArrayList;

public class LengthsOfStrings {
   public static ArrayList<Integer> lengths(ArrayList<String> list) {
       ArrayList<Integer> lengthList = new ArrayList<Integer>();
       // write your code here
       return lengthList;
   }

   public static void main(String[] args) {
       ArrayList<String> list = new ArrayList<String>();
       list.add("Ciao");
       list.add("Moi");
       list.add("Benvenuto!");
       list.add("badger badger badger badger");
       ArrayList<Integer> lengths = lengths(list);

       System.out.println("The lengths of the Strings: " + lengths);
   }
}

A: You'd have to go string by string, find out its length, and put that length into the new ArrayList. This could be done using a for-each loop, like so -
import java.util.ArrayList;

public class LengthsOfStrings {
   public static ArrayList<Integer> lengths(ArrayList<String> list) {
       ArrayList<Integer> lengthList = new ArrayList<Integer>();
       for (String str : list){
           lengthList.add(str.length());
       }
       return lengthList;
   }

   public static void main(String[] args) {
       ArrayList<String> list = new ArrayList<String>();
       list.add("Ciao");
       list.add("Moi");
       list.add("Benvenuto!");
       list.add("badger badger badger badger");
       ArrayList<Integer> lengths = lengths(list);

       System.out.println("The lengths of the Strings: " + lengths);
   }
}

A: Another solution with Java 8 streams:
    public static List<Integer> lengths(ArrayList<String> list) {
       return list.stream().map(String::length).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Ciao");
        list.add("Moi");
        list.add("Benvenuto!");
        list.add("badger badger badger badger");
        List<Integer> lengths = lengths(list);

        System.out.println("The lengths of the Strings: " + lengths);
    }

And output:
The lengths of the Strings: [4, 3, 10, 27]

A: For Java 8 and above, you can simply use forEach method for that:
public static ArrayList<Integer> lengths(ArrayList<String> list) {
    ArrayList<Integer> lengthList = new ArrayList<Integer>();
    list.forEach(i -> lengthList.add(i.length()));
    return lengthList;
}

If using Java 7 or below:
public static ArrayList<Integer> lengths(ArrayList<String> list) {
    ArrayList<Integer> lengthList = new ArrayList<Integer>();
    for(String str : list) {
      lengthList.add(str.length());
    }
    return lengthList;
  }

Avoid using Stream as a simple forEach will be enough for your requirement. Unnecessary creation of Stream should be avoided for better performance.


text:
Q: Operator precedence in JavaScript I am reading operator precedence on this page. It shows "===" has higher precedence than "||" operator. If it is true, then "a === doesThisHappen()" will run first. But why I did not get console.log('This happens!')?
var a;

a = 1;

function doesThisHappen() {

    console.log('This happens!');

    return 0;
}

if (a || a === doesThisHappen()) {
    console.log('Something is there.');
}

A: Order of evaluation and operator precedence are orthogonal concepts. In a || b the left side a is evaluated first no matter what the right side b contains. More over, if the left side evaluates to true the right side is not evaluated.


text:
Q: Inserting a value anywhere within a queue I am writing a member function for a generic queue implementation using a linked list. The goal of the function is to insert a value anywhere within the queue.
In the 'else' case, I traverse the queue using a loop and update a pointer accordingly. When I arrive at the desired location, I save the 'next' location with another pointer and insert a new node that points to the previous 'next.' It seems that this is not logically sound and I am having trouble figuring out why. Is this just a syntax issue that I'm experiencing? I have included my implementation below.
template <typename T>
void queue<T>::insert_anywhere(const T& val, const int position){
    if (position == 0) {
        Node<T> *t1 = head;
        head = new Node<T>(val, t1);
        num_items++;
    } else {
        Node<T> *t2 = head;
        for(int i = 0; i <= position-1; i++){
           t2 = t2->next;
        }
        Node<T> *t3 = t2->next;
        t2->next = new Node<T>(val, t3);
        num_items++;
    }
}


text:
Q: WinAPI перетаскивание формы, предупреждение CA1901, CA1060 NativeMethods Реализовал перетаскивание формы за тело при помощи WinAPI:
public partial class FormMain : Form
{
    [DllImport("user32", CharSet = CharSet.Auto)]
    internal extern static bool PostMessage(IntPtr hWnd, uint Msg, uint WParam, uint LParam);

    [DllImport("user32", CharSet = CharSet.Auto)]
    internal extern static bool ReleaseCapture();

    const uint WM_SYSCOMMAND = 0x0112;
    const uint DOMOVE = 0xF012;
    const uint DOSIZE = 0xF008;

    public FormMain()
    {
        InitializeComponent();
    }

    private void FormMain_MouseDown(object sender, MouseEventArgs e)
    {
        ReleaseCapture();
        PostMessage(this.Handle, WM_SYSCOMMAND, DOMOVE, 0);
    }
}

при анализе кода получил 2 предупреждения:

*

*Предупреждение  CA1060  Так как метод является методом P/Invoke, 'FormMain.PostMessage(IntPtr, uint, uint, uint)' должен быть определен в классе с именем NativeMethods, SafeNativeMethods или UnsafeNativeMethods.

Как правильно реализовать класс NativeMethods ?
Решено, спасибо Uranus
public partial class FormMain : Form
{
    public static class NativeMethods
    {
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal extern static bool PostMessage(IntPtr hWnd, uint Msg, uint WParam, uint LParam);

        [DllImport("user32", CharSet = CharSet.Auto)]
        internal extern static bool ReleaseCapture();
    }
    const uint WM_SYSCOMMAND = 0x0112;
    const uint DOMOVE = 0xF012;
    const uint DOSIZE = 0xF008;

    public FormMain()
    {
        InitializeComponent();
    }

    private void FormMain_MouseDown(object sender, MouseEventArgs e)
    {
        NativeMethods.ReleaseCapture();
        NativeMethods.PostMessage(this.Handle, WM_SYSCOMMAND, DOMOVE, DOSIZE);
    }
}

*Предупреждение  CA1901  Как объявлено в вашем коде, параметр 'WParam' для P/Invoke 'FormMain.PostMessage(IntPtr, uint, uint, uint)' будет иметь размер 4 байт для 64-разрядных платформ. Это неправильно, поскольку текущее объявление в машинном коде для данного API указывает, что его размер должен быть 8 байт для 64-разрядных платформ. Обратитесь к документации MSDN Platform SDK и выясните, какой тип данных следует использовать вместо 'uint'.

Помогите с устранением CA1901 реализацией констант для UintPtr, спасибо.
Спустя несколько часов, начинаю думать, что ошибка в студии а не в моём коде.

Предупреждение    CA1901  Как объявлено в вашем коде, параметр 'Msg' для P/Invoke 'FormMain.NativeMethods.PostMessage(IntPtr, UIntPtr, UIntPtr, UIntPtr)' будет иметь размер 8 байт для 64-разрядных платформ. Это неправильно, поскольку текущее объявление в машинном коде для данного API указывает, что его размер должен быть 4 байт для 64-разрядных платформ. Обратитесь к документации MSDN Platform SDK и выясните, какой тип данных следует использовать вместо 'UIntPtr'.

Это замкнутый круг ? или всё-же есть панацея, по прежнему прошу помочь.

A: Нужно было сделать приведение типов uint к IntPtr.
public static class NativeMethods
{
    [DllImport("user32", CharSet = CharSet.Auto)]
    internal extern static bool PostMessage(IntPtr hWnd, uint Msg, IntPtr WParam, IntPtr LParam);

    [DllImport("user32", CharSet = CharSet.Auto)]
    internal extern static bool ReleaseCapture();
}

const uint WM_SYSCOMMAND = 0x0112;
const uint DOMOVE = 0xF012;
const uint DOSIZE = 0xF008;

private void FormMain_MouseDown(object sender, MouseEventArgs e)
{
    NativeMethods.ReleaseCapture();
    NativeMethods.PostMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)DOMOVE, (IntPtr)0);
}

A: *

*Просто объявите статический класс с именем NativeMethods и перенесите туда PostMessage и ReleaseCapture заменив internal на public.

*Согласно описанию в документации, рекомендуется заменить фиксированный тип uint на платформо-зависимый UIntPtr.


text:
Q: AFNetworking 2.0 AFHTTPRequestOperation PUT bad request (400)" on iOS Looking to perform the Parse Cloud REST function PUT to increment a value
 curl -X PUT \
   -H "X-Parse-Application-Id: RFtvvfffdfgwbeERRGFGFFGFHNIc6ubgwpJ5LL" \
   -H "X-Parse-REST-API-Key: SsYTGDFGDSFSDHGGGFTY56TXC435GGFhrfs0O4u0K" \
   -H "Content-Type: application/json" \
   -d '{"qtyAllocated":{"__op":"Increment","amount":1}}' \
   https://api.parse.com/1/classes/Lot/WrXPiXtB89

I came with this sample code from Chris Wagner article of How To Synchronize Core Data with a Web Service, All other methods works but not PUT, this one returns with this error
AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8dbc210> { URL: https://api.parse.com/1/classes/Lot/WrXPiXtB89 } { status code: 400, headers {
    "Access-Control-Allow-Origin" = "*";
    "Access-Control-Request-Method" = "*";
    "Cache-Control" = "no-cache";
    Connection = "keep-alive";
    "Content-Length" = 89;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Wed, 06 Aug 2014 03:24:57 GMT";
    Server = "nginx/1.6.0";
    "Set-Cookie" = "_parse_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlZjAzNDQxZDgwZDI5MDBhMjJhYzVjYTFjMGY2MzhiNTk%3D--bd6b3ec8f339e5928d44f29875b8f0d22e8f88fc; domain=.parse.com; path=/; expires=Fri, 05-Sep-2014 03:24:57 GMT; secure; HttpOnly";
    Status = "400 Bad Request";
    "X-Content-Type-Options" = nosniff;
    "X-Runtime" = "0.047238";
    "X-UA-Compatible" = "IE=Edge,chrome=1";
} }, NSLocalizedDescription=Request failed: bad request (400)}

in my subclass on AFHTTPRequestOperationManager
+ (instancetype)sharedSDAFParseAPIClient {
    static SDAFParseAPIClient *sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClient = [[SDAFParseAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kSDFParseAPIBaseURLString]];
    });

    return sharedClient;
}

-(instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        AFJSONRequestSerializer *requestSerializer = [[AFJSONRequestSerializer alloc] init];
        [requestSerializer setValue:kSDFParseAPIApplicationId forHTTPHeaderField:@"X-Parse-Application-Id"];
        [requestSerializer setValue:kSDFParseAPIKey forHTTPHeaderField:@"X-Parse-REST-API-Key"];
        [self setRequestSerializer:requestSerializer];
        [self setResponseSerializer:[AFJSONResponseSerializer serializer]];
    }

    return self;
}

- (AFHTTPRequestOperation *)UPDATERequestForClass:(NSString *)className
                                  forObjectWithId:(NSString *)objectId
                                           parameters:(NSDictionary *)field
                                          success:(SuccessBlockType)success
                                          failure:(FailureBlockType)failure {

   __block NSDictionary *parameters = nil;

    [field enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {

        NSString *jsonString = [NSString stringWithFormat:@"{\"__op\":\"Increment\",\"amount\":%@}",value];

       parameters = [NSDictionary dictionaryWithObject:jsonString forKey:key];

    }];

    AFHTTPRequestOperation *operation = [self PUT:[NSString stringWithFormat:@"classes/%@/%@", className, objectId] parameters:parameters success:success failure:failure];
    return operation;
}

Any help will be highly appreciated

A: After a while I figure out that the scape sequence on the *jsonString bellow where passing through the NSJSONSerialization. I do not know how works on the others methods of the Chris Wagner article "How To Synchronize Core Data with a Web Service", but do not work on PUT, as least for me.
        NSString *jsonString = [NSString stringWithFormat:@ {\"__op\":\"Increment\",\"amount\":%@}",value];

Since I use as source an array of parameters, finally I translate the *jsonString to this:
__block NSMutableDictionary *parameters = [NSMutableDictionary dictionary];

[field enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {

   [parameters addEntriesFromDictionary:@{key: @{@"__op":@"Increment", @"amount":value}}];

}];

A: Why don't use use the native iOS SDK instead, it does the same REST calls under the covers.
You'll save yourself a lot of pain and effort using the SDK.
UPDATE:
To the downvoters, it is an entirely valid answer to say "don't reinvent the wheel". Parse provide a rich API/SDK that has fully tested code to prevent people from having these problems.
I can understand wanting to do it yourself for learning reasons, but unless there's some really good reason not to just use the SDK in this case, my answer stands.


text:
Q: PHP Multidimensional Array - Count Number of Instances I am struggling a bit with a multidimensional array in PHP.  I am new to PHP so please be aware that I may come across as a bit of a noob.
What I am trying to achieve:  I am using ExpressionEngine as my CMS, with Freeform Pro to record answers to a survey.  The values of the answers are 1, 2, 3, 4 or 5.  That all works fine.  Then I am using a SQL query to pull that saved data out of the database.  This is where it starts getting complicated.  I need the average of each question in the survey.  So the logical thing to do (I would think) is to pull the data for each question and put it in an array:
$tva_1 = array();
$tva_2 = array();
$tva_3 = array();
$tva_4 = array();

SELECT form_field_259, form_field_260, form_field_261, form_field_262 FROM exp_freeform_form_entries_13 WHERE status='open'

array_push($tva_1, ('{form_field_259}'));
array_push($tva_2, ('{form_field_260}'));
array_push($tva_3, ('{form_field_261}'));
array_push($tva_4, ('{form_field_262}'));

Keep in mind that $tva_1 may have 5 variables in it, for example: 2, 4, 3, 1, 4.  The same goes for $tva_2 and so on.
So once I have assigned that data to the various tva_ arrays, I then need to put those four arrays into another array, namely $allNumberArray:
$allNumberArray = array($tva_1, $tva_2, $tva_3, $tva_4);

So now if I try print_r($allNumberArray); it shows me all the data is there and everything is working as it should.
Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 5
            [2] => 2
            [3] => 5
            [4] => 3
        )

    [1] => Array
        (
            [0] => 3
            [1] => 2
            [2] => 4
            [3] => 3
            [4] => 3
        )

    [2] => Array
        (
            [0] => 5
            [1] => 4
            [2] => 3
            [3] => 1
            [4] => 3
        )

    [3] => Array
        (
            [0] => 4
            [1] => 2
            [2] => 5
            [3] => 1
            [4] => 3
        )

The problem is: I need to count the number of times each rating has been used.  So for example, I can see from the above print_r that 5 is displayed 4 times, 4 is displayed 3 times, 3 is displayed 7 times, etc..  I have tried a count function such as the one below, but that only works in a single dimension array (I think):
$userStrongAgree = count(array_filter($allNumberArray, function ($agreementFive) { return $agreementFive == 5; }));

I have been stuck on this problem now for a day and a half, and my deadline is tomorrow afternoon, so I am starting to get a bit worried.  I really would appreciate any help or just a pointer in the right direction.
Many thanks

A: try to push all items into uniquq array and count it with array_count_values() :
<?php
$array=$allNumberArray; //your Array

$new_arr=array();
foreach($array as $key=>$value){
    foreach ($value as $key2 => $value2) {
        array_push($new_arr,$value2);
        }
}
$last_arr=array_count_values($new_arr);
foreach ($last_arr as $key3 => $value3) {
    echo $key3.' is '.$value3.' times<br>';
    }
?>

A: Try this out.  The index is the value/rating and the value is the count:
$count = array_count_values(call_user_func_array('array_merge', $array));


text:
Q: How to adjust visibility of UIBarButtonItem in Storyboard programmatically I have a UIBarButtonItem (defined in Storyboard), I've assigned to my own custom SwitchConsumerBarButton class.
What I want to do is dictate it's visibility on Page Init based on some criteria. I'd like to do this programmatic. I've tried implementing -(id) init but it doesn't get called, how do I control the initialization of this object? I've looked at the different initialization methods that can be called for this type, but I don't know which one the Storyboard will call?
@implementation SwitchBarButton

-(id) init
{
    if(self = [super init]) {
        NSLog(@"gwojbngowj");
    }
    return self;
}

@end

A: I'm not sure if you mean to adjust the alpha, or to hide the button outright, so here's both.
if (myCondition == YES) {
    myButton.alpha = 0.5;
    //Or if you mean hide all together...
    [myButton setHidden:YES];
}

If you are looking to create the button depending on the variable, you could do that like this:
if (myCondition == YES) {
    UIBarButtonItem *myBarItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(mySelector)];
    [self.navigationItem setRightBarButtonItem:myBarItem];
}


text:
Q: How to avoid pagebreak in two-column article I'm having some problems writing an 2-columns article with IEEEtrans document class. After compiling my file, I keep finding a page break without it being completed (check figure). It starts a new page with a new session and brings a float equation at its beginning (check figure)

This is my MWE:
\documentclass[12pt,journal,compsoc]{IEEEtran}
\usepackage{array}
\usepackage{mdwmath}
\usepackage{mdwtab}
\usepackage{fixltx2e}
\usepackage{caption}% http://ctan.org/pkg/caption
\captionsetup[table]{format=plain,labelformat=simple,labelsep=period}%
\usepackage{stfloats}
\usepackage[brazil]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{float}

I tried a lot of things: the command \nopagebreak[], the float environment to avoid the float to go to the next page, the minipage environment... but I'm not succeding. Could you guys help me? I need to use all blank spaces cause the articles max number of pages is 5.


text:
Q: Refreshing DataGridViewComboBox Items Im trying to refresh the amount of days available in the ComboBox. This is a button that i created, where mindate and maxdate get their values from a DateTime Picker, and Dia is the DataGridViewComboBoxColumn but it doesnt work. Can anyone help me find the source of the problem and how to fix it. Or if you know another way of doing it, it would also help.
EDIT:The button i was talking is button3.
public partial class InserirViagens : Form
{
    private DateTime mindate;
    private DateTime maxdate;
    public InserirViagens()
    {
        InitializeComponent();
        textBox1.Text = (Dados.agência.Viagens.Count + 1).ToString();
        textBox1.Enabled = false;
        dateTimePicker1.MinDate = DateTime.Now;
        dateTimePicker2.MinDate = DateTime.Now;
        mindate = dateTimePicker1.Value;
        maxdate = dateTimePicker2.Value;

    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            int cod = int.Parse(textBox1.Text);
            string des = textBox2.Text;
            double preço = double.Parse(textBox3.Text);
            DateTime inicio = dateTimePicker1.Value;
            DateTime fim = dateTimePicker2.Value;
            int contalinhas = (int)dataGridView1.RowCount-1;
            if (inicio<=fim)
            {
                Viagem v = new Viagem(cod, des, preço, inicio, fim);
                Dados.agência.Viagens.Add(cod, v);

                MessageBox.Show("Viagem Inserida com sucesso!\nContém " + contalinhas + " actividades.\n"+ Dados.dados.Viagens.Count + " Viagens existentes");
                this.Close();
            }
            else MessageBox.Show("Data de fim inválida!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }
        catch(FormatException)
        {
            MessageBox.Show("Erro de formatação!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

    }

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {

        mindate = dateTimePicker1.Value;

    }

    private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
    {

        maxdate = dateTimePicker2.Value;

    }

    private void button3_Click(object sender, EventArgs e)
    {

       Dia.Items.Clear();
       while (mindate.DayOfYear < maxdate.DayOfYear)
       {
           Dia.Items.Add(mindate.Day + "/" + mindate.Month + "/" + mindate.Year);
           mindate.AddDays(1);
       }

    }
}

}

A:    Dia.Items.Clear();
   while (mindate.DayOfYear < maxdate.DayOfYear)
   {
       Dia.Items.Add(mindate.Day + "/" + mindate.Month + "/" + mindate.Year);
       mindatee.AddDays(1);
   }

mindatee.AddDays(1); doesn't work.
AddDays method information

Returns a new DateTime that adds the specified number of days to the
  value of this instance.

So it returns a new DateTime and doesn't change the old (in this case the mindate) value.
Solution
Save mindate.AddDays(1) in a temp variable and replace the current mindate with the temp datetime value.
   Dia.Items.Clear();
   while (mindatee.DayOfYear < maxdatee.DayOfYear)
   {
       Dia.Items.Add(mindate.Day + "/" + mindate.Month + "/" + mindate.Year);
       var tempDate = mindate.AddDays(1);
       mindate = tempDate;
   }

If you don't want to use a temp variable you can also do it in one line of code:
mindate = mindate.AddDays(1);

A: public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Btn_Click(object sender, EventArgs e)
    {
        DateTime minDate = Convert.ToDateTime(mindate.Value);
        DateTime maxDate = Convert.ToDateTime(maxdate.Value);

        foreach ( DataGridViewComboBoxColumn cmbCol in dataGridView1.Columns) {
            cmbCol.Items.Clear();

            while (minDate.Day < maxDate.Day) {
                cmbCol.Items.Add($"{minDate.Day}/{minDate.Month}/{minDate.Year}");
               minDate= minDate.AddDays(1);
            }
        }
    }
}


text:
Q: Help decoding a regular expression for use with Google Analytics Update
I missed this in my original explanation.  I set this up yesterday, and it ran over night.  No data populated in my profile overnight.  So, either my regex is wrong, or Google cannot see internal traffic IPs.
It seems that everyone has their own variation on the syntax for regular expressions.
I'm trying to include only internal traffic on one of my profiles in Google Analytics

Can someone verify for me what they expect that regular expression to match?  In CIDER notation?

A: I don't know what CIDER notation is, but that regex matches a string that

*

*starts with 10.

*followed by 90. or 60.

*followed by 10 or 9

*followed by zero or more dots.

You probably want ^10\.[96]0\.(10|9)\..*$
Since the last bit (.*) is a bit too vague (unless you know that there will only ever be valid IP addresses in the live data), you might want to change that to \d+ or (if you want to restrict to a valid range from 0 to 255) 25[0-5]|2[0-4]\d|1?\d?\d

A: Don't know about CIDR notation, but that will match any of 10.90.9.*, 10.90.10.*, 10.60.9.* or 10.60.10.*

A: instead of the last asterisk, place \d+. The way you wrote it, in the end you've got to have 0 or more dots for the expression to validate.


text:
Q: How do I use existing module with new Function() constructor? I have a universal eventEmitter in my app called eventEmitter.js.
eventEmitter.js:
const EventEmitter = require('events').EventEmitter
const events = new EventEmitter()

module.exports = events

I want to use it in my new Function() constructor.
fnConstructor.js:
let fn =  `const events = require('./eventEmitter')
  events.on('hi', ()=>console.log('hi'))
  events.emit('hi')`

let func = new Function(fn)
func()

This produces an error:
undefined:3
const events = require('./eventEmitter')
               ^

ReferenceError: require is not defined

Which I believe is expected since the new Function() constructor basically sandboxes the code execution away from the global scope.
I know I can make this work with eval(), but all of my research about eval() says not to use it for security reasons, that it performs very poorly, and that new Function() is recommended.
Is there any way to require existing application modules inside of new Function() scripts? If not, what are some other alternatives? Or, would I be okay with eval() knowing that the code I'll be executing will only be my code, despite the potential performance hits?


text:
Q: Python logger stops logging after uncaught exception The native python logger used by our flask app seems to stop writing to the log after an exception happens. The last entry logged before each stoppage is a message describing the exception. Typically the next message is one written by code in after_request but for cases where the logger stops, the after_request message is never written out.
Any idea what could be causing this?
Note: I originally posted this question on Serverfault (https://serverfault.com/questions/655683/python-logger-stops-logging) thinking it was an infrastructure issue. But now that we have narrowed the issue down to it occurring after an exception, this issue may be better suited for Stackoverflow.
Update [12/22/2015]:
Logger instantiation:
logging.addLevelName(Config.LOG_AUDIT_LEVEL_NUM, Config.LOG_AUDIT_LEVEL_NAME)

logger = logging.getLogger(Config.LOGGER_NAME)
logger.setLevel(Config.LOG_LEVEL)

handler = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_LOCAL3)
handler.setLevel(Config.LOG_LEVEL)

formatter = log_formatter()
handler.setFormatter(formatter)
logger.addHandler(handler)

log_formatter:
class log_formatter(logging.Formatter):

    def __init__(self,
                 fmt=None,
                 datefmt=None,
                 json_cls=None,
                 json_default=_default_json_default):
        """
        :param fmt: Config as a JSON string, allowed fields;
               extra: provide extra fields always present in logs
               source_host: override source host name
        :param datefmt: Date format to use (required by logging.Formatter
            interface but not used)
        :param json_cls: JSON encoder to forward to json.dumps
        :param json_default: Default JSON representation for unknown types,
                             by default coerce everything to a string
        """

        if fmt is not None:
            self._fmt = json.loads(fmt)
        else:
            self._fmt = {}
        self.json_default = json_default
        self.json_cls = json_cls

        if 'extra' not in self._fmt:
            self.defaults = {}
        else:
            self.defaults = self._fmt['extra']

        try:
            self.source_host = socket.gethostname()
        except:
            self.source_host = ""

    def format(self, record):
        """
        Format a log record to JSON, if the message is a dict
        assume an empty message and use the dict as additional
        fields.
        """

        fields = record.__dict__.copy()
        aux_fields = [
            'relativeCreated', 'process', 'args', 'module', 'funcName', 'name',
            'thread', 'created', 'threadName', 'msecs', 'filename', 'levelno',
            'processName', 'pathname', 'lineno', 'levelname'
        ]
        for k in aux_fields:
            del fields[k]

        if isinstance(record.msg, dict):
            fields.update(record.msg)
            fields.pop('msg')
            msg = ""
        else:
            msg = record.getMessage()

        if 'msg' in fields:
            fields.pop('msg')

        if 'exc_info' in fields:
            if fields['exc_info']:
                formatted = tb.format_exception(*fields['exc_info'])
                fields['exception'] = formatted
            fields.pop('exc_info')

        if 'exc_text' in fields and not fields['exc_text']:
            fields.pop('exc_text')

        logr = self.defaults.copy()

        logr = {
            'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
            'host': self.source_host,
        }
        logr.update(self._build_fields(logr, fields))

        if msg:
            logr['message'] = msg

        something = json.dumps(logr, default=self.json_default, cls=self.json_cls)
        return something

    def _build_fields(self, defaults, fields):
        return dict(defaults.get('fields', {}).items() + fields.items())

Update [01/03/2015]:
Answering questions posted:
Is the application still working after the exception?
Yes, the application continues to run.
Which type of exception is raised and what's the cause of it?
Internal/custom exception. Logger has stopped due to different types of exceptions.
Are you using threads in you application?
Yes, the app is threaded by gunicorn.
How is the logging library used?
We are using default FileHandler, SysLogHandler and a custom formatter (outputs JSON)
Does it log on a file? Does it use log rotation?
Yes, it logs to a file, but no rotation.

A: In regards to after_request, from the docs:

As of Flask 0.7 this function might not be executed at the end of the
  request in case an unhandled exception occurred.

And as for your logging issue, it may be that your debug flag is set to true, which would cause the debugger to kick in and possibly stop the logging.
References:
(http://flask.pocoo.org/docs/0.10/api/#flask.Flask.after_request)
(http://flask.pocoo.org/docs/0.10/errorhandling/#working-with-debuggers)

A: You didn't provide enough information.
Is the application still working after the exception?
Which type of exception is raised and what's the cause of it?
Are you using threads in you application?
How is the logging library used? Does it log on a file? Does it use log rotation?
Supposing you're using threads in you application, the explanation is that the exception causes the Thread to shut down, therefore you won't see any activity from that specific thread. You should notice issues with the application as well.
If the application is still working but becomes silent, my guess is that the logging library is not configured properly. As you reported on Serverfault, the issue seemed to appear after adding fluentd which might not play well with the way your application uses the logging library.


text:
Q: Debug.Assert-s use the same error message. Should I promote it to a static variable? I love Asserts and code readability but not code duplication, and in several places I use a Debug.Assert which checks for the same condition like so:
Debug.Assert(kosherBaconList.SelectedIndex != -1, "An error message along the lines - you should not ever be able to click on edit button without selecting a kosher bacon first.");

This is in response to an actual bug, although the actual list does not contain kosher bacon. Anyhow, I can think of two approaches:
private static readonly mustSelectKosherBaconBeforeEditAssertMessage =
    "An error message along the lines - you should not ever be able to " +
    "click on edit button without selecting a something first.";
...
Debug.Assert(
    kosherBaconList.SelectedIndex != -1,
    mustSelectKosherBaconBeforeEditAssertMessage)

or:
if (kosherBaconList.SelectedIndex == -1)
{
    AssertMustSelectKosherBaconBeforeEdit();
}
...
[Conditional("DEBUG")]
private void AssertMustSelectKosherBaconBeforeEdit()
{
    // Compiler will optimize away this variable.
    string errorMessage =
        "An error message along the lines - you should not ever be able to " +
        "click on edit button without selecting a something first.";

    Debug.Assert(false, errorMessage);
}

or is there a third way which sucks less than either one above? Please share.
General helpful relevant tips are also welcome.

A: Use the first (repetitive) form.
The reasons for this are:

*

*It's less work. Asserts are debug-only, so the repetition doesn't add any inefficiency to the release build. Don't waste time trying to make code "pretty" or "elegant" when it is already perfectly readable and functional.

*I'd argue it's actually shorter, more readable, and more easily maintained than your alternatives.

*When you hit an Assert in your debugger, it's very useful to have the full message in the code so you can see what the assert means. A lot of programmers use Assert(kosherBaconList.SelectedIndex != -1); with no explanation at all, which is fine if you wrote the code, but when you hit someone else's Assert you have no idea what it means. i.e. I know I called your method "wrong", but what the heck do I have to fix to call it "right"? The assert message should therefore indicate what the problem is, and what the person staring at the Assert() call needs to do to fix it. And you want it right there in front of you when your debugger stops in the middle of your test run.

*Sometimes you'll find it is useful to add additonal information relating to the context in which the assert fired, so you don't have to actually debug the code to work out which of your 3 "identical" asserts failed. I often use assert text like "BaconManager.Cook: You must select..." and "BaconManager.Wrap: You must select..." for this reason.

*If you include the text in the Assert call, it will not be compiled into your release build. But as soon as you make it a static variable, you will include the (unused) string in your release build, clogging it up with debugging junk.
A subroutine could be used if you want to check more than one condition to test the validity of your object, i.e.
[Conditional("DEBUG")]
private void AssertValidity()
{
    Debug.Assert(kosherBaconList.SelectedIndex != -1, "Nothing selected in kosher bacon list");
    Debug.Assert(kosherBaconList.COunt > 0, "kosher bacon list is empty!");
}

A: Keep it Simple, I would go for the static mustSelectKosherBaconBeforeEditAssertMessage = " ". And maybe even for inline strings if there were a few small differences.
Your AssertMustSelectKosherBaconBeforeEdit() looks too much like a premature/micro optimization.

A: One more suggestion:  rather than static variable, make it:
private const string mustSelectKosherBaconBeforeEditAssertMessage =
    "An error message along the lines - you should not ever be able to " +
    "click on edit button without selecting a something first.";

More on const vs static readonly: Link

The difference is that the value of a
static readonly field is set at run
time, and can thus be modified by the
containing class, whereas the value of
a const field is set to a compile time
constant.

Also here:
http://msdn.microsoft.com/en-us/magazine/cc300489.aspx


text:
Q: Powershell to truncate a string I'm trying to truncate a string which I'm fetching from an excel file.
The string(URL) is: ;#://abc.com/sites/abcx/000000103483/default.aspx;#000000103483;#
I need it to be: abc.com/sites/abcx/000000103483/
But the problem is abcx in the URL ranges from abcx to abcxxxx, where x is an integer.
How can I get the required result?

A: In PowerShell, you could split on /s and build the string you want like this:
$string = ";#://abc.com/sites/abcx/000000103483/default.aspx;#000000103483;#"
$split = $string.Split("/")
$split[2] + "/" + $split[3] + "/" + $split[4] + "/" + $split[5] + "/"

Output:
abc.com/sites/abcx/000000103483/

A: Remove default.aspx and everything that comes behind it.
$s = ';#://abc.com/sites/abcx/000000103483/default.aspx;#000000103483;#'
$s -replace 'default\.aspx.*'


text:
Q: NodeJS script on Azure VM I've setup a Linux VM on Azure which has NodeJS and MongoDB installed.
Then I have a single node script that I need to be constantly running (it receives and sends Google push notifications generated from an Android app and saves to my MongoDB accordingly).
So far the only way I can get it to run is by connecting via ssh on my local machine, running the script with "node gcm.js", which works fine. But when I disconnect from the server the script stops running... So how do I run it without needing to connect with my local machine? A cron job that starts just one time? Or have I gone about this in completely the wrong way?

A: Per my experience, there is a simple way for keeping the current process running as a background job.
Here is the steps below.

*

*Connecting via ssh on local machine, then running the script node gcm.js.

*Enter Ctrl+Z for stoping the current process, then you will see below, the N number of the [N]+ below is the job id.
^Z
[N]+  Stopped                 node gcm.js

*Enter bg %N to convert the N job from a stoped foregroud job into a background job.

*Enter disown -h %N to remove the N job from the job list of the current shell, then the process will be running after closing the current ssh connection.

More details for these linux commands, I think you can easily get via search engine.
Hope it helps.


text:
Q: ASP.NET gridview dynamic changing cell background I have a griview which is bounded to a sqldatasource and changed dynamically. How do I change the background cell color based on the value? e.g., 0-0.5 green, 0.5-1 red, sth like that.
   <asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource3">

A: You probably want to use the RowDataBound event of the GridView, something like this:
<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False"
     DataSourceID="SqlDataSource3" OnRowDataBound="ChangeRowColor">

protected void ChangeRowColor(object sender, GridViewRowEventArgs e)
{
   if( ((DataRow)e.Row.DataItem)[1] == .5)
   {
     e.Row.Cell[1].BackColor = Colors.Green;
   }
}

In my example, I'm assuming the data used to fill the grid are DataRows (i.e. from a datatable), but essentially the idea is to cast the DataItem of the current row to whatever type of object is being bound to, check the value of the property you need, and then set the BackColor of the corresponding cell.
You could also inspect the Cell's text property, but you might have to do extra parsing or what-not to get from the string to whatever value you want to compare.

A: One solution is to create a server method that you can call during databind, that will return a css class name.
Bind the css class attribute to a call to this method, and pass in the appropriate data element.
This is an example of the concept, you'd have to adapt it for your uses.
... Css file
.NegativeMoneyText
{
    color: #FF0000;
}

... Aspx file
<asp:Label ID="lblPaid" runat="server" CssClass='<%# getMoneyCssClass(Eval("PAID_AMOUNT").ToString()) %>' Text='<%# formatMoney(Eval("PAID_AMOUNT").ToString()) %>'></asp:Label>

... Code behind
public string getMoneyCssClass(string amount)
{
    if (!string.IsNullOrEmpty(amount))
    {
        double val = double.Parse(amount);
        if (val < 0)
            return "NegativeMoneyTextCss";
    }
    return return "PositiveMoneyTextCss";
}


text:
Q: Shift cards over to next row when browser size is 915px width How do I shift the content over to the next row when browser width is 915px?
This is what I have now:

                    <svg>
                        <circle cx="70" cy="70" r="70"></circle>
                        <circle cx="70" cy="70" r="70"></circle>
                    </svg>

90%

Html

                    <svg>
                        <circle cx="70" cy="70" r="70"></circle>
                        <circle cx="70" cy="70" r="70"></circle>
                    </svg>

85%

CSS

                    <svg>
                        <circle cx="70" cy="70" r="70"></circle>
                        <circle cx="70" cy="70" r="70"></circle>
                    </svg>

60%

Javascript

And my css
.body {
  display: flex;
  justify-content: center;
  align-items: center;

  min-height: 100vh;
}

.container {
  display: flex;
  justify-content: space-around;
}
.container .card {
  margin-left: 20px;
  position: relative;
  width: 250px;
  background: #222;
  background: linear-gradient(0deg, #1b1b1b, #222, #1b1b1b);
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  border-radius: 4px;
  text-align: center;
  overflow: hidden;
  transition: 0.5s;
}
.container .card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
  transform: translateY(-10px);
}
.container .card:before {
  content: "";
  position: absolute;
  top: 0;
  left: -50%;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.03);
  pointer-events: none;
  z-index: 1;
}
.percent {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  box-shadow: inset 0 0 50px #000;
  background: #222;
  z-index: 100;
}
.percent .number {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
}
.percent .number h2 {
  color: #777;
  font-weight: 700;
  font-size: 40px;
  transition: 0.5s;
}
.card:hover .percent .number h2 {
  color: #fff;
  font-size: 60px;
}
.percent .number h2 span {
  font-size: 24px;
  color: #777;
}
.text {
  color: #777;
  margin-top: 20px;
  font-weight: 700;
  font-size: 18px;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: 0.5s;
}
.card:hover .text {
  color: #fff;
}
svg {
  position: relative;
  width: 150px;
  height: 150px;
  z-index: 1000;
}
circle {
  width: 100%;
  height: 100%;
  fill: none;
  stroke: #191919;
  stroke-width: 10;
  stroke-linecap: round;
  transform: translate(5px, 5px);
}
circle:nth-child(2) {
  stroke-dasharray: 440;
  stroke-dashoffset: 440;
}
.card:nth-child(1) svg circle:nth-child(2) {
  stroke-dashoffset: calc(440 - (440 * 90) / 100);
  stroke: #00ff43;
}
.card:nth-child(2) svg circle:nth-child(2) {
  stroke-dashoffset: calc(440 - (440 * 85) / 100);
  stroke: #00a1ff;
}
.card:nth-child(3) svg circle:nth-child(2) {
  stroke-dashoffset: calc(440 - (440 * 60) / 100);
  stroke: #c104ff;
}

@media only screen and (max-width: 915px) {
  /* your css of 1024 px screen size */
  .card {
    flex: 10% !important;
  }
}

How do I make the content shift downwards when on 915px browser width so it looks good on mobile. I've tried flex, change display, change width but nothing works. I don't know if it has to do with any of that but I'd appreciate the help.

A: You can use the grid layout. First, set the container to display: grid;. After you can set how your grid will be with the grid-template-columns: 1fr; (1fr = one column, 1fr 1fr = 2 column, 1fr 2fr = 2 column, but the right one is bigger... etc). After that, you can add gap: 1rem; to have a gap between you column and row.
The Grid Documentation on W3School
Here is a example:

.body {
  display: flex;
  justify-content: center;
  align-items: center;

  min-height: 100vh;
}

.container {
  display: flex;
  justify-content: space-around;
}
.container .card {
  margin-left: 20px;
  position: relative;
  width: 250px;
  background: #222;
  background: linear-gradient(0deg, #1b1b1b, #222, #1b1b1b);
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  border-radius: 4px;
  text-align: center;
  overflow: hidden;
  transition: 0.5s;
}
.container .card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
  transform: translateY(-10px);
}
.container .card:before {
  content: "";
  position: absolute;
  top: 0;
  left: -50%;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.03);
  pointer-events: none;
  z-index: 1;
}
.percent {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  box-shadow: inset 0 0 50px #000;
  background: #222;
  z-index: 100;
}
.percent .number {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
}
.percent .number h2 {
  color: #777;
  font-weight: 700;
  font-size: 40px;
  transition: 0.5s;
}
.card:hover .percent .number h2 {
  color: #fff;
  font-size: 60px;
}
.percent .number h2 span {
  font-size: 24px;
  color: #777;
}
.text {
  color: #777;
  margin-top: 20px;
  font-weight: 700;
  font-size: 18px;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: 0.5s;
}
.card:hover .text {
  color: #fff;
}
svg {
  position: relative;
  width: 150px;
  height: 150px;
  z-index: 1000;
}
circle {
  width: 100%;
  height: 100%;
  fill: none;
  stroke: #191919;
  stroke-width: 10;
  stroke-linecap: round;
  transform: translate(5px, 5px);
}
circle:nth-child(2) {
  stroke-dasharray: 440;
  stroke-dashoffset: 440;
}
.card:nth-child(1) svg circle:nth-child(2) {
  stroke-dashoffset: calc(440 - (440 * 90) / 100);
  stroke: #00ff43;
}
.card:nth-child(2) svg circle:nth-child(2) {
  stroke-dashoffset: calc(440 - (440 * 85) / 100);
  stroke: #00a1ff;
}
.card:nth-child(3) svg circle:nth-child(2) {
  stroke-dashoffset: calc(440 - (440 * 60) / 100);
  stroke: #c104ff;
}

@media only screen and (max-width: 915px) {
  /* your css of 1024 px screen size */
  .card {
    flex: 10% !important;
  }
  .grid-class{
      display: grid;
    grid-template-columns: 1fr;
    gap: 1rem;
  }
}

                    <svg>
                        <circle cx="70" cy="70" r="70"></circle>
                        <circle cx="70" cy="70" r="70"></circle>
                    </svg>

90%

Html

                    <svg>
                        <circle cx="70" cy="70" r="70"></circle>
                        <circle cx="70" cy="70" r="70"></circle>
                    </svg>

85%

CSS

                    <svg>
                        <circle cx="70" cy="70" r="70"></circle>
                        <circle cx="70" cy="70" r="70"></circle>
                    </svg>

60%

Javascript


text:
Q: how to add ads in listview in MyAdapter How can I add AdMob ads in a list view?
I just add MyAdapter class and MyViewHolder class but I get an error.
Here is my code:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

/// LIST ADS
private static final int MENU_ITEM_VIEW_TYP = 0;
private static final int AD_VIEW_TYPE = 1;
/// LIST ADS

Context c;
ArrayList<Article> articles;
public MyAdapter(Context c, ArrayList<Article> articles) {
    this.c = c;
    this.articles = articles;
}

public class NativeExpressAdsViewHoolder extends MyViewHolder {
    NativeExpressAdsViewHoolder(View view){
        super(view);
    }

}

@Override
public int getItemCount() {
    return articles.size();
}
@Override
public long getItemId(int position) {
    return (position % 8 == 0) ? AD_VIEW_TYPE: position;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
   switch (viewType) {
        case AD_VIEW_TYPE:
            View nativ = LayoutInflater.from(c).inflate(R.layout.native_expres_continer, parent, false);
            return new MyViewHolder(nativ);
       case MENU_ITEM_VIEW_TYP:
        default:

            View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false);
            return new MyViewHolder(v);

    }

}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    Article article=articles.get(position);

    NativeExpressAdsViewHoolder nativeExpressHolder = (NativeExpressAdsViewHoolder)holder;
    NativeExpressAdView adsView = (NativeExpressAdView)articles.get(position);

    Article adview=articles.get(position);

    String title=article.getTitle();
    String desc=article.getDescription();
    String date=article.getDate();
   /// String imageUrl=article.getImageUrl();
    holder.titleTxt.setText(title);
    holder.desctxt.setText(desc);
    holder.dateTxt.setText(date);
   // PicassoClient.downloadImage(c,imageUrl,holder.img);
}

}
Myviewholder class
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleTxt,desctxt,dateTxt,adview;
ImageView img;
public MyViewHolder(View itemView) {
    super(itemView);
    titleTxt= (TextView) itemView.findViewById(R.id.titleTxt);
    desctxt= (TextView) itemView.findViewById(R.id.descTxt);
    dateTxt= (TextView) itemView.findViewById(R.id.dateTxt);

   // img= (ImageView) itemView.findViewById(R.id.articleImage);
}

}

A: Without knowing the exact error you get I think the code might be problematic because of how you integrate the ads.
First you will never actually show all the articles actually in the list because you just say for every 8th article it should display an ad instead but the original 8th article in the list won't be shown.
Now I think where your example crashes is in onBindViewHolder at the 8th element when you actually try to access titleTxt, desctxt or dateTxt on it. The ViewHolder you inflated is a NativeExpressAdsViewHoolder (because it's also of type RecyclerView.ViewHolder <- btw you can leave that whole check. The holder of onBindViewHolder will always be a ViewHolder) so it won't have those fields and the program will crash.
In order for this to work you will need to have a representation for the ads available in the backing collection you supply to the Adapter.
So instead of giving your Adapter a list of articles I would introduce an interface like this:
interface ListElement {

    ElementType getType();

    enum ElementType {
        ARTICLE,
        AD
    }
}

Of course now your Article class will need to implement this interface and always statically return ElementType.ARTICLE in the getType method and you need an empty class Ad that also implements the interface and always returns ElementType.AD in its getType method.
Now I assume you load your articles somewhere from the web and then pass them to the Adapter? So now before passing them to the adapter you insert the Ad placeholder classes. So whereever you instanciate your Adapter do something like this:
private MyAdapter createAdapter(List<Article> articlesLoadedFromWeb) {
    final List<ListElement> articlesAndAds = new ArrayList<>();

    for (int i = 0; i < articlesLoadedFromWeb.size(); i++) {
        if (i % 8 == 0) {
            articlesAndAds.add(new Ad());
        } else {
            articlesAndAds.add(articlesLoadedFromWeb(i));
        }
    }

    return new MyAdapter(getContext(), articlesAndAds);
}

And then your Adapter could look like this:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    final Context c;
    final List<ListElement> articlesAndAds;

    public MyAdapter(Context c, List<ListElement> articlesAndAds) {
        this.c = c;
        this.articlesAndAds = articlesAndAds;
    }

    public class NativeExpressAdsViewHolder extends MyViewHolder {
        NativeExpressAdsViewHolder(View view){
            super(view);
        }

    }

    @Override
    public int getItemCount() {
        return articlesAndAds.size();
    }

    @Override
    public long getItemId(int position) {
        return articlesAndAds.get(position).getType().ordinal();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       switch (viewType) {
            case ListElement.ElementType.AD.ordinal():
                View nativ = LayoutInflater.from(c).inflate(R.layout.native_express_container, parent, false);
                return new MyViewHolder(nativ);
           case ListElement.ElementType.ARTICLE.ordinal():
           default:

                View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false);
                return new MyViewHolder(v);

        }

    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        if (articlesAndAds.get(position).getType() == ListElement.ElementType.ARTICLE) {
            final Article article = (Article) articles.get(position);

            String title = article.getTitle();
            String desc = article.getDescription();
            String date = article.getDate();
            /// String imageUrl = article.getImageUrl();
            holder.titleTxt.setText(title);
            holder.desctxt.setText(desc);
            holder.dateTxt.setText(date);
            // PicassoClient.downloadImage(c, imageUrl, holder.img);
        }
    }

}


text:
Q: RVM on Mac .... .... ....? I want to run Jeckyll on Mac.
It says I need gem.
So I try to get RVM to manage ruby.
https://rvm.io/rvm/security

Garretts-MBP:~ garrettsmith$ which gpg
Garretts-MBP:~ garrettsmith$ gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
-bash: gpg: command not found

What do I do?

A: Looks like you need GPG/PGP. You could use something like the suite provided via https://gpgtools.org/. Alternatively, you should be able to install it via homebrew. I believe it's brew install gnupg.


text:
Q: How read data from sqlite with SQLite.swift? I want to build a Dictionary app for iOS. I try to read data from sqlite database file with SQLite.swift here.
My code
func configureCell(){
    //Todo: read sqlite file
    //let path = Bundle.main.path(forResource: "taidict", ofType: "sqlite")!

    do{
        let path = Bundle.main.path(forResource: "taidict", ofType: "sqlite")!

        let db = try Connection(path, readonly: true)
        let users = Table("words")
        let id = Expression<Int64>("id")
        let word = Expression<String?>("word")
        let shanword_uni = Expression<String>("shanword_uni")

        for user in try db.prepare(users.select(id, word, shanword_uni)) {
            print("id: \(user[id]), word: \(user[word]), meaning: \(user[shanword_uni])")
            // id: 1, email: alice@mac.com
        }

    }catch{
        print(error)
    }

}

When I try to run, I have got an error like below.
    2017-10-03 21:59:57.826502+0630 TaiDict[60682:516343] [MC] Lazy loading NSBundle MobileCoreServices.framework
2017-10-03 21:59:57.827558+0630 TaiDict[60682:516343] [MC] Loaded MobileCoreServices.framework
2017-10-03 21:59:57.841476+0630 TaiDict[60682:516343] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/saitanwgpha/Library/Developer/CoreSimulator/Devices/BA4F6AD0-6C4D-4F29-B0E0-34B9F63607A0/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
fatal error: 'try!' expression unexpectedly raised an error: Unexpected null value for column `"id"`: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.59/src/swift/stdlib/public/core/ErrorType.swift, line 181
2017-10-03 21:59:57.870943+0630 TaiDict[60682:516343] fatal error: 'try!' expression unexpectedly raised an error: Unexpected null value for column `"id"`: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.59/src/swift/stdlib/public/core/ErrorType.swift, line 181
Message from debugger: The LLDB RPC server has crashed. The crash log is located in ~/Library/Logs/DiagnosticReports and has a prefix 'lldb-rpc-server'. Please file a bug and attach the most recent crash log.

How should I fix it? Please help me.
Best,
Sai Pha


text:
Q: fitnesse - threading issues on older versions For a java project using Slim we have built up a quite a few suites, each with a couple of hundred tests. As these suites have grown we are seeing some pretty random null exceptions occurring more frequently as the suite size increase.
This would suggest some threading issues.
The query method returned: Exception: queryTable_3_2

We are using quite an old fitnesse version (20111026), wondering if anyone has issues with such issues in fitnesse and what solved them.
Not seeing any chanage log in regard to release, anyone know has any thread related fixes gone in since v.20111026?


text:
Q: How to create an incremental load with Salesforce as source in Azure data factory? Is there any way we can fetch the max of last modified date from the last processed file and store it in a config table

A: From Supported data stores and formats you can see Salesforce, Salesforce service cloud and Marketing cloud are supported.
You have to perform the following steps:

*

*Prepare the data store to store the watermark value.

*Create a data factory.

*Create linked services.

*Create source, sink, and watermark datasets.

*Create a pipeline.

*Run the pipeline.

Follow this to setup Linked Service with Salesforce in Azure Data Factory

When copying data from Salesforce, you can use either SOQL query or SQL query. Note that these two has different syntax and functionality support, do not mix it. You are suggested to use the SOQL query, which is natively supported by Salesforce.
Process for incremental loading, or delta loading, of data through a watermark:
In this case, you define a watermark in your source database. A watermark is a column that has the last updated time stamp or an incrementing key. The delta loading solution loads the changed data between an old watermark and a new watermark. The workflow for this approach is depicted in the following diagram:

ADF will scan all the files from the source store, apply the file filter by their LastModifiedDate, and only copy the new and updated file since last time to the destination store.
For capabilities, Prerequisites and Salesforce request limits refer Copy data from and to Salesforce by using Azure Data Factory
Refer doc: Delta copy from a database with a control table This article describes a template that's available to incrementally load new or updated rows from a database table to Azure by using an external control table that stores a high-watermark value.
This template requires that the schema of the source database contains a timestamp column or incrementing key to identify new or updated rows.
The template contains four activities:

*

*Lookup  retrieves the old high-watermark value, which is stored in an external control table.

*Another  Lookup  activity retrieves the current high-watermark value from the source database.

*Copy  copies only changes from the source database to the destination store. The query that identifies the changes in the source database is similar to 'SELECT * FROM Data_Source_Table WHERE TIMESTAMP_Column > "last high-watermark" and TIMESTAMP_Column <= "current high-watermark"'.

*StoredProcedure  writes the current high-watermark value to an external control table for delta copy next time.

Go to the Delta copy from Database template. Create a New connection to the source database that you want to data copy from.
Create connections to the external control table and stored procedure that you created and   Select  Use this template.
Choose the available pipeline
For Stored procedure name, choose [dbo].[update_watermark]. Select Import parameter, and then select Add dynamic content.

click  Add dynamic content and Type in below query. This will get a  maximum date  in your watermark column that we can use for delta slice.
You can use this query to fetch the max of last modified date from the last processed file
select MAX(LastModifytime) as NewWatermarkvalue from data_source_table"

or
For files only you can use Incrementally copy new and changed files based on LastModifiedDate by using the Copy Data tool
Refer: Source:  ADF Incremental loading with configuration stored in a table