问:
disable click after clicking on $('body').on('click') event
hi  I want to disable click after the user clicked  on an element

the elements loaded after my script (elements built by javascript) and I can't use these code

```<code>     $('.disableClick').click(
            function (e) {
                e.stopPropagation();
                return false;
            }
        )
</code>```

and I use these code to do work on the element by click

```<code>    $('body').on('click','.disableClick',
                function (e) {
                    if(!is_valid)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                }
            );
</code>```

I think disabling click codes like e.stopPropagation()  don't support for

$('body').on('click')
  event

答:
try this:

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script type="text/javascript">
    $('body').on('click','.disableClick',
            function (e) {

                   $(this).attr("disabled", true);
            }
        );
</script>
</code>```

It works on body as well as on document both

Body:
hi  I want to disable click after the user clicked  on an element

the elements loaded after my script (elements built by javascript) and I can't use these code

     $('.disableClick').click(
            function (e) {
                e.stopPropagation();
                return false;
            }
        )

and I use these code to do work on the element by click

    $('body').on('click','.disableClick',
                function (e) {
                    if(!is_valid)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                }
            );

I think disabling click codes like e.stopPropagation()  don't support for

$('body').on('click')
  event

Body:
try this:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script type="text/javascript">
    $('body').on('click','.disableClick',
            function (e) {

                   $(this).attr("disabled", true);
            }
        );
</script>

It works on body as well as on document both


来源: stackexchange

问:
Updating an object with setState in React
Is it at all possible to update object's properties with setState?

Something like:

```<code>this.state = {
   jasper: { name: 'jasper', age: 28 },
}
</code>```

I have tried:

```<code>this.setState({jasper.name: 'someOtherName'});
</code>```

and this:

```<code>this.setState({jasper: {name: 'someothername'}})
</code>```

The first results in a syntax error and the second just does nothing. Any ideas?

答:
Without using Async and Await Use this...

```<code>funCall(){
     this.setState({...this.state.jasper, name: 'someothername'});
}
</code>```

If you using with Async And Await use this...

```<code>async funCall(){
      await this.setState({...this.state.jasper, name: 'someothername'});
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it at all possible to update object's properties with setState?

Something like:

this.state = {
   jasper: { name: 'jasper', age: 28 },
}

I have tried:

this.setState({jasper.name: 'someOtherName'});

and this:

this.setState({jasper: {name: 'someothername'}})

The first results in a syntax error and the second just does nothing. Any ideas?

Body:
Without using Async and Await Use this...

funCall(){
     this.setState({...this.state.jasper, name: 'someothername'});
}

If you using with Async And Await use this...

async funCall(){
      await this.setState({...this.state.jasper, name: 'someothername'});
}


Title: Function that give me all date list of a month

Body:
Is there a function that could list me all dates in a specified month(year)

that is:

proper_function("January",2019)

result is

 [1] "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04" "2019-01-05" "2019-01-06" "2019-01-07"
 [8] "2019-01-08" "2019-01-09" "2019-01-10" "2019-01-11" "2019-01-12" "2019-01-13" "2019-01-14"
[15] "2019-01-15" "2019-01-16" "2019-01-17" "2019-01-18" "2019-01-19" "2019-01-20" "2019-01-21"
[22] "2019-01-22" "2019-01-23" "2019-01-24" "2019-01-25" "2019-01-26" "2019-01-27" "2019-01-28"
[29] "2019-01-29" "2019-01-30" "2019-01-31"

I could write a simple program since except for Feb each month has fixed dates for any year, but I suppose there should be some exist function in some basic packages

Body:
It should not be difficult to write one. Using only base R you can do

proper_function <- function(month, year) {
   start <- as.Date(paste0("01", month,year), "%d%B%Y")
   end <- seq(start, length.out = 2, by = "month")[2]
   seq(start, end - 1, by  = "day")
}

proper_function("June",2019)
# [1] "2019-06-01" "2019-06-02" "2019-06-03" "2019-06-04" "2019-06-05"....
#     "2019-06-25" "2019-06-26" "2019-06-27" "2019-06-28" "2019-06-29" "2019-06-30"

proper_function("February",2019)
#[1] "2019-02-01" "2019-02-02" "2019-02-03" "2019-02-04" "2019-02-05" ....
#    "2019-02-25" "2019-02-26" "2019-02-27" "2019-02-28"

You can decide the format your input is going to take and change the format option in as.Date accordingly.


问:
Why GuzzleHttp client throws ClientException when using it to make network request on Laravel/Lumen?
I am currently building a Financial micro service application using Laravel/Lumen micro framework.Everything have been working perfectly as expected. My problem now is that i am trying to make a network request to my internal services via Api call from ApiGateway using GuzzleHttp client. The problem is that when i make request to the internal service, it always throws an exception of ClientException.

ClientException.

Client error: GET http://127.0.0.1:8081/v1/admin resulted in a 401
  Unauthorized response: {"error":"Unauthorized.","code":401}

I have tried to make network request to the same internal services using postman; and it works fine. However, for some reason still fail to work with GuzzleHttp. I don't know what i am doing wrong. Please your assist will be appreciated.

Here is the httpClient.php in ApiGateway.

```<code>//Constructor method
public function __construct() {
    $this->baseUri = config('services.auth_admin.base_uri');
}

public function httpRequest($method, $requestUrl, $formParams = [], $headers = []) {
    //Instantiate the GazzleHttp Client
    $client = new Client([
        'base_uri' => $this->baseUri,
    ]);
    //Send the request
    $response = $client->request($method, $requestUrl, ['form_params' => $formParams, 'headers' => $headers]);
    //Return a response
    return $response->getBody();
}

//Internal Service Communication in ApiGateway**
public function getAdmin($header) {
    return $this->httpRequest('GET', 'admin', $header);
}
</code>```

InternalServiceController.php

```<code>   public function getAdmin(Request $request) {
        return $this->successResponse($this->authAdminService->getAdmin($request->header()));
    }
</code>```

I am using Lumen version: 5.8 and GuzzleHttp Version: 6.3

答:
You pass your headers as formParams (third index instead of fourth).

Try below:

```<code>return $this->httpRequest('GET', 'admin', [], $header);
</code>```

Body:
I am currently building a Financial micro service application using Laravel/Lumen micro framework.Everything have been working perfectly as expected. My problem now is that i am trying to make a network request to my internal services via Api call from ApiGateway using GuzzleHttp client. The problem is that when i make request to the internal service, it always throws an exception of ClientException.

ClientException.

Client error: GET http://127.0.0.1:8081/v1/admin resulted in a 401
  Unauthorized response: {"error":"Unauthorized.","code":401}

I have tried to make network request to the same internal services using postman; and it works fine. However, for some reason still fail to work with GuzzleHttp. I don't know what i am doing wrong. Please your assist will be appreciated.

Here is the httpClient.php in ApiGateway.

//Constructor method
public function __construct() {
    $this->baseUri = config('services.auth_admin.base_uri');
}

public function httpRequest($method, $requestUrl, $formParams = [], $headers = []) {
    //Instantiate the GazzleHttp Client
    $client = new Client([
        'base_uri' => $this->baseUri,
    ]);
    //Send the request
    $response = $client->request($method, $requestUrl, ['form_params' => $formParams, 'headers' => $headers]);
    //Return a response
    return $response->getBody();
}

//Internal Service Communication in ApiGateway**
public function getAdmin($header) {
    return $this->httpRequest('GET', 'admin', $header);
}

InternalServiceController.php

   public function getAdmin(Request $request) {
        return $this->successResponse($this->authAdminService->getAdmin($request->header()));
    }

I am using Lumen version: 5.8 and GuzzleHttp Version: 6.3

Body:
You pass your headers as formParams (third index instead of fourth).

Try below:

return $this->httpRequest('GET', 'admin', [], $header);


问:
Saving an image on top of another image in Swift
I am learning Swift and I am creating an app that uses a personal photo and puts another on top of it. I now have a hacky solution, to create a screenshot of the area and save it. I need to do this in Swift

```<code>@IBAction func saveImage(sender: AnyObject) {
    //Create the UIImage
    UIGraphicsBeginImageContext(imageView.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
</code>```

But, this was working and isn't anymore. But, this is also not the best solution.

So guys, how can I save an image to the camera roll from a personal image, with an image as overlay?

Help would be greatly appreciated!! Thanks!

答:
Apple advises against UIGraphicsBeginImageContext, so as long as your app does not support devices older than iOS 10, then use something like this:

```<code>private func drawLogoIn(_ image: UIImage, _ logo: UIImage, position: CGPoint) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: image.size)
    return renderer.image { context in
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        logo.draw(in: CGRect(origin: position, size: logo.size))
    }
}
</code>```

Besides performance gains, you get full P3 range.

Body:
I am learning Swift and I am creating an app that uses a personal photo and puts another on top of it. I now have a hacky solution, to create a screenshot of the area and save it. I need to do this in Swift

@IBAction func saveImage(sender: AnyObject) {
    //Create the UIImage
    UIGraphicsBeginImageContext(imageView.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

But, this was working and isn't anymore. But, this is also not the best solution.

So guys, how can I save an image to the camera roll from a personal image, with an image as overlay?

Help would be greatly appreciated!! Thanks!

Body:
Apple advises against UIGraphicsBeginImageContext, so as long as your app does not support devices older than iOS 10, then use something like this:

private func drawLogoIn(_ image: UIImage, _ logo: UIImage, position: CGPoint) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: image.size)
    return renderer.image { context in
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        logo.draw(in: CGRect(origin: position, size: logo.size))
    }
}

Besides performance gains, you get full P3 range.


问:
strptime string to datetime object conversion
I have a Python2.7 script with a variable date= "21/05/2019" that works fine.
I need the date variable to be datetime.now - 60 days.

However the output must be like time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=-1)

datetime.datetime.now() with strptime won't work.

```<code>import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date
</code>```

I expect to be able to use datetime.datetime.today() - datetime.timedelta(days=N) but the output to be a datetime object.

Edit:

It looks like I haven't explained myself very well. Sorry about that.

The script is:

```<code>import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date
</code>```

Output:

```<code>time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)
</code>```

Script using datetime.now - datetime.timedelta:

```<code>import datetime, time
from datetime import timedelta

N = 60
pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)

print pre_create_date
</code>```

Output:

```<code>2019-03-31 21:09:25.183459
</code>```

Expected output:

```<code>time.struct_time(tm_year=2019, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)
</code>```

答:
When using
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

You are creating a time.struct_time object.

Use datetime.datetime.strptime("28/04/2019", "%d/%m/%Y") instead and I think you'll get what you aim for

Body:
I have a Python2.7 script with a variable date= "21/05/2019" that works fine.
I need the date variable to be datetime.now - 60 days.

However the output must be like time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=-1)

datetime.datetime.now() with strptime won't work.

import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date

I expect to be able to use datetime.datetime.today() - datetime.timedelta(days=N) but the output to be a datetime object.

Edit:

It looks like I haven't explained myself very well. Sorry about that.

The script is:

import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date

Output:

time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)

Script using datetime.now - datetime.timedelta:

import datetime, time
from datetime import timedelta

N = 60
pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)

print pre_create_date

Output:

2019-03-31 21:09:25.183459

Expected output:

time.struct_time(tm_year=2019, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)


问:
How to make serialization run in parallel
guys,
If I have a tree structure, and I want to serialize the tree and sub nodes. how to do the serialization for each nodes in parallel.
If I assign each node with a independent task, the output data will be disordered.
Is there some pattern for concurrent serialization?

Edit: If the structure is not a tree, but a DAG? How to handle this structure? How to serialize DAG and make the serialization to be concurrent.

答:
From your very brief description it's not clear what constraints you have so I'll answer generally.

If you want to process nodes in a tree in parallel while you want to keep the result of the processing ordered, you could do something like this.

Give each node a number 1-N in the order you want to have the result.

Give the nodes together with the assigned number to some "machinery" which can process things in parallel. Many options here how to do things.

Wait until all finishes and then sort the results based on the assigned number.

Here the ordering is kept by keeping the number given in #1 through the whole chain.

Step #2 could be a threadpool-backed class you just add items (number-node pairs) into.

ContentLicense: CC BY-SA 3.0


问:
Error inflating class android.support.design.widget.AppBarLayout
I tried to create a game show the pictures and list of character name it. But when I run the app, it keeps crashing and show the error:

Error inflating class android.support.design.widget.AppBarLayout.

Here is the log:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.user.celebguess, PID: 3166
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.celebguess/com.example.user.celebguess.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.AppBarLayout
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                  at android.os.Handler.dispatchMessage(Handler.java:105)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6541)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
               Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.AppBarLayout
               Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.AppBarLayout
               Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout" on path: DexPathList[[zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/base.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/lib/x86, /system/lib, /vendor/lib]]
                  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
                  at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
                  at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                  at android.view.LayoutInflater.createView(LayoutInflater.java:606)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                  at com.example.user.celebguess.MainActivity.onCreate(MainActivity.java:36)
                  at android.app.Activity.performCreate(Activity.java:6975)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                  at android.os.Handler.dispatchMessage(Handler.java:105)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6541)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

Here is the activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.user.celebguess.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />
/>
</code>```

Also here is the styles.xml:

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

Also here is the main_activity.java for the Java part:

```<code>import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

private GridView gridView;
private SharedPreferences preferences;
private ArrayAdapter<String> names;
private Toast currentToast;
private ImageView img;
private int numberOfChoice;
private ArrayList<String> nameList;
private ArrayList<Integer> photos;
private ArrayList<String> nameForChoose;
private Map<String,Integer> nameMap;
private int currentPicNumber;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

@Override
protected void onStart() {
    super.onStart();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    int orientation = getResources().getConfiguration().orientation;
    if(orientation== Configuration.ORIENTATION_PORTRAIT) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        Intent intent = new Intent(this,Settings.class);
        startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}
</code>```

答:
Add below to bulid.gradle:app module :

```<code>implementation 'com.android.support:design:28.0.0'
</code>```

Body:
I tried to create a game show the pictures and list of character name it. But when I run the app, it keeps crashing and show the error:

Error inflating class android.support.design.widget.AppBarLayout.

Here is the log:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.user.celebguess, PID: 3166
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.celebguess/com.example.user.celebguess.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.AppBarLayout
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                  at android.os.Handler.dispatchMessage(Handler.java:105)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6541)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
               Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.AppBarLayout
               Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.AppBarLayout
               Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout" on path: DexPathList[[zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/base.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.user.celebguess-t-FEyHBoSS08L3kZz9tsZg==/lib/x86, /system/lib, /vendor/lib]]
                  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
                  at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
                  at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                  at android.view.LayoutInflater.createView(LayoutInflater.java:606)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                  at com.example.user.celebguess.MainActivity.onCreate(MainActivity.java:36)
                  at android.app.Activity.performCreate(Activity.java:6975)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                  at android.os.Handler.dispatchMessage(Handler.java:105)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6541)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Here is the activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.user.celebguess.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />
/>

Also here is the styles.xml:

<resources>

Body:
Add below to bulid.gradle:app module :

implementation 'com.android.support:design:28.0.0'


问:
Calendar week end days issue
I am getting a calendar instance

```<code>Calendar.getInstance()
</code>```

In one mobile it is showing Saturday as weekend while in another it is showing Sunday as weekend
The timezone of both devices is same

If i set the calendar instance locale to US or any other country it works perfectly.
But i dont want it to be constant. I want it to be regional but consistent on all devices

I want the weekend on both devices same if the time zone is same

答:
The first (and therefore also the last) day of the week varies by locale (not by time zone nor GMT offset). A locale may define a country or region and/or a language. The language isn’t relevant (at least usually not), but the country is. For example Pakistan:

```<code>    WeekFields wf = WeekFields.of(Locale.forLanguageTag("ur-PK"));
    System.out.println("Last day of week is " + wf.getFirstDayOfWeek().plus(6));
</code>```

Output is:

Last day of week is SATURDAY

Or United Arab Emirates, since you mentioned the Gulf (I assumed the Persian Gulf):

```<code>    WeekFields wf = WeekFields.of(Locale.forLanguageTag("ar-AE"));
</code>```

Last day of week is FRIDAY

To use the default locale, specify Locale.getDefault():

```<code>    WeekFields wf = WeekFields.of(Locale.getDefault());
</code>```

Since my locale is Denmark (Europe), I get Last day of week is SUNDAY now.

I am using the WeekFields class of java.time, the modern Java date and time API. The Calendar class that you are using is poorly designed and long outdated, and the modern API offers a richer functionality.

What happened?

Possible explanations for the behaviour you have observed include:

Your two devices have different country settings. I consider this the likely explanation. You have not told us the country setting of each device.

On at least one device the JVM does not respect the device locale setting. It is possible to start a JVM with a locale setting that differs from that of the underlying system (not that I know how to do that on Android). It is also possible to change the locale setting of the JVM dynamically through one of the Locale.setDefault methods.

Locale data have been changed between the Android versions of your devices, so for the country in question, one device thinks that the day starts on Sunday, on the other device Monday. Locale data are being updated all the time.

For getting the matter a little closer I would start by outputting Locale.getDefault().getDisplayCountry() on each device.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Title: Calendar week end days issue

Body:
I am getting a calendar instance

Calendar.getInstance()

In one mobile it is showing Saturday as weekend while in another it is showing Sunday as weekend
The timezone of both devices is same

If i set the calendar instance locale to US or any other country it works perfectly.
But i dont want it to be constant. I want it to be regional but consistent on all devices

I want the weekend on both devices same if the time zone is same

Body:
The first (and therefore also the last) day of the week varies by locale (not by time zone nor GMT offset). A locale may define a country or region and/or a language. The language isn’t relevant (at least usually not), but the country is. For example Pakistan:

    WeekFields wf = WeekFields.of(Locale.forLanguageTag("ur-PK"));
    System.out.println("Last day of week is " + wf.getFirstDayOfWeek().plus(6));

Output is:

Last day of week is SATURDAY

Or United Arab Emirates, since you mentioned the Gulf (I assumed the Persian Gulf):

    WeekFields wf = WeekFields.of(Locale.forLanguageTag("ar-AE"));

Last day of week is FRIDAY

To use the default locale, specify Locale.getDefault():

    WeekFields wf = WeekFields.of(Locale.getDefault());

Since my locale is Denmark (Europe), I get Last day of week is SUNDAY now.

I am using the WeekFields class of java.time, the modern Java date and time API. The Calendar class that you are using is poorly designed and long outdated, and the modern API offers a richer functionality.

What happened?

Possible explanations for the behaviour you have observed include:

Your two devices have different country settings. I consider this the likely explanation. You have not told us the country setting of each device.

On at least one device the JVM does not respect the device locale setting. It is possible to start a JVM with a locale setting that differs from that of the underlying system (not that I know how to do that on Android). It is also possible to change the locale setting of the JVM dynamically through one of the Locale.setDefault methods.

Locale data have been changed between the Android versions of your devices, so for the country in question, one device thinks that the day starts on Sunday, on the other device Monday. Locale data are being updated all the time.

For getting the matter a little closer I would start by outputting Locale.getDefault().getDisplayCountry() on each device.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


问:
Can't set TOP margin to buttonBarView using XLPagerTabStrip
I'm using the library XLPagerTabStrip extending on my Main ViewController of ButtonBarPagerTabStripViewController, and my problem comes that I can't add top margin to buttonBarView, it shows in top always. I need to add 64 top margin.

```<code>import UIKit
import XLPagerTabStrip

class MainVc : ButtonBarPagerTabStripViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
</code>```

Thanks all!

答:
navigationController?.navigationBar.isTranslucent = false
use this code

Solution:
in appdelegate

```<code>window?.rootViewController = UINavigationController(rootViewController: MainVc())
</code>```

the problem with you is you don't have navigationBar, so you need to pass this view from navigationController

Body:
I'm using the library XLPagerTabStrip extending on my Main ViewController of ButtonBarPagerTabStripViewController, and my problem comes that I can't add top margin to buttonBarView, it shows in top always. I need to add 64 top margin.

import UIKit
import XLPagerTabStrip

class MainVc : ButtonBarPagerTabStripViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Thanks all!

Body:
navigationController?.navigationBar.isTranslucent = false
use this code

Solution:
in appdelegate

window?.rootViewController = UINavigationController(rootViewController: MainVc())

the problem with you is you don't have navigationBar, so you need to pass this view from navigationController


问:
Docker Hub Registry cannot build docker image from Github repository
Since two days, i don't know why, i cannot build a docker image from Docker Hub Registry with linked github projects (it's working previously)

Many answers were about a github submodule
It was not my case.

Here are the logs

```<code>Building in Docker Cloud's infrastructure...
Cloning into '.'...
Warning: Permanently added the RSA host key for IP address '192.30.253.113' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
please ensure the correct public key is added to the list of trusted keys for this repository (128)
</code>```

I tried searching, I did not fall on the answers that not concerned me.

答:
After many hours of searching, I think found the answer.

I put here the answer, for those who would fall on the same problem.

It looks like Docker have changed is the name of his app. Rename from Docker Hub Registry to Docker Hub Builder

For repair it, so I cut the application link between Docker and Github. And re-create the link.

It added me an application for authorization in Github, the proof in image width Docker Hub Builder

Body:
Since two days, i don't know why, i cannot build a docker image from Docker Hub Registry with linked github projects (it's working previously)

Many answers were about a github submodule
It was not my case.

Here are the logs

Building in Docker Cloud's infrastructure...
Cloning into '.'...
Warning: Permanently added the RSA host key for IP address '192.30.253.113' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
please ensure the correct public key is added to the list of trusted keys for this repository (128)

I tried searching, I did not fall on the answers that not concerned me.


问:
Using dropdownlist in a View where datasource is from database table
I am writing code where a View is required that includes a dropdownlist enabling the user to select from list of values, these values are from a database table. The table is different from the data model used in the view.

The View allows only One data Model to be used. In my case I need at least 4 different tables to be used in different dropdownlist in the view.

I am using  Entity Framework database in ASP.NET Core 2.0 with C# code.

答:
You can use ViewBag to  pass your dropdownlist data-source as following e.g.
we get Types from DB and pass it to the view using ViewBag Value named Types
then bind it in our view.

```<code>public ActionResult Create()
{
     ViewBag.Types = new SelectList(db.Types.ToList(), "Id", "Name");

     return View();
}

@Html.DropDownListFor(model => model.Type, (SelectList)ViewBag.Types, new { @class = "form-control"})
</code>```

Body:
You can use ViewBag to  pass your dropdownlist data-source as following e.g.
we get Types from DB and pass it to the view using ViewBag Value named Types
then bind it in our view.

public ActionResult Create()
{
     ViewBag.Types = new SelectList(db.Types.ToList(), "Id", "Name");

     return View();
}

@Html.DropDownListFor(model => model.Type, (SelectList)ViewBag.Types, new { @class = "form-control"})


问:
i am webscraping with bs4 and the urls wont show up
i am new to webscaping and wanted to scape all the charackterportraits from the lol site and when i examined one of the pictures in the browser it was in a "img scr="url" tag and i want to get the url to download the picture but when i do soup.select('img[src]') or soup.select('img') it returns an empty list and i dont know why

here is the code:

```<code>data=requests.get(website)
data.raise_for_status()

soup = bs4.BeautifulSoup(data.text,"lxml")
print(soup)
#soup returns html

elems = soup.select('img[src]')
print(elems)
#elems returns an empty list
</code>```

答:
Use the same endpoint the page does. Find it in network tab</p>

```<code>import requests

base = 'https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/'
r = requests.get('https://ddragon.leagueoflegends.com/cdn/9.11.1/data/en_US/champion.json').json()
images = [base + r['data'][item]['image']['full'] for item in r['data']]
print(images)
</code>```

Body:
i am new to webscaping and wanted to scape all the charackterportraits from the lol site and when i examined one of the pictures in the browser it was in a "img scr="url" tag and i want to get the url to download the picture but when i do soup.select('img[src]') or soup.select('img') it returns an empty list and i dont know why

here is the code:

data=requests.get(website)
data.raise_for_status()

soup = bs4.BeautifulSoup(data.text,"lxml")
print(soup)
#soup returns html

elems = soup.select('img[src]')
print(elems)
#elems returns an empty list

Body:
Use the same endpoint the page does. Find it in network tab

import requests

base = 'https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/'
r = requests.get('https://ddragon.leagueoflegends.com/cdn/9.11.1/data/en_US/champion.json').json()
images = [base + r['data'][item]['image']['full'] for item in r['data']]
print(images)


问:
Open url in new tab based on data in service in Kendo Menu
I searched around number of posts, but haven't any solution applicable to my scenario. I am population kendo-menu dynamically using an array build via sql.

```<code><kendo-menu [items]="items"
            [vertical]="true"
            style="display:inline-block;">
</kendo-menu>
</code>```

This is the sample I am following:

https://www.telerik.com/kendo-angular-ui/components/menus/menu/vertical/

Here is how items array is structured:

```<code>export const items: any[] = [
  {
  text: 'Reportingd',
    items: [{ text: 'Dash', url: "https://www.google.com" },  {
    text: 'Realtime',
      items: [{ text: 'DesktopNew', url: "https://www.telerik.com" }, { text: 'laptop', url: "https://www.msn.com" }]
  }]
},
{
  text: 'Other Reporting',
  items: [{ text: 'Training', url: "https://www.msn.com" }, { text: 'UserManual', url: "https://www.msn.com" }, { text: 'Guide',
    items: }]
},
{
  text: 'Tools',
  items:[{ text: 'Training', url: "https://www.msn.com" }]
}];
</code>```

However, this on click of menu/sub-menu opens url in the same window. I want to open in different window or new tab. HTML  tag does not work here. Please suggest

```<code><a href="https://www.thesitewizard.com/" target="_blank">thesitewizard.com</a>
</code>```

答:
Write select event for kendo menu something like below.

```<code><kendo-menu [items]="items" (select)="onSelect($event)"></kendo-menu>
</code>```

After that in onSelect method use window.open method like below.

```<code>public onSelect({ item }): void {
        if (!item.items) {
            window.open([item.url], "_blank");
        }
    }
</code>```

Body:
I searched around number of posts, but haven't any solution applicable to my scenario. I am population kendo-menu dynamically using an array build via sql.

<kendo-menu [items]="items"
            [vertical]="true"
            style="display:inline-block;">
</kendo-menu>

This is the sample I am following:

https://www.telerik.com/kendo-angular-ui/components/menus/menu/vertical/

Here is how items array is structured:

export const items: any[] = [
  {
  text: 'Reportingd',
    items: [{ text: 'Dash', url: "https://www.google.com" },  {
    text: 'Realtime',
      items: [{ text: 'DesktopNew', url: "https://www.telerik.com" }, { text: 'laptop', url: "https://www.msn.com" }]
  }]
},
{
  text: 'Other Reporting',
  items: [{ text: 'Training', url: "https://www.msn.com" }, { text: 'UserManual', url: "https://www.msn.com" }, { text: 'Guide',
    items: }]
},
{
  text: 'Tools',
  items:[{ text: 'Training', url: "https://www.msn.com" }]
}];

However, this on click of menu/sub-menu opens url in the same window. I want to open in different window or new tab. HTML  tag does not work here. Please suggest

thesitewizard.com

Body:
Write select event for kendo menu something like below.

<kendo-menu [items]="items" (select)="onSelect($event)"></kendo-menu>

After that in onSelect method use window.open method like below.

public onSelect({ item }): void {
        if (!item.items) {
            window.open([item.url], "_blank");
        }
    }


问:
Session works only on one page in php
I set session variable for login of user but it doesn't work on another pages than login.php.

login.php:

```<code><?php
    session_start();

    if(isset($_POST['submit'])) {

        $conn = mysqli_connect('localhost', 'cp72722_lucky', '3AIp!9f4', 'cp72722_lucky');
        $user_username = mysqli_real_escape_string($conn, trim($_POST['username']));
        $user_password = mysqli_real_escape_string($conn, trim($_POST['password']));
        if(!empty($user_username) && !empty($user_password)) {

            $query = "SELECT user_id , username FROM users WHERE username = '$user_username' AND pwd = SHA('$user_password')";
            $data = mysqli_query($conn,$query);
            if(mysqli_num_rows($data) == 1) {

                $row = mysqli_fetch_assoc($data);
                $user_value = $row['username'];
                $user_id_value = $row['user_id'];
                $_SESSION['username'] = $user_value;
                $_SESSION['user_id'] = $user_id_value;
                echo "Hello," . $_SESSION['username'];
                $home_url = 'http://' . $_SERVER['SERVER_NAME'];
                header('Location: ' . $home_url);
                print_r($home_url);
                exit();
            }
            else {
                echo 'Извините, вы должны ввести правильные имя пользователя и пароль';
            }
        }
        else {
            echo 'Извините, вы должны заполнить поля правильно';
        }
    }

?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="style/style.css" rel="stylesheet">
</head>
<body>
<header>
<ul>
    <li><a href="/">Главная</a></li>

</ul>
</header>
<h2>Вход</h2>
<div class="container">
<form action="http://<?php echo $_SERVER['SERVER_NAME']; ?>" method="POST">
        <label for="username">Логин:</label>
    <input type="text" name="username">
    <label for="password">Пароль:</label>
    <input type="password" name="password">
    <button type="submit" name="submit">Вход</button>
    <a href="auth/signup.php">Регистрация</a>
    </form>
    </div>
<footer>
    <p>Все права защищены</p>
</footer>

</body>

</html>
</code>```

My header.php shows almost on all pages and I want to welcome the users after login. If the session is not set, then should display the form to login. Problem is, if the user is logged in and the profile links, it always displays second choice because session is not set. How do I resolve this issue?

header.php:

```<code><?php

session_start();

print_r($_SESSION);
?>
...
<header id="header">
    <?php
echo 'Glad to see you,'. htmlspecialchars($_SESSION['username']);
?>
...
<div>
<?php
    if(!isset($_SESSION['username'])) {
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <label for="username">Login:</label>
    <input type="text" name="username">
    <label for="password">Password:</label>
    <input type="password" name="password">
    <button type="submit" name="submit">Enter</button>
    <a href="auth/signup.php">Registration</a>
    </form>
<?php
}
else {
    ?>
    <p><a href="myprofile.php">Profile</a></p>
    <p><a href="exit.php">Exit(<?php echo $_SESSION['username']; ?>)</a></p>
<?php
}
?>
</div>
</code>```

答:
if($_SESSION['username']) means that $_SESSION['username'] is true. Instead, you should use an isset function to check if the session is set. Your code should look like this

```<code>if(!isset($_SESSION['username'])) {//If $_SESSION['username'] is not set then show the login form
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <label for="username">Login:</label>
    <input type="text" name="username">
    <label for="password">Password:</label>
    <input type="password" name="password">
    <button type="submit" name="submit">Enter</button>
    <a href="auth/signup.php">Registration</a>
    </form>
<?php
}
</code>```

Title: Session works only on one page in php

Body:
I set session variable for login of user but it doesn't work on another pages than login.php.

login.php:

<?php
    session_start();

    if(isset($_POST['submit'])) {

        $conn = mysqli_connect('localhost', 'cp72722_lucky', '3AIp!9f4', 'cp72722_lucky');
        $user_username = mysqli_real_escape_string($conn, trim($_POST['username']));
        $user_password = mysqli_real_escape_string($conn, trim($_POST['password']));
        if(!empty($user_username) && !empty($user_password)) {

            $query = "SELECT user_id , username FROM users WHERE username = '$user_username' AND pwd = SHA('$user_password')";
            $data = mysqli_query($conn,$query);
            if(mysqli_num_rows($data) == 1) {

                $row = mysqli_fetch_assoc($data);
                $user_value = $row['username'];
                $user_id_value = $row['user_id'];
                $_SESSION['username'] = $user_value;
                $_SESSION['user_id'] = $user_id_value;
                echo "Hello," . $_SESSION['username'];
                $home_url = 'http://' . $_SERVER['SERVER_NAME'];
                header('Location: ' . $home_url);
                print_r($home_url);
                exit();
            }
            else {
                echo 'Извините, вы должны ввести правильные имя пользователя и пароль';
            }
        }
        else {
            echo 'Извините, вы должны заполнить поля правильно';
        }
    }

?>
<!DOCTYPE html>

<meta charset="utf-8">
<link href="style/style.css" rel="stylesheet">

Главная

Вход

<form action="http://<?php echo $_SERVER['SERVER_NAME']; ?>" method="POST">
        Логин:
    <input type="text" name="username">
    Пароль:
    <input type="password" name="password">
    <button type="submit" name="submit">Вход</button>
    Регистрация
    </form>

Все права защищены

My header.php shows almost on all pages and I want to welcome the users after login. If the session is not set, then should display the form to login. Problem is, if the user is logged in and the profile links, it always displays second choice because session is not set. How do I resolve this issue?

header.php:

<?php

session_start();

print_r($_SESSION);
?>
...

    <?php
echo 'Glad to see you,'. htmlspecialchars($_SESSION['username']);
?>
...

<?php
    if(!isset($_SESSION['username'])) {
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        Login:
    <input type="text" name="username">
    Password:
    <input type="password" name="password">
    <button type="submit" name="submit">Enter</button>
    Registration
    </form>
<?php
}
else {
    ?>

Profile

Exit(<?php echo $_SESSION['username']; ?>)

<?php
}
?>

Body:
if($_SESSION['username']) means that $_SESSION['username'] is true. Instead, you should use an isset function to check if the session is set. Your code should look like this

if(!isset($_SESSION['username'])) {//If $_SESSION['username'] is not set then show the login form
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <label for="username">Login:</label>
    <input type="text" name="username">
    <label for="password">Password:</label>
    <input type="password" name="password">
    <button type="submit" name="submit">Enter</button>
    <a href="auth/signup.php">Registration</a>
    </form>
<?php
}


问:
What output and recording ports does the Java Sound API find on your computer?
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

```<code>import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}
</code>```

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

```
Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
```

答:
```OS: Windows XP 5.1/x86
Java: 1.6.0_12 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [VIA AC'97 Audio (WAVE)]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [VIA AC'97 Audio (WAVE)]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port VIA AC'97 Audio (WAVE)]
  Port: Stereo Mixer source port
    Control: Stereo Mixer (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Port: MICROPHONE source port
    Control: Mic (compound - values below)
      Control: Select (boolean)
      Control: Mic2 Select (boolean)
      Control: 20dB boost (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Port: LINE\_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Port: COMPACT\_DISC source port
    Control: CD Player (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Port: Video source port
    Control: Video (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Port: Aux source port
    Control: Aux (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)```

OwnerDisplayName: Dave Carpeneto

Body:
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)

LastEditorDisplayName: sqook

OwnerDisplayName: anoterUser

ContentLicense: CC BY-SA 2.5


问:
Bootstrap is not working even though included
Hi Guys I have a problem about bootstrap bootstrap.min.css  jquery.min.js and   bootstrap.min.js are already included in my project but I cannot use well well-sm class and when I add manually by links this time divs engage you can see in the picture. where is the problem I don't understand?

my code :

```<code>@model xx.Web.Models.MiniRepairViewModel
@{
    Layout = null;
}
<div class="pageWrapper">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    @Html.Action("Breadcrumb", "Manage")
    <div class="TextBody">
        <div class="container">
            @Html.Action("LeftMenu", "Manage") //menu engage
            <div class="col-threeQuarters">
     @using (Ajax.BeginForm("MiniRepairServiceAdd", "Ajax", new AjaxOptions { OnSuccess = "jsFilt", OnFailure = "OnFailure" }))
                {
                    <ul class="Form">
                        <li class="oneColumsFull">
                            @Html.DropDownListFor(x => x.GetCityModel.a, (IEnumerable<SelectListItem>)ViewBag.CitiesList, "select", new { name = "x", id = "y" })
                        </li>
                        <li id="ilce" class="twoColumsFull" style="display:none;">
                        </li>
                        <li class="oneColums"><input type="text" name="serviceName" id="serviceName" placeholder="Service"></li>

                        <li class="button"><input class=".bh-sl-reset" id="reset" type="button" value="clear" onclick="javascript: window.location.reload();"></li>
                        <li class="button"><input type="submit" value="search" name="search"></li>
                    </ul>
                }
                <div id="myDiv" class="well well-sm"> </div> //not working
            </div>
        </div>
    </div>
</div>
</code>```

答:
You Need to include headtag before Bodytag and add the bootstrap cdn in that head and write you js cdn at bottom of body tag.
SO the code structure will be like this</p>

```<code><html>
<head>
<bootstrap cdn>
</head>
<body>
your content
...
..
<js cdns>
</body>
</html>
</code>```

Body:
Hi Guys I have a problem about bootstrap bootstrap.min.css  jquery.min.js and   bootstrap.min.js are already included in my project but I cannot use well well-sm class and when I add manually by links this time divs engage you can see in the picture. where is the problem I don't understand?

my code :

@model xx.Web.Models.MiniRepairViewModel
@{
    Layout = null;
}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    @Html.Action("Breadcrumb", "Manage")

            @Html.Action("LeftMenu", "Manage") //menu engage

     @using (Ajax.BeginForm("MiniRepairServiceAdd", "Ajax", new AjaxOptions { OnSuccess = "jsFilt", OnFailure = "OnFailure" }))
                {

                            @Html.DropDownListFor(x => x.GetCityModel.a, (IEnumerable<SelectListItem>)ViewBag.CitiesList, "select", new { name = "x", id = "y" })

<input type="text" name="serviceName" id="serviceName" placeholder="Service">

<input class=".bh-sl-reset" id="reset" type="button" value="clear" onclick="javascript: window.location.reload();">

<input type="submit" value="search" name="search">

                }

 //not working

Body:
You Need to include headtag before Bodytag and add the bootstrap cdn in that head and write you js cdn at bottom of body tag.
SO the code structure will be like this

<html>
<head>
<bootstrap cdn>
</head>
<body>
your content
...
..
<js cdns>
</body>
</html>


问:
how to fix django-db-mailer SMS API language argument changing the language of the application
when we are applying language='ar' kwargs to the send_db_sms() API it will change the Language of the entire web application.

```<code>from dbmail import send_db_sms
send_db_sms(
    # slug which defined on db template
    slug='welcome',

    # recipient can be list, or str separated with comma or simple
    # string
    recipient='+79031234567',

    # All *args params will be accessible on template context
    {
        'username': request.user.username,
        'full_name': request.user.get_full_name(),
        'signup_date': request.user.date_joined
    },

    # Optional kwargs:

    language='ar',
    )
</code>```

by giving language='ar',kwargs to the send_db_sms() function, it should not change the language of the entire web application.

Please help,

答:
Ideally, it should not happen.

It may possible that you have defined the language variable outside the function too and it is overriding all the variables. Please check that you haven't used it anywhere else.

Apart from that, you can have a default language for your application outside of this function so, outside this function your app will consider that default language.

Hope this helps.

Body:
when we are applying language='ar' kwargs to the send_db_sms() API it will change the Language of the entire web application.

from dbmail import send_db_sms
send_db_sms(
    # slug which defined on db template
    slug='welcome',

    # recipient can be list, or str separated with comma or simple
    # string
    recipient='+79031234567',

    # All *args params will be accessible on template context
    {
        'username': request.user.username,
        'full_name': request.user.get_full_name(),
        'signup_date': request.user.date_joined
    },

    # Optional kwargs:

    language='ar',
    )

by giving language='ar',kwargs to the send_db_sms() function, it should not change the language of the entire web application.

Please help,


问:
Select data where condition matches and if none, then select all?

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id
```

<p>scenario1:
     @id = 'user1'</p>

```dept1
```

<p>scenario2:
    @id = 'user5'</p>

```dept1
dept2
dept3
dept4
```

<p>this is what it looks like from a noobish query</p>

<pre class="lang-sql prettyprint-override"><code>declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0
</code>```

答:
```<code>DECLARE @id VARCHAR(5) = 'user1';
--DECLARE @id VARCHAR(5) = 'user5';
  WITH  UsersAndDepartments
AS ( SELECT   *
    FROM     ( VALUES ( 'dept1', 'user1'), ( 'dept2', 'user2'),
            ( 'dept3', 'user3'), ( 'dept4', 'user4') ) x ( [department], [user] )
    )
SELECT  *
FROM    UsersAndDepartments ud1
WHERE   ud1.[user] =
    CASE
        WHEN EXISTS ( SELECT 1 FROM UsersAndDepartments ud2 WHERE ud2.[user] = @id ) THEN @id
        ELSE ud1.[user]
    END
</code>```

The above just checks on user column if any row exists for an id, else matches on all.

Body:
select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

scenario1:
     @id = 'user1'

dept1

scenario2:
    @id = 'user5'

dept1
dept2
dept3
dept4

this is what it looks like from a noobish query

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0

Body:
DECLARE @id VARCHAR(5) = 'user1';
--DECLARE @id VARCHAR(5) = 'user5';
  WITH  UsersAndDepartments
AS ( SELECT   *
    FROM     ( VALUES ( 'dept1', 'user1'), ( 'dept2', 'user2'),
            ( 'dept3', 'user3'), ( 'dept4', 'user4') ) x ( [department], [user] )
    )
SELECT  *
FROM    UsersAndDepartments ud1
WHERE   ud1.[user] =
    CASE
        WHEN EXISTS ( SELECT 1 FROM UsersAndDepartments ud2 WHERE ud2.[user] = @id ) THEN @id
        ELSE ud1.[user]
    END

The above just checks on user column if any row exists for an id, else matches on all.


问:
React Helmet not updating meta title tag
I've been setting my react.js SPA's page titles by doing:

```<code>document.title = {some title}
</code>```

...so far and it worked fine. Now, I also wanted to update the meta title tag and so I installed react-helmet.

In my component, I've imported Helmet from the library and did:

```<code>render() {
  {/* ... */}
  return (
    <div>
      <Helmet>
        <title>{docTitle}</title>
        <meta name="title" content={docTitle} />
      </Helmet>
      {/* ... */}
    </div>
  )
}
</code>```

When opening the page, I saw that the document title is properly updated, but when inspecting the elements in the browser, I noticed that <meta name="title" is not being updated, while a few lines down, <title> is updated.

What am I doing wrong here?

答:
In my  code, I added the following tag in the index.html file:

```<code><meta name="title" content="Default Title">
</code>```

When updating that meta tag using react-helmet, I still saw that tag un-updated in the index.html file when inspecting the elements in my browser.

However, what I did not notice, is that at the very bottom of the , Helmet apparently added this tag instead:

```<code><meta name="title" content="Default Title" data-react-helmet="true">
</code>```

I'm guessing (and hoping) that this will be crawled by search engine bots.

Update:

After some time has passed, I can verify that Facebook and Google properly read helmet's title tag.

Body:
I've been setting my react.js SPA's page titles by doing:

document.title = {some title}

...so far and it worked fine. Now, I also wanted to update the meta title tag and so I installed react-helmet.

In my component, I've imported Helmet from the library and did:

render() {
  {/* ... */}
  return (

      <Helmet>
        <title>{docTitle}</title>
        <meta name="title" content={docTitle} />
      </Helmet>
      {/* ... */}

  )
}

When opening the page, I saw that the document title is properly updated, but when inspecting the elements in the browser, I noticed that <meta name="title" is not being updated, while a few lines down, <title> is updated.

What am I doing wrong here?

Body:
In my <head> code, I added the following tag in the index.html file:

<meta name="title" content="Default Title">

When updating that meta tag using react-helmet, I still saw that tag un-updated in the index.html file when inspecting the elements in my browser.

However, what I did not notice, is that at the very bottom of the <head>, Helmet apparently added this tag instead:

<meta name="title" content="Default Title" data-react-helmet="true">

I'm guessing (and hoping) that this will be crawled by search engine bots.

Update:

After some time has passed, I can verify that Facebook and Google properly read helmet's title tag.


问:
How do i get a function to repeat its self without generating an exit code 0?
I made a simple dice roller  with a for-in loop that takes 2 pieces of input, the number of dice and the number of sides of the dice.  When the roll is made the results are printed to the screen.

After the initial roll is made I'd like to have the code begin again, with new inputs, with out generating an exit code 0.

##Original design obviously does not loop
from random import randint
import time
dice = int(input("\nHow many dice?\n   "))
sides = int(input("How many sides?\n   "))

def roll():
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

roll()
```

<p>I moved the <code>input</code> variables from a <code>global scope</code> to a <code>local scope</code> so they can be updated with each repetition.  When ending the <code>function</code> by calling the <code>function</code>, I achieve some success.  I am able to <code>loop</code> the process endlessly without generating an <code>exit code 0</code> but any number of dice beyond <code>1</code> does not seem to register.  I can only roll one dice at a time this way.</p>

<pre class="lang-py prettyprint-override"><code>##Design 2 does not generate any exit codes and continues to loop
##endlessly but will not register more than 1 dice
from random import randint
import time

def roll():
    dice = int(input("\nHow many dice?\n   "))
    sides = int(input("How many sides?\n   "))
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))
        roll()

roll()
</code>```

I've changed the function so that it does not end by calling itself.  Instead I created a new function that does nothing but call the first.  I've placed the redundant function after the first and have been able to successfully achieve my goal of rolling any number of sided dice as I please... twice.  After two iterations/cycles this generates an exit code 0

##Current design will register all input data correctly
##but only loops 2 times before generating an `exit code 0`
from random import randint
import time

def roll():
    dice = int(input("\nHow many dice?\n   "))
    sides = int(input("How many sides?\n   "))
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

def roll_again():
    roll()

roll()
roll_again()
```

Anyone know what I'm doing wrong?

答:
You need to place the game logic inside a while loop; enter zero dices to exit when you are done playing.</p>

```<code>from random import randint
import time

def roll():
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

while True:
    dice = int(input("\nHow many dice? (zero to stop)\n   "))
    if dice == 0:
        break
    sides = int(input("How many sides?\n   "))
    roll()
</code>```

Body:
I made a simple dice roller  with a for-in loop that takes 2 pieces of input, the number of dice and the number of sides of the dice.  When the roll is made the results are printed to the screen.

After the initial roll is made I'd like to have the code begin again, with new inputs, with out generating an exit code 0.

##Original design obviously does not loop
from random import randint
import time
dice = int(input("\nHow many dice?\n   "))
sides = int(input("How many sides?\n   "))

def roll():
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

roll()

I moved the input variables from a global scope to a local scope so they can be updated with each repetition.  When ending the function by calling the function, I achieve some success.  I am able to loop the process endlessly without generating an exit code 0 but any number of dice beyond 1 does not seem to register.  I can only roll one dice at a time this way.

##Design 2 does not generate any exit codes and continues to loop
##endlessly but will not register more than 1 dice
from random import randint
import time

def roll():
    dice = int(input("\nHow many dice?\n   "))
    sides = int(input("How many sides?\n   "))
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))
        roll()

roll()

I've changed the function so that it does not end by calling itself.  Instead I created a new function that does nothing but call the first.  I've placed the redundant function after the first and have been able to successfully achieve my goal of rolling any number of sided dice as I please... twice.  After two iterations/cycles this generates an exit code 0

##Current design will register all input data correctly
##but only loops 2 times before generating an `exit code 0`
from random import randint
import time

def roll():
    dice = int(input("\nHow many dice?\n   "))
    sides = int(input("How many sides?\n   "))
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

def roll_again():
    roll()

roll()
roll_again()

Anyone know what I'm doing wrong?

Body:
You need to place the game logic inside a while loop; enter zero dices to exit when you are done playing.

from random import randint
import time

def roll():
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

while True:
    dice = int(input("\nHow many dice? (zero to stop)\n   "))
    if dice == 0:
        break
    sides = int(input("How many sides?\n   "))
    roll()


问:
how to add binary file to buildroot generated image?
How can i include a pre-built binary file into buildroot generated image?

I have tried to include the binary file into appropriate folder in build_dir but every time i try to do make the image is being created without the file.

答:
You can use a root filesystem overlay.

See chapter Project-specific customization in the Buildroot manual.


问:
FAILURE: Build failed with an exception in ionic 4
I have created an app called phone(ionic v-4). I have tried to implement Phone authentication i,e OTP verification using firebase by following this article   in the medium.

Now i tried to deploy my app(phone) in my android device, using below command.

```<code>ionic cordova run android
</code>```

I am getting this error:

But the app runs fine in the browser.

I am unable to perceive the error.

答:
Do this:

```<code> ionic cordova plugin rm cordova-plugin-firebase

 ionic cordova plugin add https://github.com/dpa99c/cordova-plugin-firebase#GH-1057-April-05-android-build-issue
</code>```

and see this link

Ionic build issue -firebase

Body:
I have created an app called phone(ionic v-4). I have tried to implement Phone authentication i,e OTP verification using firebase by following this article   in the medium.

Now i tried to deploy my app(phone) in my android device, using below command.

ionic cordova run android

I am getting this error:

But the app runs fine in the browser.

I am unable to perceive the error.

Body:
Do this:

 ionic cordova plugin rm cordova-plugin-firebase

 ionic cordova plugin add https://github.com/dpa99c/cordova-plugin-firebase#GH-1057-April-05-android-build-issue

and see this link

Ionic build issue -firebase


问:
C# How to terminate a click-event handler with another click-event
I have a click-event handler to a button that forms an ssh connection. I want to terminate this function with another "cancel" button click.

However, when executing an event handler, "cancel" click event handler doesn't run while the first handler executing. I want to override the first handler with "cancel" handler.

private void button_sshconnection_Click(object sender, EventArgs e)
        { /* some code to create ssh connection */ }

private void button_cancel_Click(object sender, EventArgs e)
        { /* some code to terminate button_sshconnection_Click */ }

```

I tried a code-structure like the above code but as I said second function doesnt run while the first function running. If the structure is wrong, can someone tell me how to do this job.

Thanks in advance,

Onur

答:
You can try implementing async version of your routine, e.g.

```<code>   private CancellationTokenSource m_Cancellation;

   private async void button_sshconnection_Click(object sender, EventArgs e) {
     // if method is executing, do nothing. Alternative: cancel and start again
     if (m_Cancellation != null)
       return;

     try {
       using (m_Cancellation = new CancellationTokenSource()) {
         var token = m_Cancellation.Token;

         await Task.Run(() => {
           //TODO: implement your logic here, please, note that cancellation is cooperative
           // that's why you should check token.IsCancellationRequested

         }, token);
       }
     }
     finally {
       m_Cancellation = null;
     }
   }

   private void button_cancel_Click(object sender, EventArgs e) {
     // If we can cancel, do it
     m_Cancellation?.Cancel();
   }
</code>```

Body:
I have a click-event handler to a button that forms an ssh connection. I want to terminate this function with another "cancel" button click.

However, when executing an event handler, "cancel" click event handler doesn't run while the first handler executing. I want to override the first handler with "cancel" handler.

private void button_sshconnection_Click(object sender, EventArgs e)
        { /* some code to create ssh connection */ }

private void button_cancel_Click(object sender, EventArgs e)
        { /* some code to terminate button_sshconnection_Click */ }

I tried a code-structure like the above code but as I said second function doesnt run while the first function running. If the structure is wrong, can someone tell me how to do this job.

Thanks in advance,

Onur

Body:
You can try implementing async version of your routine, e.g.

   private CancellationTokenSource m_Cancellation;

   private async void button_sshconnection_Click(object sender, EventArgs e) {
     // if method is executing, do nothing. Alternative: cancel and start again
     if (m_Cancellation != null)
       return;

     try {
       using (m_Cancellation = new CancellationTokenSource()) {
         var token = m_Cancellation.Token;

         await Task.Run(() => {
           //TODO: implement your logic here, please, note that cancellation is cooperative
           // that's why you should check token.IsCancellationRequested

         }, token);
       }
     }
     finally {
       m_Cancellation = null;
     }
   }

   private void button_cancel_Click(object sender, EventArgs e) {
     // If we can cancel, do it
     m_Cancellation?.Cancel();
   }


问:
How to trim only white space but not \n in Java
I have a string like

String str = " hello world\n "

when I call str.trim(),
it returns

"hello world"

However, I need the string looks like

"hello world\n"

How could I do it for only remove leading and trailing white space in a string?

答:
You can replace all \n character with \\n. then trim it. after trimming replace '\\n' with \n

```<code>String str = " hello world\n ";
str=str.replace("\n", "\\n");          // replace '\n' with '\\n'

System.out.println(str);

str=str.trim();                       // trim it
System.out.println(str);

str=str.replace("\\n", "\n");          // reverse it
System.out.println(str);

System.out.println("end");            // to see new line
</code>```

Output:

```<code> hello world

 hello world\n
hello world\n
hello world

end
</code>```

Body:
You can replace all \n character with \\n. then trim it. after trimming replace '\\n' with \n

String str = " hello world\n ";
str=str.replace("\n", "\\n");          // replace '\n' with '\\n'

System.out.println(str);

str=str.trim();                       // trim it
System.out.println(str);

str=str.replace("\\n", "\n");          // reverse it
System.out.println(str);

System.out.println("end");            // to see new line

Output:

 hello world

 hello world\n
hello world\n
hello world

end


问:
How do you write a image to browser as a binary stream in coldfusion?
I have a service on a Coldfusion 9 server that creates image banners on the fly for us. A separate machine has to save these files with something like:

```<code>wget http://myserver.com/services/local/bannerCreator/250x250-v3.cfm?prodID=3&percentSaving=19
</code>```

The problem is that I can't think of how to get coldfusion to write out binary data without using a temporary file. At the minute the image is just displayed as an image tag like this:

```<code><cfimage action = "writeToBrowser" source="#banner#" width="#banner.width#" height="#banner.height#" />
</code>```

Any ideas? Or should I just use a temporary file?

答:
Take out the height and width attributes and add the format attribute:

```<code><cfimage action = "writeToBrowser" source="#banner#" format="png" />
</code>```

wget should honor the redirection to the physical file CF creates in the CFFileServlet folder but if it doesn't there is a flag you can set to make it --max-redirect=10.

And as you suggest, a temporary file would work too. Just write the file and use cfheader and cfcontent to write it out. Just make sure to make the temp file name more unique.

```<code><cfimage action="write" destination="tempfile.png" source="#banner#" format="png" />
<cfheader name="content-disposition" value="attachment; filename=banner.png" />
<cfcontent file="tempfile.png" deletefile="true" type="image/png" />
</code>```

Body:
I have a service on a Coldfusion 9 server that creates image banners on the fly for us. A separate machine has to save these files with something like:

wget http://myserver.com/services/local/bannerCreator/250x250-v3.cfm?prodID=3&percentSaving=19

The problem is that I can't think of how to get coldfusion to write out binary data without using a temporary file. At the minute the image is just displayed as an image tag like this:

<cfimage action = "writeToBrowser" source="#banner#" width="#banner.width#" height="#banner.height#" />

Any ideas? Or should I just use a temporary file?

Body:
Take out the height and width attributes and add the format attribute:

<cfimage action = "writeToBrowser" source="#banner#" format="png" />

wget should honor the redirection to the physical file CF creates in the CFFileServlet folder but if it doesn't there is a flag you can set to make it --max-redirect=10.

And as you suggest, a temporary file would work too. Just write the file and use cfheader and cfcontent to write it out. Just make sure to make the temp file name more unique.

<cfimage action="write" destination="tempfile.png" source="#banner#" format="png" />
<cfheader name="content-disposition" value="attachment; filename=banner.png" />
<cfcontent file="tempfile.png" deletefile="true" type="image/png" />


问:
In Jolt how to modified the keys of out put json and copy values from input
In Nifi I want to copy all input values to output which has modified keys compared to input.

Input:

```<code>{
    "test": {
    "name":"John",
    "salary":"2500.145263"
    }
}
</code>```

Output:

```<code>{
    "company": {
    "fn":"JOHN",
    "sl":"2500.14"
    }
}
</code>```

Here I want to make the name uppercase and salary rounded off to two decimal places.

答:
You can use the ExecuteScript processor to do the conversions and write your own piece of code. </p>

<p>I have used ECMA script for this, but there are other options too. </p>

```<code>    var StreamCallback = Java.type("org.apache.nifi.processor.io.StreamCallback");
    var IOUtils = Java.type("org.apache.commons.io.IOUtils");
    var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
    var flowFile = session.get();
    var obj = {};
    var strname = ""
    var strupper = ""
    var queryjson = {};
var sal

if (flowFile != null) {
    // Create a new StreamCallback, passing in a function to define the interface method
    try {
        flowFile = session.write(flowFile,
            new StreamCallback(
                function (inputStream, outputStream) {
                    var text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)

                    obj = JSON.parse(text)

                    obj.company = obj.test

                     strname = obj.test.name
                    strupper = strname.toUpperCase()
                    obj.company.fn = strupper

                    sal = parseFloat(obj.test.salary).toFixed(2)
                    obj.company.sl = sal

                    delete obj.test.name
                    delete obj.test.salary
                    delete obj.test

                    outputStream.write(JSON.stringify(obj).getBytes(StandardCharsets.UTF_8))
                }
            )
        );

        session.transfer(flowFile, REL_SUCCESS)
    }
    catch (e) {
        flowFile = session.putAttribute(flowFile, 'error', e);
        session.transfer(flowFile, REL_FAILURE)
    }
}
</code>```

Body:
In Nifi I want to copy all input values to output which has modified keys compared to input.

Input:

{
    "test": {
    "name":"John",
    "salary":"2500.145263"
    }
}

Output:

{
    "company": {
    "fn":"JOHN",
    "sl":"2500.14"
    }
}

Here I want to make the name uppercase and salary rounded off to two decimal places.

Body:
You can use the ExecuteScript processor to do the conversions and write your own piece of code.

I have used ECMA script for this, but there are other options too.

    var StreamCallback = Java.type("org.apache.nifi.processor.io.StreamCallback");
    var IOUtils = Java.type("org.apache.commons.io.IOUtils");
    var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
    var flowFile = session.get();
    var obj = {};
    var strname = ""
    var strupper = ""
    var queryjson = {};
var sal

if (flowFile != null) {
    // Create a new StreamCallback, passing in a function to define the interface method
    try {
        flowFile = session.write(flowFile,
            new StreamCallback(
                function (inputStream, outputStream) {
                    var text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)

                    obj = JSON.parse(text)

                    obj.company = obj.test

                     strname = obj.test.name
                    strupper = strname.toUpperCase()
                    obj.company.fn = strupper

                    sal = parseFloat(obj.test.salary).toFixed(2)
                    obj.company.sl = sal

                    delete obj.test.name
                    delete obj.test.salary
                    delete obj.test

                    outputStream.write(JSON.stringify(obj).getBytes(StandardCharsets.UTF_8))
                }
            )
        );

        session.transfer(flowFile, REL_SUCCESS)
    }
    catch (e) {
        flowFile = session.putAttribute(flowFile, 'error', e);
        session.transfer(flowFile, REL_FAILURE)
    }
}


问:
what is the advantage of map over heap in c++
currently i am doing problem on data structure and i have a question in which i have to find kth largest element in an array. the actual problem is here:
https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/.

i did this question in two different way using heap and second is using map.

my solution using map.

```<code>   int t;
cin>>t;
while(--t>=0){
int n,k;
cin>>n;
vector<int> A(n);
for(int i=0;i<n;i++){
cin>>A[i];
 }
cin>>k;
map<int,int> m;
for(int i=0;i<n;i++){
    m[A[i]]++;
}
auto it=m.begin();
for(int i=1;i<=k-1;i++){
    it++;
}
cout<<it->first<<endl;
</code>```

but my map solution is giving Time Limit Exceeded. according to me map solution also has a time complexity of (n+klog(n)), same as heap solution.
so why is map solution giving TLE?

答:
The time complexity for your solution using maps would be O(k + nlog(n)). Each insertion into std::map takes log(n) time and you are performing 'n' insertions. Time complexity for insertion alone would take O(nlog(n)) time.

See http://www.cplusplus.com/reference/map/map/insert/ for more information about inserting elements into std::map.

Body:
currently i am doing problem on data structure and i have a question in which i have to find kth largest element in an array. the actual problem is here:
https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/.

i did this question in two different way using heap and second is using map.

my solution using map.

   int t;
cin>>t;
while(--t>=0){
int n,k;
cin>>n;
vector<int> A(n);
for(int i=0;i<n;i++){
cin>>A[i];
 }
cin>>k;
map<int,int> m;
for(int i=0;i<n;i++){
    m[A[i]]++;
}
auto it=m.begin();
for(int i=1;i<=k-1;i++){
    it++;
}
cout<<it->first<<endl;

but my map solution is giving Time Limit Exceeded. according to me map solution also has a time complexity of (n+klog(n)), same as heap solution.
so why is map solution giving TLE?