问:
How to insert EditText in between multiple TextViews in Android?
I am developing and Android app that has a "fill in the blanks" activity. For that matter, I wish to have a TextView followed by an EditText followed by another TextView, to show something like:

Lorem ipsum dolor sit amet, consectetur ________ elit. Aliquam quis
  est ex. In maximus consectetur tortor, quis lacinia risus _______ eu.
  Etiam purus nulla, tincidunt ac mattis sit amet, lobortis non orci.

However, I'm unable to concatenate EditText at the end of a multi-line TextView, since the second line's width takes up the whole screen.

Does anyone have a suggestion on how to implement such feature?

A couple of workarounds that I though as plan B would be to have a multiline EditText where I programmatically prevent touches outside the area I want to edit or to have the "fill in the blank" indicated in the main text but a separate input to actually insert the text. But none of these actually please me.

Can anyone help with the original solution?

答:
Not quite a duplicated question, but have a read through this guys answer.

It may help you out

How to set the part of the text view is clickable


来源: stackexchange

问:
Android ProgessBar while loading WebView
In my application, I have a WebView which loads any URL from the internet. Now, sometimes due to slow networks the page takes a long time to load and the user sees only a blank screen.

I want to show a ProgressBar while the WebView gets loaded and hide the ProgessBar when the WebView gets loaded completely.

I know how to use the ProgressBar and AsyncTasks, but here is my problem.

This is the code that I use to load my WebView.

```<code>    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebViewClient(new HelloWebViewClient());
    mWebView.loadUrl(web_URL);
</code>```

And this my custom WebViewClient class

```<code>private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
</code>```

Now, if I try to show the ProgressBar using AsyncTasks then I guess I would have to give the code to load the URL in the doInBackGround() function of my AsyncTask and show the progress through the onProgressUpdate() function.

But, how do I load the URL inside the doInBackground() as doInBackground() runs on the Non-UI thread and I wont be able to use mWebView.loadUrl(web_URL) inside it.

Any suggestions? Am I missing something obvious? Please guide me.

答:
This simple solution worked for me in KOTLIN:

```<code>private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my application, I have a WebView which loads any URL from the internet. Now, sometimes due to slow networks the page takes a long time to load and the user sees only a blank screen.

I want to show a ProgressBar while the WebView gets loaded and hide the ProgessBar when the WebView gets loaded completely.

I know how to use the ProgressBar and AsyncTasks, but here is my problem.

This is the code that I use to load my WebView.

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebViewClient(new HelloWebViewClient());
    mWebView.loadUrl(web_URL);

And this my custom WebViewClient class

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Now, if I try to show the ProgressBar using AsyncTasks then I guess I would have to give the code to load the URL in the doInBackGround() function of my AsyncTask and show the progress through the onProgressUpdate() function.

But, how do I load the URL inside the doInBackground() as doInBackground() runs on the Non-UI thread and I wont be able to use mWebView.loadUrl(web_URL) inside it.

Any suggestions? Am I missing something obvious? Please guide me.

Body:
This simple solution worked for me in KOTLIN:

private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}


问:
Play Sounds of Varying Varying Pitch Asynchronously and Concurrently
My goal is to use Python to play sounds with the following requirements in a computer game context.

Take some input WAV file and randomly Vary the pitch to +/- 50% of original. Changing the sample rate seems to be an easy way to do this with PyDub.

Play the sound.

Be able to call this function rapidly so that long and short duration sounds overlap in actual playback.

I have spent over 24 work-hours searching for a way to meet all these requirements. I have done this before in Visual Basic and I was surprised at how difficult it is in Python.

Here is what I know so far:

PyGame.Mixer can play overlapping sounds concurrently, but it must play them all at the same sample rate. There doesn't appear to be a way to vary pitch.

PyDub can vary pitch by changing samplerate, but it can't play overlapping sounds with its basic playback. And, I have to write the output sound to file then immediately load it back, which feels wasteful.

WinSound can play PyDub's varying-samplerate sounds, but not with concurrent playback, not even with threading.

Playsound package does not work with python 3.6.

PyAudio can play PyDub's varying-samplerate sounds with concurrent playback if I use Threading, however, any more than a couple times and it causes horrible memory problems that quickly make Python crash.

My question: How can I achieve my 3 goals above without causing problems?

Here is the best result that I have so far (this is the PyAudio version which causes a crash if tested more than once or twice):

```<code>from pydub import AudioSegment
from random import random, seed
from time import sleep
import os
import threading
import pyaudio
import wave

def PlayAsyncWithRandPitch(WavPath):
    MyBaseFilename = os.path.basename(WavPath)
    sound = AudioSegment.from_file(WavPath, format="wav")
    seed()
    octaves = ((random()-0.50))
    print("random octave factor for this sound is: "+str(octaves))
    print("current sound frame rate:"+str(sound.frame_rate))
    new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
    print("new sound frame rate:"+str(new_sample_rate))
    newpitchsound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
    MyTotalNewPath = os.getcwd()+"\\Soundfiles\\Temp\\Mod_"+MyBaseFilename
    newpitchsound.export(MyTotalNewPath, format="wav")
    SoundThread = threading.Thread(target=PAPlay, args=(MyTotalNewPath,))
    SoundThread.start()
#=======================================================================================

#This function is just code for playing a sound in PyAudio
def PAPlay(filename):
    CHUNK = 1024
    wf = wave.open(filename, 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    data = wf.readframes(CHUNK)
    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)
    stream.stop_stream()
    stream.close()
    p.terminate()
    return

if __name__ == "__main__":
    #Example sounds to test if more than one can play at once
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\RifleMiss.WAV')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\splash.wav')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\sparkhit1.WAV')
    sleep(5.0)
</code>```

Thank you in advance for your kind help!

答:
Thanks to another hour of googling, I was able to solve it by finding an obscure note about PyDub. There is a way to actually change the samplerate, but "not actually" change the sample rate. It's called the chipmunk method.

https://github.com/jiaaro/pydub/issues/157#issuecomment-252366466

I really don't pretend to understand the nuance here, but it seems the concept is "take a sound, set the samplerate to some modified value, then convert the sample rate back to the traditional 44,100 HZ value."

They give this example which works very well:

```<code>from pydub import AudioSegment
sound = AudioSegment.from_file('./test/data/test1.mp3')
# shift the pitch up by half an octave (speed will increase proportionally)
octaves = 0.5
new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
# keep the same samples but tell the computer they ought to be played at the
# new, higher sample rate. This file sounds like a chipmunk but has a weird sample rate.
chipmunk_sound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
# now we just convert it to a common sample rate (44.1k - standard audio CD) to
# make sure it works in regular audio players. Other than potentially losing audio quality (if
# you set it too low - 44.1k is plenty) this should now noticeable change how the audio sounds.
chipmunk_ready_to_export = chipmunk_sound.set_frame_rate(44100)
</code>```

It doesn't make much sense to me, but it does work :) Hope this helps someone out there.

Body:
My goal is to use Python to play sounds with the following requirements in a computer game context.

Take some input WAV file and randomly Vary the pitch to +/- 50% of original. Changing the sample rate seems to be an easy way to do this with PyDub.

Play the sound.

Be able to call this function rapidly so that long and short duration sounds overlap in actual playback.

I have spent over 24 work-hours searching for a way to meet all these requirements. I have done this before in Visual Basic and I was surprised at how difficult it is in Python.

Here is what I know so far:

PyGame.Mixer can play overlapping sounds concurrently, but it must play them all at the same sample rate. There doesn't appear to be a way to vary pitch.

PyDub can vary pitch by changing samplerate, but it can't play overlapping sounds with its basic playback. And, I have to write the output sound to file then immediately load it back, which feels wasteful.

WinSound can play PyDub's varying-samplerate sounds, but not with concurrent playback, not even with threading.

Playsound package does not work with python 3.6.

PyAudio can play PyDub's varying-samplerate sounds with concurrent playback if I use Threading, however, any more than a couple times and it causes horrible memory problems that quickly make Python crash.

My question: How can I achieve my 3 goals above without causing problems?

Here is the best result that I have so far (this is the PyAudio version which causes a crash if tested more than once or twice):

from pydub import AudioSegment
from random import random, seed
from time import sleep
import os
import threading
import pyaudio
import wave

def PlayAsyncWithRandPitch(WavPath):
    MyBaseFilename = os.path.basename(WavPath)
    sound = AudioSegment.from_file(WavPath, format="wav")
    seed()
    octaves = ((random()-0.50))
    print("random octave factor for this sound is: "+str(octaves))
    print("current sound frame rate:"+str(sound.frame_rate))
    new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
    print("new sound frame rate:"+str(new_sample_rate))
    newpitchsound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
    MyTotalNewPath = os.getcwd()+"\\Soundfiles\\Temp\\Mod_"+MyBaseFilename
    newpitchsound.export(MyTotalNewPath, format="wav")
    SoundThread = threading.Thread(target=PAPlay, args=(MyTotalNewPath,))
    SoundThread.start()
#=======================================================================================

#This function is just code for playing a sound in PyAudio
def PAPlay(filename):
    CHUNK = 1024
    wf = wave.open(filename, 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    data = wf.readframes(CHUNK)
    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)
    stream.stop_stream()
    stream.close()
    p.terminate()
    return

if __name__ == "__main__":
    #Example sounds to test if more than one can play at once
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\RifleMiss.WAV')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\splash.wav')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\sparkhit1.WAV')
    sleep(5.0)

Thank you in advance for your kind help!

Body:
Thanks to another hour of googling, I was able to solve it by finding an obscure note about PyDub. There is a way to actually change the samplerate, but "not actually" change the sample rate. It's called the chipmunk method.

https://github.com/jiaaro/pydub/issues/157#issuecomment-252366466

I really don't pretend to understand the nuance here, but it seems the concept is "take a sound, set the samplerate to some modified value, then convert the sample rate back to the traditional 44,100 HZ value."

They give this example which works very well:

from pydub import AudioSegment
sound = AudioSegment.from_file('./test/data/test1.mp3')
# shift the pitch up by half an octave (speed will increase proportionally)
octaves = 0.5
new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
# keep the same samples but tell the computer they ought to be played at the
# new, higher sample rate. This file sounds like a chipmunk but has a weird sample rate.
chipmunk_sound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
# now we just convert it to a common sample rate (44.1k - standard audio CD) to
# make sure it works in regular audio players. Other than potentially losing audio quality (if
# you set it too low - 44.1k is plenty) this should now noticeable change how the audio sounds.
chipmunk_ready_to_export = chipmunk_sound.set_frame_rate(44100)

It doesn't make much sense to me, but it does work :) Hope this helps someone out there.


答:
Just use correct conversion symbol</p>

```<code>printf("2^%u = %u\n", i, x);
</code>```

Title: Why is a variable declared as an unsigned int generating a negative value?

Body:
I wrote this bit of code to learn about bit shifting.  To my surprise, even though I declared x to be an unsigned int, the output includes a negative number, namely when the leftmost bit is set to 1.  My question:  why?  I thought an unsigned int was never negative.  Per sizeof(x), x is 4 bytes wide.

Here is the code fragment:

int main(void)
{
    unsigned int x;

    x = 1;

    for (int i = 0; i < 32; i++)
    {
        printf("2^%i = %i\n", i, x);
        x <<= 1;
    }

    return 0;
}

Here is the output:

2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
2^7 = 128
2^8 = 256
2^9 = 512
2^10 = 1024
2^11 = 2048
2^12 = 4096
2^13 = 8192
2^14 = 16384
2^15 = 32768
2^16 = 65536
2^17 = 131072
2^18 = 262144
2^19 = 524288
2^20 = 1048576
2^21 = 2097152
2^22 = 4194304
2^23 = 8388608
2^24 = 16777216
2^25 = 33554432
2^26 = 67108864
2^27 = 134217728
2^28 = 268435456
2^29 = 536870912
2^30 = 1073741824
2^31 = -2147483648

Body:
Just use correct conversion symbol

printf("2^%u = %u\n", i, x);


问:
how can i test login password
i have a project to use phpseclib  connect  cisco and H3C  Swtich device .

these devices' passowrd are not different.so i must try to test these password ,when i first login these device.

i write some code  to find the correct password in the password list,but the correct password is only effect when it's first used to login .

```<code>  function loginssh_keybo(){
    $user = user::find()->all();
    $ssh = new SSH2($this->ip);
    if (@$ssh->login($user[$this->i]->username, $user[$this->i]->password)) {
      return $ssh;
    }else{
        return false;
    }

}

function loginssh_pass(){
    $user = user::find()->all();
    $ssh = new SSH2($this->ip);
    if (@$ssh->login($user[$this->i]->username, $user[$this->i]->password, $user[$this->i]->password)) {
        return $ssh;
    }else{
        return false;
    }

}
function loginssh()
{
    $user = user::find()->all();
    $max = 3;
    $this->i = 0;
    do {
        if (@$ssh=$this->loginssh_keybo()) {
            $this->islogin = True;
            break;
        } elseif (@$ssh=$this->loginssh_pass()) {
            $this->islogin = True;
            break;
        }  elseif
        ($this->i > $max) {
            return false;
        }
        $this->i += 1;
    } while (!$this->islogin);
    $this->user = $user[$this->i]->username;
    $this->password = $user[$this->i]->password;
    return $ssh;
}
</code>```

答:
From https://github.com/phpseclib/phpseclib/issues/1144:</p>

```<code>if ($ssh->login('username', 'password1')) {
    return true;
}
if ($ssh->login('username', 'password2')) {
     return true;
}
if ($ssh->login('username', 'password3')) {
     return true;
}
return false;
</code>```

Title: how can i test login password

Body:
i have a project to use phpseclib  connect  cisco and H3C  Swtich device .

these devices' passowrd are not different.so i must try to test these password ,when i first login these device.

i write some code  to find the correct password in the password list,but the correct password is only effect when it's first used to login .

  function loginssh_keybo(){
    $user = user::find()->all();
    $ssh = new SSH2($this->ip);
    if (@$ssh->login($user[$this->i]->username, $user[$this->i]->password)) {
      return $ssh;
    }else{
        return false;
    }

}

function loginssh_pass(){
    $user = user::find()->all();
    $ssh = new SSH2($this->ip);
    if (@$ssh->login($user[$this->i]->username, $user[$this->i]->password, $user[$this->i]->password)) {
        return $ssh;
    }else{
        return false;
    }

}
function loginssh()
{
    $user = user::find()->all();
    $max = 3;
    $this->i = 0;
    do {
        if (@$ssh=$this->loginssh_keybo()) {
            $this->islogin = True;
            break;
        } elseif (@$ssh=$this->loginssh_pass()) {
            $this->islogin = True;
            break;
        }  elseif
        ($this->i > $max) {
            return false;
        }
        $this->i += 1;
    } while (!$this->islogin);
    $this->user = $user[$this->i]->username;
    $this->password = $user[$this->i]->password;
    return $ssh;
}

Body:
From https://github.com/phpseclib/phpseclib/issues/1144:

if ($ssh->login('username', 'password1')) {
    return true;
}
if ($ssh->login('username', 'password2')) {
     return true;
}
if ($ssh->login('username', 'password3')) {
     return true;
}
return false;


问:
Is it possible to click on labels in Mapbox like on Google maps?
Is it possible to click on labels in Mapbox and highlight the city like on Google maps?

Example Screenshot

答:
All visible map elements, including labels, in a mapbox-gl map can be clicked.

see https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/

In that example, instead of catching the mousemove event, catch the click event like this:

```<code>map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point);
    document.getElementById('features').innerHTML = JSON.stringify(features, null, 2);
});
</code>```

Body:
All visible map elements, including labels, in a mapbox-gl map can be clicked.

see https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/

In that example, instead of catching the mousemove event, catch the click event like this:

map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point);
    document.getElementById('features').innerHTML = JSON.stringify(features, null, 2);
});


问:
ASP.Net VB string to date based on format used in string
I'm using a JavaScript datepicker that gives me the selected date based on the language. So when the language is Dutch I get an output like 21-09-2017 (dd-mm-yyyy) And for English 21/09/2017.

When I want to cast these Strings to Dates (CDate) I get a problem with the format. Day = Month or Month = Day. What is the best way to make a Date from a string based on the format used in the string?

A solution would be to write a function for each specific culture to handle the dates but i'm guessing there is a default function in .Net??

答:
```<code>Convert.ToDateTime(String).ToString("dd-MM-yyyy")
</code>```

OR

```<code>DateTime.ParseExact(String, "dd/MM/yyyy", CultureInfo.InvariantCulture)
</code>```

Body:
Convert.ToDateTime(String).ToString("dd-MM-yyyy")

OR

DateTime.ParseExact(String, "dd/MM/yyyy", CultureInfo.InvariantCulture)


问:
Cannot exec into docker container due to application
Yesterday I restarted my docker container for my database. My applications can still connect as normal however:

The following line no-longer works

```<code>docker exec -i -t database_1 bash
</code>```

Instead it gives me this error:

```<code>unable to find user postgres: no matching entries in passwd file
</code>```

I don't know why it's not just giving me bash

答: This is some sort of bug in docker.  Apparently docker stop <container>; docker start <container> will fix it, and using docker cp can cause it to happen.

Body:
Yesterday I restarted my docker container for my database. My applications can still connect as normal however:

The following line no-longer works

docker exec -i -t database_1 bash

Instead it gives me this error:

unable to find user postgres: no matching entries in passwd file

I don't know why it's not just giving me bash


问:
How to display a progress bar when WebView loads a URL, in Android ？
I am new in android apps development and learning it.

I have developed an application which loads a website link using a WebView. And it's working fine.

But I am facing problems to display and hide progress bar when the WebView loads a page.

I want to display a progress bar (Just spinner in center) when the WebView loads the main link and internal links of a website and hide progress bar when page is completely loaded.

My Java code:

```<code>package in.matebook.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webView);
        myWebView.setWebViewClient(new MyWebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://www.labnol.org");
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (Uri.parse(url).getHost().equals("www.labnol.org")) {
                // This is my web site, so do not override; let my WebView load the page
                //or we can add more allowed host in if condition
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

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

And my layout XML code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleLarge"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
</code>```

Right now, the progress bar is displayed, but it does not hide.

When I create progressbar object and add below line in Java code then the progress bar is not displayed.

```<code>progressbar.setVisibility(View.GONE);
</code>```

I have also tried an other answer but the progress bar does not work when I click on internal links.

I want to display progress bar when main page load and hide progress bar when the main page is completely loaded.

I want to display the progress bar again when the user clicks on internal links of the website and same as above, hide the progress bar when the page is completely loaded.

Please help, I am beginner in Android apps development.

答:
In case anyone is looking for a Kotlin solution, this simple one worked for me:

```<code>private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}
</code>```

Body:
I am new in android apps development and learning it.

I have developed an application which loads a website link using a WebView. And it's working fine.

But I am facing problems to display and hide progress bar when the WebView loads a page.

I want to display a progress bar (Just spinner in center) when the WebView loads the main link and internal links of a website and hide progress bar when page is completely loaded.

My Java code:

package in.matebook.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webView);
        myWebView.setWebViewClient(new MyWebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://www.labnol.org");
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (Uri.parse(url).getHost().equals("www.labnol.org")) {
                // This is my web site, so do not override; let my WebView load the page
                //or we can add more allowed host in if condition
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

And my layout XML code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleLarge"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Right now, the progress bar is displayed, but it does not hide.

When I create progressbar object and add below line in Java code then the progress bar is not displayed.

progressbar.setVisibility(View.GONE);

I have also tried an other answer but the progress bar does not work when I click on internal links.

I want to display progress bar when main page load and hide progress bar when the main page is completely loaded.

I want to display the progress bar again when the user clicks on internal links of the website and same as above, hide the progress bar when the page is completely loaded.

Please help, I am beginner in Android apps development.

Body:
In case anyone is looking for a Kotlin solution, this simple one worked for me:

private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}


问:
Pycharm - Anaconda2 - Windows7 - py35 environment - SDK error
I've been trying to set a virtual environment for some time now, but with no success. I read many topics regarding this manner, but couldn't find a solution for my problem.

I am running:

Windows 7

Pycharm Community Edition 2017.1.4

Anaconda 2

Python 2.7.13

I am trying to set up an environment of Python 3.5.3 - Anaconda
I used this command:

conda create -n py35 python=3.5 anaconda

(also tried : conda create -n py35 python=3.5.3 anaconda) same result

via PyCharm terminal.
It does seem that it sets up an environment and I am able to switch between them in the terminal, but when I try to add it as a local Interpreter I keep receiving a message:

Cannot set up a python SDK  at Python 3.5.3
  (C:\Users\Cossack\Anaconda2\envs\py35\python.exe)
  (C:\Users\Cossack\Anaconda2\envs\py35\python.exe). The SDK seems
  invalid.

I also tried creating conda Env via PyCharm settings, but same error appears.
I tried creating environment for python 3.6 just to see if that was the problem source, but again, the same error appeared.

I really need both Python 2.7 and 3.5, but I keep getting errors which I have no Idea on how to solve.

Thank you very much in advance, hope that someone can help me in solving this issue.

答:
Googling Cannot set up a python SDK at Python returns a number of stack overflow discussions

Cannot set up a python SDK in Pycharm?

Invalid Python SDK Error while using python 3.4 on pycharm

Multilpe python versions and interpreters

All of these hint to the PYTHONPATH being setup incorrectly and pointing to the wrong place. Is your issue different than these in any way? Have you tried setting up PYTHONPATH env var for windows?


问:
Redux Form, Radio Button Fields, how to support variable values?
In my react redux form, I have the following:

```<code>        <fieldset className="form-group">
          <legend>Radio buttons</legend>
          {this.props.job_titles.map(jobTitle => (
          <div className="form-check" key={jobTitle.id}>
            <label className="form-check-label">
              <Field
                name="job_title_id"
                component="input"
                type="radio"
                value={jobTitle.id}
              />
              {' '}
              {jobTitle.title}
            </label>
          </div>
          ))}
        </fieldset>
</code>```

This renders the radio buttons correctly, but when you click to select a radio button, the radio button never sets as selected. You can't select an option - the form is broken.

What's strange is if I update: value={jobTitle.id} to value="anything" then the radio buttons can be selected.

I'm not seeing anything in the redux form docs about radio buttons dynamically generated. What am I doing wrong?

Thanks

答:
Set the checked property to a state or prop, then update that in the click handler.

<Field
    onClick={
        () => {
            this.setState((prevState) => {
                return {isChecked: !prevState.isChecked};
            });
        }
    }
    name="job_title_id"
    component="input"
    type="radio"
    checked={this.state.isChecked}
    value={jobTitle.id}
/>
```

Body:
In my react redux form, I have the following:

        <fieldset className="form-group">
          <legend>Radio buttons</legend>
          {this.props.job_titles.map(jobTitle => (

              <Field
                name="job_title_id"
                component="input"
                type="radio"
                value={jobTitle.id}
              />
              {' '}
              {jobTitle.title}

          ))}
        </fieldset>

This renders the radio buttons correctly, but when you click to select a radio button, the radio button never sets as selected. You can't select an option - the form is broken.

What's strange is if I update: value={jobTitle.id} to value="anything" then the radio buttons can be selected.

I'm not seeing anything in the redux form docs about radio buttons dynamically generated. What am I doing wrong?

Thanks


问:
Using media queries, following standards with SASS and BEM?
I am following the BEM practice and want to add specific break points, it appears 2 formats work for me. Does anyone know the advantage of either ?

Here is the first, I embed the media directly into the element (BEM)

```<code>.my-component {
  &__section-field {
    display: flex;
    flex-wrap: wrap;
  }

  &__section-sep {
    width: 100%;
    @media(min-width: 900px) {
        width: 50%;
    }
  }
}
</code>```

Here is the second, where I embed the media query outside of the section and redefine the section again.

```<code>.my-component {
  &__section-field {
    display: flex;
    flex-wrap: wrap;
  }

  &__section-sep {
    width: 100%;
  }
  @media(min-width: 900px) {
    &__section-sep {
      width: 50%;
    }
  }
}
</code>```

As you can see the, I am basically changing the width of an item between either 50% or 100% depending if it's mobile only resolution. I am using flexbox with flex-wrap and it wraps depending on there is space left on the line.

They both seem to work the same as far as I can say. Would anyone confirm if there is a difference and which one would be more scalable and maintainable?

Maybe there is something that I haven't thought of, I did think about storing my media queries in a separate file but I was trying to keep everything together and follow the bem methodology.

答:
I prefer the 2nd variant for the following reason: when you have many media queries, indeed, the 1st variant requires less copy/paste.

But though, the code becomes much less readable if you have many elements or modifiers in the block, i.e. selectors. It's common to face a situation when it's needed to change style for several elements/modifiers at exact screen. And when that case appears - as for me - it's easier to navigate between media queries, find the needed media and change code there - so you work at one place in the file, whereas in the 1st variant you would need to jump between selectors. In my opinion when it comes to work with media queries - it's faster to navigate between them, then to navigate between selectors.

imagine the following code with media query inside every selector :

```<code>.section_name_educational {
    display: flex;
    flex-direction: row;
    padding: 0px;

    .fp-tableCell {
        display: flex;
        flex-direction: row;
    }

    .section {

        &__inner {
            display: flex;
            flex-direction: row-reverse;
            height: 100vh;
            height: calc(100vh - 80px);
            box-sizing: border-box;
            width: 50%;
            padding-left: 40px;
            margin-top: auto;
            padding-bottom: 40px;
        }

        &__header {
            position: relative;
            width: 100%;
            top: 62px;
            left: 40px;
        }

        &__text-holder {
            width: 100%;
        }

        &__title {
            font-size: 48px;
        }

        &__subtitle {
            width: 150%;
            margin: 20px 0px;
        }

        &__description {
            color: #669900;
            font-size: 18px;
        }

        &__primary {
            height: 100%;
            display: flex;
            box-sizing: border-box;
            flex-direction: column;
            justify-content: space-between;
            width: 100%;
        }

        &__additional {
            display: none;
        }

        &__kettles {
            display: flex;
        }

        &__kettle {
            height: auto;
            margin-right: 20px;

            &_order {
                &_1 {
                    width: 183px;
                    min-width: 183px;
                    max-width: 183px;
                }

                &_2 {
                    width: 108px;
                    min-width: 108px;
                    max-width: 108px;
                }

                &_3 {
                    width: 127px;
                    min-width: 127px;
                    max-width: 127px;
                }
            }
        }

        &__background-holder {
            overflow: hidden;
            max-height: 100vh;
        }

        &__background {
            position: relative;
            width: auto;
            height: 100vh;
        }
    }
}

@media all and (max-height: 600px) {
.section_name_educational {
    .section {
        &__kettle {
            &_order {
                &_2 {
                    width: 68px;
                    max-width: 68px;
                    min-width: 68px;
                    height: 120px;
                    margin-left: 30px;
                }

                &_3 {
                    width: 78px;
                    max-width: 78px;
                    min-width: 78px;
                    height: 120px;
                }
            }
        }
    }
}
}

@media all and (max-height: 760px) {
.section_name_educational {
    .section {
        &__header {
            top: 40px;
        }

        &__subtitle {
            width: 100% !important;
        }

        &__additional {
            display: none !important;
        }
    }
}
}

@media (--large) {
.section_name_educational {
    .section {
        &__subtitle {
            width: 120%;
        }
    }
}
}

@media (--xlarge) {
.section_name_educational {
    padding-top: 120px;

    .section {

        &__inner {
            height: calc(100vh - 60px);
            margin-top: 0;
        }

        &__header {
            transition-delay: 1s;
            opacity: 0;
            right: -100px;
            bottom: -40px;
            transform: translateY(20px);
        }

        &__subtitle {
            width: 120%;
        }

        &__primary {
            width: calc(100% - 160px);
        }

        &__additional {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        &__bubbles {
            display: block;
            position: relative;
            top: 40px;
            width: 160px;
            min-width: 160px;
            max-width: 160px;
            height: auto;
            transform: translateY(20px);
            opacity: 0;
            transition-delay: 1s;
        }

        &__kettle {
            opacity: 0;
            transform: translateY(20px);
            transition-delay: 1s;
        }
    }

    &.active {
        .section {
            &__header {
                    transition: opacity 1s ease-out 0.8s,
                            transform 0.8s ease-out 0.8s;
                opacity: 1;
                transform: translateY(0px);
            }

            &__kettle {
                opacity: 1;
                transform: translateY(0px);
                transition: opacity 0.6s ease-out,
                            transform 0.6s ease-out;
                &_order {
                    &_1 {
                        transition-delay: 1.6s;
                        display: block;
                    }

                    &_2 {
                        transition-delay: 1.9s;
                    }

                    &_3 {
                        transition-delay: 2.1s;
                    }
                }
            }

            &__bubbles {
                transition: opacity 0.8s ease-out 2.5s,
                            transform 0.8s ease-out 2.3s;
                transform: translateY(0px);
                opacity: 1;
            }
        }
    }
}
}

@media all and (min-width: 1400px) {
.section_name_educational {
    .section {
        &__header {
            left: 60px;
        }

        &__subtitle {
            width: 110%;
        }
    }
}
}

@media (--xxlarge) {
.section_name_educational {
    .section {

        &__primary {
            width: calc(100% - 148px);
        }

        &__subtitle {
            width: 80%;
            margin: 40px 0px;
        }

        &__description-inner {
            width: 60%;
        }

        &__bubbles {
            width: 148px;
            min-width: 148px;
            max-width: 148px;
            top: 40px;
        }
    }
}
}

@media (--monster) {
.section_name_educational {
    .section {
        &__primary {
            width: calc(100% - 227px);
        }

        &__header {
            left: 200px;
            top: 150px;
        }

        &__title {
            font-size: 58px;
        }

        &__subtitle {
            font-size: 24px;
            width: 80%;
        }

        &__description {
            font-size: 24px;
        }

        &__bubbles {
            width: 227px;
            min-width: 227px;
            max-width: 227px;
            left: 0px;
        }
    }
}
}
</code>```

As for me - it would be difficult to read it if I had done it with the 1st variant.

ContentLicense: CC BY-SA 4.0

Body:
I am following the BEM practice and want to add specific break points, it appears 2 formats work for me. Does anyone know the advantage of either ?

Here is the first, I embed the media directly into the element (BEM)

.my-component {
  &__section-field {
    display: flex;
    flex-wrap: wrap;
  }

  &__section-sep {
    width: 100%;
    @media(min-width: 900px) {
        width: 50%;
    }
  }
}

Here is the second, where I embed the media query outside of the section and redefine the section again.

.my-component {
  &__section-field {
    display: flex;
    flex-wrap: wrap;
  }

  &__section-sep {
    width: 100%;
  }
  @media(min-width: 900px) {
    &__section-sep {
      width: 50%;
    }
  }
}

As you can see the, I am basically changing the width of an item between either 50% or 100% depending if it's mobile only resolution. I am using flexbox with flex-wrap and it wraps depending on there is space left on the line.

They both seem to work the same as far as I can say. Would anyone confirm if there is a difference and which one would be more scalable and maintainable?

Maybe there is something that I haven't thought of, I did think about storing my media queries in a separate file but I was trying to keep everything together and follow the bem methodology.

Body:
I prefer the 2nd variant for the following reason: when you have many media queries, indeed, the 1st variant requires less copy/paste.

But though, the code becomes much less readable if you have many elements or modifiers in the block, i.e. selectors. It's common to face a situation when it's needed to change style for several elements/modifiers at exact screen. And when that case appears - as for me - it's easier to navigate between media queries, find the needed media and change code there - so you work at one place in the file, whereas in the 1st variant you would need to jump between selectors. In my opinion when it comes to work with media queries - it's faster to navigate between them, then to navigate between selectors.

imagine the following code with media query inside every selector :

.section_name_educational {
    display: flex;
    flex-direction: row;
    padding: 0px;

    .fp-tableCell {
        display: flex;
        flex-direction: row;
    }

    .section {

        &__inner {
            display: flex;
            flex-direction: row-reverse;
            height: 100vh;
            height: calc(100vh - 80px);
            box-sizing: border-box;
            width: 50%;
            padding-left: 40px;
            margin-top: auto;
            padding-bottom: 40px;
        }

        &__header {
            position: relative;
            width: 100%;
            top: 62px;
            left: 40px;
        }

        &__text-holder {
            width: 100%;
        }

        &__title {
            font-size: 48px;
        }

        &__subtitle {
            width: 150%;
            margin: 20px 0px;
        }

        &__description {
            color: #669900;
            font-size: 18px;
        }

        &__primary {
            height: 100%;
            display: flex;
            box-sizing: border-box;
            flex-direction: column;
            justify-content: space-between;
            width: 100%;
        }

        &__additional {
            display: none;
        }

        &__kettles {
            display: flex;
        }

        &__kettle {
            height: auto;
            margin-right: 20px;

            &_order {
                &_1 {
                    width: 183px;
                    min-width: 183px;
                    max-width: 183px;
                }

                &_2 {
                    width: 108px;
                    min-width: 108px;
                    max-width: 108px;
                }

                &_3 {
                    width: 127px;
                    min-width: 127px;
                    max-width: 127px;
                }
            }
        }

        &__background-holder {
            overflow: hidden;
            max-height: 100vh;
        }

        &__background {
            position: relative;
            width: auto;
            height: 100vh;
        }
    }
}

@media all and (max-height: 600px) {
.section_name_educational {
    .section {
        &__kettle {
            &_order {
                &_2 {
                    width: 68px;
                    max-width: 68px;
                    min-width: 68px;
                    height: 120px;
                    margin-left: 30px;
                }

                &_3 {
                    width: 78px;
                    max-width: 78px;
                    min-width: 78px;
                    height: 120px;
                }
            }
        }
    }
}
}

@media all and (max-height: 760px) {
.section_name_educational {
    .section {
        &__header {
            top: 40px;
        }

        &__subtitle {
            width: 100% !important;
        }

        &__additional {
            display: none !important;
        }
    }
}
}

@media (--large) {
.section_name_educational {
    .section {
        &__subtitle {
            width: 120%;
        }
    }
}
}

@media (--xlarge) {
.section_name_educational {
    padding-top: 120px;

    .section {

        &__inner {
            height: calc(100vh - 60px);
            margin-top: 0;
        }

        &__header {
            transition-delay: 1s;
            opacity: 0;
            right: -100px;
            bottom: -40px;
            transform: translateY(20px);
        }

        &__subtitle {
            width: 120%;
        }

        &__primary {
            width: calc(100% - 160px);
        }

        &__additional {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        &__bubbles {
            display: block;
            position: relative;
            top: 40px;
            width: 160px;
            min-width: 160px;
            max-width: 160px;
            height: auto;
            transform: translateY(20px);
            opacity: 0;
            transition-delay: 1s;
        }

        &__kettle {
            opacity: 0;
            transform: translateY(20px);
            transition-delay: 1s;
        }
    }

    &.active {
        .section {
            &__header {
                    transition: opacity 1s ease-out 0.8s,
                            transform 0.8s ease-out 0.8s;
                opacity: 1;
                transform: translateY(0px);
            }

            &__kettle {
                opacity: 1;
                transform: translateY(0px);
                transition: opacity 0.6s ease-out,
                            transform 0.6s ease-out;
                &_order {
                    &_1 {
                        transition-delay: 1.6s;
                        display: block;
                    }

                    &_2 {
                        transition-delay: 1.9s;
                    }

                    &_3 {
                        transition-delay: 2.1s;
                    }
                }
            }

            &__bubbles {
                transition: opacity 0.8s ease-out 2.5s,
                            transform 0.8s ease-out 2.3s;
                transform: translateY(0px);
                opacity: 1;
            }
        }
    }
}
}

@media all and (min-width: 1400px) {
.section_name_educational {
    .section {
        &__header {
            left: 60px;
        }

        &__subtitle {
            width: 110%;
        }
    }
}
}

@media (--xxlarge) {
.section_name_educational {
    .section {

        &__primary {
            width: calc(100% - 148px);
        }

        &__subtitle {
            width: 80%;
            margin: 40px 0px;
        }

        &__description-inner {
            width: 60%;
        }

        &__bubbles {
            width: 148px;
            min-width: 148px;
            max-width: 148px;
            top: 40px;
        }
    }
}
}

@media (--monster) {
.section_name_educational {
    .section {
        &__primary {
            width: calc(100% - 227px);
        }

        &__header {
            left: 200px;
            top: 150px;
        }

        &__title {
            font-size: 58px;
        }

        &__subtitle {
            font-size: 24px;
            width: 80%;
        }

        &__description {
            font-size: 24px;
        }

        &__bubbles {
            width: 227px;
            min-width: 227px;
            max-width: 227px;
            left: 0px;
        }
    }
}
}

As for me - it would be difficult to read it if I had done it with the 1st variant.


问:
awk to extract lines in file that contain matching pattern and variable digit
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa
</code>```

desired output tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa
</code>```

awk

```<code> awk '$2 ~ /^exon [0-9][0-9] sequence$/' file
</code>```

答:
```<code>awk '$3 ~ /exon/' file

Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa
</code>```

Body:
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa

desired output tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa

awk

 awk '$2 ~ /^exon [0-9][0-9] sequence$/' file


答:
You're using the %i format specifier, which prints its argument as a signed int.

If you want to print as unsigned, use the %u format specifier.

```<code>printf("2^%i = %u\n", i, x);
</code>```

Body:
You're using the %i format specifier, which prints its argument as a signed int.

If you want to print as unsigned, use the %u format specifier.

printf("2^%i = %u\n", i, x);


问:
What is the LINQ to XML equivalent for this XPath
I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ:

```<code>/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned
</code>```

I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain section of the XML tree, dependent on the value of ancestor attributes.

答:
A more verbal solution:

```<code>var nodesIWantReturned = from m in doc.Elements("topNode").Elements("middleNode")
              from p in m.Elements("penultimateNode")
              from n in p.Elements("nodesIWantReturned")
              where m.Attribute("filteringAttribute").Value == "filterValue"
              where p.Attribute("anotherFilterAttribute").Value == "somethingElse"
              select n;
</code>```

OwnerDisplayName: Handleman

ContentLicense: CC BY-SA 2.5

Body:
I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ:

/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned

I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain section of the XML tree, dependent on the value of ancestor attributes.

Body:
A more verbal solution:

var nodesIWantReturned = from m in doc.Elements("topNode").Elements("middleNode")
              from p in m.Elements("penultimateNode")
              from n in p.Elements("nodesIWantReturned")
              where m.Attribute("filteringAttribute").Value == "filterValue"
              where p.Attribute("anotherFilterAttribute").Value == "somethingElse"
              select n;

OwnerDisplayName: bruno conde


问:
Find workspace location using ANT
I'm working on a build script in the Flash Builder version of Eclipse. This build script needs to import launch configuration .launch files into the user's workspace. However there doesn't seem to be an available ANT var for determining the workspace location. While stepping through the available vars with intellisense I noticed that ${osgi.instance.area} does point to my current workspace but when I tried to echo it back in a running ant script it just spat out "${osgi.instance.area}" and not the path.

Any help would be greatly appreciated. Thank you!!!

答:
This worked for me with a regular Eclipse installation, providing the script is run in Eclipse's own JVM:

```<code><eclipse.convertPath resourcepath="workspace_loc:/" property="eclipse.workspace.home"/>
</code>```

In order to denote an Ant script should run in Eclipse's own JVM, open the "External Tools Configurations..." dialog, choose your script from the left panel, go to the "JRE" tab, and choose the obvious radio button.

Amnon Grossman

Title: Find workspace location using ANT

Body:
This worked for me with a regular Eclipse installation, providing the script is run in Eclipse's own JVM:

<eclipse.convertPath resourcepath="workspace_loc:/" property="eclipse.workspace.home"/>

In order to denote an Ant script should run in Eclipse's own JVM, open the "External Tools Configurations..." dialog, choose your script from the left panel, go to the "JRE" tab, and choose the obvious radio button.

Amnon Grossman


答:
When you talk about the sign of a integral value in C (C++ and many other programming languages) you are just talking about how you interpret some data.

You must understand that what's stored inside an unsigned int are just bits regardless of the sign, the fact that they behave as "unsigned" when used is a mere interpretation of the value.

So by using %i specifier you are treating it as a signed value, regardless how it is declared. Try with %u which specifies that you want to treat them as unsigned.

Body:
I wrote this bit of code to learn about bit shifting.  To my surprise, even though I declared x to be an unsigned int, the output includes a negative number, namely when the leftmost bit is set to 1.  My question:  why?  I thought an unsigned int was never negative.  Per sizeof(x), x is 4 bytes wide.

Here is the code fragment:

int main(void)
{
    unsigned int x;

    x = 1;

    for (int i = 0; i < 32; i++)
    {
        printf("2^%i = %i\n", i, x);
        x <<= 1;
    }

    return 0;
}

Here is the output:

2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
2^7 = 128
2^8 = 256
2^9 = 512
2^10 = 1024
2^11 = 2048
2^12 = 4096
2^13 = 8192
2^14 = 16384
2^15 = 32768
2^16 = 65536
2^17 = 131072
2^18 = 262144
2^19 = 524288
2^20 = 1048576
2^21 = 2097152
2^22 = 4194304
2^23 = 8388608
2^24 = 16777216
2^25 = 33554432
2^26 = 67108864
2^27 = 134217728
2^28 = 268435456
2^29 = 536870912
2^30 = 1073741824
2^31 = -2147483648


问:
how to show progress bar on webview?
I am trying to open a webpage in my application using WebView. When I open webpage it shows me blank screen for a while and then open that page in browser inside my application.

Anyone suggest me how to show progress or get rid of that blank screen which comes during loading of webview?

I am using following code:

```<code>WebView mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);

// error handling
final Activity activity = this;

mWebView.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
    }
});

// error  handling

mWebView.loadUrl(URL);
mWebView.setWebViewClient(new HelloWebViewClient());
</code>```

答:
Here is the code I'm using in KOTLIN:

```<code>private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}
</code>```

Title: how to show progress bar on webview?

Body:
I am trying to open a webpage in my application using WebView. When I open webpage it shows me blank screen for a while and then open that page in browser inside my application.

Anyone suggest me how to show progress or get rid of that blank screen which comes during loading of webview?

I am using following code:

WebView mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);

// error handling
final Activity activity = this;

mWebView.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
    }
});

// error  handling

mWebView.loadUrl(URL);
mWebView.setWebViewClient(new HelloWebViewClient());

Body:
Here is the code I'm using in KOTLIN:

private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}


问:
How do I prevent overlapping text in the Slideshow for WordPress?
I have vertically-overlapping text in the Slideshow for a website using WordPress. It only appears to occur on mobile devices, so I will need to apply my changes in CSS using @media query. The direct container outside of it is a div, which appears to not have a user defined name. I would normally just increase the height of the div class surrounding the area to see if that's the problem, but I can't seem to do that, and I can't seem to make the text smaller either. The text is implemented in the Slideshow section of WordPress in the Content Block as

Accelerate Your Career
 etc..

Again this only happens on mobile devices when they are in portrait mode as far as I can tell. The website is http://avantirecruiters.com/

How can I prevent the overlapping text?

答:
The issue is with the line-height 13px. How about changing the line-height to 35px or something similar?

```<code>@media only screen and (max-width: 388px) and (min-width: 359px)
.caption-type2 > div h1.quote {
    width: 300px;
    font-size: 12px;
    line-height: 35px;
    margin: -193px auto 5px auto!important;
}
</code>```

Body:
The issue is with the line-height 13px. How about changing the line-height to 35px or something similar?

@media only screen and (max-width: 388px) and (min-width: 359px)
.caption-type2 > div h1.quote {
    width: 300px;
    font-size: 12px;
    line-height: 35px;
    margin: -193px auto 5px auto!important;
}


问:
Leaflet Draw 0.4.9 control not working with Leaflet 1.1.0?
I created a very minimal codepen, but I am getting an error when trying to create the draw control.

See: https://codepen.io/DrYSG/pen/QgmVZg

I assume it is something simple that I doing wrong. But I looked at the CDN I am using , and I see nothing obvious:

https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.9/leaflet.draw-src.js

These are the errors I am seeing in the console:

```<code>Util.js:15 Uncaught TypeError: Cannot add property segmentsIntersect, object is not extensible
    at Object.extend (Util.js:15)
    at LineUtil.Intersect.js:6
    at EditToolbar.Delete.js:145 extend @ Util.js:15 (anonymous) @ LineUtil.Intersect.js:6 (anonymous) @ EditToolbar.Delete.js:145 pen.js:11 Uncaught TypeError: L.Control.Draw is not a constructor
    at pen.js:11
</code>```

```<code>var map = L.map("root").setView([42, -71], 7);

L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy <a href="http://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}).addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: drawnItems
  }
});
map.addControl(drawControl);
</code>```

答: Indeed, Leaflet.draw is not working with Leaflet 1.1.0 . It has been reported. As long as this issue is not closed, consider the problem still there.</p>

Body:
I created a very minimal codepen, but I am getting an error when trying to create the draw control.

See: https://codepen.io/DrYSG/pen/QgmVZg

I assume it is something simple that I doing wrong. But I looked at the CDN I am using , and I see nothing obvious:

https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.9/leaflet.draw-src.js

These are the errors I am seeing in the console:

Util.js:15 Uncaught TypeError: Cannot add property segmentsIntersect, object is not extensible
    at Object.extend (Util.js:15)
    at LineUtil.Intersect.js:6
    at EditToolbar.Delete.js:145 extend @ Util.js:15 (anonymous) @ LineUtil.Intersect.js:6 (anonymous) @ EditToolbar.Delete.js:145 pen.js:11 Uncaught TypeError: L.Control.Draw is not a constructor
    at pen.js:11

var map = L.map("root").setView([42, -71], 7);

L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy OpenStreetMap contributors'
}).addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: drawnItems
  }
});
map.addControl(drawControl);


问:
Why does this code say that C::f overrides A::f but not B::f?
In the 3rd code example here the comment says that C::f overrides A::f. Why is this? My intuition says that it should override B::f.</p>

```<code>struct A { virtual void f(); };     // A::f is virtual
struct B : A { void f(); };         // B::f overrides A::f in B
struct C : virtual B { void f(); }; // C::f overrides A::f in C
struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D
struct E : C, D  {       // E does not introduce an overrider, C::f is final in E
    using A::f; // not a function declaration, just makes A::f visible to lookup
};
int main() {
   E e;
   e.f();    // virtual call calls C::f, the final overrider in e
   e.E::f(); // non-virtual call calls A::f, which is visible in E
}
</code>```

答:
The text of the C++14 standard is (class.virtual/2):

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. For convenience we say that any virtual function overrides itself.

So C::f overrides all of A::f, B::f and C::f.

Body:
In the 3rd code example here the comment says that C::f overrides A::f. Why is this? My intuition says that it should override B::f.

struct A { virtual void f(); };     // A::f is virtual
struct B : A { void f(); };         // B::f overrides A::f in B
struct C : virtual B { void f(); }; // C::f overrides A::f in C
struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D
struct E : C, D  {       // E does not introduce an overrider, C::f is final in E
    using A::f; // not a function declaration, just makes A::f visible to lookup
};
int main() {
   E e;
   e.f();    // virtual call calls C::f, the final overrider in e
   e.E::f(); // non-virtual call calls A::f, which is visible in E
}


问:
iPhone SDK - Table view, error with spaces
I have little knowledge with the iPhone SKD (don't even know what code it is objective c?). I have so far got a table view working, and then showing content on another nib file once a row clicked.

I have elseif statements for each row, telling them to load a nib file inside the ViewController. However, One row is causing a problem, it crases the app.

```<code>else if ([[array objectAtIndex:indexPath.row] isEqual:@"ASCII Characters"])
    {
        Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"ASCII Characters" bundle:nil];
        [self.navigationController pushViewController:asciicharacters animated:YES];
        [asciicharacters release];

    }
</code>```

Here is an image of the debugger console:

I don't what to do, there is no errors displaying at all. It just crashes the app, if that row is clicked (both on simulator and iPhone). I think is't something to do with the spaces with in the name. This is the only row that has a space. But I need a space otherwise it would look silly. Thanks :)

答:
I think you need to change the line

```<code>   Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"ASCII Characters" bundle:nil];
</code>```

with

```<code>   Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"Asciicharacters" bundle:nil];
</code>```

then only it works as with rule of objective C

Body:
I have little knowledge with the iPhone SKD (don't even know what code it is objective c?). I have so far got a table view working, and then showing content on another nib file once a row clicked.

I have elseif statements for each row, telling them to load a nib file inside the ViewController. However, One row is causing a problem, it crases the app.

else if ([[array objectAtIndex:indexPath.row] isEqual:@"ASCII Characters"])
    {
        Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"ASCII Characters" bundle:nil];
        [self.navigationController pushViewController:asciicharacters animated:YES];
        [asciicharacters release];

    }

Here is an image of the debugger console:

I don't what to do, there is no errors displaying at all. It just crashes the app, if that row is clicked (both on simulator and iPhone). I think is't something to do with the spaces with in the name. This is the only row that has a space. But I need a space otherwise it would look silly. Thanks :)

Body:
I think you need to change the line

   Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"ASCII Characters" bundle:nil];

with

   Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"Asciicharacters" bundle:nil];

then only it works as with rule of objective C


问:
VHDL: creating a very slow clock pulse based on a very fast clock
(I'd post this in EE but it seems there are far more VHDL questions here...)

Background: I'm using the Xilinx Spartan-6LX9 FPGA with the Xilinx ISE 14.4 (webpack).

I stumbled upon the dreaded "PhysDesignRules:372 - Gated clock" warning today, and I see there's a LOT of discussion out there concerning that in general. The consensus seems to be to use one of the DCMs on the FPGA to do clock division but... my DCM doesn't appear to be capable of going from 32 MHz to 4.096 KHz (per the wizard it bottoms out at 5MHz based on 32MHz... and it seems absurd to try to chain multiple DCMs for this low-frequency purpose).

My current design uses clk_in to count up to a specified value (15265), resets that value to zero and toggles the clk_out bit (so I end up with a duty cycle of 50%, FWIW). It does the job, and I can easily use the rising edge of clk_out to drive the next stage of my design. It seems to work just fine, but... gated clock (even though it isn't in the range where clock skew would IMHO be very relevant). (Note: All clock tests are done using the rising_edge() function in processes sensitive to the given clock.)

So, my questions:

If we're talking about deriving a relatively slow clk_out from a much faster clk_in, is gating still considered bad? Or is this sort of "count to x and send a pulse" thing pretty typical for FPGAs to generate a "clock" in the KHz range and instead some other unnecessary side-effect may be triggering this warning instead?

Is there a better way to create a low KHz-range clock from a MHz-range master clock, keeping in mind that using multiple DCMs appears to be overkill here (if it's possible at all given the very low output frequency)? I realize the 50% duty cycle may be superfluous but assuming one clock in and not using the on-board DCMs how else would one perform major clock division with an FPGA?

Edit: Given the following (where CLK_MASTER is the 32 MHz input clock and CLK_SLOW is the desired slow-rate clock, and LOCAL_CLK_SLOW was a way to store the state of the clock for the whole duty-cycle thing), I learned that this configuration causes the warning:

```<code>architecture arch of clock is
    constant CLK_MASTER_FREQ: natural := 32000000; -- time := 31.25 ns
    constant CLK_SLOW_FREQ: natural := 2048;
    constant MAX_COUNT: natural := CLK_MASTER_FREQ/CLK_SLOW_FREQ;
    shared variable counter: natural := 0;
    signal LOCAL_CLK_SLOW: STD_LOGIC := '0';
begin
    clock_proc: process(CLK_MASTER)
    begin
        if rising_edge(CLK_MASTER) then
            counter := counter + 1;
            if (counter >= MAX_COUNT) then
                counter := 0;
                LOCAL_CLK_SLOW <= not LOCAL_CLK_SLOW;
                CLK_SLOW <= LOCAL_CLK_SLOW;
            end if;
        end if;
    end process;
end arch;
</code>```

Whereas this configuration does NOT cause the warning:

```<code>architecture arch of clock is
    constant CLK_MASTER_FREQ: natural := 32000000; -- time := 31.25 ns
    constant CLK_SLOW_FREQ: natural := 2048;
    constant MAX_COUNT: natural := CLK_MASTER_FREQ/CLK_SLOW_FREQ;
    shared variable counter: natural := 0;
begin
    clock_proc: process(CLK_MASTER)
    begin
        if rising_edge(CLK_MASTER) then
            counter := counter + 1;
            if (counter >= MAX_COUNT) then
                counter := 0;
                CLK_SLOW <= '1';
            else
                CLK_SLOW <= '0';
            end if;
        end if;
    end process;
end arch;
</code>```

So, in this case it was all for lack of an else (like I said, the 50% duty cycle was originally interesting but wasn't a requirement in the end, and the toggle of the "local" clock bit seemed quite clever at the time...) I was mostly on the right track it appears.

What's not clear to me at this point is why using a counter (which stores lots of bits) isn't causing warnings, but a stored-and-toggled output bit does cause warnings. Thoughts?

答:
Here's a Complete Sample Code :</p>

```<code>LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.NUMERIC_STD.ALL;

ENTITY Test123 IS

    GENERIC (
        clk_1_freq_generic : unsigned(31 DOWNTO 0) := to_unsigned(0, 32); -- Presented in Hz
        clk_in1_freq_generic : unsigned(31 DOWNTO 0) := to_unsigned(0, 32) -- Presented in Hz, Also
    );

    PORT (
        clk_in1 : IN std_logic := '0';
        rst1 : IN std_logic := '0';
        en1 : IN std_logic := '0';
        clk_1 : OUT std_logic := '0'
    );

END ENTITY Test123;

ARCHITECTURE Test123_Arch OF Test123 IS
    --
    SIGNAL clk_en_en : std_logic := '0';
    SIGNAL clk_en_cntr1 : unsigned(31 DOWNTO 0) := (OTHERS => '0');
    --
    SIGNAL clk_1_buffer : std_logic := '0';
    SIGNAL clk_1_freq : unsigned(31 DOWNTO 0) := (OTHERS => '0'); -- Presented in Hz, Also
    SIGNAL clk_in1_freq : unsigned(31 DOWNTO 0) := (OTHERS => '0'); -- Presented in Hz
    --
    SIGNAL clk_prescaler1 : unsigned(31 DOWNTO 0) := (OTHERS => '0'); -- Presented in Cycles (Relative To The Input Clk.)
    SIGNAL clk_prescaler1_halved : unsigned(31 DOWNTO 0) := (OTHERS => '0');
    --

BEGIN
    clk_en_gen : PROCESS (clk_in1)
    BEGIN
        IF (clk_en_en = '1') THEN

            IF (rising_edge(clk_in1)) THEN
                clk_en_cntr1 <= clk_en_cntr1 + 1;

                IF ((clk_en_cntr1 + 1) = clk_prescaler1_halved) THEN   -- a Register's (F/F) Output Only Updates Upon a Clock-Edge : That's Why This Comparison Is Done This Way !

                    clk_1_buffer <= NOT clk_1_buffer;
                    clk_1 <= clk_1_buffer;
                    clk_en_cntr1 <= (OTHERS => '0');

                END IF;

            END IF;

        ELSIF (clk_en_en = '0') THEN

            clk_1_buffer <= '0';
            clk_1 <= clk_1_buffer;
            clk_en_cntr1 <= (OTHERS => '0'); -- Clear Counter 'clk_en_cntr1'

        END IF;

    END PROCESS;

    update_clk_prescalers : PROCESS (clk_in1_freq, clk_1_freq)
    BEGIN
        clk_prescaler1 <= (OTHERS => '0');
        clk_prescaler1_halved <= (OTHERS => '0');
        clk_en_en <= '0';

        IF ((clk_in1_freq > 0) AND (clk_1_freq > 0)) THEN

            clk_prescaler1 <= (clk_in1_freq / clk_1_freq); -- a Register's (F/F) Output Only Updates Upon a Clock-Edge : That's Why This Assignment Is Done This Way !
            clk_prescaler1_halved <= ((clk_in1_freq / clk_1_freq) / 2); -- (Same Thing Here)

            IF (((clk_in1_freq / clk_1_freq) / 2) > 0) THEN -- (Same Thing Here, Too)
                clk_en_en <= '1';
            END IF;

        ELSE
            NULL;
        END IF;

    END PROCESS;

    clk_1_freq <= clk_1_freq_generic;
    clk_in1_freq <= clk_in1_freq_generic;

END ARCHITECTURE Test123_Arch;
</code>```

Body:
(I'd post this in EE but it seems there are far more VHDL questions here...)

Background: I'm using the Xilinx Spartan-6LX9 FPGA with the Xilinx ISE 14.4 (webpack).

I stumbled upon the dreaded "PhysDesignRules:372 - Gated clock" warning today, and I see there's a LOT of discussion out there concerning that in general. The consensus seems to be to use one of the DCMs on the FPGA to do clock division but... my DCM doesn't appear to be capable of going from 32 MHz to 4.096 KHz (per the wizard it bottoms out at 5MHz based on 32MHz... and it seems absurd to try to chain multiple DCMs for this low-frequency purpose).

My current design uses clk_in to count up to a specified value (15265), resets that value to zero and toggles the clk_out bit (so I end up with a duty cycle of 50%, FWIW). It does the job, and I can easily use the rising edge of clk_out to drive the next stage of my design. It seems to work just fine, but... gated clock (even though it isn't in the range where clock skew would IMHO be very relevant). (Note: All clock tests are done using the rising_edge() function in processes sensitive to the given clock.)

So, my questions:

If we're talking about deriving a relatively slow clk_out from a much faster clk_in, is gating still considered bad? Or is this sort of "count to x and send a pulse" thing pretty typical for FPGAs to generate a "clock" in the KHz range and instead some other unnecessary side-effect may be triggering this warning instead?

Is there a better way to create a low KHz-range clock from a MHz-range master clock, keeping in mind that using multiple DCMs appears to be overkill here (if it's possible at all given the very low output frequency)? I realize the 50% duty cycle may be superfluous but assuming one clock in and not using the on-board DCMs how else would one perform major clock division with an FPGA?

Edit: Given the following (where CLK_MASTER is the 32 MHz input clock and CLK_SLOW is the desired slow-rate clock, and LOCAL_CLK_SLOW was a way to store the state of the clock for the whole duty-cycle thing), I learned that this configuration causes the warning:

architecture arch of clock is
    constant CLK_MASTER_FREQ: natural := 32000000; -- time := 31.25 ns
    constant CLK_SLOW_FREQ: natural := 2048;
    constant MAX_COUNT: natural := CLK_MASTER_FREQ/CLK_SLOW_FREQ;
    shared variable counter: natural := 0;
    signal LOCAL_CLK_SLOW: STD_LOGIC := '0';
begin
    clock_proc: process(CLK_MASTER)
    begin
        if rising_edge(CLK_MASTER) then
            counter := counter + 1;
            if (counter >= MAX_COUNT) then
                counter := 0;
                LOCAL_CLK_SLOW <= not LOCAL_CLK_SLOW;
                CLK_SLOW <= LOCAL_CLK_SLOW;
            end if;
        end if;
    end process;
end arch;

Whereas this configuration does NOT cause the warning:

architecture arch of clock is
    constant CLK_MASTER_FREQ: natural := 32000000; -- time := 31.25 ns
    constant CLK_SLOW_FREQ: natural := 2048;
    constant MAX_COUNT: natural := CLK_MASTER_FREQ/CLK_SLOW_FREQ;
    shared variable counter: natural := 0;
begin
    clock_proc: process(CLK_MASTER)
    begin
        if rising_edge(CLK_MASTER) then
            counter := counter + 1;
            if (counter >= MAX_COUNT) then
                counter := 0;
                CLK_SLOW <= '1';
            else
                CLK_SLOW <= '0';
            end if;
        end if;
    end process;
end arch;

So, in this case it was all for lack of an else (like I said, the 50% duty cycle was originally interesting but wasn't a requirement in the end, and the toggle of the "local" clock bit seemed quite clever at the time...) I was mostly on the right track it appears.

What's not clear to me at this point is why using a counter (which stores lots of bits) isn't causing warnings, but a stored-and-toggled output bit does cause warnings. Thoughts?

Body:
Here's a Complete Sample Code :

LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.NUMERIC_STD.ALL;

ENTITY Test123 IS

    GENERIC (
        clk_1_freq_generic : unsigned(31 DOWNTO 0) := to_unsigned(0, 32); -- Presented in Hz
        clk_in1_freq_generic : unsigned(31 DOWNTO 0) := to_unsigned(0, 32) -- Presented in Hz, Also
    );

    PORT (
        clk_in1 : IN std_logic := '0';
        rst1 : IN std_logic := '0';
        en1 : IN std_logic := '0';
        clk_1 : OUT std_logic := '0'
    );

END ENTITY Test123;

ARCHITECTURE Test123_Arch OF Test123 IS
    --
    SIGNAL clk_en_en : std_logic := '0';
    SIGNAL clk_en_cntr1 : unsigned(31 DOWNTO 0) := (OTHERS => '0');
    --
    SIGNAL clk_1_buffer : std_logic := '0';
    SIGNAL clk_1_freq : unsigned(31 DOWNTO 0) := (OTHERS => '0'); -- Presented in Hz, Also
    SIGNAL clk_in1_freq : unsigned(31 DOWNTO 0) := (OTHERS => '0'); -- Presented in Hz
    --
    SIGNAL clk_prescaler1 : unsigned(31 DOWNTO 0) := (OTHERS => '0'); -- Presented in Cycles (Relative To The Input Clk.)
    SIGNAL clk_prescaler1_halved : unsigned(31 DOWNTO 0) := (OTHERS => '0');
    --

BEGIN
    clk_en_gen : PROCESS (clk_in1)
    BEGIN
        IF (clk_en_en = '1') THEN

            IF (rising_edge(clk_in1)) THEN
                clk_en_cntr1 <= clk_en_cntr1 + 1;

                IF ((clk_en_cntr1 + 1) = clk_prescaler1_halved) THEN   -- a Register's (F/F) Output Only Updates Upon a Clock-Edge : That's Why This Comparison Is Done This Way !

                    clk_1_buffer <= NOT clk_1_buffer;
                    clk_1 <= clk_1_buffer;
                    clk_en_cntr1 <= (OTHERS => '0');

                END IF;

            END IF;

        ELSIF (clk_en_en = '0') THEN

            clk_1_buffer <= '0';
            clk_1 <= clk_1_buffer;
            clk_en_cntr1 <= (OTHERS => '0'); -- Clear Counter 'clk_en_cntr1'

        END IF;

    END PROCESS;

    update_clk_prescalers : PROCESS (clk_in1_freq, clk_1_freq)
    BEGIN
        clk_prescaler1 <= (OTHERS => '0');
        clk_prescaler1_halved <= (OTHERS => '0');
        clk_en_en <= '0';

        IF ((clk_in1_freq > 0) AND (clk_1_freq > 0)) THEN

            clk_prescaler1 <= (clk_in1_freq / clk_1_freq); -- a Register's (F/F) Output Only Updates Upon a Clock-Edge : That's Why This Assignment Is Done This Way !
            clk_prescaler1_halved <= ((clk_in1_freq / clk_1_freq) / 2); -- (Same Thing Here)

            IF (((clk_in1_freq / clk_1_freq) / 2) > 0) THEN -- (Same Thing Here, Too)
                clk_en_en <= '1';
            END IF;

        ELSE
            NULL;
        END IF;

    END PROCESS;

    clk_1_freq <= clk_1_freq_generic;
    clk_in1_freq <= clk_in1_freq_generic;

END ARCHITECTURE Test123_Arch;


问:
How to delete an array element inside Map in Immutable js?
I am new to Immutable and I am pretty confused that how to delete an array element which is inside a Map. I don't want to use fromJs. I know there is a lot of resources on Stack Overflow but the don't work for me.

const test = Map({
  arr: [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
});

console.log(test.get('arr'))
```

<p>Before </p>

```arr:[{id:1},{id:2},{id:3}]
```

<p>I want to remove id : 3 </p>

```arr:[{id:1},{id:2}]
```

答:
The basic problem here is that when you create a Map it only shallowly converts the object keys in to Map keys. It does not deeply convert the object. This is ok, but you have to handle this case correctly and it can be a bit confusing when you're first dealing with this situation.

First, you should understand that this...

```<code>const test = Map({
  arr: [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
})
</code>```

Is this...

```<code>Map {
  arr: [
    { id: 1 },
    { id: 2 },
    { id: 3 }
  ]
}
</code>```

Where the value stored at arr is an Array and not an immutable List and the values stored in that array are objects not Maps.

To change the mutable values you will need to update the Map and change the array at the same time. Note that you want to do this immutably so that you do not change the mutable values stored in your immutable Map. The immutable way of doing this would look something like the following.

If you know the index of where the object with id: 3 is located, then you can slice out that index...

```<code>const i = 2
test = test  // remember that any change to an immutable object creates a new object, so assignment is required
  .update('arr', (arr) => {
    return arr.slice(0, i).concat(arr.slice(i + 1))
  })
</code>```

If you don't know the index then you can filter the array...

```<code>test = test  // remember that any change to an immutable object creates a new object, so assignment is required
  .update('arr', (arr) => {
    return arr.filter((obj) => obj.id !== 3)
  })
</code>```

This experience can be a bit painful so I wrote mudash to specifically help when dealing with mixed nested data structures. You can achieve the same as above doing this with mudash...

```<code>const _ = require('mudash')

// delete, this correctly traverses mixed structures...
test = _.delete(test, 'arr.2')

//update/filter, these methods correctly handle both immutable and stadard js types...
test = _.update(test, 'arr', (arr) => _.filter(arr, (obj) => obj.id !== 3))
</code>```

Body:
I am new to Immutable and I am pretty confused that how to delete an array element which is inside a Map. I don't want to use fromJs. I know there is a lot of resources on Stack Overflow but the don't work for me.

const test = Map({
  arr: [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
});

console.log(test.get('arr'))

Before

arr:[{id:1},{id:2},{id:3}]

I want to remove id : 3

arr:[{id:1},{id:2}]

Body:
The basic problem here is that when you create a Map it only shallowly converts the object keys in to Map keys. It does not deeply convert the object. This is ok, but you have to handle this case correctly and it can be a bit confusing when you're first dealing with this situation.

First, you should understand that this...

const test = Map({
  arr: [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
})

Is this...

Map {
  arr: [
    { id: 1 },
    { id: 2 },
    { id: 3 }
  ]
}

Where the value stored at arr is an Array and not an immutable List and the values stored in that array are objects not Maps.

To change the mutable values you will need to update the Map and change the array at the same time. Note that you want to do this immutably so that you do not change the mutable values stored in your immutable Map. The immutable way of doing this would look something like the following.

If you know the index of where the object with id: 3 is located, then you can slice out that index...

const i = 2
test = test  // remember that any change to an immutable object creates a new object, so assignment is required
  .update('arr', (arr) => {
    return arr.slice(0, i).concat(arr.slice(i + 1))
  })

If you don't know the index then you can filter the array...

test = test  // remember that any change to an immutable object creates a new object, so assignment is required
  .update('arr', (arr) => {
    return arr.filter((obj) => obj.id !== 3)
  })

This experience can be a bit painful so I wrote mudash to specifically help when dealing with mixed nested data structures. You can achieve the same as above doing this with mudash...

const _ = require('mudash')

// delete, this correctly traverses mixed structures...
test = _.delete(test, 'arr.2')

//update/filter, these methods correctly handle both immutable and stadard js types...
test = _.update(test, 'arr', (arr) => _.filter(arr, (obj) => obj.id !== 3))