问:
what is the meaning of "await" used in Rust?
This question may somewhat relate more to async-programming than Rust.But after googling a lot, there are still somepoint I think is missing. And since I am learning Rust, I would put it in a Rust way.

Let me  give my understanding of async-programming first---After all, this is the basis, maybe I am wrong or not:

To make program run efficiently, dealing tasks concurrently is essential. Then thread is used, and the thread could be joined whenever the data from the thread is needed. But thread is not enough to handle many tasks,like a server does. Then thread-pool is used, but how to fetch data when it is needed with no information of which thread should be waiting for? Then callback function(cb for short) comes up.With cb,only what needs to do in cb should be considered. In addition, to make cpu little overhead, green thread comes up.

But what if the asyn-waiting things need to do one after another, which leads to "callback hell"? Ok, the "future/promise" style comes up, which let code looks like sync-code, or maybe like a chain(like in javascript). But still the code looks not quite nice. Finally, the "async/await" style comes up, as another syntactic sugar for "future/promise" style.  And usually, the "async/await" with green thread style is called "coroutine", be it using only one native thread or multi-native threads over async tasks.

=============================================

As far as I know at this point, as keyword "await" can only be used in the scope of an "async" function, and only "async" function could be "awaited". But why? And what is it used to, as there is already "async"? Anyway, I tested the code below:

```<code>use async_std::{task};

// async fn easy_task() {
//     for i in 0..100 {
//         dbg!(i);
//     }
//     println!("finished easy task");
// }

async fn heavy_task(cnt1: i32, cnt2: i32) {
    for i in 0..cnt1 {
        println!("heavy_task1 cnt:{}", i);
    }

    println!("heavy task: waiting sub task");
    // normal_sub_task(cnt2);
    sub_task(cnt2).await;
    println!("heavy task: sub task finished");

    for i in 0..cnt1 {
        println!("heavy_task2 cnt:{}", i);
    }
    println!("finished heavy task");
}

fn normal_sub_task(cnt: i32) {
    println!("normal sub_task: start sub task");
    for i in 0..cnt {
        println!("normal sub task cnt:{}", i);
    }
    println!("normal sub_task: finished sub task");
}

async fn sub_task(cnt: i32) {
    println!("sub_task: start sub task");
    for i in 0..cnt {
        println!("sub task cnt:{}", i);
    }
    println!("sub_task: finished sub task");
}

fn outer_task(cnt: i32) {
    for i in 0..cnt {
        println!("outer task cnt:{}", i);
    }
    println!("finished outer task");
}

fn main() {
    // let _easy_f = easy_task();
    let heavy_f = heavy_task(3000, 500);
    let handle = task::spawn(heavy_f);
    print!("=================after spawn==============");
    outer_task(5000);

    // task::join_handle(handle);
    task::block_on(handle);
}

</code>```

the conclusion I got from test is:

1.No matter awaiting async sub_task or just doing normal_sub_task(sync version) in the middle of async heavy_task(), the code below that (the heavy loop task2) would not cut in line.

2.No matter awaiting async sub_task or just doing normal_sub_task(sync version) in the middle of async heavy_task(), the outer_task would sometimes cut in line, breaking the heavy_task1 or async_sub_task/normal_sub_task.

Therefore, what is the meaning of "await", it seems that only keyword "asyc" is used here.

reference:

asyc_std

sing_dance_example from rust asyncbook

module Task in official rust module

recommended article of rust this week about async-programming

another article about rust thread and async-programming using future crates

stackoverflow question:What is the purpose of async/await in Rust?
the conclusion 2 I got seems to be violated against what Shepmaster said, "...we felt async functions should run synchronously to the first await."

答:
The await keyword suspends the execution of an asynchronous function until the awaited future (future.await) produces a value.

It is the same meaning of all the other languages that uses the await concept.

When a future is awaited the "status of execution" of the async function is persisted into an internal
execution context and others async functions have the opportunity to progress if they are ready to run.

When the awaited future completes the async function resumes at the exact point of suspension.

If you think I need only async and write something like:

```<code>// OK: let result = future.await
let result = future
</code>```

You don't get a value but something that represents a value ready in the future.

And if you mark async a function without awaiting anything inside
the body of the function you are injecting into an asynchronous engine a sequential task
that when executed will run to completion as a normal function, preventing asynchronous behavoir.

Some more comments about your code

Probably the confusion arise from a misunderstaning ot the task concept.

When learning async in rust I found the async book pretty useful.

The book define tasks as:

Tasks are the top-level futures that have been submitted to an executor

heavy_task is really the unique task in your example because it is the only future submitted to the async
runtime with task::block_on.

For example, the function outer_task has nothing to do with asynchronous world:
 it is not a task, it get excuted immediately when called.

heavy_task behaves asychronously and await
sub_task(cnt2) future ... but sub_task future once executed
 goes immediately to completion.

So, as it stand, your code behave practically as sequential.

But keep in mind that things in reality are more subtle, because in presence of other async tasks the
await inside heavy_task works as a suspension point and gives opportunity to other
tasks to be executed toward completion.

Body:
This question may somewhat relate more to async-programming than Rust.But after googling a lot, there are still somepoint I think is missing. And since I am learning Rust, I would put it in a Rust way.

Let me  give my understanding of async-programming first---After all, this is the basis, maybe I am wrong or not:

To make program run efficiently, dealing tasks concurrently is essential. Then thread is used, and the thread could be joined whenever the data from the thread is needed. But thread is not enough to handle many tasks,like a server does. Then thread-pool is used, but how to fetch data when it is needed with no information of which thread should be waiting for? Then callback function(cb for short) comes up.With cb,only what needs to do in cb should be considered. In addition, to make cpu little overhead, green thread comes up.

But what if the asyn-waiting things need to do one after another, which leads to "callback hell"? Ok, the "future/promise" style comes up, which let code looks like sync-code, or maybe like a chain(like in javascript). But still the code looks not quite nice. Finally, the "async/await" style comes up, as another syntactic sugar for "future/promise" style.  And usually, the "async/await" with green thread style is called "coroutine", be it using only one native thread or multi-native threads over async tasks.

=============================================

As far as I know at this point, as keyword "await" can only be used in the scope of an "async" function, and only "async" function could be "awaited". But why? And what is it used to, as there is already "async"? Anyway, I tested the code below:

use async_std::{task};

// async fn easy_task() {
//     for i in 0..100 {
//         dbg!(i);
//     }
//     println!("finished easy task");
// }

async fn heavy_task(cnt1: i32, cnt2: i32) {
    for i in 0..cnt1 {
        println!("heavy_task1 cnt:{}", i);
    }

    println!("heavy task: waiting sub task");
    // normal_sub_task(cnt2);
    sub_task(cnt2).await;
    println!("heavy task: sub task finished");

    for i in 0..cnt1 {
        println!("heavy_task2 cnt:{}", i);
    }
    println!("finished heavy task");
}

fn normal_sub_task(cnt: i32) {
    println!("normal sub_task: start sub task");
    for i in 0..cnt {
        println!("normal sub task cnt:{}", i);
    }
    println!("normal sub_task: finished sub task");
}

async fn sub_task(cnt: i32) {
    println!("sub_task: start sub task");
    for i in 0..cnt {
        println!("sub task cnt:{}", i);
    }
    println!("sub_task: finished sub task");
}

fn outer_task(cnt: i32) {
    for i in 0..cnt {
        println!("outer task cnt:{}", i);
    }
    println!("finished outer task");
}

fn main() {
    // let _easy_f = easy_task();
    let heavy_f = heavy_task(3000, 500);
    let handle = task::spawn(heavy_f);
    print!("=================after spawn==============");
    outer_task(5000);

    // task::join_handle(handle);
    task::block_on(handle);
}

the conclusion I got from test is:

1.No matter awaiting async sub_task or just doing normal_sub_task(sync version) in the middle of async heavy_task(), the code below that (the heavy loop task2) would not cut in line.

2.No matter awaiting async sub_task or just doing normal_sub_task(sync version) in the middle of async heavy_task(), the outer_task would sometimes cut in line, breaking the heavy_task1 or async_sub_task/normal_sub_task.

Therefore, what is the meaning of "await", it seems that only keyword "asyc" is used here.

reference:

asyc_std

sing_dance_example from rust asyncbook

module Task in official rust module

recommended article of rust this week about async-programming

another article about rust thread and async-programming using future crates

stackoverflow question:What is the purpose of async/await in Rust?
the conclusion 2 I got seems to be violated against what Shepmaster said, "...we felt async functions should run synchronously to the first await."

Body:
The await keyword suspends the execution of an asynchronous function until the awaited future (future.await) produces a value.

It is the same meaning of all the other languages that uses the await concept.

When a future is awaited the "status of execution" of the async function is persisted into an internal
execution context and others async functions have the opportunity to progress if they are ready to run.

When the awaited future completes the async function resumes at the exact point of suspension.

If you think I need only async and write something like:

// OK: let result = future.await
let result = future

You don't get a value but something that represents a value ready in the future.

And if you mark async a function without awaiting anything inside
the body of the function you are injecting into an asynchronous engine a sequential task
that when executed will run to completion as a normal function, preventing asynchronous behavoir.

Some more comments about your code

Probably the confusion arise from a misunderstaning ot the task concept.

When learning async in rust I found the async book pretty useful.

The book define tasks as:

Tasks are the top-level futures that have been submitted to an executor

heavy_task is really the unique task in your example because it is the only future submitted to the async
runtime with task::block_on.

For example, the function outer_task has nothing to do with asynchronous world:
 it is not a task, it get excuted immediately when called.

heavy_task behaves asychronously and await
sub_task(cnt2) future ... but sub_task future once executed
 goes immediately to completion.

So, as it stand, your code behave practically as sequential.

But keep in mind that things in reality are more subtle, because in presence of other async tasks the
await inside heavy_task works as a suspension point and gives opportunity to other
tasks to be executed toward completion.


来源: stackexchange

问:
In EF4.1 code first, What is the difference between configuring entities using annotations, configuration files, or in the OnModelCreating?
Currently I am using separate configuration files and calling them like:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProductConfiguration());
    base.OnModelCreating(modelBuilder);
}
</code>```

It seems like most of the examples online are really basic so they define their models, the DbContext and the model configurations all in a single class.  Are there and performance issues or other compelling reasons to use one over the other?

答:
I don't know what you mean exactly with "configuration files" but there are indeed basically three options to define a model:

Conventions: When you create your model classes you name your properties in a way that EF can detect primary keys, foreign keys, relationships and so on automatically. If you do this consequently you neither need any data annotations nor to overwrite OnModelCreating.

Data annotations: Useful when you cannot or don't want to follow the convention rules. An example might be that you have an existing database whose column names doesn't match the standard naming rules of EF, for instance if you have a key column with a name which EF wouldn't recognize as a key:

```<code>public class User
{
    [Key]
    public int User_Code { get; set; }
}
</code>```

Fluent API in OnModelCreating: For advanced mapping scenarios which you can't define with data annotations. Examples are here.

For the performance I believe it doesn't matter what you use. The approach is a question of taste and of the complexity of your model. EF creates an internal model represention only once during the lifetime of an application instance. (You can see this by setting a breakpoint in OnModelCreating: You'll reach this breakpoint only once, no matter how often you create a new DbContext.)

ContentLicense: CC BY-SA 3.0

Body:
Currently I am using separate configuration files and calling them like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProductConfiguration());
    base.OnModelCreating(modelBuilder);
}

It seems like most of the examples online are really basic so they define their models, the DbContext and the model configurations all in a single class.  Are there and performance issues or other compelling reasons to use one over the other?

Body:
I don't know what you mean exactly with "configuration files" but there are indeed basically three options to define a model:

Conventions: When you create your model classes you name your properties in a way that EF can detect primary keys, foreign keys, relationships and so on automatically. If you do this consequently you neither need any data annotations nor to overwrite OnModelCreating.

Data annotations: Useful when you cannot or don't want to follow the convention rules. An example might be that you have an existing database whose column names doesn't match the standard naming rules of EF, for instance if you have a key column with a name which EF wouldn't recognize as a key:

public class User
{
    [Key]
    public int User_Code { get; set; }
}

Fluent API in OnModelCreating: For advanced mapping scenarios which you can't define with data annotations. Examples are here.

For the performance I believe it doesn't matter what you use. The approach is a question of taste and of the complexity of your model. EF creates an internal model represention only once during the lifetime of an application instance. (You can see this by setting a breakpoint in OnModelCreating: You'll reach this breakpoint only once, no matter how often you create a new DbContext.)


问:
How can I create a method that gets access to a Dependency Service and passes parameters to the method it called?
I have a method that calls a dependency service.

```<code>DependencyService.Get<IPopUp>().Popup("XYZ", "ABC",
        (Color)Application.Current.Resources["PopUpTitleColor"],
        (Color)Application.Current.Resources["PopUpMessageColor"],
        (Color)Application.Current.Resources["PopUpBackgroundColor"],
        (Color)Application.Current.Resources["PopUpSeparatorColor"],
        (sen, args) => {
            DidShowFirstMessage = true;
        });
</code>```

Interface:

```<code>public interface IPopUp
{
    void Popup(string title,
        string message,
        Color titleColor,
        Color messageColor,
        Color popUpBackgroundColor,
        Color popUpSeparatorColor,
        EventHandler handler);
}
</code>```

Is there a way I could code a helper that would call the same dependency service and also add in the parameters.

NOTE that as the dependency service calls multiple versions of Popup I need to code the Helper so the parameters are hard code in there.  Not as an extension method to Popup. This is not a duplicate of my previously asked question. I just did not explain it fully before.

```<code> Helper.Popup(("XYZ", "ABC", (sen, args) => {
            DidShowFirstMessage = true;
        });
</code>```

答:
Is this what you need? I'm not sure that I understand your problem here...

static class Helper
{
     public static void Popup (string xyz ,string abc ,EventHandler eh)
    {
        DependencyService.Get<IPopUp>().Popup(xyz, abc,
         (Color)Application.Current.Resources["PopUpTitleColor"],
         (Color)Application.Current.Resources["PopUpMessageColor"],
         (Color)Application.Current.Resources["PopUpBackgroundColor"],
         (Color)Application.Current.Resources["PopUpSeparatorColor"],
         eh;
    }
}

```

<p>usage </p>

<pre class="lang-cs prettyprint-override"><code>Helper.Popup("XYZ" , "ABC" , (sen, args) => DidShowFirstMessage = true );
</code>```

but having an extention method could be a better option here :

static class Helper
{
     public static void Popup (this IDependencyService ds, string xyz ,string abc ,EventHandler eh)
    {
        ds.Get<IPopUp>().Popup(xyz, abc,
         (Color)Application.Current.Resources["PopUpTitleColor"],
         (Color)Application.Current.Resources["PopUpMessageColor"],
         (Color)Application.Current.Resources["PopUpBackgroundColor"],
         (Color)Application.Current.Resources["PopUpSeparatorColor"],
         eh;
    }
}
```

<p>usage</p>

<pre class="lang-cs prettyprint-override"><code>DependencyService.Popup("XYZ" , "ABC" , (sen, args) => DidShowFirstMessage = true );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a method that calls a dependency service.

DependencyService.Get<IPopUp>().Popup("XYZ", "ABC",
        (Color)Application.Current.Resources["PopUpTitleColor"],
        (Color)Application.Current.Resources["PopUpMessageColor"],
        (Color)Application.Current.Resources["PopUpBackgroundColor"],
        (Color)Application.Current.Resources["PopUpSeparatorColor"],
        (sen, args) => {
            DidShowFirstMessage = true;
        });

Interface:

public interface IPopUp
{
    void Popup(string title,
        string message,
        Color titleColor,
        Color messageColor,
        Color popUpBackgroundColor,
        Color popUpSeparatorColor,
        EventHandler handler);
}

Is there a way I could code a helper that would call the same dependency service and also add in the parameters.

NOTE that as the dependency service calls multiple versions of Popup I need to code the Helper so the parameters are hard code in there.  Not as an extension method to Popup. This is not a duplicate of my previously asked question. I just did not explain it fully before.

 Helper.Popup(("XYZ", "ABC", (sen, args) => {
            DidShowFirstMessage = true;
        });

Body:
Is this what you need? I'm not sure that I understand your problem here...

static class Helper
{
     public static void Popup (string xyz ,string abc ,EventHandler eh)
    {
        DependencyService.Get<IPopUp>().Popup(xyz, abc,
         (Color)Application.Current.Resources["PopUpTitleColor"],
         (Color)Application.Current.Resources["PopUpMessageColor"],
         (Color)Application.Current.Resources["PopUpBackgroundColor"],
         (Color)Application.Current.Resources["PopUpSeparatorColor"],
         eh;
    }
}

usage

Helper.Popup("XYZ" , "ABC" , (sen, args) => DidShowFirstMessage = true );

but having an extention method could be a better option here :

static class Helper
{
     public static void Popup (this IDependencyService ds, string xyz ,string abc ,EventHandler eh)
    {
        ds.Get<IPopUp>().Popup(xyz, abc,
         (Color)Application.Current.Resources["PopUpTitleColor"],
         (Color)Application.Current.Resources["PopUpMessageColor"],
         (Color)Application.Current.Resources["PopUpBackgroundColor"],
         (Color)Application.Current.Resources["PopUpSeparatorColor"],
         eh;
    }
}

usage

DependencyService.Popup("XYZ" , "ABC" , (sen, args) => DidShowFirstMessage = true );


问:
Capture url inside method onBackPressed
How can i capture the url when the method onBackPressed is fired?

I already tried use the method getUrl(), but it brings me a url of the page i'm on and not the page I came back to.

I need the behavior that the method shouldOverrideUrlLoading has, but inside the onBackPressed (because i need to do the same condition).

Is there a way to do this?

PS: I'm using an WebView.

My Activity:

```<code>public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

    String mosaicUrl = "https://www.mosaicapp.com.br";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        myWebView = findViewById(R.id.webview);

        myWebView.loadUrl(mosaicUrl);

        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                CookieSyncManager.getInstance().sync();
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                setContentView(R.layout.activity_error);
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                int slashslash = url.indexOf("//") + 2;
                String domain = url.substring(slashslash, url.indexOf('/', slashslash));

                ImageView imageview = findViewById(R.id.imageBack);

                if (domain.equals("www.mosaicapp.com.br")) {
                    imageview.setVisibility(View.GONE);
                } else {
                    imageview.setVisibility(View.VISIBLE);
                }

                return false;
            }
        });

        WebSettings webSettings = myWebView.getSettings();

        // Enable JavaScript
        webSettings.setJavaScriptEnabled(true);

        // Return to Home
        ImageView imageBack = findViewById(R.id.imageBack);
        imageBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                myWebView.loadUrl(mosaicUrl);
            }
        });
    }

    @Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            // Let the system handle the back button
            super.onBackPressed();
        }
    }
}
</code>```

答:
What you need to do is ask for pageFinish, once the page finishes loading, you have to ask for the current url:

```<code>public String currentUrl = "";
webView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        currentUrl = webView.getUrl();
    }

});
</code>```

This should do the job.

Title: Capture url inside method onBackPressed

Body:
How can i capture the url when the method onBackPressed is fired?

I already tried use the method getUrl(), but it brings me a url of the page i'm on and not the page I came back to.

I need the behavior that the method shouldOverrideUrlLoading has, but inside the onBackPressed (because i need to do the same condition).

Is there a way to do this?

PS: I'm using an WebView.

My Activity:

public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

    String mosaicUrl = "https://www.mosaicapp.com.br";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        myWebView = findViewById(R.id.webview);

        myWebView.loadUrl(mosaicUrl);

        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                CookieSyncManager.getInstance().sync();
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                setContentView(R.layout.activity_error);
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                int slashslash = url.indexOf("//") + 2;
                String domain = url.substring(slashslash, url.indexOf('/', slashslash));

                ImageView imageview = findViewById(R.id.imageBack);

                if (domain.equals("www.mosaicapp.com.br")) {
                    imageview.setVisibility(View.GONE);
                } else {
                    imageview.setVisibility(View.VISIBLE);
                }

                return false;
            }
        });

        WebSettings webSettings = myWebView.getSettings();

        // Enable JavaScript
        webSettings.setJavaScriptEnabled(true);

        // Return to Home
        ImageView imageBack = findViewById(R.id.imageBack);
        imageBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                myWebView.loadUrl(mosaicUrl);
            }
        });
    }

    @Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            // Let the system handle the back button
            super.onBackPressed();
        }
    }
}

Body:
What you need to do is ask for pageFinish, once the page finishes loading, you have to ask for the current url:

public String currentUrl = "";
webView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        currentUrl = webView.getUrl();
    }

});

This should do the job.


问:
How to convert string of image urls in android
I am have a list (100's) of image urls which I want to display in a ListView together with text. The problem I am having is that my listview displays all the URLs as string and not IMAGE. I have implemented a BITMAP class and tested it with a sigle image url, and on an IMAGEVIEW, it worked. I have read some post but can't really figure it out working with ListView. How to load an ImageView by URL in Android?

In the my code below, imageUrls holds all the image urls as string and concatString holds img + text, which was used in the adapter. My question is how do I apply the BITMAP class on a STRING that holds all the urls before putting it in the adapter, that is imageUrls? Or is ther a better approach.

```<code>Bitmap bitmap;
String temp, json, namesImg, imageUrls, allImageANDnames;
StringBuffer sb = new StringBuffer();
ArrayList<String> concatString = new ArrayList<String>(); // ARRAYLIST THAT HOLDS IMG & TXT
JSONObject object;

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

    // Reading json file from assets folder
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open(
                "myjson.json")));
        while ((temp = br.readLine()) != null)
            sb.append(temp);

        json = new String(sb);
        JSONArray jsonArray = new JSONArray(json);

        for (int i = 0; i < jsonArray.length(); i++) {
            // Creating JSONObject from JSONArray
            object = jsonArray.getJSONObject(i);
            namesImg = object.getString("name"); // holds all text
            imageUrls = object.getString("url"); // holds all image urls (HERE IS WHERE I NEED HELP)
            allImageANDnames = imageUrls + "\t\t" + namesImg; // holds text and img urls
            concatString.add(allImageANDnames); //(I WANT THIS TO HOLD IMAGES & TEXT) not urls & text
        }

    } catch (IOException e) {
        e.printStackTrace();
    }  catch (JSONException e) {
        e.printStackTrace();
    }finally {
        if ((br != null)) {
            try {
                br.close(); // stop reading
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // adapter to show list in activity
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, concatString); // I USED THE HOLDER HERE

    ListView list = (ListView) findViewById(R.id.listView);
    list.setAdapter(adapter); // LIST THAT POPULATE THE IMG & TXT
}

    // HOW CAN I APPLY THIS CLASS ON ***imageUrls***
    public class ImageFromUrl extends AsyncTask<String, Void, Bitmap> {
    ImageView imageView;
    public GetImageFromUrl(ImageView img){
        this.imageView = img;
    }
    @Override
    protected Bitmap doInBackground(String... url) {
        String stringUrl = url[0];
        bitmap = null;
        InputStream inputStream;
        try {
            inputStream = new java.net.URL(stringUrl).openStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap){
        super.onPostExecute(bitmap);
        imageView.setImageBitmap(bitmap);
    }
}
</code>```

.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >
    </ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Sorry I am ney on this.

答:
Use ImageView for showing images with recyclerview instead of the listview.

and the solution is simple. Use library(like glide, Picasso, etc) that coverts the URL into Image and set on to the location.
Picasso.get()
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

Use this Library Picasso

Body:
I am have a list (100's) of image urls which I want to display in a ListView together with text. The problem I am having is that my listview displays all the URLs as string and not IMAGE. I have implemented a BITMAP class and tested it with a sigle image url, and on an IMAGEVIEW, it worked. I have read some post but can't really figure it out working with ListView. How to load an ImageView by URL in Android?

In the my code below, imageUrls holds all the image urls as string and concatString holds img + text, which was used in the adapter. My question is how do I apply the BITMAP class on a STRING that holds all the urls before putting it in the adapter, that is imageUrls? Or is ther a better approach.

Bitmap bitmap;
String temp, json, namesImg, imageUrls, allImageANDnames;
StringBuffer sb = new StringBuffer();
ArrayList<String> concatString = new ArrayList<String>(); // ARRAYLIST THAT HOLDS IMG & TXT
JSONObject object;

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

    // Reading json file from assets folder
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open(
                "myjson.json")));
        while ((temp = br.readLine()) != null)
            sb.append(temp);

        json = new String(sb);
        JSONArray jsonArray = new JSONArray(json);

        for (int i = 0; i < jsonArray.length(); i++) {
            // Creating JSONObject from JSONArray
            object = jsonArray.getJSONObject(i);
            namesImg = object.getString("name"); // holds all text
            imageUrls = object.getString("url"); // holds all image urls (HERE IS WHERE I NEED HELP)
            allImageANDnames = imageUrls + "\t\t" + namesImg; // holds text and img urls
            concatString.add(allImageANDnames); //(I WANT THIS TO HOLD IMAGES & TEXT) not urls & text
        }

    } catch (IOException e) {
        e.printStackTrace();
    }  catch (JSONException e) {
        e.printStackTrace();
    }finally {
        if ((br != null)) {
            try {
                br.close(); // stop reading
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // adapter to show list in activity
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, concatString); // I USED THE HOLDER HERE

    ListView list = (ListView) findViewById(R.id.listView);
    list.setAdapter(adapter); // LIST THAT POPULATE THE IMG & TXT
}

    // HOW CAN I APPLY THIS CLASS ON ***imageUrls***
    public class ImageFromUrl extends AsyncTask<String, Void, Bitmap> {
    ImageView imageView;
    public GetImageFromUrl(ImageView img){
        this.imageView = img;
    }
    @Override
    protected Bitmap doInBackground(String... url) {
        String stringUrl = url[0];
        bitmap = null;
        InputStream inputStream;
        try {
            inputStream = new java.net.URL(stringUrl).openStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap){
        super.onPostExecute(bitmap);
        imageView.setImageBitmap(bitmap);
    }
}

.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >
    </ListView>
</androidx.constraintlayout.widget.ConstraintLayout>

Sorry I am ney on this.


问:
From Notification: AlertDialog without UI
I'm creating a notification which fires an Intent. Here a really shortened excerpt of my code...

```<code>Notification notification = new Notification(R.drawable.icon, "notification", System.currentTimeMillis());
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(BackgroundService.this, ConnectionHandler.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, getString(R.string.notification_title), getString(R.string.notification_body), pendingIntent);
notification.flags |= notification.FLAG_AUTO_CANCEL;
nm.notify(1, notification);
</code>```

In my intent (ConnectionHandler.class), I'd like to show an AlertDialog, which works. But I'd like the AlertDialog to show up without opening a new UI-Window. The best for me was if the AlertDialog simply appears without anything else when tapping the notification-entry.

Any idea is appreciated.

Regards, Tobi

答:
Create transparent Activity like below:

How do I create a transparent Activity on Android?

and combine it with dialog theme.

Body:
I'm creating a notification which fires an Intent. Here a really shortened excerpt of my code...

Notification notification = new Notification(R.drawable.icon, "notification", System.currentTimeMillis());
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(BackgroundService.this, ConnectionHandler.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, getString(R.string.notification_title), getString(R.string.notification_body), pendingIntent);
notification.flags |= notification.FLAG_AUTO_CANCEL;
nm.notify(1, notification);

In my intent (ConnectionHandler.class), I'd like to show an AlertDialog, which works. But I'd like the AlertDialog to show up without opening a new UI-Window. The best for me was if the AlertDialog simply appears without anything else when tapping the notification-entry.

Any idea is appreciated.

Regards, Tobi


问:
Java and fractions
I'm trying to add three instance methods to the public interface of class 'Fraction' that all return a 'Fraction' as a result:

add, subtraction and multiplication. is it possible to change it from my current code into instance methods?

I just can't get it to work

Here is my code:

```<code>class Fraction {
    private Integer numerator;
    private Integer denumerator;

    public Fraction(Integer numerator, Integer denumerator) {

        int gcd = 1;

        for (int i = 1; i <= numerator && i <= denumerator; i++) {
            if (numerator % i == 0 && denumerator % i == 0)
                gcd = i;
        }
        this.numerator = numerator / gcd;
        this.denumerator = denumerator / gcd;
    }

    public Fraction(Integer numerator) {
        this.numerator = numerator;
        this.denumerator = 1;
    }

    public String toString() {

        return numerator + "/" + denumerator;
    }

    public static Fraction add(Fraction f1,Fraction f2){
        return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
    }
    public static Fraction subtract(Fraction f1,Fraction f2){
        return new Fraction(f1.numerator*f2.denumerator-f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
    }
    public static Fraction mul(Fraction f1,Fraction f2){
        return new Fraction(f1.numerator*f2.numerator,f1.denumerator*f2.denumerator);
    }
}

class Main
{
    public static void main(String[] arguments)
    {
        final Fraction HALF = new Fraction(1, 2);
        final Fraction THREE_FIFTH = new Fraction(3, 5);
        System.out.println(HALF.add(HALF, THREE_FIFTH).toString());
        System.out.println(THREE_FIFTH.subtract(HALF, THREE_FIFTH).toString());
        System.out.println(HALF.mul(HALF, THREE_FIFTH).toString());
    }
}
</code>```

答:
```<code>public static Fraction add(Fraction f1,Fraction f2){
  return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,
                      f1.denumerator*f2.denumerator);
}
</code>```

is a class method (because of the static it does not need an instance to call "on").

Making it instance method would look like

```<code>public Fraction add(Fraction other){
  return new Fraction(this.numerator*other.denumerator+other.numerator*this.denumerator,
                      this.denumerator*other.denumerator);
}
</code>```

of course you do not actually need to write the thiss there, just they emphasize that f1 became the current object, and f2 became the single argument.

Then you could use it as

```<code>Fraction HALF = new Fraction(1, 2);
Fraction THREE_FIFTH = new Fraction(3, 5);
System.out.println(HALF.add(THREE_FIFTH));
</code>```

without repeating HALF (like HALF.add(HALF,THREE_FIFTH) in the original code).

Side comment: class methods (static stuff) can be referred via the name of the class, your original code would be more conventionally called in the form Fraction.add(...):

```<code>System.out.println(Fraction.add(HALF,THREE_FIFTH));
</code>```

(System.out.println() knows that it should call toString() so you do not actually need to do that yourself)

Title: Java and fractions

Body:
I'm trying to add three instance methods to the public interface of class 'Fraction' that all return a 'Fraction' as a result:

add, subtraction and multiplication. is it possible to change it from my current code into instance methods?

I just can't get it to work

Here is my code:

class Fraction {
    private Integer numerator;
    private Integer denumerator;

    public Fraction(Integer numerator, Integer denumerator) {

        int gcd = 1;

        for (int i = 1; i <= numerator && i <= denumerator; i++) {
            if (numerator % i == 0 && denumerator % i == 0)
                gcd = i;
        }
        this.numerator = numerator / gcd;
        this.denumerator = denumerator / gcd;
    }

    public Fraction(Integer numerator) {
        this.numerator = numerator;
        this.denumerator = 1;
    }

    public String toString() {

        return numerator + "/" + denumerator;
    }

    public static Fraction add(Fraction f1,Fraction f2){
        return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
    }
    public static Fraction subtract(Fraction f1,Fraction f2){
        return new Fraction(f1.numerator*f2.denumerator-f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
    }
    public static Fraction mul(Fraction f1,Fraction f2){
        return new Fraction(f1.numerator*f2.numerator,f1.denumerator*f2.denumerator);
    }
}

class Main
{
    public static void main(String[] arguments)
    {
        final Fraction HALF = new Fraction(1, 2);
        final Fraction THREE_FIFTH = new Fraction(3, 5);
        System.out.println(HALF.add(HALF, THREE_FIFTH).toString());
        System.out.println(THREE_FIFTH.subtract(HALF, THREE_FIFTH).toString());
        System.out.println(HALF.mul(HALF, THREE_FIFTH).toString());
    }
}

Body:
public static Fraction add(Fraction f1,Fraction f2){
  return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,
                      f1.denumerator*f2.denumerator);
}

is a class method (because of the static it does not need an instance to call "on").

Making it instance method would look like

public Fraction add(Fraction other){
  return new Fraction(this.numerator*other.denumerator+other.numerator*this.denumerator,
                      this.denumerator*other.denumerator);
}

of course you do not actually need to write the thiss there, just they emphasize that f1 became the current object, and f2 became the single argument.

Then you could use it as

Fraction HALF = new Fraction(1, 2);
Fraction THREE_FIFTH = new Fraction(3, 5);
System.out.println(HALF.add(THREE_FIFTH));

without repeating HALF (like HALF.add(HALF,THREE_FIFTH) in the original code).

Side comment: class methods (static stuff) can be referred via the name of the class, your original code would be more conventionally called in the form Fraction.add(...):

System.out.println(Fraction.add(HALF,THREE_FIFTH));

(System.out.println() knows that it should call toString() so you do not actually need to do that yourself)


问:
Python: Reading an Access database
This Python script has worked beautifully until today. I recently added a column to the table listed in the FROM clause. However, it is not the field listed in the error message.

I have also tried adding pyodbc.pooling = False to the code but that changed nothing.

I am at a loss and any help would be greatly appreciated.

```<code># Load the needed packages
import pyodbc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

# Define the connection parameters for MS Access
myDataSources = pyodbc.dataSources()
access_driver = myDataSources['MS Access Database']
file = '\Datasets\BookData.accdb'

# Connect to MS Access
cnxn = pyodbc.connect(Driver = access_driver, DBQ = file)

# Create a query which pulls in the correct data from MS Access
query = pd.read_sql_query('''SELECT * FROM table''', cnxn)

# Close the connection to the MS Access database
cnxn.close()
</code>```

Error Message

DatabaseError: Execution failed on sql 'SELECT * FROM table':
  ('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] The
  specified field 'different_table.[field] could refer to more than one
  table listed in the FROM clause of your SQL statement. (-3007)
  (SQLExecDirectW)")

答:
As discussed, likely table in SQL query is not actual table but a stored query or view (as used in other databases) which is queryable like a table. Access raises an error because somewhere in query you reference a duplicate field without aliasing table. For example, Customers and Orders tables can have a field named CustomerID and you run this form:

SELECT CustomerID, ...
FROM Customers c
INNER JOIN Orders o
  ON c.CustomerID = o.CustomerID
```

<p>Or even ran this query:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM Customers c
INNER JOIN Orders o
  ON c.CustomerID = o.CustomerID
</code>```

Then in Python you call this form which raises the error due to multiple sources for CustomerID:

SELECT * FROM myStoredQuery
```

<p>Why did this error raise now and not before? Because you may have added same named columns in underlying tables and then used <code>*</code> in <code>SELECT</code> clause of top query. So <em>any</em> new column added to <em>any</em> referenced table is pulled into final query.</p>

<p>To resolve, consider aliasing any potential name collisions. And as advised in most applications running SQL (beyond Python):</p>

<ul>
<li><p>Always explicitly identify columns in <code>SELECT</code> clause and do not abbreviate with <code>*</code>.</p></li>
<li><p>Always period qualify the table sources of columns when more than one table is referenced in query (i.e., <code>c.CustomerID</code> or <code>o.CustomerID</code>) such as with joins.</p></li>
</ul>

<p>See adjusted SQL:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT c.CustomerID AS Customer_CustomerID,
       o.CustomerID AS Order_CustomerID,
       ...
FROM Customers c
INNER JOIN Orders o
  ON c.CustomerID = o.CustomerID
</code>```

While it seems tedious to write out every column, doing so helps in maintainability as you control and clearly see intended output and account for restructured changes like new, dropped, duplicate, or special named columns. Maybe too you do not need all columns in Pandas and so can omit them in SELECT.

Finally, remember SQL is a declarative, special purpose language designed to send explicit commands to database engine in readable form for user. The engine uses different code to handle the requests. For Access' Jet/ACE Engine being Window .dlls this may be C or C++.

Title: Python: Reading an Access database

Body:
This Python script has worked beautifully until today. I recently added a column to the table listed in the FROM clause. However, it is not the field listed in the error message.

I have also tried adding pyodbc.pooling = False to the code but that changed nothing.

I am at a loss and any help would be greatly appreciated.

# Load the needed packages
import pyodbc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

# Define the connection parameters for MS Access
myDataSources = pyodbc.dataSources()
access_driver = myDataSources['MS Access Database']
file = '\Datasets\BookData.accdb'

# Connect to MS Access
cnxn = pyodbc.connect(Driver = access_driver, DBQ = file)

# Create a query which pulls in the correct data from MS Access
query = pd.read_sql_query('''SELECT * FROM table''', cnxn)

# Close the connection to the MS Access database
cnxn.close()

Error Message

DatabaseError: Execution failed on sql 'SELECT * FROM table':
  ('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] The
  specified field 'different_table.[field] could refer to more than one
  table listed in the FROM clause of your SQL statement. (-3007)
  (SQLExecDirectW)")

Body:
As discussed, likely table in SQL query is not actual table but a stored query or view (as used in other databases) which is queryable like a table. Access raises an error because somewhere in query you reference a duplicate field without aliasing table. For example, Customers and Orders tables can have a field named CustomerID and you run this form:

SELECT CustomerID, ...
FROM Customers c
INNER JOIN Orders o
  ON c.CustomerID = o.CustomerID

Or even ran this query:

SELECT *
FROM Customers c
INNER JOIN Orders o
  ON c.CustomerID = o.CustomerID

Then in Python you call this form which raises the error due to multiple sources for CustomerID:

SELECT * FROM myStoredQuery

Why did this error raise now and not before? Because you may have added same named columns in underlying tables and then used * in SELECT clause of top query. So any new column added to any referenced table is pulled into final query.

To resolve, consider aliasing any potential name collisions. And as advised in most applications running SQL (beyond Python):

Always explicitly identify columns in SELECT clause and do not abbreviate with *.

Always period qualify the table sources of columns when more than one table is referenced in query (i.e., c.CustomerID or o.CustomerID) such as with joins.

See adjusted SQL:

SELECT c.CustomerID AS Customer_CustomerID,
       o.CustomerID AS Order_CustomerID,
       ...
FROM Customers c
INNER JOIN Orders o
  ON c.CustomerID = o.CustomerID

While it seems tedious to write out every column, doing so helps in maintainability as you control and clearly see intended output and account for restructured changes like new, dropped, duplicate, or special named columns. Maybe too you do not need all columns in Pandas and so can omit them in SELECT.

Finally, remember SQL is a declarative, special purpose language designed to send explicit commands to database engine in readable form for user. The engine uses different code to handle the requests. For Access' Jet/ACE Engine being Window .dlls this may be C or C++.


问:
Check if a string contains the keywords of a file c#
I'm trying to check if a string contains a keyword present in a text file but nothing was done

If you need more information ask me

For exemple i have a keywords.txt like this :

```<code>example1
example2
example3
</code>```

and i want to see if one of these keyword are in a json string like this :

```<code>{
     "title":"new doc 4",
     "rotate":0,
     "sort_key":"new doc 4",
     "tag_ids":"",
     "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
     "co_token":"",
     "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
     "t":"1474932063",
     "c":"2",
     "updated":"1474932063"
}
</code>```

You can see what i have try below
So I'm hoping you can help me solve this problem thanks

```<code>if (json.Contains(File.ReadAllText(@"keywords.txt")))
{
    //My if logic
}
else
{
    //My else logic
}
</code>```

答:
The below approach will help eliminate the false positives, it checks if the Specific keyword is present in the JSON string and only then process further

Just doing String.contains might swallow these false positives and
  come up as true

Input File KeyWords

```<code>keyword  //This will return as false
keyword1 //This will return true
</code>```

Input File Json

```<code>{
   "title":"new doc 4",
   "rotate":0,
   "sort_key":"new doc 4",
   "tag_ids":"",
   "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
   "co_token":"",
   "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
   "t":"1474932063",
   "c":"2",
   "updated":"keyword1"
}
</code>```

Main

```<code>var keyWordFilePath = @"keyWord.txt";
var jsonFilePath = @"json.txt";
var jsonString = File.ReadAllText(jsonFilePath);
var keywords = File.ReadAllText(keyWordFilePath).Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

foreach (var key in keywords)
{

      //We are checking if json string contains key and also checking that it is only that definite key
      var extractSpecificKey = jsonString.Substring(jsonString.IndexOf(key), key.Length+1);

      if (extractSpecificKey == key+ @"""")
      {

         Console.WriteLine($"Key {extractSpecificKey} present in json");

      }
     //False Positives
      else
      {
         Console.WriteLine($"Key {key} NOT present in json");
      }
}

Console.Read();

</code>```

Output

```<code>Key keyword NOT present in json
Key keyword1" present in json
</code>```

Body:
I'm trying to check if a string contains a keyword present in a text file but nothing was done

If you need more information ask me

For exemple i have a keywords.txt like this :

example1
example2
example3

and i want to see if one of these keyword are in a json string like this :

{
     "title":"new doc 4",
     "rotate":0,
     "sort_key":"new doc 4",
     "tag_ids":"",
     "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
     "co_token":"",
     "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
     "t":"1474932063",
     "c":"2",
     "updated":"1474932063"
}

You can see what i have try below
So I'm hoping you can help me solve this problem thanks

if (json.Contains(File.ReadAllText(@"keywords.txt")))
{
    //My if logic
}
else
{
    //My else logic
}

Body:
The below approach will help eliminate the false positives, it checks if the Specific keyword is present in the JSON string and only then process further

Just doing String.contains might swallow these false positives and
  come up as true

Input File KeyWords

keyword  //This will return as false
keyword1 //This will return true

Input File Json

{
   "title":"new doc 4",
   "rotate":0,
   "sort_key":"new doc 4",
   "tag_ids":"",
   "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
   "co_token":"",
   "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
   "t":"1474932063",
   "c":"2",
   "updated":"keyword1"
}

Main

var keyWordFilePath = @"keyWord.txt";
var jsonFilePath = @"json.txt";
var jsonString = File.ReadAllText(jsonFilePath);
var keywords = File.ReadAllText(keyWordFilePath).Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

foreach (var key in keywords)
{

      //We are checking if json string contains key and also checking that it is only that definite key
      var extractSpecificKey = jsonString.Substring(jsonString.IndexOf(key), key.Length+1);

      if (extractSpecificKey == key+ @"""")
      {

         Console.WriteLine($"Key {extractSpecificKey} present in json");

      }
     //False Positives
      else
      {
         Console.WriteLine($"Key {key} NOT present in json");
      }
}

Console.Read();

Output

Key keyword NOT present in json
Key keyword1" present in json


问:
How to succinctly call a PL/SQL procedure and return its output variables in Spring with JdbcTemplate?
New to Oracle here.  My experience is building web apps which send queries to a database and get a "result set" back, for example in Java with Spring and JdbcTemplate.

For example, here's a code sample with a regular SQL query, using a RowMapper class to turn the rows of a result set into a Java list:

public List<Widget> findAllWidgets() {
    return jdbcTemplate.query("SELECT * FROM widgets", new WidgetRowMapper());
}
```

<p>Now I am tasked with writing a query that calls a PL/SQL stored procedure.  This procedure has two input arguments (these I can handle) and two output arguments (let's call them <code>error_code</code> and <code>error_message</code>).  I want to send a query to the database that will (a) run the procedure with my inputs and (b) return the two outputs.  I would be equally happy to have the two outputs as a "row" or simply bind them to two Java variables.</p>

<p>Here's what I've tried, and it's not throwing an error but it's not getting the output values, either.  The Java variables <code>errorCode</code> and <code>errorMessage</code> remain empty strings:</p>

<pre class="lang-java prettyprint-override"><code>public Map<String,String> callMyProcedure() {
    String errorCode="";
    String errorMessage="";
    jdbcTemplate.update("call myprocedure(?,?,?,?)","input1","input2",errorCode,errorMessage);
    return Map.of("errorCode",errorCode,"errorMessage",errorMessage);
}
</code>```

The question is: How can I capture the values of the PL/SQL procedure's "OUT" variables when calling the procedure from Java with JdbcTemplate?

EDIT: I accepted Alex's answer which doesn't use JdbcTemplate, because it seems to be the better way.  My own answer does use JdbcTemplate but takes a lot more code, so if you're searching for something that specifically answers the question, that will do it.

答:
You can use plain JDBC.

```<code>final String charlie;
final String zulu;
try (CallableStatement cs = connection.prepareCall("{call myprocedure(?,?,?,?,?,?,?,?)}")) {
    cs.setString(1, "foo");
    cs.setString(2, "bar");
    cs.setString(3, "baz");
    cs.setString(4, "whisky");
    cs.setString(5, "tango");
    cs.setString(6, "foxtrot");
    cs.registerOutParameter(7, Types.VARCHAR);
    cs.registerOutParameter(8, Types.VARCHAR);
    cs.execute();
    connection.commit(); // optional
    charlie = cs.getString(7);
    zulu = cs.getString(8);
}
</code>```

When using JDBC, it is dangerous to use the getInt method and similar ones, since they convert the type to primitive and zero is replaced by 0. It is better to use a (Integer) cs.getObject(). Similarly, setInt does not support the reference type.

Body:
New to Oracle here.  My experience is building web apps which send queries to a database and get a "result set" back, for example in Java with Spring and JdbcTemplate.

For example, here's a code sample with a regular SQL query, using a RowMapper class to turn the rows of a result set into a Java list:

public List<Widget> findAllWidgets() {
    return jdbcTemplate.query("SELECT * FROM widgets", new WidgetRowMapper());
}

Now I am tasked with writing a query that calls a PL/SQL stored procedure.  This procedure has two input arguments (these I can handle) and two output arguments (let's call them error_code and error_message).  I want to send a query to the database that will (a) run the procedure with my inputs and (b) return the two outputs.  I would be equally happy to have the two outputs as a "row" or simply bind them to two Java variables.

Here's what I've tried, and it's not throwing an error but it's not getting the output values, either.  The Java variables errorCode and errorMessage remain empty strings:

public Map<String,String> callMyProcedure() {
    String errorCode="";
    String errorMessage="";
    jdbcTemplate.update("call myprocedure(?,?,?,?)","input1","input2",errorCode,errorMessage);
    return Map.of("errorCode",errorCode,"errorMessage",errorMessage);
}

The question is: How can I capture the values of the PL/SQL procedure's "OUT" variables when calling the procedure from Java with JdbcTemplate?

EDIT: I accepted Alex's answer which doesn't use JdbcTemplate, because it seems to be the better way.  My own answer does use JdbcTemplate but takes a lot more code, so if you're searching for something that specifically answers the question, that will do it.

Body:
You can use plain JDBC.

final String charlie;
final String zulu;
try (CallableStatement cs = connection.prepareCall("{call myprocedure(?,?,?,?,?,?,?,?)}")) {
    cs.setString(1, "foo");
    cs.setString(2, "bar");
    cs.setString(3, "baz");
    cs.setString(4, "whisky");
    cs.setString(5, "tango");
    cs.setString(6, "foxtrot");
    cs.registerOutParameter(7, Types.VARCHAR);
    cs.registerOutParameter(8, Types.VARCHAR);
    cs.execute();
    connection.commit(); // optional
    charlie = cs.getString(7);
    zulu = cs.getString(8);
}

When using JDBC, it is dangerous to use the getInt method and similar ones, since they convert the type to primitive and zero is replaced by 0. It is better to use a (Integer) cs.getObject(). Similarly, setInt does not support the reference type.


问:
transfer object ownership with placement new
I have a Visual Studio 2008 C++ project with a class that manages a resource that cannot be copied. I have implemented transfer-by-reference-structure semantics (ala std::auto_ptr).

```<code>class Test;

struct Test_Ref
{
    Test& ref_;
    Test_Ref( Test& t ) : ref_( t ) { };
private:
    Test_Ref& operator=( Test_Ref const& );
}; // struct Test_Ref

class Test
{
public:
    explicit Test( int f = 0 ) : foo_( f ) { };

    Test( Test& other ) : foo_( other.Detach() ) { };

    Test& operator=( Test& other )
    {
        foo_ = other.Detach();
        return *this;
    };

    Test( Test_Ref other ) : foo_( other.ref_.Detach() ) { };

    Test& operator=( Test_Ref other )
    {
        foo_ = other.ref_.Detach();
        return *this;
    };

    operator Test_Ref() { return Test_Ref( *this ); };

private:

    int Detach()
    {
        int tmp = foo_;
        foo_ = 0;
        return tmp;
    };

    // resource that cannot be copied.
    int foo_;
}; // class Test
</code>```

Unfortunately, when I use this pattern with a library that uses placement-new, I get a compiler error:

```<code>.\test.cpp(58) : error C2558: class 'Test' : no copy constructor available or copy constructor is declared 'explicit'
    .\test.cpp(68) : see reference to function template instantiation 'void Copy<Test>(T *,const T &)' being compiled
    with
    [
        T=Test
    ]
</code>```

For example:

```<code>template< class T > inline void Copy( T* p, const T& val )
{
    new( p ) T( val );
}

int _tmain( int /*argc*/, _TCHAR* /*argv*/[] )
{
    Test* __p = new Test();
    Test __val;
    Copy( __p, __val );
    return 0;
}
</code>```

How can I modify Test such that it can be used with placement new and still retain its ownership semantics?

Thanks,
PaulH

答: Your problem has nothing to do with placement new. In void Copy then you attempted to copy an object of type Test, but you disallow copying. That's the problem. Also, you attempted to placement new on NULL. You failed to implement the structure properly because of the constness- operator test_ref() can never be called because you took a const T& and it's a non-const operator. This means that unless you want to surprise people with moves when they think it should be copies, you cannot do this.

Body:
I have a Visual Studio 2008 C++ project with a class that manages a resource that cannot be copied. I have implemented transfer-by-reference-structure semantics (ala std::auto_ptr).

class Test;

struct Test_Ref
{
    Test& ref_;
    Test_Ref( Test& t ) : ref_( t ) { };
private:
    Test_Ref& operator=( Test_Ref const& );
}; // struct Test_Ref

class Test
{
public:
    explicit Test( int f = 0 ) : foo_( f ) { };

    Test( Test& other ) : foo_( other.Detach() ) { };

    Test& operator=( Test& other )
    {
        foo_ = other.Detach();
        return *this;
    };

    Test( Test_Ref other ) : foo_( other.ref_.Detach() ) { };

    Test& operator=( Test_Ref other )
    {
        foo_ = other.ref_.Detach();
        return *this;
    };

    operator Test_Ref() { return Test_Ref( *this ); };

private:

    int Detach()
    {
        int tmp = foo_;
        foo_ = 0;
        return tmp;
    };

    // resource that cannot be copied.
    int foo_;
}; // class Test

Unfortunately, when I use this pattern with a library that uses placement-new, I get a compiler error:

.\test.cpp(58) : error C2558: class 'Test' : no copy constructor available or copy constructor is declared 'explicit'
    .\test.cpp(68) : see reference to function template instantiation 'void Copy<Test>(T *,const T &)' being compiled
    with
    [
        T=Test
    ]

For example:

template< class T > inline void Copy( T* p, const T& val )
{
    new( p ) T( val );
}

int _tmain( int /*argc*/, _TCHAR* /*argv*/[] )
{
    Test* __p = new Test();
    Test __val;
    Copy( __p, __val );
    return 0;
}

How can I modify Test such that it can be used with placement new and still retain its ownership semantics?

Thanks,
PaulH


问:
Applying borders to InlineShape applies to table it resides in rather than image
So I have some InlineShapes that resides in a table in WORD. I'm trying to take all the InlineShapes in the third column of the table and apply a border around them. Unfortunately for the life of me I can't figure out how to apply it to the picture rather than the cell of the table.

Here is my code:

```<code>ActiveDocument.Tables(1).Columns(3).Select

For Each iPicture In Selection.InlineShapes
    With iPicture
        .Borders.Enable = True
        .Borders.OutsideColor = wdColorRed
        .Borders.OutsideLineWidth = wdLineWidth150pt
        .Borders.OutsideLineStyle = wdLineStyleSingle
    End With
Next
</code>```

I also tried putting the following code inside With iPicture but didn't seem to make a difference, still drawing a border around the cell rather than the picture.

```<code>With .Borders(wdBorderLeft)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

With .Borders(wdBorderRight)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

With .Borders(wdBorderTop)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

With .Borders(wdBorderBottom)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With
</code>```

答:
My tests were inconclusive. Some objects received a border; with others, the border was applied to the cell.

In all the latter cases, however, if I placed a space after the object (at the end of the cell) the border was applied correctly.

I therefore suspect that it has something to do with the hidden paragraph mark at the end of a cell that's somehow, sometimes, getting picked up by the InlineShape object.

The following sample code adds a space after each InlineShape if the number of the characters in the cell is less than or equal to two (contains only the InlineShape and end-of-cell marker).

Inserting the space collapses the selection. Therefore the table and selected column are noted at the beginning and that column re-selected after that action. If the space is a problem for you, add code that goes through and removes it after the borders have been created.

```<code>Sub BorderInlineShapes()
    Dim sel As Word.Selection
    Dim ils As Word.InlineShape
    Dim rng As Word.Range
    Dim colNr As Long
    Dim tbl As Word.Table

    Set sel = Selection
    If sel.Tables.Count = 1 Then
        Set tbl = sel.Tables(1)
        colNr = sel.Information(wdEndOfRangeColumnNumber)
        For Each ils In sel.InlineShapes
            If Not ils.Borders.Enable Then ils.Borders.Enable = True
            If ils.Range.Cells.Count > 0 Then
                Set rng = ils.Range
                If rng.Cells(1).Range.Characters.Count <= 2 Then
                    rng.InsertAfter " "
                    tbl.Columns(colNr).Select
                End If
            End If
            ils.Borders.OutsideColor = wdColorRed
            ils.Borders.OutsideLineWidth = wdLineWidth075pt
        Next
    End If
End Sub
</code>```

Body:
So I have some InlineShapes that resides in a table in WORD. I'm trying to take all the InlineShapes in the third column of the table and apply a border around them. Unfortunately for the life of me I can't figure out how to apply it to the picture rather than the cell of the table.

Here is my code:

ActiveDocument.Tables(1).Columns(3).Select

For Each iPicture In Selection.InlineShapes
    With iPicture
        .Borders.Enable = True
        .Borders.OutsideColor = wdColorRed
        .Borders.OutsideLineWidth = wdLineWidth150pt
        .Borders.OutsideLineStyle = wdLineStyleSingle
    End With
Next

I also tried putting the following code inside With iPicture but didn't seem to make a difference, still drawing a border around the cell rather than the picture.

With .Borders(wdBorderLeft)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

With .Borders(wdBorderRight)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

With .Borders(wdBorderTop)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

With .Borders(wdBorderBottom)
    .LineStyle = wdLineStyleSingle
    .LineWidth = wdLineWidth150pt
    .Color = wdColorRed
End With

Body:
My tests were inconclusive. Some objects received a border; with others, the border was applied to the cell.

In all the latter cases, however, if I placed a space after the object (at the end of the cell) the border was applied correctly.

I therefore suspect that it has something to do with the hidden paragraph mark at the end of a cell that's somehow, sometimes, getting picked up by the InlineShape object.

The following sample code adds a space after each InlineShape if the number of the characters in the cell is less than or equal to two (contains only the InlineShape and end-of-cell marker).

Inserting the space collapses the selection. Therefore the table and selected column are noted at the beginning and that column re-selected after that action. If the space is a problem for you, add code that goes through and removes it after the borders have been created.

Sub BorderInlineShapes()
    Dim sel As Word.Selection
    Dim ils As Word.InlineShape
    Dim rng As Word.Range
    Dim colNr As Long
    Dim tbl As Word.Table

    Set sel = Selection
    If sel.Tables.Count = 1 Then
        Set tbl = sel.Tables(1)
        colNr = sel.Information(wdEndOfRangeColumnNumber)
        For Each ils In sel.InlineShapes
            If Not ils.Borders.Enable Then ils.Borders.Enable = True
            If ils.Range.Cells.Count > 0 Then
                Set rng = ils.Range
                If rng.Cells(1).Range.Characters.Count <= 2 Then
                    rng.InsertAfter " "
                    tbl.Columns(colNr).Select
                End If
            End If
            ils.Borders.OutsideColor = wdColorRed
            ils.Borders.OutsideLineWidth = wdLineWidth075pt
        Next
    End If
End Sub


问:
how to have a lock on a mysql database and dequeue the waiting jobs
i was wondering if anyone knew how to lock a database, and then dequeue the waiting jobs. so i have a hashtable in a database, and im storing data in the database where multiple users are sending requests to edit that data at the same time, but the data needs to be persistent across all users and that only one user can acesss/edit it at a time.

thanks a bunch = )

答: You might find something interesting at http://dev.mysql.com/doc/refman/5.0/en/innodb-deadlocks.html. One technique for serializing transactions is to create a table with just one row in it, and have every transaction update this row before commencing its real work.</p>


问:
pip didn't install package from requirements.txt but did from command
I've two files related to requirements. I was getting this error, when calling:

```<code>$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages
</code>```

Error:

```<code>Looking in links: file:///tmp/packages
Requirement already satisfied: asgiref==3.2.3 in d:\virtual_envs\scolarte\lib\site-packages (from -r requirements-dev.txt (line 1)) (3.2.3)
Collecting boto3==1.12.0 (from -r requirements-dev.txt (line 2))
  Url 'file:///tmp/packages' is ignored: it is neither a file nor a directory.
  Could not find a version that satisfies the requirement boto3==1.12.0 (from -r requirements-dev.txt (line 2)) (from versions: )
No matching distribution found for boto3==1.12.0 (from -r requirements-dev.txt (line 2))
</code>```

But the package installed when calling:

```<code>pip install boto3==1.12.0
</code>```

why?

a) requirements.txt:

```<code>-r requirements-dev.txt
gunicorn
psycopg2
</code>```

b) requirements-dev.txt

```<code>asgiref==3.2.3
boto3==1.12.0
botocore==1.14.16
defusedxml==0.6.0
diff-match-patch==20181111
dj-database-url==0.5.0
dj-static==0.0.6
Django==3.0.3
django-crispy-forms==1.8.1
django-import-export==2.0.1
django-sendgrid-v5==0.8.1
django-storages==1.9.1
djangorestframework==3.11.0
docutils==0.15.2
et-xmlfile==1.0.1
future==0.18.2
jdcal==1.4.1
jmespath==0.9.4
MarkupPy==1.14
numpy==1.18.1
odfpy==1.4.1
openpyxl==3.0.3
pandas==0.25.3
Pillow==7.0.0
python-dateutil==2.8.1
python-decouple==3.3
python-http-client==3.2.4
pytz==2019.3
PyYAML==5.3
s3transfer==0.3.3
sendgrid==6.1.1
six==1.14.0
sqlparse==0.3.0
static3==0.7.0
tablib==0.14.0
urllib3==1.25.8
xlrd==1.2.0
xlwt==1.3.0
</code>```

答:
When you are using

```<code>pip install boto3==1.12.0
</code>```

You are installing from PyPI (The Python Package Index). Whereas by using the --no-index option in

```<code>pip install -r requirements.txt --no-index --find-links file:///tmp/packages
</code>```

you are explicitly telling pip not to look for it in the PyPI.

Form the PyPI Documentation

--no-index

Ignore package index (only looking at --find-links URLs instead).

-f, --find-links <url>

If a url or path to an html file, then parse for links to archives. If a local path or file:// url that’s a
  directory, then look for archives in the directory listing.

Also on how pip finds packages (emphasis mine)

pip looks for packages in a number of places: on PyPI (if not disabled
  via --no-index), in the local filesystem, and in any additional
  repositories specified via --find-links or --index-url. There is no
  ordering in the locations that are searched. Rather they are all
  checked, and the “best” match for the requirements (in terms of
  version number - see PEP 440 for details) is selected.

Body:
I've two files related to requirements. I was getting this error, when calling:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

Error:

Looking in links: file:///tmp/packages
Requirement already satisfied: asgiref==3.2.3 in d:\virtual_envs\scolarte\lib\site-packages (from -r requirements-dev.txt (line 1)) (3.2.3)
Collecting boto3==1.12.0 (from -r requirements-dev.txt (line 2))
  Url 'file:///tmp/packages' is ignored: it is neither a file nor a directory.
  Could not find a version that satisfies the requirement boto3==1.12.0 (from -r requirements-dev.txt (line 2)) (from versions: )
No matching distribution found for boto3==1.12.0 (from -r requirements-dev.txt (line 2))

But the package installed when calling:

pip install boto3==1.12.0

why?

a) requirements.txt:

-r requirements-dev.txt
gunicorn
psycopg2

b) requirements-dev.txt

asgiref==3.2.3
boto3==1.12.0
botocore==1.14.16
defusedxml==0.6.0
diff-match-patch==20181111
dj-database-url==0.5.0
dj-static==0.0.6
Django==3.0.3
django-crispy-forms==1.8.1
django-import-export==2.0.1
django-sendgrid-v5==0.8.1
django-storages==1.9.1
djangorestframework==3.11.0
docutils==0.15.2
et-xmlfile==1.0.1
future==0.18.2
jdcal==1.4.1
jmespath==0.9.4
MarkupPy==1.14
numpy==1.18.1
odfpy==1.4.1
openpyxl==3.0.3
pandas==0.25.3
Pillow==7.0.0
python-dateutil==2.8.1
python-decouple==3.3
python-http-client==3.2.4
pytz==2019.3
PyYAML==5.3
s3transfer==0.3.3
sendgrid==6.1.1
six==1.14.0
sqlparse==0.3.0
static3==0.7.0
tablib==0.14.0
urllib3==1.25.8
xlrd==1.2.0
xlwt==1.3.0

Body:
When you are using

pip install boto3==1.12.0

You are installing from PyPI (The Python Package Index). Whereas by using the --no-index option in

pip install -r requirements.txt --no-index --find-links file:///tmp/packages

you are explicitly telling pip not to look for it in the PyPI.

Form the PyPI Documentation

--no-index

Ignore package index (only looking at --find-links URLs instead).

-f, --find-links <url>

If a url or path to an html file, then parse for links to archives. If a local path or file:// url that’s a
  directory, then look for archives in the directory listing.

Also on how pip finds packages (emphasis mine)

pip looks for packages in a number of places: on PyPI (if not disabled
  via --no-index), in the local filesystem, and in any additional
  repositories specified via --find-links or --index-url. There is no
  ordering in the locations that are searched. Rather they are all
  checked, and the “best” match for the requirements (in terms of
  version number - see PEP 440 for details) is selected.


问:
Why does Python believe return_value is a string?
What is wrong with the following bit of code?

```<code>class Dice:
    def roll_dice(x):
        import random
        return_value = '('
        try:
            y = int(x)
        except ValueError:
            return None
        for char in range(y):
            return_value += f'{random.randint(1, 6)}, '
        return_value = list(return_value).remove[-1 and -2]
        return_value = ''.join(str(e) for e in return_value)
        return return_value + ')'

parameter = input('Number of dice rolls: ')
print(Dice.roll_dice(parameter))
</code>```

The error is

```<code>Traceback (most recent call last):
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 17, in <module>
    print(Dice.roll_dice(parameter))
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 11, in roll_dice
    return_value = list(return_value).remove[-1 and -2]
TypeError: 'builtin_function_or_method' object is not subscriptable
</code>```

If I understand Python correctly, it thinks return_value is a string. But didn't I take the list of return_value on line 11 where the problem is? How does that work?

答:
The problem is remove[-1 and -2]. remove is a method, so it must be followed by parentheses, not brackets. That's what not subscriptable means.

Also, -1 and -2 does not do what you think it does, apply remove(-1) and remove(-2) separately.

Body:
What is wrong with the following bit of code?

class Dice:
    def roll_dice(x):
        import random
        return_value = '('
        try:
            y = int(x)
        except ValueError:
            return None
        for char in range(y):
            return_value += f'{random.randint(1, 6)}, '
        return_value = list(return_value).remove[-1 and -2]
        return_value = ''.join(str(e) for e in return_value)
        return return_value + ')'

parameter = input('Number of dice rolls: ')
print(Dice.roll_dice(parameter))

The error is

Traceback (most recent call last):
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 17, in <module>
    print(Dice.roll_dice(parameter))
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 11, in roll_dice
    return_value = list(return_value).remove[-1 and -2]
TypeError: 'builtin_function_or_method' object is not subscriptable

If I understand Python correctly, it thinks return_value is a string. But didn't I take the list of return_value on line 11 where the problem is? How does that work?


问:
Formatting Array into Lat Lng Array for Google Map API Format in Javascript
How to format this array:

```<code>array = ["37.772, -122.214", "-27.467, 153.027"]
</code>```

into Lat/Lng for google map API that look like this:

```<code>flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: -27.467, lng: 153.027}];
</code>```

I'm trying this code:

```<code>let latLngArray = [];
for (let i = 0; i < array.length; i++) {
  const gData = new google.maps.LatLng(array[i][0], array[i][1]);
  latLngArray.push(gData);
}
</code>```

but it resulting lat lng without value:

答:
Using map, split and destructing

const flightPlanCoordinates = ["37.772, -122.214", "-27.467, 153.027"]
  .map(coor => {
    const [lat,lng] = coor.split(",");
    return {lat:+lat,lng:+lng}
  })

console.log(flightPlanCoordinates)

// OR mapping to number after splitting

const flightPlanCoordinates1 = ["37.772, -122.214", "-27.467, 153.027"]
  .map(coor => {
    const [lat,lng] = coor.split(",").map(Number);
    return {lat,lng}
  })

console.log(flightPlanCoordinates1)```

Body:
How to format this array:

array = ["37.772, -122.214", "-27.467, 153.027"]

into Lat/Lng for google map API that look like this:

flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: -27.467, lng: 153.027}];

I'm trying this code:

let latLngArray = [];
for (let i = 0; i < array.length; i++) {
  const gData = new google.maps.LatLng(array[i][0], array[i][1]);
  latLngArray.push(gData);
}

but it resulting lat lng without value:


问:
Changing scale legend label after creation in ggplot2
Let's say I have a function like this one:

```<code>library(tidyverse)
#autoplotter
scatterplot = function(data, x, y, z) {
  ggplot(data, aes(!!as.symbol(x), !!as.symbol(y), color = !!as.symbol(z))) +
    geom_point() +
    scale_color_gradient2(low = "blue",
                         high = "red",
                         mid = "white",
                         midpoint = 0,
                         limit = c(-1, 1),
                         space = "Lab",
                         name = "Default label")
}
</code>```

We can then call it on some data:

```<code>#default
mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")
</code>```

But what if we want another label for the color scale without changing the gradient settings? One cannot just use labs():

```<code>mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  labs(color = "new label")
</code>```

This does not change anything since labs() apparently cannot override the scale_color_gradient2() in the function.

We can overwrite the scale, but this resets the color scheme:

```<code>mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  scale_color_gradient2("new label")
</code>```

I feel like this should be possible, either by specifying that ggplot2 should only update the label parameter, or by using ggplot2::ggplot_build() to directly change the label parameter only, and then rebuild the plot. However I can't find the label value for the color scale in the object. Too hard to search, but it should be there somewhere!

答:
You can use guides and guide_colourbar :

```<code>p <- mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")
p + guides(color=guide_colorbar(title="new label"))
</code>```

Body:
Let's say I have a function like this one:

library(tidyverse)
#autoplotter
scatterplot = function(data, x, y, z) {
  ggplot(data, aes(!!as.symbol(x), !!as.symbol(y), color = !!as.symbol(z))) +
    geom_point() +
    scale_color_gradient2(low = "blue",
                         high = "red",
                         mid = "white",
                         midpoint = 0,
                         limit = c(-1, 1),
                         space = "Lab",
                         name = "Default label")
}

We can then call it on some data:

#default
mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")

But what if we want another label for the color scale without changing the gradient settings? One cannot just use labs():

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  labs(color = "new label")

This does not change anything since labs() apparently cannot override the scale_color_gradient2() in the function.

We can overwrite the scale, but this resets the color scheme:

mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z") +
  scale_color_gradient2("new label")

I feel like this should be possible, either by specifying that ggplot2 should only update the label parameter, or by using ggplot2::ggplot_build() to directly change the label parameter only, and then rebuild the plot. However I can't find the label value for the color scale in the object. Too hard to search, but it should be there somewhere!

Body:
You can use guides and guide_colourbar :

p <- mpg %>%
  mutate(z = runif(n(), min = -1, max = 1)) %>%
  scatterplot("displ", "cyl", "z")
p + guides(color=guide_colorbar(title="new label"))


问:
Retrieve Calendar Entry TimeZone
I am developing an app that connects to Google Calendar in Java. So far I've managed to retrieve all the data I wanted, I realized yesterday that Google now allows to define events with different timezones than the calendar's.

Is there a way of getting an event timezone?

Thanks in advance.

Mikywan.

答:
They gave this answer in Google Calendar Api's forum:

http://code.google.com/apis/calendar/community/forum.html?place=topic%2Fgoogle-calendar-help-dataapi%2FpYf-9CIeZnw%2Fdiscussion

Title: Retrieve Calendar Entry TimeZone


问:
Select the most popular song based on other column values
I have a temporary table that is generated on top of other tables. Now I have a problem to get the top-ranked(count) song based on each country. Five is the highest rank in this case, then four, three...

```<code>Country     Song    count

=================================
Japan       s006     5
USA         s004     5
Italy       sx32     5
Holland     tm31     5
Japan       st00     4
Italy       tm31     4
Japan       tm31     4
Holland     ab45     4
USA         mn55     3
USA         5607     3
Holland     sx32     3
Italy       ab45     2
USA         i202     1
Holland     s004     1
Japan       sx32     1
Holland     s004     1

Expect output:

Country     Song

====================
Japan       s006
USA         s004
Italy       sx32
Holland     tm31
</code>```

Then how can I get the top II rank e.g of each country?

Output 2:

```<code>Country     Song

====================
Japan       s006
Japan       st00
USA         s004
USA         mn55 (note 5607 has the same rank, maybe just ignore?)
Italy       sx32
Italy       tm31
Holland     tm31
Holland     ab45
</code>```

I have tried several options. The most close one was like select distinct(country), max(count). But then I don't have the code of that song show in the column. FYI, I have already used count function when I made primary query. Ant suggestions? Thanks!

答:
You can do it with row_number():

```<code>select t.Country, t.Song
from (
  select *,
    row_number() over (partition by Country order by count desc) rn
  from tablename
) t
where t.rn = 1
</code>```

See the demo.

Results:

```<code>| country | song |
| ------- | ---- |
| Holland | tm31 |
| Italy   | sx32 |
| Japan   | s006 |
| USA     | s004 |
</code>```

Change the condition to:

```<code>where t.rn <= 2
</code>```

to get the top 2 ranked songs for each country.

Body:
I have a temporary table that is generated on top of other tables. Now I have a problem to get the top-ranked(count) song based on each country. Five is the highest rank in this case, then four, three...

Country     Song    count

=================================
Japan       s006     5
USA         s004     5
Italy       sx32     5
Holland     tm31     5
Japan       st00     4
Italy       tm31     4
Japan       tm31     4
Holland     ab45     4
USA         mn55     3
USA         5607     3
Holland     sx32     3
Italy       ab45     2
USA         i202     1
Holland     s004     1
Japan       sx32     1
Holland     s004     1

Expect output:

Country     Song

====================
Japan       s006
USA         s004
Italy       sx32
Holland     tm31

Then how can I get the top II rank e.g of each country?

Output 2:

Country     Song

====================
Japan       s006
Japan       st00
USA         s004
USA         mn55 (note 5607 has the same rank, maybe just ignore?)
Italy       sx32
Italy       tm31
Holland     tm31
Holland     ab45

I have tried several options. The most close one was like select distinct(country), max(count). But then I don't have the code of that song show in the column. FYI, I have already used count function when I made primary query. Ant suggestions? Thanks!

Body:
You can do it with row_number():

select t.Country, t.Song
from (
  select *,
    row_number() over (partition by Country order by count desc) rn
  from tablename
) t
where t.rn = 1

See the demo.

Results:

| country | song |
| ------- | ---- |
| Holland | tm31 |
| Italy   | sx32 |
| Japan   | s006 |
| USA     | s004 |

Change the condition to:

where t.rn <= 2

to get the top 2 ranked songs for each country.


问:
SQL Query Execute error when using SQL SRV (Php)
I am trying to execute following query, but it provides a syntax error which i couldn't find. Appreciate your help to resolve the issue.

Error

Array ( [0] => Array ( [0] => 07002 [SQLSTATE] => 07002 [1] => 0
  [code] => 0 [2] => [Microsoft][ODBC Driver 17 for SQL Server]COUNT
  field incorrect or syntax error [message] => [Microsoft][ODBC Driver
  17 for SQL Server]COUNT field incorrect or syntax error ) )

```<code><?php

session_start();
require_once '../../../config/dbconfig.php';

$sql = "EXEC    smeProBizInspecInsert
@strLeadRefNo   =  ? ,
@strCustName =  ? ,
@strEnteredBy  =  ? ,
@dtmEnteredDate =  '',
@strInspectStatus = 'SMS06',
@strBranch = ? ";

$stmt=sqlsrv_prepare($conn,$sql,array(&$_POST['strLeadRefNo'],&$_POST['customerName'],&$_SESSION['NAME'], &$_SESSION['BRANCH']));
sqlsrv_execute($stmt);

$stmt = sqlsrv_prepare($conn, $sql);
if (!sqlsrv_execute($stmt)) {die( print_r( sqlsrv_errors(), true) );}
else {echo json_encode("success");}

?>
</code>```

答:
The issue was resolved, when i passed @dtmEnteredDate and @strInspectStatus through variables. Also i have mistakenly kept the following, which caused the error.

sqlsrv_execute($stmt); $stmt = sqlsrv_prepare($conn, $sql);

```<code><?php

session_start();
require_once '../../../config/dbconfig.php';

$sql = "EXEC    smeProBizInspecInsert
@strLeadRefNo   =  ? ,
@strCustName =  ? ,
@strEnteredBy  =  ? ,
@dtmEnteredDate =  ? ,
@strInspectStatus = ?,
@strBranch = ? ";

$edate = '';
$status = 'SMS06';

$stmt=sqlsrv_prepare($conn,$sql,array(&$_POST['strLeadRefNo'],&$_POST['customerName'],&$_SESSION['NAME'],
&$edate, &$status ,&$_SESSION['BRANCH']));

if (!sqlsrv_execute($stmt)) {

  die( print_r( sqlsrv_errors(), true) );

}

else
{

  echo json_encode("success");

}

?>
</code>```

Body:
I am trying to execute following query, but it provides a syntax error which i couldn't find. Appreciate your help to resolve the issue.

Error

Array ( [0] => Array ( [0] => 07002 [SQLSTATE] => 07002 [1] => 0
  [code] => 0 [2] => [Microsoft][ODBC Driver 17 for SQL Server]COUNT
  field incorrect or syntax error [message] => [Microsoft][ODBC Driver
  17 for SQL Server]COUNT field incorrect or syntax error ) )

<?php

session_start();
require_once '../../../config/dbconfig.php';

$sql = "EXEC    smeProBizInspecInsert
@strLeadRefNo   =  ? ,
@strCustName =  ? ,
@strEnteredBy  =  ? ,
@dtmEnteredDate =  '',
@strInspectStatus = 'SMS06',
@strBranch = ? ";

$stmt=sqlsrv_prepare($conn,$sql,array(&$_POST['strLeadRefNo'],&$_POST['customerName'],&$_SESSION['NAME'], &$_SESSION['BRANCH']));
sqlsrv_execute($stmt);

$stmt = sqlsrv_prepare($conn, $sql);
if (!sqlsrv_execute($stmt)) {die( print_r( sqlsrv_errors(), true) );}
else {echo json_encode("success");}

?>

Body:
The issue was resolved, when i passed @dtmEnteredDate and @strInspectStatus through variables. Also i have mistakenly kept the following, which caused the error.

sqlsrv_execute($stmt); $stmt = sqlsrv_prepare($conn, $sql);

<?php

session_start();
require_once '../../../config/dbconfig.php';

$sql = "EXEC    smeProBizInspecInsert
@strLeadRefNo   =  ? ,
@strCustName =  ? ,
@strEnteredBy  =  ? ,
@dtmEnteredDate =  ? ,
@strInspectStatus = ?,
@strBranch = ? ";

$edate = '';
$status = 'SMS06';

$stmt=sqlsrv_prepare($conn,$sql,array(&$_POST['strLeadRefNo'],&$_POST['customerName'],&$_SESSION['NAME'],
&$edate, &$status ,&$_SESSION['BRANCH']));

if (!sqlsrv_execute($stmt)) {

  die( print_r( sqlsrv_errors(), true) );

}

else
{

  echo json_encode("success");

}

?>


问:
How can I add 15 minutes to time and handle overflow?
I have an exercise in which I need to input hours and minutes in 24 hour format and after that the program will show me the time after 15 minutes. It doesn't work when minutes overflow after 59 minutes. When I have for example the input:

```<code>15
59
</code>```

My output is:

```<code>15:74
</code>```

I know that after 59 minutes at a normal clock will be 16:14. How can I handle this case correctly?

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
      Scanner in = new Scanner(System.in);

      int hours = in.nextInt();
      int minutes = in.nextInt();

      if ( minutes == 59 ){
          hours = hours + 1;
          minutes = 00;
          minutes = minutes + 14; //because I passed 1 minute
      }
      else{
          minutes = minutes + 15;
      }
      System.out.printf("%d:%02d" , hours , minutes);
    }
}
</code>```

答:
Do it as follows:

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int hours = in.nextInt();
        int minutes = in.nextInt();

        minutes=minutes+15;
        if (minutes > 59) {
            hours++;
        }

        minutes = minutes % 60;
        hours = hours % 24;

        System.out.printf("%d:%02d", hours, minutes);
    }
}
</code>```

A sample run:

```<code>15
59
16:14
</code>```

Another sample run:

```<code>23
59
0:14
</code>```

Body:
I have an exercise in which I need to input hours and minutes in 24 hour format and after that the program will show me the time after 15 minutes. It doesn't work when minutes overflow after 59 minutes. When I have for example the input:

15
59

My output is:

15:74

I know that after 59 minutes at a normal clock will be 16:14. How can I handle this case correctly?

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
      Scanner in = new Scanner(System.in);

      int hours = in.nextInt();
      int minutes = in.nextInt();

      if ( minutes == 59 ){
          hours = hours + 1;
          minutes = 00;
          minutes = minutes + 14; //because I passed 1 minute
      }
      else{
          minutes = minutes + 15;
      }
      System.out.printf("%d:%02d" , hours , minutes);
    }
}

Body:
Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int hours = in.nextInt();
        int minutes = in.nextInt();

        minutes=minutes+15;
        if (minutes > 59) {
            hours++;
        }

        minutes = minutes % 60;
        hours = hours % 24;

        System.out.printf("%d:%02d", hours, minutes);
    }
}

A sample run:

15
59
16:14

Another sample run:

23
59
0:14


答:
Use map and split methods.

const array = ["37.772, -122.214", "-27.467, 153.027"];

const updated = array.map(item => {
  const [lat, lng] = item.split(", ").map(x => Number(x));
  return { lat, lng };
});

console.log(updated);```

Title: Formatting Array into Lat Lng Array for Google Map API Format in Javascript