问:
How to add private DNS zone to kube-dns in GKE
I have created a k8 cluster in GKE.

I have a docker registry created in Artifactory, this artifactory is hosted on AWS. I have a route53 entry for docker-repo.aws.abc.com in aws.abc.com Hosted zone in AWS

Now, I need to configure my cluster so that the docker images are pulled from artifactory.

I went through documentation and understand I will have to add stubDomain in my kube-dns configmaps.

```<code>kubectl edit cm kube-dns -n kube-system
apiVersion: v1
data:
  stubDomains: |
    {"aws.abc.com" : ["XX.XX.XX.XX"]}
kind: ConfigMap
metadata:
  creationTimestamp: 2019-05-21T14:30:15Z
  labels:
    addonmanager.kubernetes.io/mode: EnsureExists
  name: kube-dns
  namespace: kube-system
  resourceVersion: "7669"
  selfLink: /api/v1/namespaces/kube-system/configmaps/kube-dns
  uid: f378aa5f-7bd4-11e9-9df2-42010aa93d03
</code>```

However, still docker pull command fails.

docker pull docker-repo.aws.abc.com/abc-sampleapp-java/abc-service:V-57bc9c9-201

Error response from daemon: Get https://docker-repo.aws.abc.com/v2/: dial tcp: lookup docker-dev-repo.aws.abc.com on 169.254.169.254:53: no such host

Note: When I make an entry in /etc/hosts file on worker nodes, docker pull works fine.

答:
Pulling an image from registry on pod start uses different DNS settings than when we call DNS from pods inside a cluster.

When Kubernetes starts new pod, it schedules it to the node and then agent on the node named kubelet calls container engine (Docker) to download an image and run it with designed configuration.

Docker uses system DNS to resolve the address of a registry, because it works right on our host system, not in the Kubernetes, that is why any DNS settings will not affect DNS resolving on the image downloading stage. https://github.com/kubernetes/kubernetes/issues/8735 is a discussion about it on Github.

If we want to change DNS settings and override the registry IP to use it on image downloading stage, we should set it in the  host system. In the configuration, we need to modify DNS settings on all your nodes in the cluster. The simplest way to do it is using /etc/hosts file and adding a record with your custom IP, e.g. 192.168.1.124 example.com.

After that modifications, Docker on nodes will use the record from /etc/hosts for your registry instead of global DNS records, because that file has higher priority and you will be able to run pods with your image.

To update the host file.
you can use a DeamonSet with Security Context as privileged see below:

```<code>apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: hosts-fix-script
  namespace: kube-system
  labels:
    app: hosts-fix-script
spec:
  selector:
    matchLabels:
      name: hosts-fix
  template:
    metadata:
      labels:
        name: hosts-fix
    spec:
      hostPID: true
      containers:
      - name: hosts-fix-script
        image: gcr.io/google-containers/startup-script:v1
        imagePullPolicy: Always
        securityContext:
          privileged: true
        env:
        - name: STARTUP_SCRIPT
          value: |
            #!/bin/bash
                echo "10.0.0.11 onprem.registry" >> /etc/hosts
            echo 'Done'
</code>```

you need to run the kubectl apply -f

Body:
I have created a k8 cluster in GKE.

I have a docker registry created in Artifactory, this artifactory is hosted on AWS. I have a route53 entry for docker-repo.aws.abc.com in aws.abc.com Hosted zone in AWS

Now, I need to configure my cluster so that the docker images are pulled from artifactory.

I went through documentation and understand I will have to add stubDomain in my kube-dns configmaps.

kubectl edit cm kube-dns -n kube-system
apiVersion: v1
data:
  stubDomains: |
    {"aws.abc.com" : ["XX.XX.XX.XX"]}
kind: ConfigMap
metadata:
  creationTimestamp: 2019-05-21T14:30:15Z
  labels:
    addonmanager.kubernetes.io/mode: EnsureExists
  name: kube-dns
  namespace: kube-system
  resourceVersion: "7669"
  selfLink: /api/v1/namespaces/kube-system/configmaps/kube-dns
  uid: f378aa5f-7bd4-11e9-9df2-42010aa93d03

However, still docker pull command fails.

docker pull docker-repo.aws.abc.com/abc-sampleapp-java/abc-service:V-57bc9c9-201

Error response from daemon: Get https://docker-repo.aws.abc.com/v2/: dial tcp: lookup docker-dev-repo.aws.abc.com on 169.254.169.254:53: no such host

Note: When I make an entry in /etc/hosts file on worker nodes, docker pull works fine.

Body:
Pulling an image from registry on pod start uses different DNS settings than when we call DNS from pods inside a cluster.

When Kubernetes starts new pod, it schedules it to the node and then agent on the node named kubelet calls container engine (Docker) to download an image and run it with designed configuration.

Docker uses system DNS to resolve the address of a registry, because it works right on our host system, not in the Kubernetes, that is why any DNS settings will not affect DNS resolving on the image downloading stage. https://github.com/kubernetes/kubernetes/issues/8735 is a discussion about it on Github.

If we want to change DNS settings and override the registry IP to use it on image downloading stage, we should set it in the  host system. In the configuration, we need to modify DNS settings on all your nodes in the cluster. The simplest way to do it is using /etc/hosts file and adding a record with your custom IP, e.g. 192.168.1.124 example.com.

After that modifications, Docker on nodes will use the record from /etc/hosts for your registry instead of global DNS records, because that file has higher priority and you will be able to run pods with your image.

To update the host file.
you can use a DeamonSet with Security Context as privileged see below:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: hosts-fix-script
  namespace: kube-system
  labels:
    app: hosts-fix-script
spec:
  selector:
    matchLabels:
      name: hosts-fix
  template:
    metadata:
      labels:
        name: hosts-fix
    spec:
      hostPID: true
      containers:
      - name: hosts-fix-script
        image: gcr.io/google-containers/startup-script:v1
        imagePullPolicy: Always
        securityContext:
          privileged: true
        env:
        - name: STARTUP_SCRIPT
          value: |
            #!/bin/bash
                echo "10.0.0.11 onprem.registry" >> /etc/hosts
            echo 'Done'

you need to run the kubectl apply -f


来源: stackexchange

问:
Confused on boost::asio::io_context::run() and boost::thread::join()
As the boost document stated here, boost::asio::io_context::run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_context has been stopped.

Now I am confused why my code located before one more handler dispatching (t.join()) was not executed until all the handlers completed their works.

I have tried the boost asio tutorial Timer.5 - Synchronising handlers in multithreaded programs

And I added one line code following the io.run():

int main()
{
    boost::asio::io_context io;
    printer p(io);
    boost::thread t(boost::bind(&boost::asio::io_context::run, &io));
    io.run();
    std::cout << "between run and join" << std::endl;
    t.join();

    return 0;
}
```

<p>Here are the console outputs:</p>

```Timer 2: 0
Timer 1: 1
Timer 2: 2
Timer 1: 3
Timer 1: 4
Timer 2: 5
Timer 2: 6
Timer 1: 7
Timer 2: 8
Timer 1: 9
between run and join
Final count is 10
```

I wonder why t.join() was executed before my std::cout << "between run and join" << std::endl; code? I expect the output "between run and join" to be before all the 2nd thread's outputs.

I think I must be lost at something.

答:
line with "Final count" is executed in destructor of printer class, that is executed when main reaches return();

run terminates when all timers expires (there is no more work to wait/do)

Once run returns/unblocks  "cout << between run and join" is executed.

ContentLicense: CC BY-SA 4.0

Body:
As the boost document stated here, boost::asio::io_context::run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_context has been stopped.

Now I am confused why my code located before one more handler dispatching (t.join()) was not executed until all the handlers completed their works.

I have tried the boost asio tutorial Timer.5 - Synchronising handlers in multithreaded programs

And I added one line code following the io.run():

int main()
{
    boost::asio::io_context io;
    printer p(io);
    boost::thread t(boost::bind(&boost::asio::io_context::run, &io));
    io.run();
    std::cout << "between run and join" << std::endl;
    t.join();

    return 0;
}

Here are the console outputs:

Timer 2: 0
Timer 1: 1
Timer 2: 2
Timer 1: 3
Timer 1: 4
Timer 2: 5
Timer 2: 6
Timer 1: 7
Timer 2: 8
Timer 1: 9
between run and join
Final count is 10

I wonder why t.join() was executed before my std::cout << "between run and join" << std::endl; code? I expect the output "between run and join" to be before all the 2nd thread's outputs.

I think I must be lost at something.


问:
send 50 requests from spring scheduler each 1 second
I have scheduler with method:

```<code>@Scheduled(fixedDelay = 1000L)
public void sendRequest() {
 client.getData();   //send request to some server
}
</code>```

Each second I need send 50 request(call client.getData())
 How can I do it?

This example very bad, but I write it to show what I need:

```<code>@Scheduled(fixedDelay = 1000L)
public void sendRequest() {
 for(int i=0; i<50; i++){
 taskExecutor.execute(() -> client.getData());   //send request to some server
 }
}
</code>```

Or maby I need create 50 schedulers and each scheduler will trigger each second?

答:
```<code>@Scheduled(fixedDelay = 1000L)
</code>```

Processing of @Scheduled annotations is performed by registering a ScheduledAnnotationBeanPostProcessor. Bean post-processor that registers methods annotated with @Scheduled to be invoked by a TaskScheduler according to the "fixedRate", "fixedDelay", or "cron" expression provided via the annotation.
And here we have a concurrency story. If you use ThreadPoolTaskScheduler as the TaskScheduler implementation, literally, you have implementation of Spring's TaskScheduler interface, wrapping a native ScheduledThreadPoolExecutor. Step by step we come to Threads. They do require CPU time. CPU time is about your machine and it's configuration.

You can use this annotation for your purpose, but real performance depends on your machine, where the app's deployed. If machine's configuration (CPU and so on) provides ability to process/send 50 requests exactly every second - you're welcome. If you try to launch 50 schedulers as standalone apps on different computers it may also solve your problem.

Body:
I have scheduler with method:

@Scheduled(fixedDelay = 1000L)
public void sendRequest() {
 client.getData();   //send request to some server
}

Each second I need send 50 request(call client.getData())
 How can I do it?

This example very bad, but I write it to show what I need:

@Scheduled(fixedDelay = 1000L)
public void sendRequest() {
 for(int i=0; i<50; i++){
 taskExecutor.execute(() -> client.getData());   //send request to some server
 }
}

Or maby I need create 50 schedulers and each scheduler will trigger each second?

Body:
@Scheduled(fixedDelay = 1000L)

Processing of @Scheduled annotations is performed by registering a ScheduledAnnotationBeanPostProcessor. Bean post-processor that registers methods annotated with @Scheduled to be invoked by a TaskScheduler according to the "fixedRate", "fixedDelay", or "cron" expression provided via the annotation.
And here we have a concurrency story. If you use ThreadPoolTaskScheduler as the TaskScheduler implementation, literally, you have implementation of Spring's TaskScheduler interface, wrapping a native ScheduledThreadPoolExecutor. Step by step we come to Threads. They do require CPU time. CPU time is about your machine and it's configuration.

You can use this annotation for your purpose, but real performance depends on your machine, where the app's deployed. If machine's configuration (CPU and so on) provides ability to process/send 50 requests exactly every second - you're welcome. If you try to launch 50 schedulers as standalone apps on different computers it may also solve your problem.


问:
How can I specify number of rows in detail band?
I've two problems :

1 - I want to specify number of rows which must be shown in every page of my report.

2 - If the number of fetched rows from datasource is less than amount required to fill page height, I want to fill remaining space with blank rows (every row is distinguished using its field borders). For example, if 50 rows can displayed in every page & there are only 20 rows of data which fetched from datasource, then I want to print 30 empty rows after last printed row.
Consider that I cant do this with changing my sql select statement.

Can anybody help me please ?

答:
I can help you with your second request:

Add a TextField with this relative position

left:1 pixel

top:1 pixel

Put inside "\n\n..." 50 times. That print 50 rows always.

Change the size of your text

width: 1 pixels

height: 15 pixels

Tick option: Strecht when overflow.

Greetings

ContentLicense: CC BY-SA 3.0


问:
Updated FacobookLogin Pod, Got Error: No known class method for selector 'objectForJSONString:error:'
Recently I have updated the Below mentioned pods for FacebookLogin Button implemented in my app

```<code>pod 'FacebookCore'
pod 'FacebookLogin'
</code>```

The versions of both pods are 0.7.0

I had updated the pods using the command

```<code>pod update
</code>```

After updating the when I built the project there is an error in the path

Pods/FBSDKLoginKit/FBSDKLoginKit/FBSDKLoginKit/Internal/FBSDKLoginManagerLogger.m:163:60: No known class method for selector 'objectForJSONString:error:'

Both these errors is occurring in two places in the same class

No known class method for selector 'objectForJSONString:error:'

```<code>NSDictionary<id, id> *clientState = [FBSDKBasicUtility objectForJSONString:parameters[FBSDKLoginManagerLoggingClientStateKey] error:NULL];
</code>```

答:
I have also received a notification from Facebook to upgrade the Facebook SDK to 5.0.(Previously it was 4.39.0) Below is the link which shows the latest features of Facebook SDK :

https://developers.facebook.com/docs/app-events/upgrade-guide

If you want to use these then you have to update the SDK and at code level integrate new pods for Facebook as shown in the above link.

If you don't want to use these features then you have to restrict your pods to a specific version so in future pod update the Facebook pods are not changed.

Hope this helps.

Body:
Recently I have updated the Below mentioned pods for FacebookLogin Button implemented in my app

pod 'FacebookCore'
pod 'FacebookLogin'

The versions of both pods are 0.7.0

I had updated the pods using the command

pod update

After updating the when I built the project there is an error in the path

Pods/FBSDKLoginKit/FBSDKLoginKit/FBSDKLoginKit/Internal/FBSDKLoginManagerLogger.m:163:60: No known class method for selector 'objectForJSONString:error:'

Both these errors is occurring in two places in the same class

No known class method for selector 'objectForJSONString:error:'

NSDictionary<id, id> *clientState = [FBSDKBasicUtility objectForJSONString:parameters[FBSDKLoginManagerLoggingClientStateKey] error:NULL];


问:
Reading from file in Eclipse plugin
I need to read the configuration details from a properties file in eclipse. I have put the  config.properties at the same level as plugin.xml and in the class file I call:

```<code>Properties properties = new Properties();
FileInputStream file;
String path = "./config.properties";
file = new FileInputStream(path);
properties.load(file);
</code>```

I get a file not found exception. Is there a better way of doing this?

答:
If it is a plugin, you should tell it that your file must be included into the target. It is set in the build.properties file. Open it and look - you haven't your file mentioned there.

Open plugin.xml, go to build tab and include your file in the binary.build by checking it. Save. That will change the build.properties file correctly. Go to build.properties tab and look at the file again - now you see your file included correctly.

Of course, you could do it by hand, but plugin UI is convenient and you can be sure you haven't any problem ends of line or spaces.

For absolute addressing the files in the plugins look here

Title: Reading from file in Eclipse plugin

Body:
I need to read the configuration details from a properties file in eclipse. I have put the  config.properties at the same level as plugin.xml and in the class file I call:

Properties properties = new Properties();
FileInputStream file;
String path = "./config.properties";
file = new FileInputStream(path);
properties.load(file);

I get a file not found exception. Is there a better way of doing this?


问:
Binary XML runtime exception when trying to start activity
I'm trying to launch the application, but I get a RuntimeException stating that "RuntimeException: Unable to start activity ". Can someone help me?

Here's the code:

```<code>public class MainActivity extends AppCompatActivity {
    LinearLayout splash_screen;
    WebView myWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView)findViewById(R.id.webview);
        splash_screen = (LinearLayout) findViewById(R.id.splash_screen);
        myWebView.loadUrl("https://www.africanshooting.com");
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new MyWebViewClient());
        if (!isConnected())
        {
            AlertDialog alert = new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Internet Connection")
                    .setMessage("Oups!il semblerait que vous n'etes pas connecter verifier vos parametres reseau")
                    .setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).create();
                    alert.show();
        }

    }
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            splash_screen.setVisibility(View.VISIBLE);
            view.setVisibility(View.INVISIBLE);

        }
        @Override
        public void onPageFinished(WebView view, String url) {
            splash_screen.setVisibility(View.GONE);
            view.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
        }
    }  private boolean isConnected() {
        ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo= connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
}
</code>```

And here's the log:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.africanshooting, PID: 25248
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.africanshooting/com.example.africanshooting.MainActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.RelativeLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.RelativeLayout
        at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.africanshooting.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:6309)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.constraint.RelativeLayout
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.africanshooting.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:6309)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.constraint.RelativeLayout" on path: DexPathList[[zip file "/data/app/com.example.africanshooting-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.africanshooting-2/lib/arm, /vendor/lib, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
        at android.view.LayoutInflater.createView(LayoutInflater.java:583)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.africanshooting.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:6309)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
        Suppressed: java.lang.ClassNotFoundException: android.support.constraint.RelativeLayout
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
</code>```

答:
xml-code of your activity layout (R.layout.activity_main) contains android.support.constraint.RelativeLayout. which doesnt exist in Android framework.

I guess you have smth like this in activity_main.xml file:

<android.support.constraint.RelativeLayout
```

<p>Just change it with</p>

<pre class="lang-xml prettyprint-override"><code><RelativeLayout
</code>```

Body:
I'm trying to launch the application, but I get a RuntimeException stating that "RuntimeException: Unable to start activity ". Can someone help me?

Here's the code:

public class MainActivity extends AppCompatActivity {
    LinearLayout splash_screen;
    WebView myWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView)findViewById(R.id.webview);
        splash_screen = (LinearLayout) findViewById(R.id.splash_screen);
        myWebView.loadUrl("https://www.africanshooting.com");
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new MyWebViewClient());
        if (!isConnected())
        {
            AlertDialog alert = new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Internet Connection")
                    .setMessage("Oups!il semblerait que vous n'etes pas connecter verifier vos parametres reseau")
                    .setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).create();
                    alert.show();
        }

    }
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            splash_screen.setVisibility(View.VISIBLE);
            view.setVisibility(View.INVISIBLE);

        }
        @Override
        public void onPageFinished(WebView view, String url) {
            splash_screen.setVisibility(View.GONE);
            view.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
        }
    }  private boolean isConnected() {
        ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo= connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
}

And here's the log:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.africanshooting, PID: 25248
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.africanshooting/com.example.africanshooting.MainActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.RelativeLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.RelativeLayout
        at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.africanshooting.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:6309)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.constraint.RelativeLayout
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.africanshooting.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:6309)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.constraint.RelativeLayout" on path: DexPathList[[zip file "/data/app/com.example.africanshooting-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.africanshooting-2/lib/arm, /vendor/lib, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
        at android.view.LayoutInflater.createView(LayoutInflater.java:583)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.africanshooting.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:6309)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5788)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
        Suppressed: java.lang.ClassNotFoundException: android.support.constraint.RelativeLayout
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)

Body:
xml-code of your activity layout (R.layout.activity_main) contains android.support.constraint.RelativeLayout. which doesnt exist in Android framework.

I guess you have smth like this in activity_main.xml file:

<android.support.constraint.RelativeLayout

Just change it with

<RelativeLayout


问:
Angular 7- How to sum time string elements of two arrays?
I have two arrays of different time string.

```<code>startingTime: string["09:00:00", "5:50:00", "6:30:00"];
duration: string["0:15:00", "01:00:00", "01:00:00"];
</code>```

I want to sum these arrays in final like

```<code>endingTime: string ["09:15:00", "6:50:00", "7:30:00"]
</code>```

I'm building Single page application using angular 7,trying to use momentjs but not sure how to implement it.
I would appreciate any help.

答:
Try like this:</p>

```<code>let seta = ["09:00:00", "5:50:00", "6:30:00"];
let setb = ["0:15:00", "01:00:00", "01:00:00"]

let totalArray = []

seta.forEach((time,index) => {
  totalArray.push(this.addTimes([time,setb[index]))
});

addTimes(times) {

const z = (n) => (n < 10 ? '0' : '') + n;

let hour = 0
let minute = 0
let second = 0
for (const time of times) {
    const splited = time.split(':');
    hour += parseInt(splited[0]);
    minute += parseInt(splited[1])
    second += parseInt(splited[2])
}
const seconds = second % 60
const minutes = parseInt(minute % 60) + parseInt(second / 60)
const hours = hour + parseInt(minute / 60)

return z(hours) + ':' + z(minutes) + ':' + z(seconds)
}
</code>```

Body:
I have two arrays of different time string.

startingTime: string["09:00:00", "5:50:00", "6:30:00"];
duration: string["0:15:00", "01:00:00", "01:00:00"];

I want to sum these arrays in final like

endingTime: string ["09:15:00", "6:50:00", "7:30:00"]

I'm building Single page application using angular 7,trying to use momentjs but not sure how to implement it.
I would appreciate any help.

Body:
Try like this:

let seta = ["09:00:00", "5:50:00", "6:30:00"];
let setb = ["0:15:00", "01:00:00", "01:00:00"]

let totalArray = []

seta.forEach((time,index) => {
  totalArray.push(this.addTimes([time,setb[index]))
});

addTimes(times) {

const z = (n) => (n < 10 ? '0' : '') + n;

let hour = 0
let minute = 0
let second = 0
for (const time of times) {
    const splited = time.split(':');
    hour += parseInt(splited[0]);
    minute += parseInt(splited[1])
    second += parseInt(splited[2])
}
const seconds = second % 60
const minutes = parseInt(minute % 60) + parseInt(second / 60)
const hours = hour + parseInt(minute / 60)

return z(hours) + ':' + z(minutes) + ':' + z(seconds)
}


问:
How or which Payment system do I need to use for Subscription services which are mentioned as below , Stripe Or Google's In-App Billing?
I'm currently very much confused about with which subscription service to use between any Third-party or Google's In-App billing system.

Let me explain first , I have an app which is providing service to Landlord for Posting their vacant Properties where we are providing free trial 60 Days for full app features & after trial expires I would like to add Subscription Plans as below:

Silver: Less than 50 units (monthly or yearly)

Gold: Less than 51 - 100 units (monthly or yearly)

Platinum 100 and up units (monthly or yearly)

Now I'm exploring options to include to implement this subscription features & found that Stripe would be a good option for me but soon I find out about in-app purchases guidelines where they mentioned that In-app purchases must use Google Play’s payment system & also mentioned , examples of products not currently supported by Google Play In-app Billing:

So , basically there are two questions from my side :

Can I use other payment system or should I need to use Google's Play Billing system ?

For Google's Play system , How can I divide or how many subscriptions items will be there for above subscriptions plans?

Any help would be appreciated!

答: I recommended to use Google's In-App Billing. Because most of country payment support by google and user first trust on google that most benefit for you.


问:
How to Loop through a list of elements
My question is very simple, how can i create a loop that will loop a simple list of elements.

```<code>List li=["-","\\","|","/"];
</code>```

this is my dart list and i want to create this simple animation.

答:
Different ways to Loop through a List of elements

1 classic For

```<code>for (var i = 0; i < li.length; i++) {
  // TO DO
  var currentElement = li[i];
}
</code>```

2 Enhanced For loop

```<code>for(final e in li){
  //
  var currentElement = e;
}
</code>```

Notice the keyword final. It means single-assignment, a final variable's value cannot be changed.

3 while loop

```<code>var i = 0;
while(i < li.length){
  var currentElement = li[i];
  i++;
}
</code>```

For the while loop, you will use var to reassign the variable value.

Title: How to Loop through a list of elements

Body:
My question is very simple, how can i create a loop that will loop a simple list of elements.

List li=["-","\\","|","/"];

this is my dart list and i want to create this simple animation.

Body:
Different ways to Loop through a List of elements

1 classic For

for (var i = 0; i < li.length; i++) {
  // TO DO
  var currentElement = li[i];
}

2 Enhanced For loop

for(final e in li){
  //
  var currentElement = e;
}

Notice the keyword final. It means single-assignment, a final variable's value cannot be changed.

3 while loop

var i = 0;
while(i < li.length){
  var currentElement = li[i];
  i++;
}

For the while loop, you will use var to reassign the variable value.


问:
How to hide a navigation bar from one particular view controller
I've created a two splash screen iPhone app. Afterwards user is taken to first view. I've added a UINavigationController. It works perfectly fine.

How do I remove the navigation bar for the opening view alone?

MainWindow

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

self.splashScreen = [[SplashScreen alloc]
                initWithNibName:@"SplashScreen"
                bundle:nil];
if (self.pageController == nil) {
openingpage *page=[[openingpage alloc]initWithNibName:@"openingpage" bundle:[NSBundle mainBundle]];
    self.pageController = page;
    [page release];
}
[self.navigationController pushViewController:self.pageController animated:YES];

[window addSubview:splashScreen.view];

 [splashScreen displayScreen];
[self.window makeKeyAndVisible];

return YES;
 }
</code>```

答:
In c# or Xamarin.IOS,
this.NavigationController.NavigationBar.Hidden = true;</p>

Body:
I've created a two splash screen iPhone app. Afterwards user is taken to first view. I've added a UINavigationController. It works perfectly fine.

How do I remove the navigation bar for the opening view alone?

MainWindow

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

self.splashScreen = [[SplashScreen alloc]
                initWithNibName:@"SplashScreen"
                bundle:nil];
if (self.pageController == nil) {
openingpage *page=[[openingpage alloc]initWithNibName:@"openingpage" bundle:[NSBundle mainBundle]];
    self.pageController = page;
    [page release];
}
[self.navigationController pushViewController:self.pageController animated:YES];

[window addSubview:splashScreen.view];

 [splashScreen displayScreen];
[self.window makeKeyAndVisible];

return YES;
 }


问:
Add one character before every special character in a string in javascript
I want to add one character for every special character in a string by regular expression i tried below expression but it is adding after the special character.

I expect the output to add one character for every special character in a string.

```<code>var string1="aaa!dd,"
var expressionResult = text.replace(/([\/,!?_])/g, '/');
</code>```

the output should be aaa/!dd/,

答:
You can use $1 in the replacement string to include the capture group's content in the replacement:

var string1="aaa!dd,"
var expressionResult = string1.replace(/([\/,!?_])/g, '/$1');
console.log(expressionResult);```
</div>
</div>
</p>

<p>More on MDN.</p>

<p>You don't need a capture group, though, you can use <code>$&</code> to refer to the text matched by the main expression:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var string1="aaa!dd,"
var expressionResult = string1.replace(/[\/,!?_]/g, '/$&');
console.log(expressionResult);</code>```

(If you needed to do something more complex in the replacement, you can pass in a function as the second argument. It gets called with the overall match as its first argument, followed by arguments for each capture group; its return value is used in the resulting string. You don't need that here, but...)

Body:
I want to add one character for every special character in a string by regular expression i tried below expression but it is adding after the special character.

I expect the output to add one character for every special character in a string.

var string1="aaa!dd,"
var expressionResult = text.replace(/([\/,!?_])/g, '/');

the output should be aaa/!dd/,

Body:
You can use $1 in the replacement string to include the capture group's content in the replacement:

var string1="aaa!dd,"
var expressionResult = string1.replace(/([\/,!?_])/g, '/$1');
console.log(expressionResult);

More on MDN.

You don't need a capture group, though, you can use $& to refer to the text matched by the main expression:

var string1="aaa!dd,"
var expressionResult = string1.replace(/[\/,!?_]/g, '/$&');
console.log(expressionResult);

(If you needed to do something more complex in the replacement, you can pass in a function as the second argument. It gets called with the overall match as its first argument, followed by arguments for each capture group; its return value is used in the resulting string. You don't need that here, but...)


问:
How can I build a URL with query parameters containing multiple values for the same key in Swift?
I am using AFNetworking in my iOS app and for all the GET requests it makes, I build the url from a base URL and than add parameters using NSDictionary Key-Value pairs.

The problem is that I need same key for different values.

Here is an example of what I need the finally URL to look like -

http://example.com/.....&id=21212&id=21212&id=33232

It's not possible in NSDictionary to have different values in same keys. So I tried NSSet but did not work.

```<code>let productIDSet: Set = [prodIDArray]
let paramDict = NSMutableDictionary()
paramDict.setObject(productIDSet, forKey: "id")
</code>```

答:
In Swift Forming URL with multiple params

```<code>func rateConversionURL(with array: [String]) -> URL? {
            var components = URLComponents()
            components.scheme = "https"
            components.host = "example.com"
            components.path = "/hello/"
            components.queryItems = array.map { URLQueryItem(name: "value", value: $0)}

        return components.url
    }
</code>```

Body:
I am using AFNetworking in my iOS app and for all the GET requests it makes, I build the url from a base URL and than add parameters using NSDictionary Key-Value pairs.

The problem is that I need same key for different values.

Here is an example of what I need the finally URL to look like -

http://example.com/.....&id=21212&id=21212&id=33232

It's not possible in NSDictionary to have different values in same keys. So I tried NSSet but did not work.

let productIDSet: Set = [prodIDArray]
let paramDict = NSMutableDictionary()
paramDict.setObject(productIDSet, forKey: "id")

Body:
In Swift Forming URL with multiple params

func rateConversionURL(with array: [String]) -> URL? {
            var components = URLComponents()
            components.scheme = "https"
            components.host = "example.com"
            components.path = "/hello/"
            components.queryItems = array.map { URLQueryItem(name: "value", value: $0)}

        return components.url
    }


问:
How can I position my progress bar at the bottom of a button?
I am facing a bit of an issue and I can't seem to figure it out.

I am trying to create a button and add a bootstrap progress bar at the bottom of it, but I cant seem to figure out how to get it to do just that.

Here's my current setup. https://jsfiddle.net/bob_mosh/7qeazm9w/3/

HTML:

```<code><button id="sample_button" type="button" class="soundButton">
<label class="buttonTitle">Bird Song</label>
<label class="buttonDescription">A nice bird song.</label>
<div class="progress volume-slider">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</button>
</code>```

CSS:

```<code>.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}
</code>```

This is the current state on the right and the way I am envisioning it on the left.

For some reason I cant get the absolute positioning to work. Every time I try to set the position of the progress bar to absolute, it completely disappears. Can anyone help me figure this out?

答:
I figured it out!

Turns out I had to add another div to make it work. The working code looks like this:

```<code><button id="sample_button" type="button" class="soundButton">
  <div class="buttonWrapperInside">
    <label class="buttonTitle">Bird Song</label>
    <label class="buttonDescription">A nice bird song.</label>
  </div>
  <div class="progress volume-slider">
    <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
  </div>
</button>
</code>```

```<code>.progress {
    background-color: rgba(0, 0, 0, 0.15) !important;
    vertical-align: bottom;
}

.progress-bar {
    width: 100%;
    height: 8px;
}

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 0px 0px 8px 0px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

.volume-slider {
    bottom:0px;
    height: 8px !important;
        position: relative;
        width: 100%;
}

.buttonWrapperInside {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 8px;
}
</code>```

This works!

Thanks so much for your help guys there were a lot of pointers that helped me get there! Your help is very much appreciated!

Body:
I am facing a bit of an issue and I can't seem to figure it out.

I am trying to create a button and add a bootstrap progress bar at the bottom of it, but I cant seem to figure out how to get it to do just that.

Here's my current setup. https://jsfiddle.net/bob_mosh/7qeazm9w/3/

HTML:

<button id="sample_button" type="button" class="soundButton">
Bird Song
A nice bird song.

</button>

CSS:

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 8px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

body {
  background-color: rgba(37, 38, 43, 1.00)
}

.buttonTitle {
    font-weight: 700;
    font-size: 1.5em;
    display: block;
}

.volume-slider {
    bottom:0;
    height: 8px !important;
}

This is the current state on the right and the way I am envisioning it on the left.

For some reason I cant get the absolute positioning to work. Every time I try to set the position of the progress bar to absolute, it completely disappears. Can anyone help me figure this out?

Body:
I figured it out!

Turns out I had to add another div to make it work. The working code looks like this:

<button id="sample_button" type="button" class="soundButton">
  <div class="buttonWrapperInside">
    <label class="buttonTitle">Bird Song</label>
    <label class="buttonDescription">A nice bird song.</label>
  </div>
  <div class="progress volume-slider">
    <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
  </div>
</button>

.progress {
    background-color: rgba(0, 0, 0, 0.15) !important;
    vertical-align: bottom;
}

.progress-bar {
    width: 100%;
    height: 8px;
}

.soundButton {
    display: table-cell;
    background-color: rgba(255, 255, 255, 0.650);
    margin: 4px;
    padding: 0px 0px 8px 0px;
    width: 250px;
    height: 120px !important;
    border-radius: 8px;
    border: none !important;
    float: left !important;
}

.soundButton label {
    color: rgba(37, 38, 43, 1.00) !important;
}

.volume-slider {
    bottom:0px;
    height: 8px !important;
        position: relative;
        width: 100%;
}

.buttonWrapperInside {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 8px;
}

This works!

Thanks so much for your help guys there were a lot of pointers that helped me get there! Your help is very much appreciated!


问:
Referencing inserted ID in multiple insert transactions in Postgres
I need to build a SQL query that must be able to insert data in a first table, grab the inserted ID and then use it as foreign key in the following tables.

```<code>WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

SELECT * FROM inserted; -- this has the inserted id

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', ???)
</code>```

So how do I reference the id in inserted in the secondTable insert?

答:
You can try this:</p>

```<code>INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', (SELECT
MAX (id) FROM firstTable))
</code>```

Body:
I need to build a SQL query that must be able to insert data in a first table, grab the inserted ID and then use it as foreign key in the following tables.

WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

SELECT * FROM inserted; -- this has the inserted id

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', ???)

So how do I reference the id in inserted in the secondTable insert?

Body:
You can try this:

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', (SELECT
MAX (id) FROM firstTable))


问:
Getting "ErrImageNeverPull" in pods
Am using minikube to test out the deployment and was going through this link

And my manifest file for deployment is like

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: webapp
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        imagePullPolicy: Never # <-- here we go!
        image: sams
        ports:
        - containerPort: 80
</code>```

and after this when I tried to execute the below commands got output

```<code>user@usesr:~/Downloads$ kubectl create -f mydeployment.yaml --validate=false

deployment "webapp" created

user@user:~/Downloads$ kubectl get deployments

NAME      DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
----     --------   -------   ----------   ---------   ----
webapp    1         1         1            0           9s

user@user:~/Downloads$ kubectl get pods

NAME                     READY     STATUS              RESTARTS   AGE
----     --------   -------   ----------   ---------   ----
webapp-5bf5bd94d-2xgs8   0/1       ErrImageNeverPull   0          21s
</code>```

I tried to pull images even from Docker-Hub by removing line imagePullPolicy: Never  from the deployment.yml But getting the same error.
Can anyone help me here to identify where and what's going wrong?

Updated the question as per the comment

```<code>kubectl describe pod $POD_NAME
Name:           webapp-5bf5bd94d-2xgs8
Namespace:      default
Node:           minikube/10.0.2.15
Start Time:     Fri, 31 May 2019 14:25:41 +0530
Labels:         app=webapp
            pod-template-hash=5bf5bd94d
Annotations:    <none>
Status:         Pending
IP:             172.17.0.4
Controlled By:  ReplicaSet/webapp-5bf5bd94d
Containers:
  webapp:
    Container ID:
    Image:          sams
    Image ID:
    Port:           80/TCP
    State:          Waiting
      Reason:       ErrImageNeverPull
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-wf82w (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-wf82w:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-wf82w
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
             node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason             Age                From               Message
  ----     ------             ----               ----               -------
  Normal   Scheduled          18m                default-scheduler  Successfully assigned default/webapp-5bf5bd94d-2xgs8 to minikube
  Warning  ErrImageNeverPull  8m (x50 over 18m)  kubelet, minikube  Container image "sams" is not present with pull policy of Never
  Warning  Failed             3m (x73 over 18m)  kubelet, minikube  Error: ErrImageNeverPull

docker images:

REPOSITORY                             TAG                 IMAGE ID            CREATED             SIZE
----------                             ---                 --------            -------             ----
<none>                                 <none>              723ce2b3d962        3 hours ago         1.91GB
bean_ben501/sams                       latest              c7c4a04713f4        4 hours ago         278MB
sams                                   latest              c7c4a04713f4        4 hours ago         278MB
sams                                   v1                  c7c4a04713f4        4 hours ago         278MB
<none>                                 <none>              b222da630bc3        4 hours ago         1.91GB
mcr.microsoft.com/dotnet/core/sdk      2.2-stretch         e4747ec2aaff        9 days ago          1.74GB
mcr.microsoft.com/dotnet/core/aspnet   2.2-stretch-slim    f6d51449c477        9 days ago          260MB
</code>```

答:
When using a single VM for Kubernetes, it’s useful to reuse Minikube’s built-in Docker daemon. Reusing the built-in daemon means you don’t have to build a Docker registry on your host machine and push the image into it. Instead, you can build inside the same Docker daemon as Minikube, which speeds up local experiments.

The following command does the magic
eval $(minikube docker-env)
Then you have to rebuild your image again.

for imagePullPolicy: Never the images need to be on the minikube node.

This answer provide details

local-images-in minikube docker environment

Title: Getting "ErrImageNeverPull" in pods

Body:
Am using minikube to test out the deployment and was going through this link

And my manifest file for deployment is like

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: webapp
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        imagePullPolicy: Never # <-- here we go!
        image: sams
        ports:
        - containerPort: 80

and after this when I tried to execute the below commands got output

user@usesr:~/Downloads$ kubectl create -f mydeployment.yaml --validate=false

deployment "webapp" created

user@user:~/Downloads$ kubectl get deployments

NAME      DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
----     --------   -------   ----------   ---------   ----
webapp    1         1         1            0           9s

user@user:~/Downloads$ kubectl get pods

NAME                     READY     STATUS              RESTARTS   AGE
----     --------   -------   ----------   ---------   ----
webapp-5bf5bd94d-2xgs8   0/1       ErrImageNeverPull   0          21s

I tried to pull images even from Docker-Hub by removing line imagePullPolicy: Never  from the deployment.yml But getting the same error.
Can anyone help me here to identify where and what's going wrong?

Updated the question as per the comment

kubectl describe pod $POD_NAME
Name:           webapp-5bf5bd94d-2xgs8
Namespace:      default
Node:           minikube/10.0.2.15
Start Time:     Fri, 31 May 2019 14:25:41 +0530
Labels:         app=webapp
            pod-template-hash=5bf5bd94d
Annotations:    <none>
Status:         Pending
IP:             172.17.0.4
Controlled By:  ReplicaSet/webapp-5bf5bd94d
Containers:
  webapp:
    Container ID:
    Image:          sams
    Image ID:
    Port:           80/TCP
    State:          Waiting
      Reason:       ErrImageNeverPull
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-wf82w (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-wf82w:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-wf82w
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
             node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason             Age                From               Message
  ----     ------             ----               ----               -------
  Normal   Scheduled          18m                default-scheduler  Successfully assigned default/webapp-5bf5bd94d-2xgs8 to minikube
  Warning  ErrImageNeverPull  8m (x50 over 18m)  kubelet, minikube  Container image "sams" is not present with pull policy of Never
  Warning  Failed             3m (x73 over 18m)  kubelet, minikube  Error: ErrImageNeverPull

docker images:

REPOSITORY                             TAG                 IMAGE ID            CREATED             SIZE
----------                             ---                 --------            -------             ----
<none>                                 <none>              723ce2b3d962        3 hours ago         1.91GB
bean_ben501/sams                       latest              c7c4a04713f4        4 hours ago         278MB
sams                                   latest              c7c4a04713f4        4 hours ago         278MB
sams                                   v1                  c7c4a04713f4        4 hours ago         278MB
<none>                                 <none>              b222da630bc3        4 hours ago         1.91GB
mcr.microsoft.com/dotnet/core/sdk      2.2-stretch         e4747ec2aaff        9 days ago          1.74GB
mcr.microsoft.com/dotnet/core/aspnet   2.2-stretch-slim    f6d51449c477        9 days ago          260MB


问:
How to run multiple query in Codeigniter that are separated by semicolon
I have an attendance table and i want to insert data in it if not exits and update if exist, query in Loop working fine but take too much time. So to reduce time i concatenate  all  query as string separated by semicolon. The result get after concatenation work in phpMyAdmin but not in Codeigniter,
any guess Why?
Thanks in advance. </p>

```<code>function set_attendance()
    {
        $today = date('Y-m-d');
        $data = $this->input->post('member');
        $str='';
        foreach ($data as  $value)
        {
            $query = $this->db->select('*')
                            ->from('attendance')
                            ->where('user_id',$value['user_id'])
                            ->where('date',$today)
                            ->get();

            if($query->num_rows()>0)
            {
                $obj = array(
                       'attendance'    => $value['status'],
                       'leavetype' => $value['leavetype'],
                );

                $where = "user_id =  '{$value['user_id']}' AND date = '{$today}'";

                $str .= $this->db->update_string('attendance', $obj, $where);
                $str.=';';
            }
            else
            {
                 $obj = array(
                        's-no'  => null,
                        'user_id' => $value['user_id'],
                        'date' => $today,
                        'regby'=>'t',
                        'leavetype' => $value['leavetype'],
                       'attendance'    => $value['status'],
                );
                $str .= $this->db->insert_string('attendance', $obj);
                 $str.=';';

            }

        }

        $this->db->query($str);
        $output = array('result'=>true);
        return $output ;
    }
</code>```

答:
Ok I get answer
Just run php native multi_query() function</p>

```<code>function set_attendance()
    {
        $today = date('Y-m-d');
        $data = $this->input->post('member');
        $str='';
        foreach ($data as  $value)
        {
            $query = $this->db->select('*')
                            ->from('attendance')
                            ->where('user_id',$value['user_id'])
                            ->where('date',$today)
                            ->get();

            if($query->num_rows()>0)
            {
                $obj = array(
                       'attendance'    => $value['status'],
                       'leavetype' => $value['leavetype'],
                );

                $where = "user_id =  '{$value['user_id']}' AND date = '{$today}'";

                $str .= $this->db->update_string('attendance', $obj, $where);
                $str.=';';
            }
            else
            {
                 $obj = array(
                        's-no'  => null,
                        'user_id' => $value['user_id'],
                        'date' => $today,
                        'regby'=>'t',
                        'leavetype' => $value['leavetype'],
                       'attendance'    => $value['status'],
                );
                $str .= $this->db->insert_string('attendance', $obj);
                 $str.=';';

            }

        }
        $link = mysqli_connect('localhost','root','','yoga_panel');
        if(mysqli_multi_query($link,$str))
        {
            $output=array('result'=>true);
            return $output;
        }
    }
</code>```

Body:
I have an attendance table and i want to insert data in it if not exits and update if exist, query in Loop working fine but take too much time. So to reduce time i concatenate  all  query as string separated by semicolon. The result get after concatenation work in phpMyAdmin but not in Codeigniter,
any guess Why?
Thanks in advance.

function set_attendance()
    {
        $today = date('Y-m-d');
        $data = $this->input->post('member');
        $str='';
        foreach ($data as  $value)
        {
            $query = $this->db->select('*')
                            ->from('attendance')
                            ->where('user_id',$value['user_id'])
                            ->where('date',$today)
                            ->get();

            if($query->num_rows()>0)
            {
                $obj = array(
                       'attendance'    => $value['status'],
                       'leavetype' => $value['leavetype'],
                );

                $where = "user_id =  '{$value['user_id']}' AND date = '{$today}'";

                $str .= $this->db->update_string('attendance', $obj, $where);
                $str.=';';
            }
            else
            {
                 $obj = array(
                        's-no'  => null,
                        'user_id' => $value['user_id'],
                        'date' => $today,
                        'regby'=>'t',
                        'leavetype' => $value['leavetype'],
                       'attendance'    => $value['status'],
                );
                $str .= $this->db->insert_string('attendance', $obj);
                 $str.=';';

            }

        }

        $this->db->query($str);
        $output = array('result'=>true);
        return $output ;
    }

Body:
Ok I get answer
Just run php native multi_query() function

function set_attendance()
    {
        $today = date('Y-m-d');
        $data = $this->input->post('member');
        $str='';
        foreach ($data as  $value)
        {
            $query = $this->db->select('*')
                            ->from('attendance')
                            ->where('user_id',$value['user_id'])
                            ->where('date',$today)
                            ->get();

            if($query->num_rows()>0)
            {
                $obj = array(
                       'attendance'    => $value['status'],
                       'leavetype' => $value['leavetype'],
                );

                $where = "user_id =  '{$value['user_id']}' AND date = '{$today}'";

                $str .= $this->db->update_string('attendance', $obj, $where);
                $str.=';';
            }
            else
            {
                 $obj = array(
                        's-no'  => null,
                        'user_id' => $value['user_id'],
                        'date' => $today,
                        'regby'=>'t',
                        'leavetype' => $value['leavetype'],
                       'attendance'    => $value['status'],
                );
                $str .= $this->db->insert_string('attendance', $obj);
                 $str.=';';

            }

        }
        $link = mysqli_connect('localhost','root','','yoga_panel');
        if(mysqli_multi_query($link,$str))
        {
            $output=array('result'=>true);
            return $output;
        }
    }


问:
How to redirect user of one opencart site to another opencart site after login?
I have 2 websites of opencart. Now, I have to redirect customers of the one opencart site to another opencart site.

I have one website, Customer of that site will allow clicking on a button that button will redirect to another opencart site and get registered on that site. and then they will be able to order on the same site.

EX: https://example.com and another site is https://example2.com there is a button "send me to store" on https://example.com Now, when the customer clicks on that button it will redirect to https://example2.com site and get register to that site.

Anybody know how can it be possible please suggest me the proper way to do this kind of redirection in between two different opencart setups.it would be a great help.

Thanks in advance. :)

答:
Let me check if I got it clear and then offer my solution:

So you want to have one customer be logged in (registered) in 2 different opencart sites?

the customer should be able to order from both sites.

there are 2 possibilities:

the easy one: Set up multistore in OpenCart. Multistore feature allows you to have one OC installation with one database, one customer table and one order list for 2 different web domains.

to set up multistore, go to your opencart admin and select in left menu system -> settings and click the plus button on top right (create new store)

then add the domain name of the second store and other information. here is a youtube video you can follow https://www.youtube.com/watch?v=xPexoqI4AMo

the hard one: if you do not want to use multistore, and would like to have two different OC installations, you will manually have to implement the logic for registering two accounts for one customer.

This would be possible if for example, you are hosting the two stores on one server, you would have access to both of the databases and just edit them with the same credentials when a user Creates/edits/deletes and account.

Another issue comes up with the SESSION. the session keeps the user logged in and it is attached to the domain name since it uses cookies to store the session id. if the users switch from one domain to the other, the cookies no longer know if this customer is logged in. so you will need to implement the logic for passing the session id to the other store when you redirect him.

I hope this gives you some understanding of you case.


问:
Unable to get bitmap from the following uri : Uri imageUri = data.getClipData().getItemAt(i).getUri()
Project: Open Gallery From a Button in One Activity, Select The Images from there and Display it on the initial Activity screen.

Solution: I know that the solution for the problem above is given but it only deals with the multiple selection of images part and getting the data of the images.

My Problem:

From here, i am unable to use the uri data to convert to bitmap and hence store in my image view. I even tried

ImageView imageView = findViewById(R.id.imageView);

Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath()) ;

imageView.setImageBitmap(bitmap); but the image doesn't show

How to get dynamic number of image views?
I want the image views on my activity.xml to be dynamic,i.e it changes its number depending on the number of selections
for eg: if the user selects 5 images on opening the gallery app, then i want to be able to display the 4 images on the initial Activity screen. If 6 images selected then 6, if 2 then 2. It should change the image view count depending on the number of selections as I dont want to hardcode the number of image views in the xml file.

How i am trying to get the bitmap is by
 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

I am getting Unhandled exceptions error , java.io.FileNotFoundException for the getBitmap part below

I have attached my code below

```<code>    public void onClick(View view){
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(requestCode == PICK_IMAGE_MULTIPLE) {
                if(resultCode == Activity.RESULT_OK) {
                    if(data.getClipData() != null) {
                        int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
                        for (int i = 0; i < count; i++){
                            Uri imageUri = data.getClipData().getItemAt(i).getUri();

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri) ; //MAIN ERROR OVER HERE

//OR

                            ImageView imageView = findViewById(R.id.imageView);
                            Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath()) ;
                            imageView.setImageBitmap(bitmap); //STILL NOT WORKING
                        }
                    }
                } else if(data.getData() != null) {
                    String imagePath = data.getData().getPath();
                    ImageView imageView = findViewById(R.id.imageView); //WANT TO AVOID THIS AND MAKE IMAGE VIEW NUMBER AS DYNAMIC
                    Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
                    imageView.setImageBitmap(bmImg);
                }
            }
        }
</code>```

答:
```<code>InputStream iStream = getContentResolver().openInputStream(selectedImageUri);
            byte[] inputData = Utils.getBytes(iStream);
            dbHelper.insertImage(inputData);
</code>```

<p>http://www.coderzheaven.com/2012/12/23/store-image-android-sqlite-retrieve-it/
</p>

Body:
Project: Open Gallery From a Button in One Activity, Select The Images from there and Display it on the initial Activity screen.

Solution: I know that the solution for the problem above is given but it only deals with the multiple selection of images part and getting the data of the images.

My Problem:

From here, i am unable to use the uri data to convert to bitmap and hence store in my image view. I even tried

ImageView imageView = findViewById(R.id.imageView);

Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath()) ;

imageView.setImageBitmap(bitmap); but the image doesn't show

How to get dynamic number of image views?
I want the image views on my activity.xml to be dynamic,i.e it changes its number depending on the number of selections
for eg: if the user selects 5 images on opening the gallery app, then i want to be able to display the 4 images on the initial Activity screen. If 6 images selected then 6, if 2 then 2. It should change the image view count depending on the number of selections as I dont want to hardcode the number of image views in the xml file.

How i am trying to get the bitmap is by
 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

I am getting Unhandled exceptions error , java.io.FileNotFoundException for the getBitmap part below

I have attached my code below

    public void onClick(View view){
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(requestCode == PICK_IMAGE_MULTIPLE) {
                if(resultCode == Activity.RESULT_OK) {
                    if(data.getClipData() != null) {
                        int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
                        for (int i = 0; i < count; i++){
                            Uri imageUri = data.getClipData().getItemAt(i).getUri();

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri) ; //MAIN ERROR OVER HERE

//OR

                            ImageView imageView = findViewById(R.id.imageView);
                            Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath()) ;
                            imageView.setImageBitmap(bitmap); //STILL NOT WORKING
                        }
                    }
                } else if(data.getData() != null) {
                    String imagePath = data.getData().getPath();
                    ImageView imageView = findViewById(R.id.imageView); //WANT TO AVOID THIS AND MAKE IMAGE VIEW NUMBER AS DYNAMIC
                    Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
                    imageView.setImageBitmap(bmImg);
                }
            }
        }

Body:
InputStream iStream = getContentResolver().openInputStream(selectedImageUri);
            byte[] inputData = Utils.getBytes(iStream);
            dbHelper.insertImage(inputData);

http://www.coderzheaven.com/2012/12/23/store-image-android-sqlite-retrieve-it/


问:
How can I change text to input field clicking on the text itself
I want to change commitment text to be changed with input field when I click on commitment and when I press enter it should show the newly entered input.

I am new to javascript but I looked many codes but they didn't slove what I want please can you provide any idea how to do this?`

```<code><div class="table-responsive">
    <table class="table table-bordered table-hover" id="dtBasicExample" cellspacing="0" width="100%">
      <!-- Table head -->
      <thead class="theader">
        <tr>
          <th>Grade</th>
          <th>Student</th>
          <th>
            <!-- Default un -->
            <!-- <div class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input" id="tableDefaultCheck1">
              <label class="custom-control-label" for="tableDefaultCheck1">P/A</label>
            </div> -->P/A
          </th>
          <th>Check-In</th>
          <th>Check-Out</th>
          <th>Tutor</th>
          <th>Videos</th>
          <th>Others</th>
          <th>Commitment</th>
        </tr>
      </thead>
<tbody>
</tr>
        <tr>
          <td>7</td>
          <td>Name</td>
          <th scope="row">
            <!-- Default un -->
            <div class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input" id="tableDefaultCheck3">
              <label class="custom-control-label" for="tableDefaultCheck3"></label>
            </div>
          </th>
          <td>Time</td>
          <td>Time</td>
          <td>Time</td>
          <td>Time</td>
          <td>Time</td>
          <td>Commitment
            <div class="md-form">
              <input type="text" id="form2" class="form-control">
              <label for="form2">New Commitment</label>
            </div>
          </td>
        </tr>
</tbody>
</table>
</code>```

答:
Is this what you are looking for?

```<code>$('.md-form input').keydown(function(e) {
  if(e.keyCode == 13 && $(this).val().length > 0){
    $(this).next().text($(this).val())
  }
});
</code>```

Working demo

$('.md-form input').keydown(function(e) {
  if (e.keyCode == 13 && $(this).val().length > 0) {
    $(this).next().show().text($(this).val())
    $(this).hide();
  }
});

$('.Commitment label').click(function() {
  $(this).prev().show();
  $(this).hide();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Commitment input {
  display: none;
}</code>```

        Grade
        Student

          P/A

        Check-In
        Check-Out
        Tutor
        Videos
        Others
        Commitment

        7
        Name

            <input type="checkbox" class="custom-control-input" id="tableDefaultCheck3">

        Time
        Time
        Time
        Time
        Time

            <input type="text" id="form2" class="form-control">
            New Commitment

        7
        Name

            <input type="checkbox" class="custom-control-input" id="tableDefaultCheck3">

        Time
        Time
        Time
        Time
        Time

            <input type="text" id="form2" class="form-control">
            New Commitment

```

Body:
I want to change commitment text to be changed with input field when I click on commitment and when I press enter it should show the newly entered input.

I am new to javascript but I looked many codes but they didn't slove what I want please can you provide any idea how to do this?`

          Grade
          Student

            P/A

          Check-In
          Check-Out
          Tutor
          Videos
          Others
          Commitment

          7
          Name

              <input type="checkbox" class="custom-control-input" id="tableDefaultCheck3">

          Time
          Time
          Time
          Time
          Time
          Commitment

              <input type="text" id="form2" class="form-control">
              New Commitment

Body:
Is this what you are looking for?

$('.md-form input').keydown(function(e) {
  if(e.keyCode == 13 && $(this).val().length > 0){
    $(this).next().text($(this).val())
  }
});

Working demo

$('.md-form input').keydown(function(e) {
  if (e.keyCode == 13 && $(this).val().length > 0) {
    $(this).next().show().text($(this).val())
    $(this).hide();
  }
});

$('.Commitment label').click(function() {
  $(this).prev().show();
  $(this).hide();
})

.Commitment input {
  display: none;
}

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<div class="table-responsive">
  <table class="table table-bordered table-hover" id="dtBasicExample" cellspacing="0" width="100%">
    <!-- Table head -->
    <thead class="theader">
      <tr>
        <th>Grade</th>
        <th>Student</th>
        <th>
          <!-- Default un -->
          <!-- <div class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input" id="tableDefaultCheck1">
              <label class="custom-control-label" for="tableDefaultCheck1">P/A</label>
            </div> -->P/A
        </th>
        <th>Check-In</th>
        <th>Check-Out</th>
        <th>Tutor</th>
        <th>Videos</th>
        <th>Others</th>
        <th>Commitment</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>7</td>
        <td>Name</td>
        <th scope="row">
          <!-- Default un -->
          <div class="custom-control custom-checkbox">
            <input type="checkbox" class="custom-control-input" id="tableDefaultCheck3">
            <label class="custom-control-label" for="tableDefaultCheck3"></label>
          </div>
        </th>
        <td>Time</td>
        <td>Time</td>
        <td>Time</td>
        <td>Time</td>
        <td>Time</td>
        <td class="Commitment">
          <div class="md-form">
            <input type="text" id="form2" class="form-control">
            <label for="form2">New Commitment</label>
          </div>
        </td>
      </tr>
      <tr>
        <td>7</td>
        <td>Name</td>
        <th scope="row">
          <!-- Default un -->
          <div class="custom-control custom-checkbox">
            <input type="checkbox" class="custom-control-input" id="tableDefaultCheck3">
            <label class="custom-control-label" for="tableDefaultCheck3"></label>
          </div>
        </th>
        <td>Time</td>
        <td>Time</td>
        <td>Time</td>
        <td>Time</td>
        <td>Time</td>
        <td class="Commitment">
          <div class="md-form">
            <input type="text" id="form2" class="form-control">
            <label for="form2">New Commitment</label>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>


问:
spring destroy-method + request scope bean
So I wanted to do something like this:

```<code>@Component
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public class MyBean {
    @Autowired HttpServletRequest request;

    @PreDestroy
    public void afterRequest() {
        try {
            System.out.println("After request...");
            // use request here:
        }
        finally {
            System.out.println("Completed successfully...");
        }
    }
}
</code>```

And I end up with the following message, AFTER the "Completed successfully..." message logs:

09:19:16 WARN  Invocation of destroy method failed on bean with name 'scopedTarget.myBean': java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I'm not really sure what to make of this, since my logging indicates the destroy method completed successfully. Does anyone know what's going on?

EDIT:
Here's the mvc-servlet.xml. As you can see there is not much going on here. It's all annotation driven:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-2.0.xsd">

<!-- properties file -->
<context:property-placeholder location="app.properties" />

<context:component-scan base-package="my.package.web" />
<context:component-scan base-package="my.package.services" />

<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/view" p:suffix=".jspx" />
</beans>
</code>```

答:
If you use request scope without spring MVC you should declare org.springframework.web.context.request.RequestContextListener in web-app  listener.

```<code><web-app>
  ...
  <listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>
  ...
</web-app>
</code>```

check http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-web-configuration

Body:
So I wanted to do something like this:

@Component
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public class MyBean {
    @Autowired HttpServletRequest request;

    @PreDestroy
    public void afterRequest() {
        try {
            System.out.println("After request...");
            // use request here:
        }
        finally {
            System.out.println("Completed successfully...");
        }
    }
}

And I end up with the following message, AFTER the "Completed successfully..." message logs:

09:19:16 WARN  Invocation of destroy method failed on bean with name 'scopedTarget.myBean': java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I'm not really sure what to make of this, since my logging indicates the destroy method completed successfully. Does anyone know what's going on?

EDIT:
Here's the mvc-servlet.xml. As you can see there is not much going on here. It's all annotation driven:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-2.0.xsd">

<context:property-placeholder location="app.properties" />

<context:component-scan base-package="my.package.web" />
<context:component-scan base-package="my.package.services" />

<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/view" p:suffix=".jspx" />
</beans>

Body:
If you use request scope without spring MVC you should declare org.springframework.web.context.request.RequestContextListener in web-app  listener.

<web-app>
  ...
  <listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>
  ...
</web-app>

check http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-web-configuration


问:
Chrome localhost cookies not being set
I'm setting up ASP.NET Core authentication in different configurations, using Google Chrome as a development and test tool. Everything worked fine locally, but suddenly it stopped.

I've inspected the http headers and I found Set-Cookie one there in my POST response, but nothing in the next request nor in the Application->Storage->Cookies tab. I've inspected the console and found no errors nor warnings there. I've restated and updated Chrome (with no effect) and finally switched to Edge and then Firefox.

And, yes, I've searched whole the Internet, looking for the solution, but the highest ranked answers for similar issues are 5+ years old, CORS or SameSite related. Only once I found the reference to the bug in Chrome causing the issue I faced.

答:
The cause of the problem was a bug in Google Chrome:

If you have a secure cookie with same name set by  https://localhost, your cookie will fail to be set, and you will not know that one exists unless you visit the page from https://localhost.

In my case I've just once called my authentication service via https, and that silently blocked all the following attempts with http. Additionally annoying thing is that restarting Chrome does not clear that (session) cookies, so the behavior persists until manual cleanup, or starting an incognito window.

Title: Chrome localhost cookies not being set


问:
Mysql Explain shows that query is using index when it shouldnt be according to Mysql doc
I created a mysql multi column index on a transactions table. This index uses 3 columns as described in my rails schema :

```<code>  add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree
</code>```

Now I have this active record query :

```<code>MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")
</code>```

which in pure sql gives :

```<code>"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"
</code>```

Now from what I read about mysql and multi column indexing :

If the table has a multiple-column index, any leftmost prefix of the
  index can be used by the optimizer to look up rows. For example, if
  you have a three-column index on (col1, col2, col3), you have indexed
  search capabilities on (col1), (col1, col2), and (col1, col2, col3).
  For more information, see Section 8.3.5, “Multiple-Column
  Indexes”.

To me, this means that the precedent query shouldnt be using the previous index.

However when I run EXPLAIN on my query MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain under the keycolumn, I get by_reference_parent_ref_kind and under the Extra column I have  Using index condition which seems to imply that the index is actually used.

How is that possible ?

答: It will use the index as you have the leftmost column listed in query (reference), i.e use case (col1) from docs. The other column in condition (kind) is not searched through the index.

Body:
I created a mysql multi column index on a transactions table. This index uses 3 columns as described in my rails schema :

  add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree

Now I have this active record query :

MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")

which in pure sql gives :

"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"

Now from what I read about mysql and multi column indexing :

If the table has a multiple-column index, any leftmost prefix of the
  index can be used by the optimizer to look up rows. For example, if
  you have a three-column index on (col1, col2, col3), you have indexed
  search capabilities on (col1), (col1, col2), and (col1, col2, col3).
  For more information, see Section 8.3.5, “Multiple-Column
  Indexes”.

To me, this means that the precedent query shouldnt be using the previous index.

However when I run EXPLAIN on my query MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain under the keycolumn, I get by_reference_parent_ref_kind and under the Extra column I have  Using index condition which seems to imply that the index is actually used.

How is that possible ?