text:
Q: Displaying pop-up picture in QGISCloud? I'm working with 2.14, plugin QGISCloud (free version) and for a shapefile (point) I want to pop-up a picture of my vacation and share it with others. It works offline with the code in the HTML box / expressions:
[%CONCAT('<img src="', "Loc", '" width="400"></img')%]

"Loc", stands for name and folder direction on my local drive. Backslash like: / (backward-sloping) not \(upward-sloping).
But my question is: How to do it online with QGISCloud? Are there alternatives (with other plugin's).

A: The main problem is that you cannot can upload photo's to Qgiscloud.
This link give you a step by step solution for this specific problem.
In sort it will look like this:
1. Make new shapefile (point)
2. Make Qtdesign, dialog menu
3. Make python script to handle the image data
4. Edit the field of the layer
5. Create a maptip with image and content.
Now you can share geotaged photo's with others by a web browser which is desktop and mobile compatible and without installing app's or login on a web page.
Explanation of FAQ from Qgiscloud website


text:
Q: Linkage and static function confusion I read that

A function with internal linkage is only visible to one compilation
  unit. (...) A function declared static has internal linkage

For .c files it sorta makes sense, but I was wondering what happens with static functions in headers, which get included by multiple .c files but usually have an include guard.
I was reading this answer about static functions in headers, and the first item mentions that it doesn't create a symbol with external linkage and the second item mentions the function is available purely through the header file. Isn't that contradictory? How can the function be available and at the same time have no external symbol? So I did a little test:
/* 1.h */
#ifndef ONE_H
#define ONE_H

#include <stdio.h>

static void foo() {
  printf("foo from 1.h %p\n", foo);
  return;
}

void bar();

#endif

/* 1.c */
#include "1.h"
#include <stdio.h>

void bar() {
  printf("foo,bar from 1.c %p,%p\n", foo, bar);
  foo();
}

/* 2.c */
#include "1.h"
#include <stdio.h>

int main() {
  printf("foo,bar from main %p,%p\n", foo, bar);
  foo();
  bar();
  return 0;
}

...

debian@pc:~ gcc 2.c 1.c
debian@pc:~ ./a.out
foo,bar from main 0x400506,0x400574
foo from 1.h 0x400506
foo,bar from 1.c 0x400559,0x400574
foo from 1.h 0x400559

As expected bar is the same across all files, but shouldn't foo be too? Isn't 1.h included only once? Adding inline to foo resulted in the same behavior. I'm kinda lost.

A: Read here, how a header file basically works. That should clarify about your actual question.
Briefly: A header file is just inserted instead of the corresponding #include directive. So any declarations or definitions are treated by the compiler as if you actually copy/pasted the text into your file.
Anyway, you should be careful with function definitions in a header. This is deemed bad style in general. It blows the code for instance, creating redundant copies of that function. Also Function pointers cannot be compared (you never know ...). It is often better to bundle the functions into a library with just the declarations in a header (non-static then: external linkage). There are good justifications sometimes, however (no rule without exceptions). One of them are inline functions.

A: -static functions are functions that are only visible to other functions in the same file (more precisely the same translation unit).
Check this article for a detailed explanation on linkage: http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a border after heading in Wordpress? I'm trying to add a border image after every header in Wordpress, but the following isn't working
h1:after {
content:' ';
border:2px solid rgb(229,164,20);
margin: 25px 0;
display:inline-block;
width: 45px;
}


text:
Q: How to assign range in a string VBA? I have a code to highlight words in a cell based on the values in another cells. It works perfectly when I assign FindW = Range("X1") . However the code does not seem to work when I assign range e.g:("X1:X1000") to the string value FindW and I could not find a way to fix this.
Does anyone have any idea?
See the code below:

Dim Rng As Range
Dim FindW As String
Dim xTmp As String
Dim x As Long
Dim m As Long
Dim y As Long
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Übersicht")

Application.ScreenUpdating = False
Application.EnableEvents = False

With ws

FindW = Range("X1:X1000")
y = Len(FindW)

For Each Rng In Range("C:H")
  With Rng
    m = UBound(Split(Rng.Value, FindW))
    If m > 0 Then
      xTmp = ""
      For x = 0 To m - 1
        xTmp = xTmp & Split(Rng.Value, FindW)(x)
        .Characters(Start:=Len(xTmp) + 1, Length:=y).Font.ColorIndex = 3
        xTmp = xTmp & FindW
      Next
    End If
  End With
Next Rng

End With
End Sub

A: You can't put the values of a Range of multiple cells directly into a single String variable.  However, you can create a String Array and store each cell value individually in the String Array.
The easiest solution is to just use a Variant variable, and put the range values directly in it, like this :
Dim mrange As Range
Dim mVariant As Variant
mVariant = myRange.Value

If you really need your variable to be a String, there are multiples ways to do so:
For example, you can loop through each cell of the Array using something like :
For each mCell in mRange.Cells
    mString(i) = mCell.Value
    i = i + 1
Next mCell

mRange being your Range, and mString being a String Array.  This solution requires for you to know how many cells are in the Range, since the String array needs to be defined with a size.
If you don't know the size of your Range, you can add a step and use a Variant variable.
See here.


text:
Q: Format of saved tables in postgreSQL What is the format of saved schema and tables in Postgresql.

A: If you use pg_dump to save the schema and tables, you have a choice of plain text (the default) or a few binary formats suitable for input to pg_restore - you can read all about them here.


text:
Q: "I will invite him to the meeting on a lower/lesser frequency/basis?" I would like to ask for help: I am organizing a meeting for X people on a weekly basis. Now, there are some less involved stakeholders that should be invited only once a month. It occurred to me that I am not sure how to say:
"Some will be invited on a lesser/lower frequency/basis" is certainly wrong but I cannot think of anything better.
I am not looking for another means to express that, I would like to find out what would be the proper adjective and noun to use in a sentence like this one.

A: I would simply say, on a less frequent basis. Or, on a merely limited number of occasions as opposed to the other folks.

A: If the schedule for these others is not rigidly defined, then you could say that "some others will be invited to these meetings intermittently"


text:
Q: Getting duplicate column ERROR while trying to insert same column with two different datatypes using SELECT INTO clause in PostgreSql I need to insert createdate column twice with two different datatypes one with the datatype defined in the table itself and another in char datatype.
I can insert it by changing the alias name of createdate column but can't insert with same alias name which i need.
so help me out to get correct way of doing it.
My query:
    SELECT DISTINCT TE.id, T.debatchqueuelink, TE.transactionlink,
                    EC.errorclassification, TE.errorvalue,
                    EC.errorparameter, TE.classificationlink, TE.description,
                    TE.createdate AS createdate, TO_CHAR(TE.createdate,  'MM/dd/yyyy') AS createdate,
                    TE.status, TE.rebutt, TE.rebuttedstatus, BQ.appbatchnumber,
                    BQ.scanbatchnumber, BQ.clientlink, BQ.locationlink, T.patientid,
                    (DEUD.firstname|| ' ' ||DEUD.lastname) AS deusername, DEUD.email AS deuseremail,
                    (QCUD.firstname|| ' ' ||QCUD.lastname) AS qcusername, TE.inactive,
                    TE.decomment
                 INTO table373
                 FROM qctransactionerror TE
                INNER JOIN errorclassification EC ON EC.id = TE.classificationlink
                INNER JOIN qctransaction T ON T.id = TE.transactionlink
                INNER JOIN batchqueue BQ ON T.debatchqueuelink = BQ.id
                INNER JOIN batchqueue QCBQ ON T.qcbatchqueuelink = QCBQ.id
                INNER JOIN userdetail QCUD ON QCBQ.assignedto = QCUD.id
                INNER JOIN userdetail DEUD ON BQ.assignedto = DEUD.id
                WHERE TE.inactive='t'
                  AND TE.status IN ('ERROR','QCCORRECTED')
                LIMIT 0

The actual error message I am getting is:
Duplicate column:column "createdate" specified more than once


text:
Q: How to loop through and modify multiple data frames in R I have data frames A, B, C, ... and want to modify each data frame in the same way, e.g. re-ordering factors levels of a factor which is present in all of the data frames:
A = data.frame( x=c('x','x','y','y','z','z') )
B = data.frame( x=c('x','y','z') )
C = data.frame( x=c('x','x','x','y','y','y','z','z','z') )

A$x = factor( A$x, levels=c('z','y','x') )
B$x = factor( B$x, levels=c('z','y','x') )
C$x = factor( C$x, levels=c('z','y','x') )

This gets laborious if there are lots of data frames and/or lots of modifications to be done. How can I do it concisely, using a loop or something better?  A straightforward approach like
for ( D in list( A, B, C ) ) {
D$x = factor( D$x, levels=c('z','y','x') )
}

does not work, because it doesn't modify the original data frames.
EDIT: added definitions of A, B, and C to make it reproducible.

A: One thing to note about R is that, with respect to assignment, <- is transitive, whereas = is not.  Thus, if your data frames are all the same in this respect, you should be able to do something like this:
A$x <- B$x <- C$x <- factor( C$x, levels=c('z','y','x') )

A: If you don't need explicit loop you can use lapply:
ll <- lapply(
    list(A, B, C),
    function(df) {
        df$x <- factor(df$x, levels=c('z', 'y', 'x'))
        return(df)
    }
)

Since data is only copied you'll have to use list returned from lapply.
Edit
dfs <- list('A', 'B', 'C')
levels <- c('z', 'y', 'x')

l <- lapply(
    dfs,
    function(df) {
        # Get data frame by name
        df <- get(df)
        df$x <- factor(df$x, levels=levels)
        return(df)
    }
)

for ( i in 1:length(dfs)) {
    assign(dfs[[i]], l[[i]])
}


text:
Q: User editable labels for check boxes I am trying to create a list of cameras allows the user to enter a custom name if needed. Ideally when they select the checkbox or surrounding text they will be able to change the text. The Name will need to be stored later in a DB.
I tried using "easy editable text", but I cannot figure it out.
Here is what I have. Any help would be appreciated. Thank you.
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
        <title>FMVSS - Camera Selection</title>
        <link rel="stylesheet"  href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />

Camera Selection

                <form action="#" method="get">

Camera request for: (Customer Name, passed or queryied)

Test Type: (Passed or queryied)

<legend>Do a look-up to see what the default views are for the selected TEST TYPE</legend>

<legend>Allow custom entries</legend>

                        <fieldset data-role="Selections">

                                <input type="checkbox" name="CameraView-1" id="CameraView-1" />
                                Oblique View From Front (Left Hand Side)

                                <input type="checkbox" name="CameraView-2" id="CameraView-2" />
                                Oblique View From Front (Right Hand Side)

                                <input type="checkbox" name="CameraView-3" id="CameraView-3" />
                                Oblique View From Rear (Right Hand Side)

                                <input type="checkbox" name="CameraView-7" id="CameraView-7" />
                                Custom Camera View #1 ***Value should be editable by user***

                                <input type="checkbox" name="CameraView-8" id="CameraView-8" />
                                Custom Camera View #2

                        </fieldset>

                </form>

A: Give this a go.
Click on the camera labels to edit them.
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
        <title>FMVSS - Camera Selection</title>
        <link rel="stylesheet"  href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />

Camera Selection

                <form action="#" method="get">

Camera request for: (Customer Name, passed or queryied)

Test Type: (Passed or queryied)

                        <fieldset data-role="Selections">

                        <legend>Allow custom entries - click on the label to edit</legend>

                                <input type="checkbox" name="CameraView-1" id="CameraView-1" />
                                Oblique View From Front (Left Hand Side)

                                <input type="checkbox" name="CameraView-2" id="CameraView-2" />
                                Oblique View From Front (Right Hand Side)

                                <input type="checkbox" name="CameraView-3" id="CameraView-3" />
                                Oblique View From Rear (Right Hand Side)

                                <input type="checkbox" name="CameraView-7" id="CameraView-7" />
                                Custom Camera View #1 ***Value should be editable by user***

                                <input type="checkbox" name="CameraView-8" id="CameraView-8" />
                                Custom Camera View #2

                        </fieldset>

                </form>


text:
Q: In android studio :how I can create two tables with references? I have project in android Studio which talk about Hotels and it have Database with two tables (Room , Customer).
I try to create customer table with foreign key(Room_ID) but I have Errors .
How I can create it ?
Another problem , when i add a new room and go to (Show Rooms) activity , the first room which i added it don't show , what is the problem ?
This is the Database class extends SqliteOpenHelper
  public DatabaseHelper(Context context) {
    super(context, "Hotel", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
        db .execSQL(room.Create_table);
        db .execSQL(customer.Create_table);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table " + room.Table_Name);
    db.execSQL("drop table " + customer.Table_Name);
    onCreate(db);
}
public  boolean insert_room (String name , String type , String price){
SQLiteDatabase db = getWritableDatabase() ;
    ContentValues data = new ContentValues();
    data.put(room.Col_Name,name);
    data.put(room.Col_Type,type);
    data.put(room.Col_Price,price);
    return db.insert(room.Table_Name,null ,data) >0 ;
 }
 public  boolean insert_customer (String name , String mobile , String
 passport,int days,int room_id){
     SQLiteDatabase db = getWritableDatabase() ;

     ContentValues data = new ContentValues();
     data.put(customer.Col_Name,name);
     data.put(customer.Col_Passport,passport);
     data.put(customer.Col_Mobile,mobile);
     data.put(customer.Col_Days,days);
     data.put(customer.Col_Room_ID,room_id);

    return db.insert(customer.Table_Name,null ,data) >0 ;
}
public ArrayList<room> getAll_rooms(){
    SQLiteDatabase db = getWritableDatabase() ;

    ArrayList<room> rooms=new ArrayList<>();
    Cursor cursor = db.rawQuery("select * from " +room.Table_Name  ,null);
    if (cursor.moveToFirst()){
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex(room.Col_Id));
            String name =cursor.getString(cursor.getColumnIndex(room.Col_Name));
            String type =cursor.getString(cursor.getColumnIndex(room.Col_Type));
            String price =cursor.getString(cursor.getColumnIndex(room.Col_Price));
            room r =new room(id,name,type,price);
            rooms.add(r);
        }
    }
    cursor.close();
    return rooms;
}

public ArrayList<customer> getAll_customers(){
    SQLiteDatabase db = getWritableDatabase() ;

    ArrayList<customer> customers=new ArrayList<>();
    Cursor cursor = db.rawQuery("select * from " +customer.Table_Name ,null);
    if (cursor.moveToFirst()){
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex(customer.Col_Id));
            String name =cursor.getString(cursor.getColumnIndex(customer.Col_Name));
          int days =cursor.getInt(cursor.getColumnIndex(customer.Col_Days));
            String mobile =cursor.getString(cursor.getColumnIndex(customer.Col_Mobile));
            String passport =cursor.getString(cursor.getColumnIndex(customer.Col_Passport));
            int room_id =cursor.getInt(cursor.getColumnIndex(customer.Col_Room_ID));
            customer c =new customer(id,name,passport,mobile,days,room_id);
            customers.add(c);
        }
    }
    cursor.close();
    return customers;
}

 }

And this Is the Customer Class

      public class customer {
    int id ;
    String name ;
    String passport_num;
    String mobile;
    int num_ofDays;
    int room_id ;

    public  static  final String Col_Id = "id";
    public  static  final String Col_Name = "name";
    public  static  final String Col_Passport= "passport_num";
    public  static  final String Col_Days= "num_ofDays";
    public  static  final String Col_Mobile= "mobile";
    public  static  final String Col_Room_ID= "room_id";
    public  static  final String Table_Name= "Customer";
    public  static  final String Create_table = " create table Customer(id integer primary key autoincrement ," +
            " name text , passport_num text , mobile text , num_ofDays integer " +
            " room_id integer , FOREIGN KEY(room_id) references Room (id))";

    public customer() {
    }

    public customer(int id, String name, String passport_num, String mobile, int num_ofDays, int room_id) {
        this.id = id;
        this.name = name;
        this.passport_num = passport_num;
        this.mobile = mobile;
        this.num_ofDays = num_ofDays;
        this.room_id = room_id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassport_num() {
        return passport_num;
    }

    public void setPassport_num(String passport_num) {
        this.passport_num = passport_num;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public int getNum_ofDays() {
        return num_ofDays;
    }

    public void setNum_ofDays(int num_ofDays) {
        this.num_ofDays = num_ofDays;
    }

    public int getRoom_id() {
        return room_id;
    }

    public void setRoom_id(int room_id) {
        this.room_id = room_id;
    }
}

This is 'Add Customer Calss'

    public class AddCustomer extends AppCompatActivity {

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

        final DatabaseHelper db=new DatabaseHelper(this);
        final Spinner type = findViewById(R.id.room_type_add);
        final EditText name = findViewById(R.id.customer_name_add);
        final EditText mobile = findViewById(R.id.mobile_num_add);
        final EditText passport = findViewById(R.id.passport_num_add);
        final EditText days = findViewById(R.id.num_days_add);
        final Button add =findViewById(R.id.addCustomer);
        final ArrayList<room> spData=db.getAll_rooms();

        room_adapter_spinner adapter=new room_adapter_spinner(this,spData);
        type.setAdapter(adapter);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String Name = name.getText().toString();
                String Mobile = mobile.getText().toString();
                String Passport = passport.getText().toString();
                String Days = days.getText().toString() ;
                int Days_i = Integer.parseInt(Days);
                int TYpe=(int) type.getSelectedItemId();
                if (db.insert_customer(Name,Mobile,Passport,Days_i ,TYpe)) {
                    Intent i = new Intent(AddCustomer.this,ShowCustomers.class);
                    startActivity(i);
                }
                else Toast.makeText(AddCustomer.this, "error", Toast.LENGTH_SHORT).show();
            }
        });

    }

}

This is Add room class

public class AddRoom extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_room);
        final  DatabaseHelper db = new DatabaseHelper(this);
        final EditText name = findViewById(R.id.room_name_add);
        final Spinner type = findViewById(R.id.room_type_add);
        final EditText price = findViewById(R.id.room_price_add);
        final Button add =findViewById(R.id.addRoom);
       add.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               String name_ = name.getText().toString();
              String type_s= type.getSelectedItem().toString();
               String price_ = price.getText().toString();
               if (db.insert_room(name_,type_s,price_)) {
                   Intent i = new Intent(AddRoom.this,ShowRooms.class);
                   startActivity(i);
               }
           }
       });

    }
}

This is (Show Rooms) class
public class ShowRooms extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_rooms);

        final ListView list = findViewById(R.id.list_rooms);
        DatabaseHelper db = new DatabaseHelper(this) ;
        ArrayList<room> data = db.getAll_rooms();
        room_adapter adapter = new room_adapter(this,data);
        list.setAdapter(adapter);

    }
}

When I run the project I have this errror
 Caused by: android.database.sqlite.SQLiteException: unknown column "room_id" in foreign key definition (code 1): , while compiling: create table Customer(id integer primary key autoincrement , name text , passport_num text , mobile text , num_ofDays integer  room_id integer , FOREIGN KEY(room_id) references Room (id))
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
        at com.example.the_hotel_project.DatabaseHelper.onCreate(DatabaseHelper.java:23)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
        at com.example.the_hotel_project.DatabaseHelper.getAll_rooms(DatabaseHelper.java:54)
        at com.example.the_hotel_project.AddCustomer.onCreate(AddCustomer.java:32)
        at android.app.Activity.performCreate(Activity.java:5104)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

A: You have a "," (comma) missing in the String Create_table of the Customer class. After num_ofDays.
It should be:
    public  static  final String Create_table = " create table Customer(id integer primary key autoincrement ,"
+ " name text , passport_num text , mobile text , num_ofDays integer, "
+ " room_id integer , FOREIGN KEY(room_id) references Room (id))";

A: For the 2nd question (please make two separate question next time), you call moveToFirst() then while(moveToNext()).
The cursor is at the first value when you call moveToFirst() and go to second position when you call moveToNext(). It is why your list starts from the second value.
What you can do is call moveToFirst() and invert the while loop :
if (cursor.moveToFirst()) {
    do {
        int id = cursor.getInt(cursor.getColumnIndex(room.Col_Id));
        String name = cursor.getString(cursor.getColumnIndex(room.Col_Name));
        String type = cursor.getString(cursor.getColumnIndex(room.Col_Type));
        String price = cursor.getString(cursor.getColumnIndex(room.Col_Price));
        room r = new room(id, name, type, price);
        rooms.add(r);
    } while (cursor.moveToNext());
}

Or check for the count and only call moveToNext()
if(cursor.getCount() != 0) {
    while(cursor.moveToNext()){
        int id = cursor.getInt(cursor.getColumnIndex(room.Col_Id));
        String name = cursor.getString(cursor.getColumnIndex(room.Col_Name));
        String type = cursor.getString(cursor.getColumnIndex(room.Col_Type));
        String price = cursor.getString(cursor.getColumnIndex(room.Col_Price));
        room r = new room(id, name, type, price);
        rooms.add(r);
    }
}

Use the same logic for getAll_customers()


text:
Q: Appending data to the specific table cell - jQuery I have some issue with jQuery TimeTable, I have created a table like

                Monday

                Tuesday

            ...... upto saturday
            ......

From and To are two dropdown lists, with this am allocatting the timings for these days,like
    var totalCol += 1;
$("#tabTimetable > tbody > tr:gt(0)").append("	");

If I click a particular cell it will ask the Section Name and StaffIncharge in a textbox, here StaffInCharge is a autocomplete box, in the selected item event am binding the data in that particular cell. I can get the CurrentRow and CurrentColumn like
currentCol = $(objCol).parent().children().index($(objCol));
currentRow = $(objCol).parent().parent().children().index($(objCol).parent());

and I have the data to be displayed as
var data = "

	" + timetable[i].Name + " ( " + timetable[i].ItemName + " )

 ";

I need to bind this "data" to that particular cell...I dunno how to do this...is it possible to bind like
$("#tabTimetable")[currentRow][currentCol].append(data);

A: try this
$("#tabTimetable tr:eq([currentRow]) td:eq([currentCol])").append(data);

eq() selectors are indexed from 0


text:
Q: Command `bundle` unrecognized.Did you mean to run this inside a react-native project?
Run the react-native bundle command in terminal from the root
  directory of your app

What is the root directory of my app? I am trying to run UIExplorer (on my device) from the official repo but its always giving me this message when I run
react-native bundle

Command bundle unrecognized.Did you mean to run this inside a react-native project?
I think I tried pretty much every directory inside /react-native-master

A: You don't need to run react-native bundle.
You should follow the 'OPTION 2' instruction in AppDelegate.m, you will find something like the screenshots below:

The instruction in the React-native website is not so clear, a clearer instructions will be:

*

*Open iOS/AppDelegate.m

*Comment out jsCodeLocation = [NSURL
URLWithString:@"http://localhost:8081/index.ios.bundle"];

*Uncomment jsCodeLocation = [[NSBundle mainBundle]
URLForResource:@"main"    withExtension:@"jsbundle"];

*Run the curl given in 'OPTION 2' (e.g.
http://localhost:8081/index.ios.bundle -o main.jsbundle)

*if this fails add the --ipv4 flag to the end of it.

*In XCode, right click on your project directory and click    Add
Files to "Project Name Here" - choose the main.jsbundle file that
you generated.

Referenced from: https://github.com/facebook/react-native/issues/240
If you still can't run it, check your main.jsbundle if it contains error. If it does, make sure the given curl path is correct. I end up changing the curl to curl http://localhost:8081/Examples/UIExplorer/UIExplorerApp.ios.bundle -o main.jsbundle in order for it to work.

A: open cmd go project dir and run git bash show Command bundle unrecognized. bat cmd does not show an error


text:
Q: Python - JsonPath insert value in retrieved path I have json paths from the results of search. I'm wondering how do I write to the particular path?
doc = {'foo':{ 'cd': {'baz': 1}, 'cd2': {'baz': 2}}}
expression = "foo.*.baz"
jsonpath_expr = parse(expression)
values = [str(match.full_path) for match in jsonpath_expr.find(doc)]
>> [foo.cd.baz, foo.cd2.baz]

for each of these results i want to insert a doc in its deep leaf like these
{'foo':{ 'cd': {'baz': 1, 'baz2': 2}, 'cd2': {'baz': 2, 'baz2': 2}}}

How do i go about these? I don't find any source of writing a value to a document given a json path. Thank you for the help.

A: This is how I did it.
def string_to_json(self, source):
      try:
        load_input_json = json.loads(source)
      except ValueError, e:
        raise Exception("Could not parse '%s' as JSON: %s" % (source, e))
      return load_input_json

  def _json_path_search(self, json, expr):
    path = parse(expr)
    return path.find(json)

  def update_json(self, doc, matches, name, value, index=0, parent=False):
    load_input_json = doc
    # matches = self._json_path_search(load_input_json, expr)
    datum_object = matches[int(index)]
    if not isinstance(datum_object, jsonpath.DatumInContext):
      raise Exception("Nothing found by the given json-path")
    path = datum_object.path
    if isinstance(path, jsonpath.Index):
      # datum_object.context.value[datum_object.path.index] = value
      datum_object.context.value[name] = value
    elif isinstance(path, jsonpath.Fields):
      # datum_object.context.value[datum_object.path.fields[0]] = value
      datum_object.context.value[name] = value
    return load_input_json


text:
Q: C++ split string with space and punctuation chars I wanna split an string using C++ which contains spaces and punctuations.
e.g. str = "This is a dog; A very good one."
I wanna get "This" "is" "a" "dog" "A" "very" "good" "one" 1 by 1.
It's quite easy with only one delimiter using getline but I don't know all the delimiters. It can be any punctuation chars.
Note: I don't wanna use Boost!

A: So, starting at the first position, you find the first valid token. You can use
index = str.find_first_not_of (yourDelimiters);

Then you have to find the first delimiter after this, so you can do
delimIndex = str.substr (index).find_first_of (yourDelimiters);

your first word will then be
// since delimIndex will essentially be the length of the word
word = str.substr (index, delimIndex);

Then you truncate your string and repeat. You have to, of course, handle all of the cases where find_first_not_of and find_first_of return npos, which means that character was/was not found, but I think that's enough to get started.
Btw, I'm not claiming that this is the best method, but it works...

A: Use std::find_if() with a lambda to find the delimiter.
auto it = std::find_if(str.begin(), str.end(), [] (const char element) -> bool {
                       return std::isspace(element) || std::ispunct(element);})

A: vmpstr's solution works, but could be a bit tedious.
Some months ago, I wrote a C library that does what you want.
http://wiki.gosub100.com/doku.php?id=librerias:c:cadenas
Documentation has been written in Spanish (sorry).
It doesn't need external dependencies. Try with splitWithChar() function.
Example of use:
#include "string_functions.h"
int main(void){

    char yourString[]= "This is a dog; A very good one.";
    char* elementsArray[8];
    int nElements;
    int i;

    /*------------------------------------------------------------*/
    printf("Character split test:\n");
    printf("Base String: %s\n",yourString);

    nElements = splitWithChar(yourString, ' ', elementsArray);

    printf("Found %d element.\n", nElements);

    for (i=0;i<nElements;i++){
        printf ("Element %d: %s\n", i, elementsArray[i]);
    }

    return 0;
}

The original string "yourString" is modified after use spliWithChar(), so be carefull.
Good luck :)

A: CPP, unlike JAVA doesn't provide an elegant way to split the string by a delimiter. You can use boost library for the same but if you want to avoid it, a manual logic would suffice.
vector<string> split(string s) {

    vector<string> words;
    string word = "";

    for(char x: s) {
        if(x == ' ' or x == ',' or x == '?' or x == ';' or x == '!'
           or x == '.') {
            if(word.length() > 0) {
                words.push_back(word);
                word = "";
            }
        }
        else
            word.push_back(x);
    }
    if(word.length() > 0) {
        words.push_back(word);
    }
    return words;


text:
Q: Checking for duplicate entries for Column A - Table A based on user_id from Table B I have two tables which have a 1 - 1 relationship.
Table A - Skill_id
Tabel A - Entry_id
Table B - Entry_id
Table B - Author_id
The two entry_id columns are a primary key - foreign key.
I need to check if a user has been allocated the same skill more than once, i.e. if there are duplicates. How can I achieve this?

A: Do a GROUP BY aggregation and see if the aggregated count is greater than 1
SELECT B.Author_id,A.Skill_id,COUNT(1) SkillEntryCount
FROM tableB B INNER JOIN tableA A USING (Entry_id)
GROUP BY B.Author_id,A.Skill_id
HAVING COUNT(1) > 1;

or collect all entry_id values for each (Author_id,Skill_id) and see it is has commas
SET group_concat_max_len = 1048576;
SELECT * FROM
(
  SELECT B.Author_id,A.Skill_id,GROUP_CONCAT(A.Entry_id) EntryIDs
  FROM tableB B INNER JOIN tableA A USING (Entry_id)
  GROUP BY B.Author_id,A.Skill_id
) AA WHERE LOCATE(',',EntryIDs) > 0;


text:
Q: php mysql username variable contains two values I am wondering if we could have one variable equals two string values? I made a login form which is not required username, only requires password. if the password matches, then it displays the the right person name. I fully understand this is not a right way or a secure way to do login form, but this form will only internally for 5 people use.
inside the php file, I set the $username = "PersonName"; the form only requires password,
if the password is correct, this person could login and the name  "PersonName1" on the page. I use mysql
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password_encrypt '");

If I want to add another PersonName2 can I have $username="PersonName1" || $username = "PersonName2";
or if someone could give me some ideas? Many thanks

A: Yes, use the OR operand in your SQL query:
SELECT * FROM users WHERE (username='$username' OR username='$username2') AND password='$password_encrypt '

A: You can also use the IN clause:
SELECT *
FROM users
WHERE username IN ('$username', '$username2')
    AND password='$password_encrypt'

A: Its possible to check for X OR Y in mysql, just make sure you use parenthesis to separate your conditions.
SELECT * FROM users WHERE (username='$firstName' || username='$secondName') AND password='$password_encrypt '

A: OR is available to use in MYSQL
   SELECT * FROM users WHERE (username='$username' OR username='$username2') AND password='$password_encrypt '

A: If the user doesn't require a username then in the SQL query just search for a matching password, then using PHP you can
while($user = mysql_fetch_assoc($result)){ /* check for a good username?? */ }

Also, mysql_* has been deprecated, research MySQLi or PDO for best practices.


text:
Q: Reading c socket from java hangs/blocks I have a problem with sockets between Java and C. I have a C program that creates a socket and starts listening. The Java client does it's work and under certain circumstances opens a socket and writes to it and tries to read from it but this blocks.
Heres the socket part of the C program:
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
char wbuffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
        cout << "ERROR opening socket" << endl;
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 23456;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
int on = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
        cout << "Couldn't set socket params!" << endl;
int so = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
while(so < 0) {
        cout << "ERROR on binding" << endl;
        sleep(1);
        so = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
        cout << "ERROR on accept" << endl;
bzero(buffer,256);
//cout << "Socket created!" << endl;
n = read(newsockfd,buffer,255);
if (n < 0)
        cout << "Error reading from socket" << endl;
 if (strcmp(buffer, "power\n") == 0) {
         // Do stuff
     strcpy(wbuffer, "off\n");
         }
     //sleep(1);
     n = write(newsockfd,wbuffer,strlen(wbuffer));
     if (n < 0)
         cout << "ERROR writing to socket" << endl;
}
//cout << "message: " << buffer << endl;
close(newsockfd);
close(sockfd);

And the Java side:
Socket socket3 = new Socket("localhost", 23456);
PrintWriter out3 = new PrintWriter(socket3.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket3.getInputStream()));
out3.write("power" + "\n");
//String status = in.readLine();
log.debug("Wrote power");
StringBuffer buffer = new StringBuffer();
while (true) {
    int ch = in.read();
    log.debug("in.read()");
    if ((ch < 0) || (ch == '\n')) {
        break;
    }
    buffer.append((char) ch);
}
String status = buffer.toString();
out3.close();
in.close();
socket3.close();

The writing works, I have done some debugging and it's the reading, specifically in.read(), that is the last thing done.
I am probably missing something on the Java side, because a C test client reads the output nicely.
Hopefully someone has some ideas how to get this working, I'm open to any solutions.

A: Your C++ code is pretty horrible. Consider what would happen in case read(2) returns less then 6. And just in general:
n = read(newsockfd,buffer,255);

if (n < 0)
    cout << "Error reading from socket" << endl;

// continuing processing after an error - BAD

// not paying attention to n - BAD
if (strcmp(buffer, "power\n") == 0) {
     // Do stuff
     strcpy(wbuffer, "off\n");
}

// potentially writing zero bytes here - BAD
n = write(newsockfd,wbuffer,strlen(wbuffer));

if (n < 0)
     cout << "ERROR writing to socket" << endl;

} // WHERE DID THIS PAREN COME FROM?

So fix those problems. Check with tcpdump(1) or wireshark what you get on the wire. Print out your input on both sides. You'll probably see that you assumptions are off somewhere.

A: Turns out that the problem wasn't actually in the reading part but in the writing. I had forgotten to flush the output so it hadn't actually started reading or was there anything to read for that matter. After adding the flush the reading worked just fine, I could even use readline() to make the code simpler.
The other cases where I only wrote to the socket worked because flush is called when closing the stream, this was throwing me off.
The C-code is nasty and I need to clean it up and actually handle the exceptions.
Thanks for everyone for helping me anyway, without the answers it would have taken a lot longer to find my mistake.

A: Maybe the problem is you're reading an Integer:
int ch = in.read()

Have you tried changing it for:
char ch = in.read()

Or having the integer cast to a char before comparing:
if((char) ch == '\n' || ch < 0)

I can't think of anything else right now...


text:
Q: Jenkins Parallel Pipeline Race Condition Blocking all Builds Any clues on why parallel pipeline would cause a race condition?
This used to work where the job would schedule tasks on all nodes and they'd execute once busy nodes freed up.
After upgrading, If jenkins maintenance job cannot execute on all nodes at first execution it creates race condition blocking jenkins from executing anything even though nodes are free to do so.
@NonCPS
List <String> getOnlineNodeNames() {
  List <String> nodeNames = []
  def allNodes = Jenkins.getInstance().getNodes()
  for (int i =0; i < allNodes.size(); i++) {
   Slave node = allNodes[i]

   if (node.getComputer().isOnline()) {
    nodeNames.add(node.name.toString())
   }
  }
  return nodeNames
}

stage name: "Prepare", concurrency: 1
List<String> nodeList = getOnlineNodeNames()

branches = [:]
stage name: "Build", concurrency: 1
for (int i =0; i < nodeList.size(); i++) {
  String nodeName = nodeList[i]
  if(nodeName.contains("win")) {
    branches[nodeName] = { node(nodeName) {
    bat '''echo On windows Node'''
   }
  }
  } else {
    branches[nodeName] = { node(nodeName) {
         sh '''echo on linux node'''
       }
    }
  }
}
parallel branches


text:
Q: C++ pointer notation So I am learning C++ right now, and I just started to get into Pointers, and I thought I would understand the semantics pretty well till iI saw this in one of the recommended solutions to an exercise int the Book I am learning with:
const char* sa = * ( static_cast < const char* const* > (a));

I understand everything aside the const* in the Type Parameter. Why is it there, what does it do?
EDIT: corrected unclear formulation

A: * in a type means that the type is a pointer to the type on the left side of the asterisk.
const in a type means that the type to the left of const is constant. For an object, const means that the value may not be modified. For a reference, const means that the object may not be modified through the reference.
char is a type that represents an integer encoded narrow character object.
const char is a const char.
const char* is a pointer to a const char.
const char* const is a const pointer to a const char.
const char* const* is a pointer to a const char* const.

Note that the pointer is indirected:
* ( static_cast < const char* const* > (a));
^ indirection operator

When a pointer is indirected, the result is a reference (lvalue) to the pointed object. If a const char* were indirected, the resulting lvalue would have the type const char. Clearly such lvalue couldn't be used to initialize the object const char* sa.
When a const char* const* is indirected, the result will be a reference (lvalue) to an object of type const char* const. Such value can be used to initialize const char* sa.

A simpler example without casts:
const char c;               // c cannot be modified
const char* const a = &c;   // a points to charcter object c
                            // a cannot be modified
const char* sa = *a;        // sa points to a as well
sa = nullptr;               // sa can be modified; it no longer points to a


text:
Q: proof verification: if $x^n \in \mathfrak{p}$ then $x \in \mathfrak{p}$ where $\mathfrak{p}$ is a prime ideal I wanted to ask if you could verify my proof for the statement given in the title. Here is my work:

Suppose $x^n \in \mathfrak{p}.$ Since $x^n=x^{n-1}x,$ by the definition of a prime ideal, either $x^{n-1}$ or $x$ is in $\mathfrak{p}.$ If $x \in \mathfrak{p}$ then we are done. Suppose not. Then $x^{n-1}=x^{n-2}x \in \mathfrak{p}.$ If $x \in \mathfrak{p}$ then again we are done. If not, then $x^{n-2}=x^{n-3}x \in \mathfrak{p}.$ Continuing this way we can conclude inductively that $x \in \mathfrak{p}.$

Thank you.


text:
Q: Round a number without using if statement This is a matter of efficiency; I'm doing a lot of rounding in a tight loop and want to avoid conditional branching. I'm rounding to whole numbers.
The following numbers on the left should round to the numbers on the right:
1.2 -> 1.0, 1.5 -> 2.0, -1.2 -> -1.0, -1.5 -> -2.0
I have made a simple function which can round positive numbers given my above constraints.
  public static float RoundFast(float num)
  {
    return (int)(num + 0.5f);
  }

However, this will not produce desired results if num is negative. I was thinking about multiplying the 0.5f with the sign of num, however Math.Sign uses conditional branching from what I understand. I cannot bitshift a float in C# and am unaware of any way other to obtain the sign from the float without using branching.
How can I make this support rounding negative numbers as well?

A: There is no way to achieve this with at least one if to determine whether the number is positive or negative.
If you want your own function, you can use this:
return num >= 0 ? (int)(num + 0.5f) : (int)(num - 0.5f);

...another possibility would be:
var a = Math.Abs(num);
var b = a / num; // "b" will be -1 for negative numbers and 1 for positive...
return (int)((a + 0.5f) * b);

...but still Math.Abs uses if statements internally. Also this adds an extra division and multiplication, and the first example uses only one if statement, which I believe it has a better performance.
Or you can use the built-in Math.Round() method, specifying a MidpointRounding:
Math.Round(1.2, MidpointRounding.AwayFromZero); // 1
Math.Round(1.5, MidpointRounding.AwayFromZero); // 2
Math.Round(-1.2, MidpointRounding.AwayFromZero); // -1
Math.Round(-1.5, MidpointRounding.AwayFromZero); // -2

Tests with custom method
I ran a test and here is the C# fiddle, and below it's the method:
public static void Main()
{
    for (var i = 0; i < int.MaxValue; i++) {
        Console.WriteLine(Round(1.2));
        Console.WriteLine(Round(1.5));
        Console.WriteLine(Round(-1.2));
        Console.WriteLine(Round(-1.5));
    }
}

public static int Round(double num)
{
    return num >= 0 ? (int)(num + 0.5f) : (int)(num - 0.5f);
}

Results:
Compile:    0.301s
Execute:    0.012s~0.047s
Memory: 406.73kb~1.68Mb
CPU:    0.016s~0.078s

Tests with Math.Round
I also tested with Math.Round and here is the Fiddle, and the method:
public static void Main()
{
    for (var i = 0; i < int.MaxValue; i++) {
        Console.WriteLine(Math.Round(1.2, MidpointRounding.AwayFromZero));
        Console.WriteLine(Math.Round(1.5, MidpointRounding.AwayFromZero));
        Console.WriteLine(Math.Round(-1.2, MidpointRounding.AwayFromZero));
        Console.WriteLine(Math.Round(-1.5, MidpointRounding.AwayFromZero));
    }
}

Results:
Compile:    0.216s
Execute:    0.016s~0.031s
Memory: 494.41kb~1.68Mb
CPU:    0.062s

Conclusion
Both methods are using 4 use cases (two positives, two negatives), and executing the four 2.147.483.647 times, which is the int.MaxValue.
The difference between both methods being executed almost ten billion times in a row isn't that much, the custom method is a bit faster than Math.Round. I'd go for Math.Round anyway, but you can make your choice.

A: I've run a bunch of the answers through BenchmarkDotNet tests. The full code of the tests is in this in this gist.
The test generates 100.000 pseudo-random floats between -2.5 and 2.5 and converts them to int in various ways.
The results are all within the same order of magnitude so I'd say for pretty much all common cases sticking to the platform standard Math.Round is perfectly ok.
When looking for the best performance, @Yves Daoust's code is the winner:
        Method |     Mean |     Error |    StdDev |
 ------------- |---------:|----------:|----------:|
         Round | 5.539 ms | 0.0545 ms | 0.0483 ms | Math.Round
    AddAndCast | 1.678 ms | 0.0356 ms | 0.1045 ms | OPs original code
   AddAndCast2 | 2.422 ms | 0.0478 ms | 0.0701 ms | Yves Daoust's code
     RoundFast | 4.494 ms | 0.0310 ms | 0.0274 ms |
  ConvertToInt | 3.890 ms | 0.0279 ms | 0.0233 ms | Convert.ToInt32

A note on the code; yes, I used Linq to loop over the data but since I used the same linq statement in all samples I think it's safe to assume that it doesn't impact the result.
I've executed this on my laptop in a .Net 4.6.1 console application built in Release configuration.
Update
I've added @harolds native code as requested in the comments end replaced the Linq code with a for-loop.
        Method |        Mean |      Error |     StdDev |
 ------------- |------------:|-----------:|-----------:|
         Round | 4,085.99 us | 78.7908 us | 77.3831 us |
    AddAndCast |   151.86 us |  2.9784 us |  2.9252 us |
   AddAndCast2 |   774.20 us | 12.8013 us | 11.9743 us |
     RoundFast | 3,043.38 us | 52.9597 us | 49.5386 us |
  ConvertToInt | 2,567.69 us | 44.3540 us | 41.4887 us |
        Native |    26.20 us |  0.4291 us |  0.4014 us |

Looks like Linq had a much bigger impact (around 1.5 ms) than I expected. I suspect the compiler can optimize the for loop much better but I'd love to hear from a more knowledgeable person about this.
The code for this test run is in another gist.

A: It is not impossible that the statement below be implemented with conditional assignments, hence be branchless. But you need to check the generated assembly:
return num >= 0 ? (int)(num + 0.5f) : (int)(num - 0.5f);

At your own risk, you can also hack into the IEEE float representation and replace all bits but the sign by the FP representation of 0.5f.

*

*Emulate a union type:
[StructLayout(LayoutKind.Explicit)]
struct Union { [FieldOffset(0)] public float x; [FieldOffset(0)] public int i; };

*Tweak the bits
Union U;
U.i = 0;

U.x= x;
U.i = 1056964608 | (-2147483648 & U.i); // Transfer the sign bit to 0.5f
int i = (int)(x + U.x);

Note that the assignment U.i= 0 is added only to please the compiler (believing in an unassigned field). When benchmarking, it should be done once for all.

A: If you allow native imports, you can write this in a separate C++ project:
extern "C" {
    __declspec(dllexport) void roundAll(int len, float* data)
    {
        int i;
        for (i = 0; i < len - 3; i += 4)
        {
            __m128 d = _mm_loadu_ps(data + i);
            d = _mm_round_ps(d, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
            _mm_storeu_ps(data + i, d);
        }
        for (; i < len; i++)
        {
            __m128 d = _mm_load_ss(data + i);
            d = _mm_round_ss(d, d, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
            _mm_store_ss(data + i, d);
        }
    }
}

Import it like this:
[DllImport("nativeFunctions.dll")] // or however you call your dll
static extern void roundAll(int len, float[] data);

In my tests it was about 14 times as fast as doing it in C# using the simple
data[i] = (float)Math.Round(data[i]) in a for loop, but your results will depend on the size of the array, which .NET version your use, and whether it's making 32bit code or 64bit code.

A: This should be without any conditional branches:
public static float RoundFast(float num)
{
    return (int) (num + 0.5f * (-1 + 2 *(1 + num - (num + 1) % num) / num));
}

Credits for the sign detection part go to: Get the sign of a number in C# without conditional statement
.NET Fiddle Demo

A: public static float RoundFast(float num)
{
    return Convert.ToInt32( num );
}


text:
Q: How can I unit test when code throws an ImportError? I have a Python module that tries to import a module, and if it fails, adds sets up a lightweight class to replicate some of the functionality as a fallback.
How can I write a unit test that covers both cases - when the module is present, and when the module is not present?
try:
    from foo import bar
except ImportError:
    class bar(object):
        def doAThing(self):
            return "blah"

For example, if bar is present, the unit tests will report that only the 2nd line is covered, and the rest of the module isn't. Python's coverage will report missing tests on the line with "except" to the end.

A: Modules are loaded from the sys.path array. If you clear that array then any non-core import will fail. The following commands were run in ipython in a virtual env with access to django
import sys

sys.path = []

import django
... ImportError ...

import os
... No ImportError ...

Your other alternative is to use two virtual environments. One which has the module and one which does not. That would make it slightly more difficult to run the tests though.
If this doesn't work then you can add a path to the start of the sys.path that has a module that will produce an ImportError when loaded. This works because the first match found when searching the sys.path is loaded, so this can replace the real module. The following is sufficient:
test.py
import sys
sys.path.insert(0, '.')

import foo

foo/__init__.py
raise ImportError()


text:
Q: Pass method and args to a function in Java So I do simple operation of finding an entry in my repository. If the entry is not present, the throw an exception.
@NotNull
public static User getUserFromUuid(UUID userUuid) {
    Optional<User> userOptional = userRepository.findByUserIdentifier(userUuid);
    if (!userOptional.isPresent()) {
        if (logger.isInfoEnabled()) logger.info(String.format("Unable to find user with uuid %s", userUuid.toString()));
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User Not Found");
    }
    return userOptional.get();
}
@NotNull
public static Group getGroupFromId(Long groupId) {
    Optional<Group> groupOptional = groupRepository.findById(groupId);
    if (!groupOptional.isPresent()) {
        if (logger.isInfoEnabled()) logger.info(String.format("Group with id %s does not exist", groupId));
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Group Not Found");
    }
    return groupOptional.get();
}

I realize I would end up doing this many times for all my find methods. And most of them will be doing a very similar task.
One way is to extend the CrudRepository with my version, but I want to implement this pattern for al by finds.
Another way would be to pass the class, method, parameters, and the error message to search with. Lambda method seems to be the way, but I was unable to understand how I would be able to apply that to my problem.
This comes close to solving the problem, but the return type is changing. I would be passing a variable number of arguments as well.
Is there any approach I can take to do this?
EDIT:
I would also like to handle this case
Optional<GroupUser> groupUser = groupUserRepository.findByUserAndGroup(user, group

Where I could end up having more than one find parameters.
Something similar in python would be
def perform( fun, *args ):
    fun( *args )

def action1( args ):
    something

def action2( args ):
    something

perform( action1 )
perform( action2, p )
perform( action3, p, r )

A: Are you looking for something like that?
public static <T, ID>  T process(Class<T> cls, CrudRepository<T,ID> r, ID id, String errTemplate){
    Optional<T> groupOptional = r.findById(id);
    if (groupOptional.isEmpty()) {
        if (logger.isInfoEnabled()) logger.info(String.format(errTemplate, id));
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, cls.getName() + " Not Found");
    }
    return groupOptional.get();
}

A: Since all your values might be represented by a String you could do the following:
public static Object getAccountDetails(String primaryKey, Class<?> targetClass) {
        Optional<?> result;

        switch(targetClass.getSimpleName())
        {
        case "Group":
             result = Test.dummyFind(primaryKey);
             break;
        case "User":
            result =  Test.dummyFind(primaryKey);
            break;
        default:
            throw new IllegalArgumentException("The provided class: "+targetClass.getCanonicalName()+" was not a valid class to be resolved by this method.");
        }

        if(result.isPresent())
        {
            logger.info(String.format("Group with id %s does not exist", groupId));
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Group Not Found");
        }

        return result.get();
    }

As far as I know, there is no need to check if the logger has the info level enabled, since this is defined by your logback configuration. So if there's no logging for info, it won't get logged.
The use of the function would be something like that (Classes are random since I wanted to  have my syntax highlighting):
UserDataHandler data = (UserDataHandler) getAccountDetails("1234", UserDataHandler.class);

This is regardless of any functionality of Spring since I don't work with it.
The <?> is a wildcard operator. Since your result however is the content of an Optional, you have to return an Object which then has to be parsed to the according type.
Two ways: Either you use a registry like that:
public static Object getAccountDetails(Object primaryKey, Class<?> targetClass) {

    Optional<?> result;

    // This map should be acquired from a Singleton where you register these classes once in @PostConstruct.
    Map<String, Method> methodMap = new TreeMap<>();
    try {
        methodMap.put("UserDataHandler", Test.class.getMethod("dummyFind"));
    } catch (NoSuchMethodException | SecurityException e) {}

    if(methodMap.containsKey(targetClass.getName()))
    {
        Method method = methodMap.get(targetClass.getName());
        try {
            result = (Optional<?>) method.invoke(primaryKey);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            // do some more error handling
            return null;
        }
    }
    else throw new IllegalArgumentException("The provided class: "+targetClass.getCanonicalName()+" was not a valid class to be resolved by this method.");

    if(!result.isPresent())
    {
        logger.info(String.format("Group with id %s does not exist", groupId));
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Group Not Found");
    }

    return result.get();
}

or a even smarter method would be just to always name the methods in the same pattern any acquire the target repository by Class.forName(String) :
public static Object getAccountDetails(Object primaryKey, Class<?> targetClass) {

    Optional<?> result;

    Class<?> myRepository = Class.forName(targetClass.getSimpleName()+"Repository");

    String methodName = "findBy"+targetClass.getName();

    try
    {
        Method findMethod = targetClass.getMethod(methodName);
        result = (Optional<?>) findMethod.invoke(primaryKey);
    }
    catch (NoSuchMethodException e){throw new IllegalArgumentException("The method "+methodName+" couldn't be found in the repository");}
    catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {return null;}

    if(!result.isPresent())
    {
        logger.info(String.format("Group with id %s does not exist", groupId));
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Group Not Found");
    }

    return result.get();
}

For both methods, your find function has to take an Object as argument which has to be casted in order to use it:
public static Optional<Long> dummyFind(Object primaryKey)
{
    long typedPrimaryKey = (long) primaryKey;
    return Optional.of(typedPrimaryKey);
}

But as I thought about this twice, everything you want already exists: EntityManager.find(Class<T> entityClass,Object primaryKey)

A: You can create generic method that accepts Optional of any type and string for log message. It will returns the object if present, or else it will exception
public <T> T returnIfPresent(Optional<T> optional, String id){

    if (!optional.isPresent()) {
        if (logger.isInfoEnabled()) logger.info(String.format("Group with id %s does not exist", id));
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Group Not Found");
    }
    return optional.get();
}

And you can call this method from every method
@NotNull
public static User getUserFromUuid(UUID userUuid) {

    Optional<User> userOptional = userRepository.findByUserIdentifier(userUuid);
    return returnIfPresent(userOptional, userUuid.toString());
 }

 @NotNull
 public static Group getGroupFromId(Long groupId) {
     Optional<Group> groupOptional = groupRepository.findById(groupId);

     return returnIfPresent(groupOptional, groupId.toString());
 }

The another suggestion i would recommend is, having message as second parameter so you can build the message in original method and pass it through
public <T> T returnIfPresent(Optional<T> optional, String message){

    if (!optional.isPresent()) {
        if (logger.isInfoEnabled()) logger.info(message);
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, message);
    }
    return optional.get();
}


text:
Q: Move left if there is a zero I am trying to create a program that will take an array of integers, say {2,0,32,0,0,8} that can be of any length, and make it so all of the nonzero numbers are to the left at the lower indexes, and all the zeros are moved to the end.
For example, {2,0,32,0,0,8} becomes {2,32,8,0,0,0}.
This array can be of any length and contain any nonnegative integers.
This is what I have so far:
public static int[] moveLeft(final int[] a) {
   for (int i = 0; i < a.length; i++) {
       if (a[i] != 0) {
           for (int j = 0; j < a.length; j++) {
               if (a[j] == 0) {
                   a[j] = a[i];
                   a[i] = 0;
               }
           }
       }
   }
   return a;

}
However, when I do this, it doesn't work for the first and second characters. If I have {1,2,0,1} it will return {2,1,1,0} when it should return {1,2,1,0}. Any help?

A: Your inner loop should stop before index i. Change this
for (int j = 0; j < a.length; j++) {

to
for (int j = 0; j < i; j++) {

And then your code works for me.


text:
Q: How to Foreign Key reference two tables where those tables themselves have a PK FK relationship? I wasn't sure how to ask this question and it's likely a simple answer.
I have two tables like this.
Office
------
PK OficeId
   OfficeName

Location
--------
PK LocationId
FK OfficeId

And one table like this where I store related information.
PurchaseOrder
-------------
PK PurchaseOrderId
FK OfficeId
FK LocationId

So my database will contain a list of Offices that have locations. That's a 1 Office to multiple locations. Office could be company or what ever.
So when I insert a purchase order I wanted to store the OfficeId really for convience, but the OfficeId and LocationId must be a configuration that would satisfy the 1 to many relationship in the other tables. I understand that I could simply just store the LocationId and join inside a query and I might end up doing this, however wanted to ask some experts about this first.
I'm using SQL Server 2012. Is there a constraint to do this without creating a trigger that will simply check if that's a valid configuration?

A: As you acknowledge yourself and as pointed out by the commentors, the OfficeID in the PurchaseOrder table is redundant and de-normalises your data model. Unless you have a burning need to keep it there, I would remove it and just do the appropriate joins when you need to get the office associated with the PurchaseOrder. Foreign keys and indexing will take care of this efficiently.
If you really want to keep the column though and ensure referential integrity, perhaps this is the answer you're looking for: Multiple-column foreign key in MySQL?

A: Over the years, I've found that when any modeling decision is made "for convenience", it ends up being a mistake.
In your model, PurchaseOrder relates to Location which relates to Office. Shortening the relation of PurchaseOrder directly to Office may work for a while. Then, years later, a minor restructuring of the company ends up reassigning the Texas location from the MidWest office in Illinois to the Western office in New Mexico.
So you (or your predecessor) updates the Location table. But now all kinds of reports and queries are returning wrong information. Maybe it turns out to be easy enough to find and fix the problem, but why open yourself up to such situations in the first place?
If you want convenience, use a method that doesn't leave you vulnerable to future anomalies due to changes in the data. In this instance, create a view which shows PurchaseOrders with Location and Office using the proper references. Now when the office changes, the view will show the new office and every report and query based on the view works as expected.
Views are great for just this kind of use. Just don't be manipulating the underlying model for trivial purposes. Your driving goal in modeling the database is Data Integrity. Sorry, but Ease Of Use is way down at the very bottom of the priority list.


text:
Q: Observations with Round-ing in Android Studio - java. And some practical explanations expected In Android Studio I had problems with calculating invoice totals because of the way java rounds. I know there are a lot of explanations, but many recommend methods that don't return reliable results.
For example:
1. Math.round((double)4.715 * (double)100 ) / (double)100 = 4.72  (expected 4.72)
2. Math.round((double)4.725 * (double)100 ) / (double)100 = 4.72  (but expected 4.73)
You can't put this code in an app for a client who calculates invoices. Because , in my case for example, the same invoice is calculated in another system and the result is different, meaning 4.72 respectively 4.73
I know that a double can't be represented exactly and the decimals are different than what we see. But we need a method that returns results as we expect.
Another example would be:
 1. java.math.BigDecimal.valueOf(4.715).setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue() = 4.72
 2. new java.math.BigDecimal(4.715).setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue() = 4.71
 3. new java.math.BigDecimal( String.valueOf(4.715) ).setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue() = 4.72
I think all these aspects could be well explained in Java documentation, but they should indicate a certain method for calculating rounds, a reliable method which returns results as we expected. I only wanted to round to 2 decimales.
In conclusion, which I hope will help some of the beginners, I think that the following method would return stable and good results:
java.math.BigDecimal.valueOf(4.715).setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue() = 4.72

Or, at least, this is my observation after 3+ years of intensive usage of an app (500+ users every working day).
All practical explanations for these above are very welcome, so we can better understand how to avoid unexpected results.

A: For the BigDecimal examples the javadoc explains the difference.
BigDecimal(double value)  ... is the exact decimal representation of the double's binary floating-point value.
Which we can check, by just printing the value.
System.out.println(new BigDecimal(4.715));
#4.714999999999999857891452847979962825775146484375

Which is barely less than 4.715, but enough such that it gets rounded down.
BigDecimal.valueOf(double value) uses the string representation of the double value from Double.toString(double value) which has quite a few rules.
System.out.println(Double.toString(4.715));
#4.715

The safest best is to just use BigDecimal for your calculations. Especially when dealing with arithmetic operations. It isn't clear when the value will switch to needing more decimal places. For example:
double d = 4.11547;
BigDecimal bd = BigDecimal.valueOf(d);
I this case, the string representation of d is 4.11547, so BigDecimal.valueOf returns the value that is written.
BigDecimal s1 = BigDecimal.valueOf(d-3);
BigDecimal s2 = bd.subtract(new BigDecimal(3));

It might be surprising to find s1 and s2 are different since '3' doesn't get rounded.
System.out.println(s1 + ", " + s2);
#1.1154700000000002, 1.11547

So it is best to use the BigDecimal methods for arithmetic too.

A: It's in the nature of binary floating point data types, like float and double in Java. double actually states this in his name. It has double precision compared to float - but it is not an exact representation of a decimal number.
Just adding some simplified math detail to the existing answer. This might help understand the seemingly strange behavior of Java floating point numbers.
The root cause of the problem is binary vs. decimal representation of numbers. You use decimal representation when you use a floating point literal in your code, e.g. double d = 1.5; or a String value, e.g. String s = "1.5";.
But the JVM uses a binary representation of the number. The mapping for integer numbers is easy (d for decimal, b for binary): 1 = 1b, 2d = 10b, 3d = 11b .... There is no issue with integer numbers. int and long work just the way you would expect. Except for the overflow...
But for floating point numbers things are different: 0.5d = 0.1b, 0.25d = 0.01b, 0.125d = 0.001b.... You are only able to add values for the series 1/2, 1/4, 1/8, 1/16... Now imagine, you want to show 0.1d in binary representation.
You start with 0.0001b = 0.0625d, which is the first binary value that is still less than 0.1d. 0.0375d remaining. You continue, and the next close value is 0.03125d, and so on. You'll acutally never get to exactly 0.1d. All you get is an approximation. You'll get closer and closer.
Consider the following piece of code. It does the approximation with the help of BigDecimal values:
public void approximate0dot1() {
    BigDecimal destVal = new BigDecimal("0.1");
    BigDecimal curVal = new BigDecimal("0");
    BigDecimal inc = new BigDecimal("1");
    BigDecimal div = new BigDecimal("2");
    for (int step = 0; step < 20; step++) {
        BigDecimal probeVal = curVal.add(inc);
        int cmp = probeVal.compareTo(destVal);
        if (cmp == 0) {
            break;
        } else if (cmp < 0) {
            curVal = probeVal;
            System.out.format("Added: %s, current value: %s, remaining: %s\n", inc, curVal, destVal.subtract(curVal));
        }
        inc = inc.divide(div);
    }
    System.out.format("Final value: %s\n", curVal);
}

And the output is:
Added: 0.0625, current value: 0.0625, remaining: 0.0375
Added: 0.03125, current value: 0.09375, remaining: 0.00625
Added: 0.00390625, current value: 0.09765625, remaining: 0.00234375
Added: 0.001953125, current value: 0.099609375, remaining: 0.000390625
Added: 0.000244140625, current value: 0.099853515625, remaining: 0.000146484375
Added: 0.0001220703125, current value: 0.0999755859375, remaining: 0.0000244140625
Added: 0.0000152587890625, current value: 0.0999908447265625, remaining: 0.0000091552734375
Added: 0.00000762939453125, current value: 0.09999847412109375, remaining: 0.00000152587890625
Final value: 0.09999847412109375

This is just a basic example to show the underlying issue. Internally, the JVM obviously does some optimization to get the best possible approximation for the available 64-bit precision, e.g.
System.out.println(new BigDecimal(0.1));
// prints 0.1000000000000000055511151231257827021181583404541015625

But this example shows, that there is already a rounding issue with decimal numbers a simple as a constant with the decimal value 0.1.
Some basic tips:

*

*Do not use BigDecimal(double) constructor if you need exact decimal math, use BigDecimal(String) instead. Bad: new BigDecimal(0.1), Good: new BigDecimal("0.1")

*Do not mix BigDecimal and floating point arithmetic, e.g. do not extract double value for further calculations like new BigDecimal("0.1").doubleValue();


text:
Q: Can you please help me change the demo code? I want to map a different function Initialisation code:
refunc = ComplexExpand[Re[(x + I*y)^6 + 6 (x + I*y) + 10]];
imfunc = ComplexExpand[Im[(x + I*y)^6 + 6 (x + I*y) + 10]];
contrans[func_, xtrans_, ytrans_] :=
func /. {x -> xtrans, y -> strains};

Manipulation:
Manipulate[
Grid[{{Text@"contour",
Text@"image"}, {ParametricPlot[{{r*Cos[t], r*Sin[t]}}, {t, 0,
  2 \[Pi]}, PlotStyle -> {Thickness[.003]},
 PlotRange -> {{-2, 2}, {-2, 2}}, AspectRatio -> Automatic,
 ImageSize -> {295}],
ParametricPlot[{{contrans[refunc, r*Cos[t], r*Sin[t]],
   contrans[imfunc, r*Cos[t], r*Sin[t]]}}, {t, 0, 2 \[Pi]},
 PlotStyle -> {Thickness[.003]},
 PlotRange -> {{-70, 90}, {-80, 80}}, AspectRatio -> Automatic,
 ImageSize -> {295}]}}], {{r, 1}, 0.5, 2},
 SaveDefinitions -> True]

This is from a Wolfram Demonstration Project.
I would like to use this code to map f(z)=z^n rather than f(z)=z^6 + 6z +10 as they have used here. Each time I try, the image part of the plot remains blank, I'm not sure what I'm doing wrong!
Thanks a lot.

A: y -> strains should be y-> ytrans


text:
Q: C - scanf value directly from terminal I have a c process that waits for a scanf() input.
I want to save its results to a *.txt file.
To terminal (linux)
./process > out.txt

What's the way to write in terminal the scanf prehand?
Thanks.

A: For the below program you could give the input as.
#include <stdio.h>
int main ()
{
    int i = 0;
    scanf("%d", &i);
    printf("Value of i = %d\n", i);
    return 0;
}

$ gcc -o exe file.c
$ echo 2 | ./exe
Value of i = 2

| or pipeline connects two commands together so that the output from one program becomes the input of the next program.
Update:
If you want to read string, or strings and ints together
int i = 0;
char str[20];
scanf("%d%s", &i, str);
printf("Value of i = %d\nValue of str = %s\n", i, str);

$ echo "45 John" | ./exe   # Ensure your input sequence is correct #
Value of i = 45
Value of str = John

For saving the output to file output.txt
$ echo "45 John" | ./exe  > output.txt
$ cat output.txt
Value of i = 45
Value of str = John

A: You can give the input like following.
One is piping,
 cat filename | ./process > sample.txt

Or else you can give like this
 ./process < filename > sample.txt

Or else
 echo "1" | ./process > sample.txt

In that file, you can only place the integer value and gave like this.

A: One way of doing this is to write your scanf() input into a text file. Your input text file should be properly formatted according to scanf() sequence. Then redirect your input text file to program binary and redirect shell output of program binary to output file.
Use following command to execute your binary.
./main < input.txt  > output.txt

For example:
If your main.c looks as follows
scanf("%s\n", &my_string);
scanf("%d\n", &my_int);

Then you should prepare an input.txt as follows
Hello
31

A: #include <stdio.h>
int main ()
{
    int i = 0;
    printf("Enter value of i:");
    scanf("%d", &i);
    printf("Value of i = %d\n", i);
    return 0;
}

if I want to give dynamic input value of i. how to give it?
in the following code static value is given by echo.
$ gcc -o exe file.c
$ echo 2 | ./exe
Value of i = 2

it should display printf statement in file and from that file I should be able to give input instead of terminal.


text:
Q: Firebreath plugin not loading in Firefox 20.0 My environment: win8 64bit, vs2010,
I follow every step in the tutorial but my own dll plugin just can't be installed, I have also installed WiX toolsets and made a msi file,  but it simply do  not work...
(1) I do all the work with prompt(privileged  ) cmd.
(2)My files are shown in below

(3)firefox about:plugins page do not contain my dll plugin after my msi file installed..
(4) failed ..

So what is going on here?

A: Are you building using the prep2010x64.cmd file (or a different x64.cmd file)? if so, that's likely your issue.  Many people, failing entirely to read the instructions on the firebreath website, mistakenly build using the x64 because they're running a 64 bit operating system.  thing is, the browsers like firefox still are 32 bit, so the plugin needs to be built 32 bit as well.
The next question, if that doesn't help, is whether or not the regsvr32 command succeeds when you run it on the .dll.
Clarification: You figured this out, but for future readers to be very clear:

Do not use prep2010x64.cmd unless you can explain clearly why you need to -- and running a 64 bit OS does not count.  Most people want to use prep2010.cmd (or whichever year).


text:
Q: Magento 2: Unable to unserialize value. Error: Control character error, possibly incorrectly encoded I am getting Bellow Error when i try to search default Magento search
https://temp.com/catalogsearch/result/?q=Hiper
Unable to unserialize value. Error: Control character error, possibly incorrectly encoded

Error Log:

{"0":"Unable to unserialize value. Error: Control character error,
  possibly incorrectly encoded","1":"#1
  Magento\Framework\View\Layout->generateElements() called at
  [generated/code/Magento/Framework/View/Layout/Interceptor.php:89]\n#2
  Magento\Framework\View\Layout\Interceptor->generateElements()
  called at
  [vendor/magento/framework/View/Layout/Builder.php:129]\n#3
  Magento\Framework\View\Layout\Builder->generateLayoutBlocks()
  called at [vendor/magento/framework/View/Page/Builder.php:55]\n#4
  Magento\Framework\View\Page\Builder->generateLayoutBlocks() called
  at [vendor/magento/framework/View/Layout/Builder.php:65]\n#5
  Magento\Framework\View\Layout\Builder->build() called at
  [vendor/magento/framework/View/Page/Config.php:208]\n#6
  Magento\Framework\View\Page\Config->build() called at
  [vendor/magento/framework/View/Page/Config.php:218]\n#7
  Magento\Framework\View\Page\Config->publicBuild() called at
  [vendor/magento/framework/App/View.php:170]\n#8
  Magento\Framework\App\View->loadLayoutUpdates() called at
  [vendor/magento/framework/App/View.php:114]\n#9
  Magento\Framework\App\View->loadLayout() called at
  [vendor/magento/module-catalog-search/Controller/Result/Index.php:119]\n#10
  Magento\CatalogSearch\Controller\Result\Index->getCacheableResult(&Magento\CatalogSearch\Helper\Data#000000006a20343000000000593f6e54#,
  &Magento\Search\Model\Query#000000006a20342000000000593f6e54#)
  called at
  [vendor/magento/module-catalog-search/Controller/Result/Index.php:91]\n#11
  Magento\CatalogSearch\Controller\Result\Index->execute() called at
  [vendor/magento/framework/Interception/Interceptor.php:58]\n#12
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->___callParent('execute',
  array()) called at
  [vendor/magento/framework/Interception/Interceptor.php:138]\n#13
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->Magento\Framework\Interception\{closure}()
  called at
  [app/code/Zemez/AjaxCatalog/Plugin/CatalogSearch/Result.php:34]\n#14
  Zemez\AjaxCatalog\Plugin\CatalogSearch\Result->aroundExecute(&Magento\CatalogSearch\Controller\Result\Index\Interceptor#000000006a20351000000000593f6e54#,
  &Closure#000000006a20343d00000000593f6e54#) called at
  [vendor/magento/framework/Interception/Interceptor.php:135]\n#15
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->Magento\Framework\Interception\{closure}()
  called at
  [vendor/magento/framework/Interception/Interceptor.php:153]\n#16
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->___callPlugins('execute',
  array(), NULL) called at
  [generated/code/Magento/CatalogSearch/Controller/Result/Index/Interceptor.php:26]\n#17
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->execute()
  called at
  [vendor/magento/framework/App/Action/Action.php:107]\n#18
  Magento\Framework\App\Action\Action->dispatch(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:58]\n#19
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->___callParent('dispatch',
  array(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#))
  called at
  [vendor/magento/framework/Interception/Interceptor.php:138]\n#20
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [app/code/Bss/Paymentshipping/Plugin/App/Action/Context.php:81]\n#21
  Bss\Paymentshipping\Plugin\App\Action\Context->aroundDispatch(&Magento\CatalogSearch\Controller\Result\Index\Interceptor#000000006a20351000000000593f6e54#,
  &Closure#000000006a20351300000000593f6e54#,
  &Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:135]\n#22
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:153]\n#23
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->___callPlugins('dispatch',
  array(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#),
  NULL) called at
  [generated/code/Magento/CatalogSearch/Controller/Result/Index/Interceptor.php:39]\n#24
  Magento\CatalogSearch\Controller\Result\Index\Interceptor->dispatch(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/App/FrontController.php:55]\n#25
  Magento\Framework\App\FrontController->dispatch(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:58]\n#26
  Magento\Framework\App\FrontController\Interceptor->___callParent('dispatch',
  array(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#))
  called at
  [vendor/magento/framework/Interception/Interceptor.php:138]\n#27
  Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/module-store/App/FrontController/Plugin/RequestPreprocessor.php:94]\n#28 Magento\Store\App\FrontController\Plugin\RequestPreprocessor->aroundDispatch(&Magento\Framework\App\FrontController\Interceptor#000000006a2036ae00000000593f6e54#,
  &Closure#000000006a2036a600000000593f6e54#,
  &Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:135]\n#29
  Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/module-page-cache/Model/App/FrontController/BuiltinPlugin.php:73]\n#30
  Magento\PageCache\Model\App\FrontController\BuiltinPlugin->aroundDispatch(&Magento\Framework\App\FrontController\Interceptor#000000006a2036ae00000000593f6e54#,
  &Closure#000000006a2036a600000000593f6e54#,
  &Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [app/code/Zemez/SiteMaintenance/Model/PageCache/App/FrontController/BuiltinPlugin.php:30]\n#31
  Zemez\SiteMaintenance\Model\PageCache\App\FrontController\BuiltinPlugin->aroundDispatch(&Magento\Framework\App\FrontController\Interceptor#000000006a2036ae00000000593f6e54#,
  &Closure#000000006a2036a600000000593f6e54#,
  &Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:135]\n#32
  Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at
  [vendor/magento/framework/Interception/Interceptor.php:153]\n#33
  Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch',
  array(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#),
  NULL) called at
  [generated/code/Magento/Framework/App/FrontController/Interceptor.php:26]\n#34
  Magento\Framework\App\FrontController\Interceptor->dispatch(&Magento\Framework\App\Request\Http#000000006a20377800000000593f6e54#)
  called at [vendor/magento/framework/App/Http.php:136]\n#35
  Magento\Framework\App\Http->launch() called at
  [generated/code/Magento/Framework/App/Http/Interceptor.php:24]\n#36
  Magento\Framework\App\Http\Interceptor->launch() called at
  [vendor/magento/framework/App/Bootstrap.php:257]\n#37
  Magento\Framework\App\Bootstrap->run(&Magento\Framework\App\Http\Interceptor#000000006a20373600000000593f6e54#)
  called at
  [index.php:41]\n</pre>","url":"/catalogsearch/result/?q=hyperline","script_name":"/index.php"}

Magento version 2.2.8
any one have idea how to fixed it ?

A: I solve this issue by flushing my Redis Cache from by running following commands
redis-cli
flushall

I hope this works.
EDIT
try this
https://www.scommerce-mage.com/blog/solved-unable-to-unserialize-value-magento-2.html

A: Go to this file location and paste below code and best way try to override this file : /vendor/magento/framework/Serialize/Serializer/Json.php
public function utf8ize( $mixed ) {
    if (is_array($mixed)) foreach ($mixed as $key => $value) $mixed[$key] = $this->utf8ize($value);
    elseif (is_string($mixed)) return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
    return $mixed;
}

public function serialize($data){
    $result = json_encode( $this->utf8ize( $data ) );
    if (false === $result) {
        throw new \InvalidArgumentException("Unable to serialize value. Error: " . json_last_error_msg());
    }
    return $result;
}

How to override this file
The preference for the SerializerInterface was added since 2.2.x version of the Magento, and declared in the app/etc/di.xml:
<preference for="Magento\Framework\Serialize\SerializerInterface" type="Magento\Framework\Serialize\Serializer\Json" />

Override Hint

Then create the class [Vendor][Module]\Serialize\Serializer\Json that extends Magento\Framework\Serialize\Serializer\Json and make your changes in there.

A: Refer this article to solve out an issue
This error means that you don't have enough space in the MySql column "params", of the table "#__extensions", to save all the required parameters that the Cookies Policy Notification Bar needs, and the json data breaks during saving the data.
change the type of the column "params" from "TEXT" to "LONGTEXT"


text:
Q: Mysql query that inserts in multiple rows depending on the number of times defined i want to run the query below depending on the number of items i key in, for example, i want to add 5 toys in the table, so the query will run 5 times.
My query looks like this:
$q = 'INSERT INTO StockDetails (stockNumber, quantity, items) VALUES (".$snumber.", "1", "toys")';

and i want to end up with a table like this:
ID      stockNumber       quantity      items
-----------------------------------------------
1        ST001               1           toys
2        ST001               1           toys
3        ST001               1           toys
4        ST001               1           toys
5        ST001               1           toys

so if i change the number of toys to ten, i will get a table with 10 rows.
please help.

A: If you want an insert query to be executed for specified number of times then it's better to wrap it inside a function and call that function with number of rows as one of the parameters, e.g.:
DELIMITER $$
DROP FUNCTION IF EXISTS `test`.`myfunction` $$
CREATE FUNCTION `test`.`myfunction` (count int, i_stockNumber varchar(20), i_quantity int, i_items int) RETURNS INT
DECLARE x INT;
SET x = 0;
BEGIN
    WHILE x <= count DO
        insert into StockDetails (stockNumber, quantity, items) values (i_stockNumber, i_quantity, i_items);
        SET x = x + 1;
    END WHILE;
  RETURN LAST_INSERT_ID();
END $$


text:
Q: find rows that has values only in certain columns I have a data frame like this:
>>> o1.columns

Index([1, 2, 3, 4, 5, 6, 'm1', 'm2', 7, 'm3', 8, 'm4', 9], dtype='object')
I want to find the rows that has data only and only in m1,m2,m3 and m4 but the rest of the columns is nan or empty. Is it possible? I have tried more or less like the following:
>>> o11=o1[(1==@nan) && (2==@nan) && (3==@nan) && (4==@nan) && (5==@nan) && (6==@nan) && (7==@nan) && (8==@nan) && (9==@nan) && (o1.m1!=@nan) && (o1.m2!=@nan) && (o1.m3!=@nan) && (o1.m4!=@nan)]

But it doesn't work. Tried "pd.query also". Maybe I am missing very simple thing. Thanks for your help.
Best Regards
Zillur

A: Call notna/isna and any/all along the first axis, AND the masks and index.
cols = ['m1', 'm2', 'm3', 'm4']
diff = df.columns.difference(cols).tolist()

df[df[cols].notna().any(1) & df[diff].isna().all(1)]

This is assuming you want ALL the data in m* to not be null, and vice versa.

A: Given a dataframe df as:
df =
         1    2    3    4    5    6    7    8    9   m1   m2    m3   m4
    0  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN
    1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN
    2  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN
    3  NaN    4  NaN  NaN  NaN  NaN  NaN  NaN  NaN  1.5  1.7  1.23  1.6
    4  NaN    1  NaN  NaN    1  NaN  NaN  NaN   12  NaN  NaN   NaN  NaN
    5  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN
    6  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN    1  1.2   1.2  1.5
    7  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN
    8  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN
    9  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN  NaN

We want only row at index = 6 to be returned (as per your requirement):
m1 = df[[1,2,3,4,5,6,7,8,9]].isna().sum(axis = 1) == 9

m2 = df[['m1', 'm2', 'm3', 'm4']].isna().sum(axis = 1) == 0

df[m1 & m2]

Output:
     1    2    3    4    5    6    7    8    9 m1   m2   m3   m4
6  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  1  1.2  1.2  1.5


text:
Q: Best way to handle and deploy XQuery stored procedures? Is there a tool for deploying things into exist? if I've got a bundle of, say, schemas and XQuery stored procedures? Is there a way of, say, bundling those into a zip or tar file and uploading them or deploying them into eXist?
Alternatively what is the best way of storing these things in a version controlled way (in a git repo, say) and deploying them to the eXist server? Ideally, it'd be nice to be able to have a simple script in a scripting language so you can simply call "deploy.py" or whatever and it'd take everything from the repository and load it into the XML database.

A: The EXpath packaging system specifies a format for generating a ZIP file with XQuery procedures (and other content) and deploying it into multiple XQuery databases.
See the specification. You should be able to use the Python zipfile module to generate these if you're inclined to use Python (though personally, I do so from a makefile).
Unfortunately, the process for checking currently installed package versions to upgrade if necessary is not standardized; I have a solution for BaseX, but nothing for eXist immediately at hand. However, eXist's implementation is well-documented, and you should have little trouble working with it.


text:
Q: Индекс находился вне границ массива, с# int[] max = new int[m];
for (int i = 0; i < n; i++)
{
     for (int j = 0; j < m; j++)
     {
         max[m] = max[m] + C[i, j];
     }
 }
 Console.WriteLine($"max = {max[m]}");

Ошибку выдает на строчке: max[m] = max[m] + C[i, j].
В чем ошибка и как исправить?

A: У вас массив имеет размеры m:
int[] max = new int[m];

По умолчанию индексация ведется с нуля, т.е. ваш массив имеет ячейки с индексами 0, 1, 2, ..., m-2, m-1.
Вы же пытаетесь обратиться к ячейке с индексом m — max[m], ее не существует, отсюда ошибка.


text:
Q: input arguments in setRange() in Accumulo I have code like the following:
Scanner s = conn.createScanner("userdata", auths);
s.setRange(new Range(input));
s.fetchColumnFamily(new Text("age"));

My question is, does anyone know that what should be the "input" part in the "new Range(input)"? is the input RowId?

A: The input to Range would be what you are looking for.  Have a look at the docs:
http://accumulo.apache.org/1.6/apidocs/org/apache/accumulo/core/data/Range.html#Range(java.lang.CharSequence)
An example might be:
s.setRange(new Range(new Text("Foo")));


text:
Q: Jasper report - getting duplicate records We are exploring Jasper reports to replace our current reporting engine. Our data source will be REST APIs, and we'll be needing to join multiple tables. I came across the CData JDBC driver for REST, and it seemed apt for the purpose.
I have created a JDBC data adapter using the CData driver, with a JSON file as a source which has data for 2 entities - users and posts.
Then I created a report with this data adapter to display fields in a table. The data is a result of join query on both the entities as below -
SELECT users.name,users.username,users.email,users.website,posts.title FROM users join posts on users._id = posts.userId
Below is the data adapter configurations -
CDataDataAdapter.xml
<jdbcDataAdapter class="net.sf.jasperreports.data.jdbc.JdbcDataAdapterImpl">
   <name>CDataDataAdapter</name>
   <driver>cdata.jdbc.rest.RESTDriver</driver>
   <username />
   <password />
   <savePassword>true</savePassword>
   <url>jdbc:rest:Format="JSON";URI="D:/Documents/ToJasper/SampleJoinJson.json";XPath="/posts;/users";DataModel="Relational";JSONFormat="JSON";SSLServerCert="*";Logfile="D:\Documents\Tasks\ToJasper\cdata-driver.log";Verbosity="4";Location="D:\Documents\Tasks\ToJasper\Schema";FlattenObjects="False";GenerateSchemaFiles="OnStart";RowScanDepth="10";</url>
   <database />
   <serverAddress />
   <classpath>I:\Program Files\CData\lib\cdata.jdbc.rest.jar</classpath>
   <classpath>I:\Program Files\CData\lib\rssbus.jar</classpath>
</jdbcDataAdapter>

The data is fetched the rendered in the report, but the problem is it gets repeated.

The table is repeated in the report 5 times, 4 times with full data, and one time with only column headers. I cannot understand why, any help is greatly appreciated.

A: I got the answer here - https://community.jaspersoft.com/questions/904196/same-detail-shown-multiple-times-page-and-multiple-pagesireports-well-jaspersoft
I added the table component in the Detail band instead of Summary band. Quoting from the answer above -
"Where did you put the table and chart element in the report? They should be placed in SUMMARY section, not detail section.  JR report detail band is called for each row fetched into report. If you have 100 rows, it will display information in the detail band 100 times each with details of that row. Tables and charts gather and tally all your data to display and should be placed in the summary band thus have them displayed only once."


text:
Q: Sencha Touch - What is wrong with this Model? Following this post I was able to get the abc project up and running in eclipse:

In Eclipse I made a model called Temperature:

In the app.js I added a single line for the models:

Which causes this when I refresh the page:

So I figure something is wrong with the model, as when I comment out the line models: ['Temperature'] the page loads correctly.

A: Try making the model definition reference abc instead of app
So
Ext.define('abc.model.Temperature', {
Also make sure the case of abc is all lower case to match the application name.
And make sure your Temperature.js file exists in the abc/app/model/ folder

A: Problem
You given application name as abc, but you defined model as App.model.Temperature
Solution
you should change model definition as abc.model.Temperature or change the application name as App.
Note
Lets say you given application name as AppName.
you should define
mode as - AppName.model.TemperatureModel
store as - AppName.store.TemperatureStore
controller as  - AppName.controller.TemperatureController
view as - AppName.view.TemperatureView
Every model,controller,store and view should follow this.
Where
AppName - name of the application
model/store/controller/view -
location of the class (TemperatureModel is with in model folder and TemperatureStore is within store folder)
TemperatureStore/TemperatureStore/TemperatureController/TemperatureView - name of the class (you can give what ever name you want but name should match file name).
Reference
Ext.app.Application