问:
How to determine branches involved in a merge?
I have a scenario where I need to Identify a merge event and the source and destination branch of this merge.

So, that I can take some actions based on the type of source branch( i.e. feature/bugfix/hotfix etc).

Are there any git commands or scripts for that?

答:
I normally use below command :

git log --graph --full-history --all --pretty=format:"%h%x09%d%x20%s"


来源: stackexchange

问:
Call JavaScript Function from Symfony Component
I have created a new JSON string (by converting a PHP array using json_encode) and stored it in $siteTree ... outputting it to the log shows the following

```<code>[
{
    "attr": {
        "id": "node_1",
        "rel": "folder"
    },
    "data": "New Title",
    "children": [
        {
            "attr": {
                "id": "node_2",
                "rel": "folder"
            },
            "data": "second document",
            "children": []
        }
    ]
}
</code>```

]

So I know the JSON is formed correctly. What I am trying to do is use that variable in a javascript function to create an object using the JSON data ... I am doing the following in the template

```<code><?php
    use_helper('JavascriptBase');
    echo javascript_tag('createTree('.$siteTree.')');
?>
</code>```

The following is shown on the output page

```<code>createTree([{"attr":{"id":"node_1","rel":"folder"},"data":"New Title","children":[{"attr":{"id":"node_2","rel":"folder"},"data":"second document","children":[]}]}])
</code>```

The function is called but the JSON has replaced the " with &quote;.  How can I stop this ?

Thanks for your help !

答:
OK .. So I managed to fix the problem ... this is how I did it ...I forgot about the json_encode and just passed an array up to the template of the component.

Within the template i processed it like this

```<code>echo javascript_tag('createTree('.json_encode($siteTree->getRawValue()).');');
</code>```

This then output the correct JavaScript.

Thanks for everyones assistance ! Got there in the end

ContentLicense: CC BY-SA 2.5

Body:
I have created a new JSON string (by converting a PHP array using json_encode) and stored it in $siteTree ... outputting it to the log shows the following

[
{
    "attr": {
        "id": "node_1",
        "rel": "folder"
    },
    "data": "New Title",
    "children": [
        {
            "attr": {
                "id": "node_2",
                "rel": "folder"
            },
            "data": "second document",
            "children": []
        }
    ]
}

]

So I know the JSON is formed correctly. What I am trying to do is use that variable in a javascript function to create an object using the JSON data ... I am doing the following in the template

<?php
    use_helper('JavascriptBase');
    echo javascript_tag('createTree('.$siteTree.')');
?>

The following is shown on the output page

createTree([{"attr":{"id":"node_1","rel":"folder"},"data":"New Title","children":[{"attr":{"id":"node_2","rel":"folder"},"data":"second document","children":[]}]}])

The function is called but the JSON has replaced the " with &quote;.  How can I stop this ?

Thanks for your help !

Body:
OK .. So I managed to fix the problem ... this is how I did it ...I forgot about the json_encode and just passed an array up to the template of the component.

Within the template i processed it like this

echo javascript_tag('createTree('.json_encode($siteTree->getRawValue()).');');

This then output the correct JavaScript.

Thanks for everyones assistance ! Got there in the end


问:
How to Alter all specific datatype to another datatype in whole table
I have one table table_name with 50 decimal(18, 0) columns and I want to change it's datatype to decimal(18, 6)

I am trying

```<code>ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]
</code>```

But for this, I have to queries 50 times.

How I do it in a single Query

答:
You can do it easily by executing a dynamic sql query.

Query

```<code>declare @sql as varchar(max);

select @sql = stuff((
        select 'alter table [your_table_name]
        alter column [' + [column_name] + '] decimal(18, 6);'
        from information_schema.columns
        where [table_name] = 'your_table_name'
        and [data_type] = 'decimal'
        for xml path('')
    )
    , 1, 0, ''
);

exec(@sql);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one table table_name with 50 decimal(18, 0) columns and I want to change it's datatype to decimal(18, 6)

I am trying

ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]

But for this, I have to queries 50 times.

How I do it in a single Query

Body:
You can do it easily by executing a dynamic sql query.

Query

declare @sql as varchar(max);

select @sql = stuff((
        select 'alter table [your_table_name]
        alter column [' + [column_name] + '] decimal(18, 6);'
        from information_schema.columns
        where [table_name] = 'your_table_name'
        and [data_type] = 'decimal'
        for xml path('')
    )
    , 1, 0, ''
);

exec(@sql);


问:
Vaadin dynamically reflect changed data to all users' screens
I am trying to dynamically reflect the changes of the data to all logged in users' screens.

There are items being added to the database or one of their attributes is being changed by users or by scheduled tasks(cron-jobs).

What I want to do is reflecting those changes to all logged-in users' screens without a need of page refresh. This includes certain parts of all screens. One part is left menu side of all screens, the other one is table contents.

I am able to do that for one logged-in user via re assigning the changed datasource to the table and re building the left-side menu after re-assignment of the datasource. But this is only for the current user. I need to change all user screens which are currently in use at that moment.

I have checked Vaadin PUSH but could not really relate to it.

How can I do that with Vaadin?

Thank you in advance.

答:
Check this out:
https://vaadin.com/docs/v8/framework/articles/BroadcastingMessagesToOtherUsers.html

In short, you can use the Observer Pattern to notify all the UIs about changes in the database. You also need to enable push and modify the UI using the UI.access(Runnable) method.


问:
QuantConv2D relation to GEMMlowp
I've followed the documentation and TF Github code and couldn't find the relation between QuantizedConv2D to GEMMlowp.

Does QuantizedConv2D use, implicitly, in a way the QuantizedMatMul(quantized_matmul_op.cc), under the hood, where the latter calls GemmlowpMultiply explicitly? Otherwise how the QuantizedConv2D using the great benefit of Google GEMM HW platform specific implementation?

答: You can process your input matrices in a convolution layer in order to perform a matrix multiplication with them. Read this great article, especially the chapter "How GEMM works for Convolutions". https://petewarden.com/2015/04/20/why-gemm-is-at-the-heart-of-deep-learning/</p>

Title: QuantConv2D relation to GEMMlowp


问:
Implicit intent to open waze or google and then start navigation
This is the thing I want to achieve: I have the LatLng object. The user clicks the button, it will let user to choose waze or googlemap to navigate
(if the user only have one of them, just go into the app and start navigation)(if the have Waze and googlemap app, show to the user and there also need have the options: Just once and set default. Then the user clicks the button, it will go the that specific navigation app directly and start navigation)
I know how to create an intent for one of them, but don't know to create an implicit intent for showing up two of them. Please help me thanks.</p>

```<code>btn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    LatLng location= new LatLng(34,118); // just for example

    String urlWaze = "https://waze.com/ul?ll="+location.latitude+","+location.longitude;
    Intent intentWaze = new Intent(Intent.ACTION_VIEW, Uri.parse(urlWaze));
    intentWaze.setPackage("com.waze");

    String uriGoogle = "google.navigation:q=" + location.latitude + "," + location.longitude;
    Intent intentGoogleNav = new Intent(Intent.ACTION_VIEW, Uri.parse(uriGoogle));
    intentGoogleNav.setPackage("com.google.android.apps.maps");

  }
}
</code>```

答: You can use App Chooser, but if you start other app from your application, you can show standard or custom Dialog with chooser, and make intentWaze or intentGoogleNav on user response.

Body:
This is the thing I want to achieve: I have the LatLng object. The user clicks the button, it will let user to choose waze or googlemap to navigate
(if the user only have one of them, just go into the app and start navigation)(if the have Waze and googlemap app, show to the user and there also need have the options: Just once and set default. Then the user clicks the button, it will go the that specific navigation app directly and start navigation)
I know how to create an intent for one of them, but don't know to create an implicit intent for showing up two of them. Please help me thanks.

btn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    LatLng location= new LatLng(34,118); // just for example

    String urlWaze = "https://waze.com/ul?ll="+location.latitude+","+location.longitude;
    Intent intentWaze = new Intent(Intent.ACTION_VIEW, Uri.parse(urlWaze));
    intentWaze.setPackage("com.waze");

    String uriGoogle = "google.navigation:q=" + location.latitude + "," + location.longitude;
    Intent intentGoogleNav = new Intent(Intent.ACTION_VIEW, Uri.parse(uriGoogle));
    intentGoogleNav.setPackage("com.google.android.apps.maps");

  }
}


问:
Find if key contains value in a map and return a boolean
I have a map within an object in Groovy. The map has keys made from long strings, I want to see if a key in my map contains a certain value within the string and return a boolean.

For example if my map key is 'X1234_RANDOM_STRING', if my parameter is X1234 I want to look in my map and see if the a key with that value exists and return true of false.

Currently I am using .find however this doesn't return a boolean, I thought I could use .containsKey() but this won't work when my parameter may only contain a portion of the string.

```<code>map.find {
   it.key.toString().contains(code)
}
</code>```

答:
Consider the following (very close to your attempt):

```<code>def map = ['X1234_RANDOM_STRING': 5150]
def code = 'X1234'

def found = map.find { it.toString().contains(code) } as Boolean
assert found

def notFound = map.find { it.toString().contains('foo') } as Boolean
assert ! notFound
</code>```

The cast works because of Groovy Truth.

Body:
I have a map within an object in Groovy. The map has keys made from long strings, I want to see if a key in my map contains a certain value within the string and return a boolean.

For example if my map key is 'X1234_RANDOM_STRING', if my parameter is X1234 I want to look in my map and see if the a key with that value exists and return true of false.

Currently I am using .find however this doesn't return a boolean, I thought I could use .containsKey() but this won't work when my parameter may only contain a portion of the string.

map.find {
   it.key.toString().contains(code)
}

Body:
Consider the following (very close to your attempt):

def map = ['X1234_RANDOM_STRING': 5150]
def code = 'X1234'

def found = map.find { it.toString().contains(code) } as Boolean
assert found

def notFound = map.find { it.toString().contains('foo') } as Boolean
assert ! notFound

The cast works because of Groovy Truth.


问:
How to fix error 403 error php files
I'm running ubuntu 16.04 and installed LAMP this way:

Install Apache

sudo apt-get install apache2

Install MySQL

sudo apt-get install mysql-server

Install PHP

sudo apt-get install php7.0 libapache2-mod-php7.0

Restart Server

sudo /etc/init.d/apache2 restart

Check Apache

Working

Check PHP

php -r 'echo "\n\nYour PHP installation is working fine.\n\n\n";'

Working

Files structure:

/var/www/html/index.html > redirects to index.php
  /var/www/html/pages/index.php < this file is not working and all php files

The owner group is set to:

chown -R www-data:www-data /var/www

The folders permissions are 755. The index.php permssions is 644 This is my apache2.conf file: https://ghostbin.com/paste/wwhog

But when i go to: http://localhost/pages/index.php I get this 403 Forbidden error. It seems like i can't see php files.

答:
Here is some ways how to fix it.

chmod files 644 and folders 755 (you have opposite side)

check owner of folders and files and chown them correctly.

Disable SELinux.

Checking error log file of Apache will give you more information about error.

Title: How to fix error 403 error php files


问:
Custom Inventory Lookup Filter
I'd like to make certain products available/unavailable to certain customers. Similar to Netflix's blocking some movies on some customers depending on geographical locations. I'm assuming I'll need a custom table for the inventory item and list of restricted customers. And then attach this somehow to the lookup filtering. How can I customised the inventory lookup dialog to achieve this ? </p>

答:
You should add PXRestrictor attribute for each selector. For example for SO301000 you should add PXRestrictor on SOLine.InventoryID. You can add it by implementing SOLine_InventoryID_CacheAttached() handler in the extension of SOOrderEntry graph.

If you would like to limit visibility all over the product for specific users,
consider using Restriction Groups, see https://help.acumatica.com/(W(19))/Wiki/ShowWiki.aspx?pageid=ad9a42c1-ff5d-4298-86d9-683039c18512 for details.

Title: Custom Inventory Lookup Filter


问:
CheckBox checked/unchecked state changes on scroll listview BaseAdapter
I have the list view with some pre-checked checked boxes. When I use to uncheck the checked checkbox and scroll it again, it gets checked, and if I check the unchecked the checkbox then scroll it, it changed to the unchecked state.

When I

check the checkbox and then scroll it, it gets unchecked

uncheck the pre checked checkbox and scroll it, it gets checked

Code:

```<code>public class Adapter extends BaseAdapter {

    private Context activity;
    private ArrayList<Data> data;
    private static LayoutInflater inflater = null;
    private View vi;
    TextView roll;
    TextView menu;
    CheckBox checkBox;
    CheckBox cb;
    boolean[] checkBoxState;//maintain a local boolean array to store the checked status of checkboxes positionwise
    public Adapter(Context context, ArrayList<Data> items) {
        this.activity = context;
        this.data = items;
        checkBoxState=new boolean[items.size()];//initializing the local boolean array inside the constructor
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        vi = view;
        final int pos = position;
        final Data items = data.get(pos);
        vi = inflater.inflate(R.layout.list_row, null);
        checkBox = (CheckBox) vi.findViewById(R.id.cb);
        menu = (TextView) vi.findViewById(R.id.nama_menu);
        roll = (TextView) vi.findViewById(R.id.roll);
        menu.setText(items.getMenu());
        roll.setText(items.getRoll());
        if (items.getRoll().equals(items.getRollBlocked())) {
            checkBox.setChecked(true);
            checkBoxState[position] = true;
            items.setCheckbox(true);//maintaining boolean check status according to conditions
            notifyDataSetChanged();
            vi.setEnabled(false);
        }
        else if (items.getRoll().equals(items.getRollLate())) {
            checkBox.setChecked(true);
            checkBoxState[position] = true;//maintaining boolean check status according to conditions
            items.setCheckbox(true);
            notifyDataSetChanged();
            vi.setEnabled(false);
        }
        else if (items.getRoll().equals(items.getRollCheck())) {
            checkBox.setChecked(true);
            checkBoxState[position] = true;
            items.setCheckbox(true);//maintaining boolean check status according to conditions
        } else if (items.getRollBlocked().equals("-")&& items.getRollCheck().equals("-") && items.getRollLate().equals("-")) {
            checkBox.setChecked(false);
            items.setCheckbox(false);
            checkBoxState[position] = false;//maintaining boolean check status according to conditions
        }

        checkBox.setChecked(checkBoxState[position]);//checkbox is finally checked depending upon the local boolean array which u just created according to ur needs
        vi.setTag(checkBox);
        vi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Data items = data.get(pos);
                cb = (CheckBox) v.getTag();
                if(items.getRoll().equals(items.getRollBlocked())){

                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true

                        vi.setEnabled(false);
                        cb.setChecked(true);
                    }
                    else {
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }
                else if(items.getRoll().equals(items.getRollLate())){
                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true

                        vi.setEnabled(false);
                        cb.setChecked(true);
                    }
                    else {
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }
                else if(items.getRoll().equals(items.getRollCheck())){
                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true
                        cb.setChecked(false);
                        items.setCheckbox(false);
                    }
                    else {
                        cb.setChecked(true);
                        items.setCheckbox(true);
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }else if (items.getRollBlocked().equals("-") && items.getRollCheck().equals("-") && items.getRollLate().equals("-")){
                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true
                        cb.setChecked(false);
                        items.setCheckbox(false);
                    }
                    else {
                        cb.setChecked(true);
                        items.setCheckbox(true);
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }else{

                }
            }
        });
        return vi;
    }

    public ArrayList<Data> getAllData(){
        return data;
    }
}
</code>```

Logcat:

```<code>FATAL EXCEPTION: main
Process: , PID: 1366
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
    at com.mark_attendance.list.adapter.Adapter.getView(Adapter.java:78)
    at android.widget.AbsListView.obtainView(AbsListView.java:2360)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
    at android.widget.ListView.onMeasure(ListView.java:1233)
    at android.view.View.measure(View.java:19731)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
    at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
    at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1391)
    at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
    at android.view.Choreographer.doCallbacks(Choreographer.java:683)
    at android.view.Choreographer.doFrame(Choreographer.java:619)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

Data .java

```<code>public class Data {

    private String roll;
    private String menu;
    private boolean check;
    private String roll_check;
    private String roll_blocked;
    private String roll_late;
    private String studentID;

    private int blockedposition;
    private int blockedposition2;

    public Data() {}

    public Data(String roll,String menu, boolean check,String roll_check,int blockedposition,String roll_blocked,int blockedposition2,String roll_late,String studentID) {
        this.roll=roll;
        this.menu = menu;
        this.check = check;
        this.roll_check = roll_check;
        this.blockedposition=blockedposition;
        this.blockedposition2=blockedposition2;
        this.roll_blocked=roll_blocked;
        this.roll_late=roll_late;
        this.studentID=studentID;
    }

    public String getRoll() {
        return roll;
    }

    public void setRoll(String roll) {
        this.roll = roll;
    }

    //-----------------------Studentid---------------------------------------

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    //--------------------------------------

    //------------------------------------------------------------

    public int getBlockedPosition() {
        return blockedposition;
    }

    public void setBlockedPosition(int blockedposition) {
        this.blockedposition = blockedposition;
    }

    //------------------------------------------------------------

    //------------------------------------------------------------

    public int getBlockedPosition2() {
        return blockedposition2;
    }

    public void setBlockedPosition2(int blockedposition2) {
        this.blockedposition2 = blockedposition2;
    }

    //------------------------------------------------------------

    public String getRollCheck() {
        return roll_check;
    }

    public void setRollCheck(String roll_check) {
        this.roll_check = roll_check;
    }

//------------------------------------------------------------

public String getRollBlocked() {
    return roll_blocked;
}

    public void setRollBlocked(String roll_blocked) {
        this.roll_blocked = roll_blocked;
    }

//-----------------------LATE-----------------------------------------------------

public String getRollLate() {
    return roll_late;
}

    public void setRollLate(String roll_late) {
        this.roll_late = roll_late;
    }

    //--------------------------------------------------------------------------

    public String getMenu() {
        return menu;
    }

    public void setMenu(String menu) {
        this.menu = menu;
    }

    public boolean isCheckbox() {
        return check;
    }

    public void setCheckbox(boolean check) {
        this.check = check;
    }
}
</code>```

答:
override this method in adapter class

```<code>@Override
public int getItemViewType(int position) {
    return position;
</code>```

}

Body:
I have the list view with some pre-checked checked boxes. When I use to uncheck the checked checkbox and scroll it again, it gets checked, and if I check the unchecked the checkbox then scroll it, it changed to the unchecked state.

When I

check the checkbox and then scroll it, it gets unchecked

uncheck the pre checked checkbox and scroll it, it gets checked

Code:

public class Adapter extends BaseAdapter {

    private Context activity;
    private ArrayList<Data> data;
    private static LayoutInflater inflater = null;
    private View vi;
    TextView roll;
    TextView menu;
    CheckBox checkBox;
    CheckBox cb;
    boolean[] checkBoxState;//maintain a local boolean array to store the checked status of checkboxes positionwise
    public Adapter(Context context, ArrayList<Data> items) {
        this.activity = context;
        this.data = items;
        checkBoxState=new boolean[items.size()];//initializing the local boolean array inside the constructor
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        vi = view;
        final int pos = position;
        final Data items = data.get(pos);
        vi = inflater.inflate(R.layout.list_row, null);
        checkBox = (CheckBox) vi.findViewById(R.id.cb);
        menu = (TextView) vi.findViewById(R.id.nama_menu);
        roll = (TextView) vi.findViewById(R.id.roll);
        menu.setText(items.getMenu());
        roll.setText(items.getRoll());
        if (items.getRoll().equals(items.getRollBlocked())) {
            checkBox.setChecked(true);
            checkBoxState[position] = true;
            items.setCheckbox(true);//maintaining boolean check status according to conditions
            notifyDataSetChanged();
            vi.setEnabled(false);
        }
        else if (items.getRoll().equals(items.getRollLate())) {
            checkBox.setChecked(true);
            checkBoxState[position] = true;//maintaining boolean check status according to conditions
            items.setCheckbox(true);
            notifyDataSetChanged();
            vi.setEnabled(false);
        }
        else if (items.getRoll().equals(items.getRollCheck())) {
            checkBox.setChecked(true);
            checkBoxState[position] = true;
            items.setCheckbox(true);//maintaining boolean check status according to conditions
        } else if (items.getRollBlocked().equals("-")&& items.getRollCheck().equals("-") && items.getRollLate().equals("-")) {
            checkBox.setChecked(false);
            items.setCheckbox(false);
            checkBoxState[position] = false;//maintaining boolean check status according to conditions
        }

        checkBox.setChecked(checkBoxState[position]);//checkbox is finally checked depending upon the local boolean array which u just created according to ur needs
        vi.setTag(checkBox);
        vi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Data items = data.get(pos);
                cb = (CheckBox) v.getTag();
                if(items.getRoll().equals(items.getRollBlocked())){

                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true

                        vi.setEnabled(false);
                        cb.setChecked(true);
                    }
                    else {
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }
                else if(items.getRoll().equals(items.getRollLate())){
                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true

                        vi.setEnabled(false);
                        cb.setChecked(true);
                    }
                    else {
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }
                else if(items.getRoll().equals(items.getRollCheck())){
                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true
                        cb.setChecked(false);
                        items.setCheckbox(false);
                    }
                    else {
                        cb.setChecked(true);
                        items.setCheckbox(true);
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }else if (items.getRollBlocked().equals("-") && items.getRollCheck().equals("-") && items.getRollLate().equals("-")){
                    if(((CheckBox)v).isChecked()) {
                        checkBoxState[position] = true; //explicitly making it true
                        cb.setChecked(false);
                        items.setCheckbox(false);
                    }
                    else {
                        cb.setChecked(true);
                        items.setCheckbox(true);
                        checkBoxState[position] = false;//explicitly making it false
                    }
                }else{

                }
            }
        });
        return vi;
    }

    public ArrayList<Data> getAllData(){
        return data;
    }
}

Logcat:

FATAL EXCEPTION: main
Process: , PID: 1366
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
    at com.mark_attendance.list.adapter.Adapter.getView(Adapter.java:78)
    at android.widget.AbsListView.obtainView(AbsListView.java:2360)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
    at android.widget.ListView.onMeasure(ListView.java:1233)
    at android.view.View.measure(View.java:19731)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
    at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
    at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1391)
    at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
    at android.view.View.measure(View.java:19731)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
    at android.view.Choreographer.doCallbacks(Choreographer.java:683)
    at android.view.Choreographer.doFrame(Choreographer.java:619)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Data .java

public class Data {

    private String roll;
    private String menu;
    private boolean check;
    private String roll_check;
    private String roll_blocked;
    private String roll_late;
    private String studentID;

    private int blockedposition;
    private int blockedposition2;

    public Data() {}

    public Data(String roll,String menu, boolean check,String roll_check,int blockedposition,String roll_blocked,int blockedposition2,String roll_late,String studentID) {
        this.roll=roll;
        this.menu = menu;
        this.check = check;
        this.roll_check = roll_check;
        this.blockedposition=blockedposition;
        this.blockedposition2=blockedposition2;
        this.roll_blocked=roll_blocked;
        this.roll_late=roll_late;
        this.studentID=studentID;
    }

    public String getRoll() {
        return roll;
    }

    public void setRoll(String roll) {
        this.roll = roll;
    }

    //-----------------------Studentid---------------------------------------

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    //--------------------------------------

    //------------------------------------------------------------

    public int getBlockedPosition() {
        return blockedposition;
    }

    public void setBlockedPosition(int blockedposition) {
        this.blockedposition = blockedposition;
    }

    //------------------------------------------------------------

    //------------------------------------------------------------

    public int getBlockedPosition2() {
        return blockedposition2;
    }

    public void setBlockedPosition2(int blockedposition2) {
        this.blockedposition2 = blockedposition2;
    }

    //------------------------------------------------------------

    public String getRollCheck() {
        return roll_check;
    }

    public void setRollCheck(String roll_check) {
        this.roll_check = roll_check;
    }

//------------------------------------------------------------

public String getRollBlocked() {
    return roll_blocked;
}

    public void setRollBlocked(String roll_blocked) {
        this.roll_blocked = roll_blocked;
    }

//-----------------------LATE-----------------------------------------------------

public String getRollLate() {
    return roll_late;
}

    public void setRollLate(String roll_late) {
        this.roll_late = roll_late;
    }

    //--------------------------------------------------------------------------

    public String getMenu() {
        return menu;
    }

    public void setMenu(String menu) {
        this.menu = menu;
    }

    public boolean isCheckbox() {
        return check;
    }

    public void setCheckbox(boolean check) {
        this.check = check;
    }
}

Body:
override this method in adapter class

@Override
public int getItemViewType(int position) {
    return position;

}


问:
K&R, find longest line, same code but not working?
I've just started to read K&R and on pages 32-33, there is a code that

finds the longest line among the inputs.

I nearly completely copy-pasted the code given in the book, just added some comment lines to make the code more understandable for me. But it isn't working.

Edit: I'm sorry for bad questioning. It seems the program does not act properly when I press Ctrl + Z, in order to terminate it. No matter how many lines I type and how many times I press Ctrl + Z, it just does nothing.

The following is my version of the code:

```<code>/* Find the longest line among the giving inputs and print it */

#include <stdio.h>
#define MAXLINE 1000            /* maximum input line length */

int getLine(char line[], int maxLine);
void copy(char to[], char from[]);

int main(void) {
    int len; /* current line length */
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here*/

    max = 0;

    /* getLine function takes all the input from user, returns it's size and equates it to the variable len
     * Then, len is compared whether it's greater than zero because if there's no input, no need to do any calculation
     * EDGE CASE
     */
    while ((len = getLine(line, MAXLINE)) > 0)
        /* If the length of input is larger than the previous max length, set max as the new length value and copy that input */
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0) /* there was a line, EDGE CASE */
        printf("%s", longest);

    return 0;
}

/* Read a line into s, return length.
 * Since the input length is unknown, there should be a limit */
int getLine(char s[], int lim) {
    int c, i;

    /* The loop's first condition is whether the input length is below the limit. EDGE CASE
     * If it's not, omit the rest because it would cause a BUFFER OVERFLOW. Next, take the input as long as it's not an EOF command.
     * Finally, if the input is end of line, finish the loop, don' take it.
     */
    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    if (c == '\n')
        s[i++] = c;
    s[i++] = '\0'; // always put a '\0' character to a string array ending, so that the compiler knows it's a string.
    return i;
}

void copy(char to[], char from[]) {
    int i = 0;

    // This loop is readily assigns all chars from the source array to the target array until it reaches the ending char.
    while ((to[i] = from[i]) != '\0')
        ++i;
}
</code>```

Thanks in advance!

答:
Okay, here's the error:

```<code>s[i++] = '\0'; // always put a '\0' character to a string array ending, so that the compiler knows it's a string.
</code>```

This will cause it to terminate the string even for no input (when it got EOF directly), and since it increments i before returning it, getLine() will never return 0 and thus main() will never stop. Removing the ++ fixed it, for my simple test.

Also, the comment is misleading, the compiler doesn't know anything. The compiler is no longer around when the code runs; the in-memory format of strings is something that's needed to keep the run-time libraries happy since that's what they expect.

Body:
I've just started to read K&R and on pages 32-33, there is a code that

finds the longest line among the inputs.

I nearly completely copy-pasted the code given in the book, just added some comment lines to make the code more understandable for me. But it isn't working.

Edit: I'm sorry for bad questioning. It seems the program does not act properly when I press Ctrl + Z, in order to terminate it. No matter how many lines I type and how many times I press Ctrl + Z, it just does nothing.

The following is my version of the code:

/* Find the longest line among the giving inputs and print it */

#include <stdio.h>
#define MAXLINE 1000            /* maximum input line length */

int getLine(char line[], int maxLine);
void copy(char to[], char from[]);

int main(void) {
    int len; /* current line length */
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here*/

    max = 0;

    /* getLine function takes all the input from user, returns it's size and equates it to the variable len
     * Then, len is compared whether it's greater than zero because if there's no input, no need to do any calculation
     * EDGE CASE
     */
    while ((len = getLine(line, MAXLINE)) > 0)
        /* If the length of input is larger than the previous max length, set max as the new length value and copy that input */
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0) /* there was a line, EDGE CASE */
        printf("%s", longest);

    return 0;
}

/* Read a line into s, return length.
 * Since the input length is unknown, there should be a limit */
int getLine(char s[], int lim) {
    int c, i;

    /* The loop's first condition is whether the input length is below the limit. EDGE CASE
     * If it's not, omit the rest because it would cause a BUFFER OVERFLOW. Next, take the input as long as it's not an EOF command.
     * Finally, if the input is end of line, finish the loop, don' take it.
     */
    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    if (c == '\n')
        s[i++] = c;
    s[i++] = '\0'; // always put a '\0' character to a string array ending, so that the compiler knows it's a string.
    return i;
}

void copy(char to[], char from[]) {
    int i = 0;

    // This loop is readily assigns all chars from the source array to the target array until it reaches the ending char.
    while ((to[i] = from[i]) != '\0')
        ++i;
}

Thanks in advance!

Body:
Okay, here's the error:

s[i++] = '\0'; // always put a '\0' character to a string array ending, so that the compiler knows it's a string.

This will cause it to terminate the string even for no input (when it got EOF directly), and since it increments i before returning it, getLine() will never return 0 and thus main() will never stop. Removing the ++ fixed it, for my simple test.

Also, the comment is misleading, the compiler doesn't know anything. The compiler is no longer around when the code runs; the in-memory format of strings is something that's needed to keep the run-time libraries happy since that's what they expect.


问:
input type date only for mobile
I am trying to make time and date picker for my project. I want to time and date picker I will use one plugins, but that's only for desktop browsers and when it will browse on mobile it will trigger mobile native time/date picker. I was looking that type plugins, but I don't get it yet. If you guys know then please let me know. I tried to do something add/remove class Depending on Screen Size. It adds and remove class, but plugins not fired.

bellow is my code

https://codepen.io/pagol/pen/MOzVMP

html

```<code><div class="datepicker test">
<input type="date" class="change" id="myinput">
</div>
</code>```

js

```<code>jQuery(document).ready(function(){

  TinyDatePicker('.test input');

});

$(function(){

$(window).bind("resize",function(){
    console.log($(this).width())
    if($(this).width() <500){
    $('.datepicker').removeClass('test').addClass('red')
    }
    else{
    $('div').removeClass('red').addClass('test')
    }
})
})
</code>```

答:
finally i able to fix what i wanted to do. so now if load in mobile it will fired native picker and if browser in desktop/laptop it will fired date picker js.

live code here codepen.io/pagol/pen/MOzVMP

Title: input type date only for mobile

Body:
I am trying to make time and date picker for my project. I want to time and date picker I will use one plugins, but that's only for desktop browsers and when it will browse on mobile it will trigger mobile native time/date picker. I was looking that type plugins, but I don't get it yet. If you guys know then please let me know. I tried to do something add/remove class Depending on Screen Size. It adds and remove class, but plugins not fired.

bellow is my code

https://codepen.io/pagol/pen/MOzVMP

html

<input type="date" class="change" id="myinput">

js

jQuery(document).ready(function(){

  TinyDatePicker('.test input');

});

$(function(){

$(window).bind("resize",function(){
    console.log($(this).width())
    if($(this).width() <500){
    $('.datepicker').removeClass('test').addClass('red')
    }
    else{
    $('div').removeClass('red').addClass('test')
    }
})
})


问:
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit).

Will these functions call destructors for static objects when called from a C++ program? Does the C++ standard make any guarantees about _Exit?

(Inspired by this question; I suddenly wondered what happens in the typical fork-exec-_exit idiom in C++.)

答:
Technically, _Exit is not defined by the C++ standard, so you can't even call it from a 100% portable C++ program.  The C++03 standard incorporates by reference the C89 standard (aka C90 or ANSI C), whereas _Exit is only defined in the newer C99 standard.  I'm not sure which version of C the upcoming C++0x standard incorporates, but I would guess that it's based on C99.

In any case, though, here are the relevant clauses from the relevant language standards:

_Exit is not guaranteed to close file descriptors.  From C99 §7.20.4.4/2 (emphasis mine):

The _Exit function causes normal program termination to occur and control to be returned to the host environment. No functions registered by the atexit function or signal handlers registered by the signal function are called. The status returned to the host environment is determined in the same way as for the exit function (7.20.4.3). Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined.

Recall that implementation-defined means that the implementation (that is, the compiler toolchain and runtime environment) can choose to do whatever it wants, but it must document what it does.

From C++03 §3.6.3/1:

Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3). These objects are destroyed in the reverse order of the completion of their constructor or of the completion of their dynamic initialization. If an object is initialized statically, the object is destroyed in the same order as if the object was dynamically initialized. For an object of array or class type, all subobjects of that object are destroyed before any local object with static storage duration initialized during the construction of the subobjects is destroyed.

§3.6.3/4:

Calling the function

    void abort();

declared in <cstdlib> terminates the program without executing destructors for objects of automatic or static storage duration and without calling the functions passed to atexit().

Practically, in most implementations, global object destructors are implemented via atexit, so what you will see is that _Exit will not call the destructors for global objects, although this behavior is not guaranteed (since _Exit and C++ are not guaranteed to both exist in the same language).

Title: How will _Exit behave in a C++ program?


答:
Thanks to @ravinder-reddy I was led to the right direction and managed to build what I need. @leran2002 answer is good when you have known items array. In my case it's unknown so had to make dynamic selection. I ended up with a stored procedure. Here it is:

```<code>CREATE DEFINER=`%`@`%` PROCEDURE `get_chart_history_pings`(IN masterId INT, IN daysLimit INT)
BEGIN
    SET SESSION group_concat_max_len = 1000000;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'ifnull(MAX(case when url = ''',
          url,
          ''' then ping end), null) AS `',
          url, '`'
        )
      ) INTO @sql
    FROM
      history
    WHERE
      url IN (
        SELECT url FROM hosts WHERE id = masterId
      )
      OR url = ( SELECT url FROM masters WHERE id = masterId LIMIT 1 );

    SET @sql = CONCAT('SELECT date_format(created_at, "%Y%-%m%-%d% %H%:%i%:00" ) as time, ', @sql, '
                      FROM history
                      WHERE created_at > DATE_SUB(now(), INTERVAL ',daysLimit,' DAY)
                      GROUP BY date_format( created_at, "%Y%m%d%H" )
                      ORDER BY created_at ASC');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
</code>```

Also credit goes to @mihai because his answer https://stackoverflow.com/a/28284999/2470912 led to this solution.

Title: Select data from MySQL for multi line chart

Body:
I'm struggling for some time now with constructing of data to a model that Google Chart would accept.

Chart requires data like this (json):

[
['Time',               'url1', 'url2', 'url3'   ],
['2017-12-06T12:00:00', 1,      2,       4      ],
['2017-12-06T13:00:00', 3,      6,       5      ],
['2017-12-06T14:00:00', 2,      5,       2      ],
['2017-12-06T15:00:00', 7,      3,       1      ],
]

So it should be extracted in similar manner. There are 3 options - construct all data in PHP/JS or select it with MySQL and then just cleanup.

MySQL database table 'ping_history' looks like this:

|--------|-----------|-------------|---------------------|
| ID     | url       | ping        | created_at          |
|--------|-----------|-------------|---------------------|
| 0      | url1      | 1           | 2017-12-06T12:00:00 |
|--------|-----------|-------------|---------------------|
| 1      | url2      | 2           | 2017-12-06T12:00:00 |
|--------|-----------|-------------|---------------------|
| 2      | url3      | 4           | 2017-12-06T12:00:10 |
|--------|-----------|-------------|---------------------|
| 3      | url1      | 3           | 2017-12-06T13:00:20 |
|--------|-----------|-------------|---------------------|
| 4      | url2      | 6           | 2017-12-06T13:00:30 |
|--------|-----------|-------------|---------------------|
| 5      | url3      | 5           | 2017-12-06T13:00:00 |
|--------|-----------|-------------|---------------------|
| 6      | url1      | 2           | 2017-12-06T14:00:40 |
|--------|-----------|-------------|---------------------|
| 7      | url2      | 5           | 2017-12-06T14:00:00 |
|--------|-----------|-------------|---------------------|
| 8      | url3      | 2           | 2017-12-06T14:00:00 |
|--------|-----------|-------------|---------------------|
| 9      | url1      | 7           | 2017-12-06T15:00:01 |
|--------|-----------|-------------|---------------------|
| 10     | url2      | 3           | 2017-12-06T15:00:02 |
|--------|-----------|-------------|---------------------|
| 11     | url3      | 1           | 2017-12-06T15:00:03 |
|--------|-----------|-------------|---------------------|

Records are grouped by HOUR(created_at), ping selected as MAX(ping).

How to make those grouped url rows appear as column titles or first row and all records for particular url make to go vertically... In case no value for date - we use null.

Maybe I just don't know how this method is called and can't google it. Something like rotating results set :) Please help!

Body:
Thanks to @ravinder-reddy I was led to the right direction and managed to build what I need. @leran2002 answer is good when you have known items array. In my case it's unknown so had to make dynamic selection. I ended up with a stored procedure. Here it is:

CREATE DEFINER=`%`@`%` PROCEDURE `get_chart_history_pings`(IN masterId INT, IN daysLimit INT)
BEGIN
    SET SESSION group_concat_max_len = 1000000;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'ifnull(MAX(case when url = ''',
          url,
          ''' then ping end), null) AS `',
          url, '`'
        )
      ) INTO @sql
    FROM
      history
    WHERE
      url IN (
        SELECT url FROM hosts WHERE id = masterId
      )
      OR url = ( SELECT url FROM masters WHERE id = masterId LIMIT 1 );

    SET @sql = CONCAT('SELECT date_format(created_at, "%Y%-%m%-%d% %H%:%i%:00" ) as time, ', @sql, '
                      FROM history
                      WHERE created_at > DATE_SUB(now(), INTERVAL ',daysLimit,' DAY)
                      GROUP BY date_format( created_at, "%Y%m%d%H" )
                      ORDER BY created_at ASC');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END

Also credit goes to @mihai because his answer https://stackoverflow.com/a/28284999/2470912 led to this solution.


问:
laravel Undefined variable when i post multiple value to view
In controller when i try to send multiple value to view such as this codes:

```<code>$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));
</code>```

i get error for this variables into view:

```<code>$categories
$selected_categories
$content
</code>```

result of dd(['content' => $content], $content_categories, $selected_categories); is:

```<code>array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]
</code>```

whats problem of my code to parse them on view or send them with correct way

my view:

```<code>1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"
</code>```

Errors:

```<code>"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"
</code>```

答:
Pass the variables to the compact without the $ sign

```<code>$categories = ContentCategories::all()->pluck('title', 'id');
$selected_categories = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit',
             compact('selected_categories', 'content_categories',
                     'content'));
</code>```

Body:
In controller when i try to send multiple value to view such as this codes:

$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));

i get error for this variables into view:

$categories
$selected_categories
$content

result of dd(['content' => $content], $content_categories, $selected_categories); is:

array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]

whats problem of my code to parse them on view or send them with correct way

my view:

1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"

Errors:

"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

Body:
Pass the variables to the compact without the $ sign

$categories = ContentCategories::all()->pluck('title', 'id');
$selected_categories = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit',
             compact('selected_categories', 'content_categories',
                     'content'));


问:
How to resolve this "required a bean" error
I am new to Springboot and I learning by Sping's tutorials and guides on "https://spring.io/guides".

Right now I try to understand and redo the tutorial: "Accessing data with MySQL"

Unfortunatelly I got the Error during Mavenbuild:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  2017-12-07 10:26:42.708 ERROR 8100 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field goodRepository in xxx.controller.GoodController required a bean of type 'xxx.repositories.GoodRepository' that could not be found.

Action:

Consider defining a bean of type 'xxx.repositories.GoodRepository' in your configuration.

Process finished with exit code 1

Here is my Code:

Good.java:

```<code>import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Good {

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

    private String name;

    public Good() {
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

GoodRepository:

```<code>import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}
</code>```

GoodController:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}
</code>```

My application.properties:

```<code>spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx
</code>```

the mysql-db exists on this port...

What did I where wrong?

答:
You need to annotate your GoodRepository with @Repository.
See the answer from : Spring Boot Inject CrudRepository into Service</p>

```<code> @Repository
 public interface GoodRepository extends CrudRepository<Good, Long>{

 }
</code>```

Body:
I am new to Springboot and I learning by Sping's tutorials and guides on "https://spring.io/guides".

Right now I try to understand and redo the tutorial: "Accessing data with MySQL"

Unfortunatelly I got the Error during Mavenbuild:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  2017-12-07 10:26:42.708 ERROR 8100 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field goodRepository in xxx.controller.GoodController required a bean of type 'xxx.repositories.GoodRepository' that could not be found.

Action:

Consider defining a bean of type 'xxx.repositories.GoodRepository' in your configuration.

Process finished with exit code 1

Here is my Code:

Good.java:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Good {

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

    private String name;

    public Good() {
    }

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

GoodRepository:

import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}

GoodController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}

My application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx

the mysql-db exists on this port...

What did I where wrong?

Body:
You need to annotate your GoodRepository with @Repository.
See the answer from : Spring Boot Inject CrudRepository into Service

 @Repository
 public interface GoodRepository extends CrudRepository<Good, Long>{

 }


问:
Mysql query select wrong record
I have a table users as,

```<code>id    name     status
---------------------
1     user1      1
2     user2      1
3     user3      1
</code>```

When I run this query it will select the record with id 2. Why this happened? I need to select record with id 2 when only the id is 2. I did the query like,

```<code>SELECT *
FROM (
`users`
)
WHERE `id` = '2a290cf764371';
</code>```

How can I fix this issue?

答: That happens because you are checking a string against an integer, so mysql autocast the string to integer and the integer of 2a290cf764371 is 2, don't do this kind of comparation, i suggest you to cast every ID to int before execute the query

Title: Mysql query select wrong record

Body:
I have a table users as,

id    name     status
---------------------
1     user1      1
2     user2      1
3     user3      1

When I run this query it will select the record with id 2. Why this happened? I need to select record with id 2 when only the id is 2. I did the query like,

SELECT *
FROM (
`users`
)
WHERE `id` = '2a290cf764371';

How can I fix this issue?


问:
How to pass a struct declared in a Qt's class to the same class's function?
```<code>#ifndef FF_H
#define FF_H

#include <QtQuick/QQuickPaintedItem>
#include "qpainter.h"
#include <QQuickItem>
#include <QQuickWindow>

class Draw_on_qimage : public QQuickPaintedItem
{
    Q_OBJECT
public:
    virtual void paint(QPainter *);
    Draw_on_qimage(QQuickPaintedItem *parent = 0);

public slots:
    void setbb_list(QList<bounding_box_struct> bb_list)
    {
        for (int h = 0; h < bb_list.size(); h++)
        {
            bounding_box_struct obj;
            obj.x = bb_list[h].x;

            m_bb_list.push_back(obj);
        }

        emit bb_listChanged(m_bb_list);
    }

protected:
    virtual void componentComplete ();

private:
    struct bounding_box_struct
    {   int x;
        int y;
        int w;
        int h;
        std::string vehicle_type;
    };

    Q_PROPERTY(QList<bounding_box_struct> bb_list
               READ bb_list
               WRITE setbb_list
               NOTIFY bb_listChanged)

    QList<bounding_box_struct> m_bb_list;

signals:
    void bb_listChanged(QList<bounding_box_struct> bb_list);
};

#endif // FF_H
</code>```

The bb_list has to be a Q_PROPERTY.

I am getting following errors:

```<code>error: ‘bounding_box_struct’ was not declared in this scope
     void setbb_list(QList<bounding_box_struct> bb_list)
                           ^
error: request for member ‘size’ in ‘bb_list’, which is of non-class type ‘int’
         for (int h = 0; h < bb_list.size(); h++)
                                     ^

error: invalid types ‘int[int]’ for array subscript
             obj.x = bb_list[h].x;
                              ^
</code>```

答:
You must define the struct before you use it. So put it in the beginning of the class.

Additionally, if you have a public method that uses this type, you should make it public, too.

Also note that if you put your method implementation outside of the class definition, you have to fully qualify the struct in return types, but it's optional in parameters:

```<code>struct MyClass {
    struct Inner {};
    Inner doThis(Inner i);
    Inner doThat(Inner i) { return i; } // Not qualified
};

MyClass::Inner MyClass::doThis(Inner i) { return i; }
// ^ required                   ^ Can be qualified
</code>```

Body:
#ifndef FF_H
#define FF_H

#include <QtQuick/QQuickPaintedItem>
#include "qpainter.h"
#include <QQuickItem>
#include <QQuickWindow>

class Draw_on_qimage : public QQuickPaintedItem
{
    Q_OBJECT
public:
    virtual void paint(QPainter *);
    Draw_on_qimage(QQuickPaintedItem *parent = 0);

public slots:
    void setbb_list(QList<bounding_box_struct> bb_list)
    {
        for (int h = 0; h < bb_list.size(); h++)
        {
            bounding_box_struct obj;
            obj.x = bb_list[h].x;

            m_bb_list.push_back(obj);
        }

        emit bb_listChanged(m_bb_list);
    }

protected:
    virtual void componentComplete ();

private:
    struct bounding_box_struct
    {   int x;
        int y;
        int w;
        int h;
        std::string vehicle_type;
    };

    Q_PROPERTY(QList<bounding_box_struct> bb_list
               READ bb_list
               WRITE setbb_list
               NOTIFY bb_listChanged)

    QList<bounding_box_struct> m_bb_list;

signals:
    void bb_listChanged(QList<bounding_box_struct> bb_list);
};

#endif // FF_H

The bb_list has to be a Q_PROPERTY.

I am getting following errors:

error: ‘bounding_box_struct’ was not declared in this scope
     void setbb_list(QList<bounding_box_struct> bb_list)
                           ^
error: request for member ‘size’ in ‘bb_list’, which is of non-class type ‘int’
         for (int h = 0; h < bb_list.size(); h++)
                                     ^

error: invalid types ‘int[int]’ for array subscript
             obj.x = bb_list[h].x;
                              ^

Body:
You must define the struct before you use it. So put it in the beginning of the class.

Additionally, if you have a public method that uses this type, you should make it public, too.

Also note that if you put your method implementation outside of the class definition, you have to fully qualify the struct in return types, but it's optional in parameters:

struct MyClass {
    struct Inner {};
    Inner doThis(Inner i);
    Inner doThat(Inner i) { return i; } // Not qualified
};

MyClass::Inner MyClass::doThis(Inner i) { return i; }
// ^ required                   ^ Can be qualified


问:
Alternative methods to using SetCurrentDirectory in VBA
I have a code to repair in VBA, which is a language that I'm learning as I go. The code calls an external exe file from a networked drive. The exe was updated recently from V5.0 to V5.3 and since that update the directories have become an issue. This is how the executable is called from the VBA code:

```<code>Sub RunExecutable()
Dim wsh As Object
SetCurrentDirectory "\\<path>\"
Statusnum = wsh.Run(Command:="program.exe ""\\<path>\inputfile.gdp""", WindowStyle:=1, waitonreturn:=True)
</code>```

This used to work perfectly. But since program.exe was updated, the path for some of it's working files has become duplicated when running from the above script. I suspect that the SetCurrentDirectory line is causing the problem. The working directory for program.exe should be, for example:

```<code>\\Drive\Folder1\Folder2\Folder3\
</code>```

But program.exe now wants to write its working files to this duplicated path:

```<code>\\Drive\Folder1\Folder2\Folder3\DRIVE\FOLDER1\FOLDER2\FOLDER3\
</code>```

Which doesn't exist on our network, and program.exe then crashes. If I create those subfolders for it to work in, it operates perfectly.

What I want to know is, is there an alternative way to call the .exe file without setting the current directory in VBA? Because the path I set as the current directory is what is being duplicated when program.exe is trying to run, and I have no way to modify the .exe file. The .exe works fine when not being called by this VBA code, there are no issues with the directories.

I tried putting in the exact path to the .exe file in this line:

```<code>wsh.Run(Command:="<path>/program.exe .....
</code>```

and removing the SetCurrentDirectory command, but in response I get an error saying that the .exe file cannot be located.

答:
How about changing the following:

```<code>Sub RunExecutable()
Dim wsh As Object
SetCurrentDirectory "\\<path>\"
Statusnum = wsh.Run(Command:="program.exe ""\\<path>\inputfile.gdp""", WindowStyle:=1, waitonreturn:=True)
</code>```

To this (you might have to also get rid of the \ before inputfile.gdp, depends on the end of your path and whether it ends with a \ or not):

```<code>Sub RunExecutable()
Dim wsh As Object
SetCurrentDirectory "\\<path>\"
Statusnum = wsh.Run(Command:="program.exe ""inputfile.gdp""", WindowStyle:=1, waitonreturn:=True)
</code>```

Or a slightly different approach using Shell Commands:

```<code>Sub RunExecutable()
Dim SetCurrentDirectory As String, varProc As Variant
On Error Resume Next
SetCurrentDirectory = "C:\Your\Path\program.exe" 'Your path here
varProc = Shell(SetCurrentDirectory , 1)
</code>```

Body:
I have a code to repair in VBA, which is a language that I'm learning as I go. The code calls an external exe file from a networked drive. The exe was updated recently from V5.0 to V5.3 and since that update the directories have become an issue. This is how the executable is called from the VBA code:

Sub RunExecutable()
Dim wsh As Object
SetCurrentDirectory "\\<path>\"
Statusnum = wsh.Run(Command:="program.exe ""\\<path>\inputfile.gdp""", WindowStyle:=1, waitonreturn:=True)

This used to work perfectly. But since program.exe was updated, the path for some of it's working files has become duplicated when running from the above script. I suspect that the SetCurrentDirectory line is causing the problem. The working directory for program.exe should be, for example:

\\Drive\Folder1\Folder2\Folder3\

But program.exe now wants to write its working files to this duplicated path:

\\Drive\Folder1\Folder2\Folder3\DRIVE\FOLDER1\FOLDER2\FOLDER3\

Which doesn't exist on our network, and program.exe then crashes. If I create those subfolders for it to work in, it operates perfectly.

What I want to know is, is there an alternative way to call the .exe file without setting the current directory in VBA? Because the path I set as the current directory is what is being duplicated when program.exe is trying to run, and I have no way to modify the .exe file. The .exe works fine when not being called by this VBA code, there are no issues with the directories.

I tried putting in the exact path to the .exe file in this line:

wsh.Run(Command:="<path>/program.exe .....

and removing the SetCurrentDirectory command, but in response I get an error saying that the .exe file cannot be located.

Body:
How about changing the following:

Sub RunExecutable()
Dim wsh As Object
SetCurrentDirectory "\\<path>\"
Statusnum = wsh.Run(Command:="program.exe ""\\<path>\inputfile.gdp""", WindowStyle:=1, waitonreturn:=True)

To this (you might have to also get rid of the \ before inputfile.gdp, depends on the end of your path and whether it ends with a \ or not):

Sub RunExecutable()
Dim wsh As Object
SetCurrentDirectory "\\<path>\"
Statusnum = wsh.Run(Command:="program.exe ""inputfile.gdp""", WindowStyle:=1, waitonreturn:=True)

Or a slightly different approach using Shell Commands:

Sub RunExecutable()
Dim SetCurrentDirectory As String, varProc As Variant
On Error Resume Next
SetCurrentDirectory = "C:\Your\Path\program.exe" 'Your path here
varProc = Shell(SetCurrentDirectory , 1)


问:
What data (if any) persists across web-requests in Ruby on Rails?
I decided to use the singleton design pattern while creating a view helper class.  This got me thinking; will the singleton instance survive across requests?  This led to another question, Which variables (if any) survive across web requests and does that change depending on deployment? (Fastcgi, Mongrel, Passenger, ...)

I know that Controller instance variables aren't persisted. I know Constants are persisted (or reloaded?). But I don't know about class variables, instance variables on a class, Eigenclasses, ...

答:
I know that this post is old, but for who is looking a solution, it's possible to use Rails.Cache, like this:

```<code>class TestEventsController < ApplicationController
  require 'httparty'

  @@cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)

  before_action :get_data, only: [:get]
  before_action :get_response, only: [:set]

  def get
    uri = "https://hooks.zapier.com/hooks/catch/zap_id/"
    event_id = event_id_generate()
    @@cache.write(event_id, "")

    result = HTTParty.post(uri.to_str,
    :body => {id: event_id, data: @data}.to_json,
    :headers => {'content-Type' => 'application/json'})
    sleep 2
    render json: { 'value': @@cache.read(event_id) }, status: 200
  end

  def set
    @@cache.write(@id, @value)
    render json: { 'value': @@cache.read(@id) }, status: 200
  end

  def get_data
    @data = params["data"]
  end
  def get_response
    @id = params["id"]
    @value = params["value"]
  end

  def event_id_generate
    token = SecureRandom.urlsafe_base64(10, false)
  end
end
</code>```

What I'm doing is receive a request in a route, sending a GET to Zapier, and waiting for the answer in another route. Rails opens a new Thread for each request, so I write in the RAM my data in format 'key: value'

Rails.cache in different threads not caching?

Body:
I know that this post is old, but for who is looking a solution, it's possible to use Rails.Cache, like this:

class TestEventsController < ApplicationController
  require 'httparty'

  @@cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)

  before_action :get_data, only: [:get]
  before_action :get_response, only: [:set]

  def get
    uri = "https://hooks.zapier.com/hooks/catch/zap_id/"
    event_id = event_id_generate()
    @@cache.write(event_id, "")

    result = HTTParty.post(uri.to_str,
    :body => {id: event_id, data: @data}.to_json,
    :headers => {'content-Type' => 'application/json'})
    sleep 2
    render json: { 'value': @@cache.read(event_id) }, status: 200
  end

  def set
    @@cache.write(@id, @value)
    render json: { 'value': @@cache.read(@id) }, status: 200
  end

  def get_data
    @data = params["data"]
  end
  def get_response
    @id = params["id"]
    @value = params["value"]
  end

  def event_id_generate
    token = SecureRandom.urlsafe_base64(10, false)
  end
end

What I'm doing is receive a request in a route, sending a GET to Zapier, and waiting for the answer in another route. Rails opens a new Thread for each request, so I write in the RAM my data in format 'key: value'

Rails.cache in different threads not caching?


问:
Ramda: Is there a way to find particular key value is nested object?
I want to find particular key value is nested object or not.

```<code>{
  'a': {
    'area': 'abc'
  },
  'b': {
    'area': {
      'city': 'aaaa',
      'state': 'ggggg'
    }
  }
}
</code>```

In above example, I want to find 'a' and 'b' is object or nested object?

答:
If you want to know whether all keys in the object contain nested objects then one possible solution is to convert all of the values of the object to boolean values using R.map and R.propSatisfies, representing whether the nested property was an object or not.

const fn = R.map(R.propSatisfies(R.is(Object), 'area'))

const example = {
  'a': {
    'area': 'abc'
  },
  'b': {
    'area': {
      'city': 'aaaa',
      'state': 'ggggg'
    }
  }
}

console.log(fn(example))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script></code>```

If you just want to know whether a specific key of an object contains a nested object, then you can do so with a composition of R.prop and R.propSatisfies.

const fn = R.pipe(R.prop, R.propSatisfies(R.is(Object), 'area'))

const example = {
  'a': {
    'area': 'abc'
  },
  'b': {
    'area': {
      'city': 'aaaa',
      'state': 'ggggg'
    }
  }
}

console.log('a:', fn('a', example))
console.log('b:', fn('b', example))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script></code>```

Body:
I want to find particular key value is nested object or not.

{
  'a': {
    'area': 'abc'
  },
  'b': {
    'area': {
      'city': 'aaaa',
      'state': 'ggggg'
    }
  }
}

In above example, I want to find 'a' and 'b' is object or nested object?

Body:
If you want to know whether all keys in the object contain nested objects then one possible solution is to convert all of the values of the object to boolean values using R.map and R.propSatisfies, representing whether the nested property was an object or not.

const fn = R.map(R.propSatisfies(R.is(Object), 'area'))

const example = {
  'a': {
    'area': 'abc'
  },
  'b': {
    'area': {
      'city': 'aaaa',
      'state': 'ggggg'
    }
  }
}

console.log(fn(example))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

If you just want to know whether a specific key of an object contains a nested object, then you can do so with a composition of R.prop and R.propSatisfies.

const fn = R.pipe(R.prop, R.propSatisfies(R.is(Object), 'area'))

const example = {
  'a': {
    'area': 'abc'
  },
  'b': {
    'area': {
      'city': 'aaaa',
      'state': 'ggggg'
    }
  }
}

console.log('a:', fn('a', example))
console.log('b:', fn('b', example))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


问:
convert all type of languages to one for comparison
I have a search text input, I use this script for search, the function I use for standardize string is str.toLowerCase. It 's worked perfectly for English statement. but in my case there is other languages like Arabic and Persian.

In this situation my search function does not work correct.  How can I Convert all string to one type of something that I can use it for compare strings.

search function:

```<code>$(document).ready(function(){
    $('#myInput').on('keyup', function () {

        var valThis = $(this).val().toLowerCase(); //<--------------

        $('#areas_list>option').each(function(){

            var text = $(this).text().toLowerCase(); // <---------

            for (var i = 0; i < text.length; i++) {
                if (text.search(valThis) > 0) {
                    $(this).show();
                }else if (!valThis) {
                    $(this).show();
                }else {
                    $(this).hide();
                }
            }
        });
    });
});
</code>```

答:
I use this script for search, the function I use for standardize
  string is str.toLowerCase. It 's worked perfectly for English
  statement. but in my case there is other languages like Arabic and
  Persian.

You can use toLocaleLowerCase

```<code>var valThis = $(this).val().toLocaleLowerCase();
</code>```

As per doc

The default locale is the host environment’s current locale.

Please note that

You need to pass the locale if your system's locale is not the locale of the data.

Body:
I have a search text input, I use this script for search, the function I use for standardize string is str.toLowerCase. It 's worked perfectly for English statement. but in my case there is other languages like Arabic and Persian.

In this situation my search function does not work correct.  How can I Convert all string to one type of something that I can use it for compare strings.

search function:

$(document).ready(function(){
    $('#myInput').on('keyup', function () {

        var valThis = $(this).val().toLowerCase(); //<--------------

        $('#areas_list>option').each(function(){

            var text = $(this).text().toLowerCase(); // <---------

            for (var i = 0; i < text.length; i++) {
                if (text.search(valThis) > 0) {
                    $(this).show();
                }else if (!valThis) {
                    $(this).show();
                }else {
                    $(this).hide();
                }
            }
        });
    });
});

Body:
I use this script for search, the function I use for standardize
  string is str.toLowerCase. It 's worked perfectly for English
  statement. but in my case there is other languages like Arabic and
  Persian.

You can use toLocaleLowerCase

var valThis = $(this).val().toLocaleLowerCase();

As per doc

The default locale is the host environment’s current locale.

Please note that

You need to pass the locale if your system's locale is not the locale of the data.


问:
Calculating the average time between orders for each customer
I've searched all over but cant seem to find how to calculate the average time between orders for each customer.  I'm using Oracle SQL Developer.  Ive tried using the lag() function with no joy.

Example data below shows a customer bought on 3 separate occasions.  The average time between all purchases is 7.5 days ((6+9)/2).

```<code>CustID   OrderDate
-------  ---------
1000000  14-AUG-12
1000000  23-AUG-12
1000000  29-AUG-12
</code>```

So how do I calculate that average for each customer?

any help would be much appreciated.

答:
Using Ed's answer as a starting point used CTE to get the average for all orders.  </p>

```<code> WITH Sales_CTE (CustomerId, OrderDays, OrderCount)
    AS
    (
    SELECT CustomerId, (datediff(day,Min(OrderTime),Max(OrderTime))) / (COUNT(*) - 1) AS OrderDays, COUNT(*) AS OrderCount
      FROM tblStoreOrders  GROUP BY CustomerId HAVING COUNT(*) > 1
    )
    SELECT Avg(OrderDays) FROM Sales_CTE
</code>```

Body:
I've searched all over but cant seem to find how to calculate the average time between orders for each customer.  I'm using Oracle SQL Developer.  Ive tried using the lag() function with no joy.

Example data below shows a customer bought on 3 separate occasions.  The average time between all purchases is 7.5 days ((6+9)/2).

CustID   OrderDate
-------  ---------
1000000  14-AUG-12
1000000  23-AUG-12
1000000  29-AUG-12

So how do I calculate that average for each customer?

any help would be much appreciated.

Body:
Using Ed's answer as a starting point used CTE to get the average for all orders.

 WITH Sales_CTE (CustomerId, OrderDays, OrderCount)
    AS
    (
    SELECT CustomerId, (datediff(day,Min(OrderTime),Max(OrderTime))) / (COUNT(*) - 1) AS OrderDays, COUNT(*) AS OrderCount
      FROM tblStoreOrders  GROUP BY CustomerId HAVING COUNT(*) > 1
    )
    SELECT Avg(OrderDays) FROM Sales_CTE


问:
Objective C/XCode - Image in ImageView not recognised by Xcode
I am developing a simple calculator to sum the prices of 3 images in a view. These images are stored inside imageviews. The image inside each imageview can be changed using button 1-6 etc etc. The price is displayed on a label at the bottom.

I am using an if statement(s) that says if the image inside xyz imageview is @"zyx", set price as yzx.

I know the calculator works because the calculator always takes the "else" value (even if the price I set for the else value changes)

```<code>if(
   self.topimage.image == [UIImage imageNamed:@"image.png"]){

    self.TopImageView.Price = 200;
}
else if(
        self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

    self.TopImageView.Price = 400;
}
else {
    self.TopImageView.Price = 9;

}
</code>```

Xcode can't recognise when the image inside the imageview equals an image of whatever name / doesn't update the price.

I tried as well pulling the image straight from the array rather than naming it:

```<code> if(
       self.topimage.image == [UIImage imageNamed:[self.imagesArray objectAtIndex: 1]]){

    self.TopImageView.Price = 200;
}
</code>```

and still the price on the label doesn't change. I'm assuming this is because the price of the imageview doesn't change.

the price on the label is given by:

```<code>_totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];
</code>```

all properties are defined and the program runs with no errors. The calculator itself works and correctly sums the 'else' values from my if clauses. All images are under "supporting files" in xcode and I know there can't be an issue with pulling them because they display on the app when pulling them from an array.

Here, for an example, is all the code I have under one button:

```<code>- (IBAction)Button2:(UIButton *)sender {

    self.clothesindex = self.clothesindex - 1;

    if (self.clothesindex == (-1)) {
        self.clothesindex = 2;
    }
    self.topimage.image = [UIImage imageNamed:[self.imagesArray objectAtIndex: self.clothesindex ]];

    if(
       self.topimage.image == [UIImage imageNamed:@"image.png"]){

        self.TopImageView.Price = 200;
    }
    else if(
            self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

        self.TopImageView.Price = 400;
    }
    else {
        self.TopImageView.Price = 9;

    }

    _totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];
}
</code>```

where "top image" is the imageview, "TopImageView" is a class, and "Price" a property of that class.

Any help would be greatly appreciated.

答:
You should do:</p>

```<code>NSString* imageName = [self.imagesArray objectAtIndex: self.clothesindex ];

if([imageName isEqualToString:@"image.png"]){

    self.TopImageView.Price = 200;
}
else if([imageName isEqualToString:@"slacks.png"]){

    self.TopImageView.Price = 400;
}
else {
    self.TopImageView.Price = 9;

}
</code>```

Body:
I am developing a simple calculator to sum the prices of 3 images in a view. These images are stored inside imageviews. The image inside each imageview can be changed using button 1-6 etc etc. The price is displayed on a label at the bottom.

I am using an if statement(s) that says if the image inside xyz imageview is @"zyx", set price as yzx.

I know the calculator works because the calculator always takes the "else" value (even if the price I set for the else value changes)

if(
   self.topimage.image == [UIImage imageNamed:@"image.png"]){

    self.TopImageView.Price = 200;
}
else if(
        self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

    self.TopImageView.Price = 400;
}
else {
    self.TopImageView.Price = 9;

}

Xcode can't recognise when the image inside the imageview equals an image of whatever name / doesn't update the price.

I tried as well pulling the image straight from the array rather than naming it:

 if(
       self.topimage.image == [UIImage imageNamed:[self.imagesArray objectAtIndex: 1]]){

    self.TopImageView.Price = 200;
}

and still the price on the label doesn't change. I'm assuming this is because the price of the imageview doesn't change.

the price on the label is given by:

_totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];

all properties are defined and the program runs with no errors. The calculator itself works and correctly sums the 'else' values from my if clauses. All images are under "supporting files" in xcode and I know there can't be an issue with pulling them because they display on the app when pulling them from an array.

Here, for an example, is all the code I have under one button:

- (IBAction)Button2:(UIButton *)sender {

    self.clothesindex = self.clothesindex - 1;

    if (self.clothesindex == (-1)) {
        self.clothesindex = 2;
    }
    self.topimage.image = [UIImage imageNamed:[self.imagesArray objectAtIndex: self.clothesindex ]];

    if(
       self.topimage.image == [UIImage imageNamed:@"image.png"]){

        self.TopImageView.Price = 200;
    }
    else if(
            self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

        self.TopImageView.Price = 400;
    }
    else {
        self.TopImageView.Price = 9;

    }

    _totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];
}

where "top image" is the imageview, "TopImageView" is a class, and "Price" a property of that class.

Any help would be greatly appreciated.

Body:
You should do:

NSString* imageName = [self.imagesArray objectAtIndex: self.clothesindex ];

if([imageName isEqualToString:@"image.png"]){

    self.TopImageView.Price = 200;
}
else if([imageName isEqualToString:@"slacks.png"]){

    self.TopImageView.Price = 400;
}
else {
    self.TopImageView.Price = 9;

}


问:
Google Translate API integration in iOS app
I am trying to do a simple translation using Google Translate in my iOS app but as i call the url, i am getting the following error in response…

```<code>{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured. Please use Google Developers Console to activate the API for your project."
   }
  ],
  "code": 403,
  "message": "Access Not Configured. Please use Google Developers Console to activate the API for your project."
 }
}
</code>```

I couldn't find anything close to any solution of this issue.. Please can anyone help here. thanks in advance…

答: This error comes when you hadn't add the Credit card detail with your Google Cloud account, as rules has changed in which you need to add credit card details if you use Google translate api.</p>

Body:
I am trying to do a simple translation using Google Translate in my iOS app but as i call the url, i am getting the following error in response…

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured. Please use Google Developers Console to activate the API for your project."
   }
  ],
  "code": 403,
  "message": "Access Not Configured. Please use Google Developers Console to activate the API for your project."
 }
}

I couldn't find anything close to any solution of this issue.. Please can anyone help here. thanks in advance…


问:
nativescript - how set global variables
I'm starting with nativescript with latest version.

I've finished tutorial on offical page, but now i have more questions than answers.

Can anybody tell me, what strategies can i use to set some variables, for example after succesfull login, how to set variable or even better, run some function that is doing checks globally, and not on every view or model file ?
I see that app.js is starting point for app, but looks like it cannot do any global checks ?

I think, second question is related :
Almost every model view file (file called as {viewname}).js is using:

```<code>var frameModule = require('ui/frame');
</code>```

Is there a way to declare this once ? Or i have to run this every time when i need frame methods ? Or maybe if this is possible, lead to poor perforance?

Thanks for any advices.

答:
Thanks Nikolay. Im using this pattern (maybe will help somebody)
register JS:</p>

```<code>var page = require ("ui/core/view");
var frameModule = require('ui/frame');
var appSettings = require('application-settings');

exports.loaded = function(args) {
page = args.object;
};

exports.register = function() {
var userName = page.getViewById('userName');
var userPass = page.getViewById('userPass');

if (userName.text != '' &&  userPass.text != '') {
    var name = userName.text;
    var pass = userPass.text;

    appSettings.setString('name', name);
    appSettings.setString('pass', pass);
    appSettings.setBoolean('auth', true);

    var topmost = frameModule.topmost();
    var navigationEntry = {
        moduleName: "main-page",
        context: { info: "something you want to pass to your page" },
        animated: true,
        transition: "curlDown",
        clearHistory: true
    };
    topmost.navigate(navigationEntry);

} else {
    alert('Please, fill form');
}
};
</code>```

Title: nativescript - how set global variables

Body:
I'm starting with nativescript with latest version.

I've finished tutorial on offical page, but now i have more questions than answers.

Can anybody tell me, what strategies can i use to set some variables, for example after succesfull login, how to set variable or even better, run some function that is doing checks globally, and not on every view or model file ?
I see that app.js is starting point for app, but looks like it cannot do any global checks ?

I think, second question is related :
Almost every model view file (file called as {viewname}).js is using:

var frameModule = require('ui/frame');

Is there a way to declare this once ? Or i have to run this every time when i need frame methods ? Or maybe if this is possible, lead to poor perforance?

Thanks for any advices.

Body:
Thanks Nikolay. Im using this pattern (maybe will help somebody)
register JS:

var page = require ("ui/core/view");
var frameModule = require('ui/frame');
var appSettings = require('application-settings');

exports.loaded = function(args) {
page = args.object;
};

exports.register = function() {
var userName = page.getViewById('userName');
var userPass = page.getViewById('userPass');

if (userName.text != '' &&  userPass.text != '') {
    var name = userName.text;
    var pass = userPass.text;

    appSettings.setString('name', name);
    appSettings.setString('pass', pass);
    appSettings.setBoolean('auth', true);

    var topmost = frameModule.topmost();
    var navigationEntry = {
        moduleName: "main-page",
        context: { info: "something you want to pass to your page" },
        animated: true,
        transition: "curlDown",
        clearHistory: true
    };
    topmost.navigate(navigationEntry);

} else {
    alert('Please, fill form');
}
};