问:
Javascript code does not work on web hosting server
I have one very strange problem. Javascript code on my web page does not work properly. The strange thing is that when I run the page on localhost (wamp) everything works perfectly, as it should. The problem starts when I upload web page to web hosting, one part of the code does not work. The part that should call pop up windows (div tags) does not work at all. When link is clicked nothing happens.

I have tried using two different free web hosts and same problem occurred on both. I also tried running developer tools (F12), but there are no errors as I expected because everything works perfectly on localhost.

Here is the particular code that does not work.

```<code><div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times</a>
     <a href="javascript:void(0)" id="myBtn">T1</a>
     <a href="javascript:void(0)" id="myBtn2">T2</a>
  <a href="javascript:void(0)" id="myBtn3">T3</a>
  <a href="javascript:void(0)" id="myBtn4">T4</a>
</div>

<script>
  var modal = document.getElementById('myModal');
  var btn = document.getElementById("myBtn");
  var span = document.getElementsByClassName("close")[0];
  btn.onclick = function() {
    modal.style.display = "block";
  }
  span.onclick = function() {
    modal.style.display = "none";
  }
</script>
<script>
  var modal2 = document.getElementById('myModal2');
  var btn2 = document.getElementById("myBtn2");
  var span2 = document.getElementsByClassName("close")[1];
  btn2.onclick = function() {
    modal2.style.display = "block";
  }
  span2.onclick = function() {
    modal2.style.display = "none";
  }
</script>
<script>
  var modal3 = document.getElementById('myModal3');
  var btn3 = document.getElementById("myBtn3");
  var span3 = document.getElementsByClassName("close")[2];
  btn3.onclick = function() {
    modal3.style.display = "block";
  }
  span3.onclick = function() {
    modal3.style.display = "none";
  }
</script>
<script>
  var modal4 = document.getElementById('myModal4');
  var btn4 = document.getElementById("myBtn4");
  var span4 = document.getElementsByClassName("close")[3];
  btn4.onclick = function() {
    modal4.style.display = "block";
  }
  span4.onclick = function() {
    modal4.style.display = "none";
  }
</script>
</code>```

I understand that javascript is the front-end technology and that it does not run on the server, but I really do not know what causes this. I hope someone had similar problem since I really have no idea what could it be.

答:
We can simplify a lot of the code if we use functions and pass some parameters.

also, we can use Event Delegation instead of adding listeners to each object, this is very effective for dynamic HTML and repetitive element structures.

Notice how we test the event.target using a matches.

I have dummied up the Modal for the demo.

// First lets use a functions
const showModal = (modalId) => {
  const modal = document.querySelector(`#${modalId}`);
  modal.style.display = 'block';
};

const hideModal = (modalId) => {
  const modal = document.querySelector(`#${modalId}`);
  modal.style.display = 'none';
};

// Now lets listen for any click
document.addEventListener('click', (e) => {
  // Based on what was clicked we will do something.
  if(e.target.matches('.showmodal')) showModal(e.target.dataset.modal);

  if(e.target.matches('.close')) hideModal(e.target.parentNode.id);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  margin-top: 25px;
  padding: 15px;
  color: white;
  background-color: blue;
  border-radius: 7px;
  display: none;
}

span.close {
  float: right;
  font-weight: bold;
}</code>```

&times
     T1
     T2
  T3
  T4

Modal 1 Close Me

Modal 2 Close Me

Modal 3 Close Me

Modal 4 Close Me
```

Body:
I have one very strange problem. Javascript code on my web page does not work properly. The strange thing is that when I run the page on localhost (wamp) everything works perfectly, as it should. The problem starts when I upload web page to web hosting, one part of the code does not work. The part that should call pop up windows (div tags) does not work at all. When link is clicked nothing happens.

I have tried using two different free web hosts and same problem occurred on both. I also tried running developer tools (F12), but there are no errors as I expected because everything works perfectly on localhost.

Here is the particular code that does not work.

&times
     T1
     T2
  T3
  T4

I understand that javascript is the front-end technology and that it does not run on the server, but I really do not know what causes this. I hope someone had similar problem since I really have no idea what could it be.

Body:
We can simplify a lot of the code if we use functions and pass some parameters.

also, we can use Event Delegation instead of adding listeners to each object, this is very effective for dynamic HTML and repetitive element structures.

Notice how we test the event.target using a matches.

I have dummied up the Modal for the demo.

// First lets use a functions
const showModal = (modalId) => {
  const modal = document.querySelector(`#${modalId}`);
  modal.style.display = 'block';
};

const hideModal = (modalId) => {
  const modal = document.querySelector(`#${modalId}`);
  modal.style.display = 'none';
};

// Now lets listen for any click
document.addEventListener('click', (e) => {
  // Based on what was clicked we will do something.
  if(e.target.matches('.showmodal')) showModal(e.target.dataset.modal);

  if(e.target.matches('.close')) hideModal(e.target.parentNode.id);

});

.modal {
  margin-top: 25px;
  padding: 15px;
  color: white;
  background-color: blue;
  border-radius: 7px;
  display: none;
}

span.close {
  float: right;
  font-weight: bold;
}

<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times</a>
     <a href="#" id="myBtn" class="showmodal" data-modal="myModal">T1</a>
     <a href="#" id="myBtn2" class="showmodal" data-modal="myModal2">T2</a>
  <a href="#" id="myBtn3" class="showmodal" data-modal="myModal3">T3</a>
  <a href="#" id="myBtn4" class="showmodal" data-modal="myModal4">T4</a>
</div>

<div id="myModal" class="modal">Modal 1 <span class="close">Close Me</span></div>
<div id="myModal2" class="modal">Modal 2 <span class="close">Close Me</span></div>
<div id="myModal3" class="modal">Modal 3 <span class="close">Close Me</span></div>
<div id="myModal4" class="modal">Modal 4 <span class="close">Close Me</span></div>


来源: stackexchange

问:
Fastest way to iterate through nodes with arbitrary number of connections to each other
I am making a fracturing script where there are nodes that each hold an arbitrary number of connections to other nodes.

Shards and chunks :

Each node represents a "shard" of a pre-fractured "chunk".

When a shard is broken all its connections to other shards and their connections to it are removed.

When this happens, I need to iterate through the shards and find out which are connected together and if the chunk is split apart to create new chunks.

What is the fastest way to do this?

Currently I have:

a Shard class that has

a reference to the parent chunk

a list of connections to adjacent shards.

a Break() method that

removes all connections from adjacent shards to this one.

clears the connections from this to adjacent shards.

calls the parent chunk's UpdateChunk() method.

a Chunk class that has

a list of all the shards that it contains.

an UpdateChunk() method that

checks if there is only one shard and then destroys this chunk.

makes a new list of all the shards in this chunk to keep track of
unprocessed shards.

calls ProcessShard() method to recursively process all shards
through their connections starting form the first shard in the
unprocessed shard list.

checks if there are still shards in the unprocessed list and if so
creates a new chunk and dumps the leftover shards in it and calls
its UpdateChunk() method.

a ProcessShard() method that

removes given shard from the unprocessed list

makes given shard's parent chunk the current chunk

loops through all the shards this one connects to and checks if they
are not in the processed list and if so calls ProcessShard() for
them.

public class Shard : MonoBehaviour
{
    public GameObject parentChunk;

    public List<GameObject> connectedShards = new List<GameObject>();

    public void Break()
    {
        // remove all connections that point to this shard
        foreach (GameObject shard in connectedShards)
        {
            // remove connection to this shard
            shard.GetComponent<Shard>().connectedShards.Remove(gameObject);
        }

        // clear connected shards list
        connectedShards.Clear();

        // check that there is a parent chunk
        if (parentChunk)
        {
            // force parent chunk to update
            parentChunk.GetComponent<Chunk>().UpdateChunk();

            // set parent chunk to null
            parentChunk = null;
        }
    }
}

public class Chunk : MonoBehaviour
{
    public List<GameObject> shards = new List<GameObject>();

    private List<GameObject> unprocessedShards = new List<GameObject>();

    public void UpdateChunk()
    {
        // if there is only one shard in this chunk
        if (shards.Count == 1)
        {
            // break shard
            shards[0].GetComponent<Shard>().parentChunk = null;
            shards[0].GetComponent<Shard>().Break();

            // destroy this chunk
            Destroy(gameObject);
        }
        else // there are multiple shards in this chunk
        {
            // fill the unprocessed shards list
            unprocessedShards = new List<GameObject>(shards);

            // process all shards in this chunk recursively starting from the first
            ProcessShard(unprocessedShards[0], gameObject);

            // if there are still unprocessed shards (this chunk was split)
            if (unprocessedShards.Count > 0)
            {
                // remove the unprocessed shards from this chunk's shard list
                foreach (GameObject unprocessedShard in unprocessedShards)
                {
                    shards.Remove(unprocessedShard);
                }

                // create new chunk(s) from the leftover shards
                parentObject.GetComponent<Fragmenter>().NewChunk(unprocessedShards);
            }
        }
    }

    // process shard
    private void ProcessShard(GameObject shard, GameObject chunk)
    {
        // remove shard from unprocessed list
        unprocessedShards.Remove(shard);

        // add shard to the given chunk
        shard.GetComponent<Shard>().parentChunk = chunk;

        // loop through all shards connected to the given shard
        foreach (GameObject connectedShard in shard.GetComponent<Shard>().connectedShards)
        {
            // connected shard has not been processed yet
            if (unprocessedShards.Contains(connectedShard))
            {
                // process all shards connected to the connected shard
                ProcessShard(connectedShard, chunk);
            }
        }
    }
}
```

I am mostly thinking about the ProcessShard() method where it usually processes each shard multiple times since one can be adjacent to many. How can I most efficiently ignore the ones that have already been processed?

答:
Firstly I would suggest moving away from List.Remove since worst case it needs to check each item to find the one to remove. Instead of removing shards that are being processed from the list of unprocessed shards, you could keep another list of processed shards and add to that. Then your condition checking if the connected shard is unprocessed would become if(!processedShards.Contains(connectedShard)).

You can read more about the performance of List operations on the microsoft docs, just scroll down to the Remarks section.

Another improvement would be to find an alternative to List.Contains when checking if a shard has been processed. Similarly to List.Remove, it needs to potentially check each item in the list before it can tell if the item is present.

One way to do so would be to use a HashSet instead of a List. It provides much quicker ways to access specific items and to check if items are present in the collection. It also provides many of the same methods so refactoring should be a breeze.

Just as a note, personally I wouldn't bother with optimization until performance becomes an issue. You might find these improvements gain you next to nothing as your collections just aren't large enough. If you have not yet, check out the Unity profiler and from there gauge where your big performance hits are coming from.

ContentLicense: CC BY-SA 4.0

Body:
I am making a fracturing script where there are nodes that each hold an arbitrary number of connections to other nodes.

Shards and chunks :

Each node represents a "shard" of a pre-fractured "chunk".

When a shard is broken all its connections to other shards and their connections to it are removed.

When this happens, I need to iterate through the shards and find out which are connected together and if the chunk is split apart to create new chunks.

What is the fastest way to do this?

Currently I have:

a Shard class that has

a reference to the parent chunk

a list of connections to adjacent shards.

a Break() method that

removes all connections from adjacent shards to this one.

clears the connections from this to adjacent shards.

calls the parent chunk's UpdateChunk() method.

a Chunk class that has

a list of all the shards that it contains.

an UpdateChunk() method that

checks if there is only one shard and then destroys this chunk.

makes a new list of all the shards in this chunk to keep track of
unprocessed shards.

calls ProcessShard() method to recursively process all shards
through their connections starting form the first shard in the
unprocessed shard list.

checks if there are still shards in the unprocessed list and if so
creates a new chunk and dumps the leftover shards in it and calls
its UpdateChunk() method.

a ProcessShard() method that

removes given shard from the unprocessed list

makes given shard's parent chunk the current chunk

loops through all the shards this one connects to and checks if they
are not in the processed list and if so calls ProcessShard() for
them.

public class Shard : MonoBehaviour
{
    public GameObject parentChunk;

    public List<GameObject> connectedShards = new List<GameObject>();

    public void Break()
    {
        // remove all connections that point to this shard
        foreach (GameObject shard in connectedShards)
        {
            // remove connection to this shard
            shard.GetComponent<Shard>().connectedShards.Remove(gameObject);
        }

        // clear connected shards list
        connectedShards.Clear();

        // check that there is a parent chunk
        if (parentChunk)
        {
            // force parent chunk to update
            parentChunk.GetComponent<Chunk>().UpdateChunk();

            // set parent chunk to null
            parentChunk = null;
        }
    }
}

public class Chunk : MonoBehaviour
{
    public List<GameObject> shards = new List<GameObject>();

    private List<GameObject> unprocessedShards = new List<GameObject>();

    public void UpdateChunk()
    {
        // if there is only one shard in this chunk
        if (shards.Count == 1)
        {
            // break shard
            shards[0].GetComponent<Shard>().parentChunk = null;
            shards[0].GetComponent<Shard>().Break();

            // destroy this chunk
            Destroy(gameObject);
        }
        else // there are multiple shards in this chunk
        {
            // fill the unprocessed shards list
            unprocessedShards = new List<GameObject>(shards);

            // process all shards in this chunk recursively starting from the first
            ProcessShard(unprocessedShards[0], gameObject);

            // if there are still unprocessed shards (this chunk was split)
            if (unprocessedShards.Count > 0)
            {
                // remove the unprocessed shards from this chunk's shard list
                foreach (GameObject unprocessedShard in unprocessedShards)
                {
                    shards.Remove(unprocessedShard);
                }

                // create new chunk(s) from the leftover shards
                parentObject.GetComponent<Fragmenter>().NewChunk(unprocessedShards);
            }
        }
    }

    // process shard
    private void ProcessShard(GameObject shard, GameObject chunk)
    {
        // remove shard from unprocessed list
        unprocessedShards.Remove(shard);

        // add shard to the given chunk
        shard.GetComponent<Shard>().parentChunk = chunk;

        // loop through all shards connected to the given shard
        foreach (GameObject connectedShard in shard.GetComponent<Shard>().connectedShards)
        {
            // connected shard has not been processed yet
            if (unprocessedShards.Contains(connectedShard))
            {
                // process all shards connected to the connected shard
                ProcessShard(connectedShard, chunk);
            }
        }
    }
}

I am mostly thinking about the ProcessShard() method where it usually processes each shard multiple times since one can be adjacent to many. How can I most efficiently ignore the ones that have already been processed?


问:
ORACLE_HOME must be set and $ORACLE_HOME/dbs must be writable error in Xubuntu Linux 16.04
Looking for some advice and help on issues, I am having with a new install of Oracle XE on my laptop running Xubuntu Linux 16.04 LTS. I followed this post for my install.

In the Oracle XE install location /u01/app/oracle/product/11.2.0/xe/
there is a /bin folder with a createdb.sh file I am trying to run to install the initial XE DB but am getting the error ORACLE_HOME must be set and $ORACLE_HOME/dbs must be writable.

My .bashrc contains the below code so I am not sure if it is correct and if it is, why am I getting the $ORACLE_HOME must be set error.

```<code>export ORACLE_HOME="/u01/app/oracle/product/11.2.0/xe"
export ORACLE_SID="XE"
export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export ORACLE_BASE="/u01/app/oracle"
export LD_LIBRARY_PATH="$ORACLE_HOME/lib:$LD_LIBRARY_PATH"
export PATH="$ORACLE_HOME/bin:$PATH:."
</code>```

In the terminal when I execute echo $ORACLE_HOME

I get

/u01/app/oracle/product/11.2.0/xe

which seems to me like the path is set correctly. On to the permissions of the $ORACLE_HOME/dbs directory.
ls -l shows this

drwxr-xr-x  2 root root 4096 Jun  5 12:50 dbs

which depicts the owner (root) has write permission. I am kind of lost on all of this and again, this is my first go round with Oracle SQL in Linux. Any help is greatly appreciated. Thanks, all.

答: You need to execute it as the oracle user. Do su oracle first and then execute the /u01/app/oracle/product/11.2.0/xe/bin/createdb.sh

ContentLicense: CC BY-SA 3.0

Body:
Looking for some advice and help on issues, I am having with a new install of Oracle XE on my laptop running Xubuntu Linux 16.04 LTS. I followed this post for my install.

In the Oracle XE install location /u01/app/oracle/product/11.2.0/xe/
there is a /bin folder with a createdb.sh file I am trying to run to install the initial XE DB but am getting the error ORACLE_HOME must be set and $ORACLE_HOME/dbs must be writable.

My .bashrc contains the below code so I am not sure if it is correct and if it is, why am I getting the $ORACLE_HOME must be set error.

export ORACLE_HOME="/u01/app/oracle/product/11.2.0/xe"
export ORACLE_SID="XE"
export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export ORACLE_BASE="/u01/app/oracle"
export LD_LIBRARY_PATH="$ORACLE_HOME/lib:$LD_LIBRARY_PATH"
export PATH="$ORACLE_HOME/bin:$PATH:."

In the terminal when I execute echo $ORACLE_HOME

I get

/u01/app/oracle/product/11.2.0/xe

which seems to me like the path is set correctly. On to the permissions of the $ORACLE_HOME/dbs directory.
ls -l shows this

drwxr-xr-x  2 root root 4096 Jun  5 12:50 dbs

which depicts the owner (root) has write permission. I am kind of lost on all of this and again, this is my first go round with Oracle SQL in Linux. Any help is greatly appreciated. Thanks, all.


问:
How to find occurence of objects in an array
I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

```<code>// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]
</code>```

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.

答:
Use findIndex:

let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}];
const index = array.findIndex(({ value }) => value == "a");
console.log(index);```

Body:
I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.


问:
Hyperlink a value in SQL Server query result in SSMS
I am trying to create something for our QA people, where a query that they would run will return a column with hyperlinked values.  I am using SQL Server 2008 R2 and SSMS.

How will I hyperlink results in SSMS so a linked value opens in a browser?

The idea is that the Qa person can simply click on the link and the appropriate ASP.Net app would open in a browser window.

The query is as below, which is right now showing an unlinked string under DocLink column.

```<code>SELECT
 DocNumber,
'https://www.xyz.com/mypage.aspx?docNumber=' + CAST(DocNumber AS varchar(20)) AS
     DocLink
FROM Docs
</code>```

答:
There is no way that I found to open URL directly from result pan but following is the way if you want to achieve open hyperlink from within SSMS.

Step 1.
Cast the result to XML. i.e.

```<code>SELECT CAST('http://www.google.com' AS XML) Google
</code>```

Step 2.
After executing the query, in the result window, click on the hyperlink. That will open another tab in SSMS.

Step 3.
In this new tab, right click on the link and select Open URL option. This will open the link into the default browser.

Try that.

Body:
I am trying to create something for our QA people, where a query that they would run will return a column with hyperlinked values.  I am using SQL Server 2008 R2 and SSMS.

How will I hyperlink results in SSMS so a linked value opens in a browser?

The idea is that the Qa person can simply click on the link and the appropriate ASP.Net app would open in a browser window.

The query is as below, which is right now showing an unlinked string under DocLink column.

SELECT
 DocNumber,
'https://www.xyz.com/mypage.aspx?docNumber=' + CAST(DocNumber AS varchar(20)) AS
     DocLink
FROM Docs

Body:
There is no way that I found to open URL directly from result pan but following is the way if you want to achieve open hyperlink from within SSMS.

Step 1.
Cast the result to XML. i.e.

SELECT CAST('http://www.google.com' AS XML) Google

Step 2.
After executing the query, in the result window, click on the hyperlink. That will open another tab in SSMS.

Step 3.
In this new tab, right click on the link and select Open URL option. This will open the link into the default browser.

Try that.


问:
Why does std::array not have an operator T*?
With C arrays, it's been the case that simply naming an array has the same effect as writing &foo[0] for something approaching 50 years.

When converting from C style arrays to std::array<> in a project I'm working on, the vast majority of "error"s that appeared were due to the above property of C arrays.

In all cases, the solution was trivial, just append .data().  However it occurred to me that a carefully crafted operator T* ought to directly solve this issue.

Is there any technical reason this operator could not be created?

答: data() is introduced to have similar interface across multiple STL containers. For example, std::string and std::vector also provide data() which gives address of actual data buffer. So std::array interface was designed to match that. Operator() that you suggest is quite different way, and doesn't seem to be absolutely appropriate. As above commenters also mentioned, the more appropriate is operator T*(), but still this is not how STL designers preferred to do - they introduced data(). Why? Maybe because it is just more readable.</p>


答:
Separate objects are never === to each other, so you'll have to use a different method. One option is to create a Set of the stringified objects, and return true once any duplicate string is found:

const hasDupes = (arr) => {
  const strings = new Set();
  for (const obj of arr) {
    const string = JSON.stringify(obj);
    if (strings.has(string)) {
      return true;
    }
    strings.add(string);
  }
  return false;
};
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]));
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]));```

Title: How to find occurence of objects in an array


答:
indexOf will return the instance of an object

```<code>{value: 'a'} !== {value: 'a'};
</code>```

as they are both different instances of objects.

You can find the object

```<code>const obj = array.find(item => item.value === 'a')
</code>```

Body:
indexOf will return the instance of an object

{value: 'a'} !== {value: 'a'};

as they are both different instances of objects.

You can find the object

const obj = array.find(item => item.value === 'a')


问:
Extracting metadata from Icecast stream using Exoplayer
Since switching from Mediaplayer to a simple implementation Exoplayer I have noticed much improved load times but I'm wondering if there is any built in functionality such as a metadata change listener when streaming audio?

I have implemented Exoplayer using a simple example as below:

```<code>    Uri uri = Uri.parse(url);
    DefaultSampleSource sampleSource =
            new DefaultSampleSource(new FrameworkSampleExtractor(context, uri, null), 2);
    TrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource);
    mExoPlayerInstance.prepare(audioRenderer);
    mExoPlayerInstance.setPlayWhenReady(true);
</code>```

答:
Icy metadata support is now in exoplayer version 2.10:</p>

```<code>ExoPlayerFactory.newSimpleInstance(this).apply {
    setAudioAttributes(
      AudioAttributes.Builder()
        .setContentType(C.CONTENT_TYPE_MUSIC)
        .setUsage(C.USAGE_MEDIA)
        .build(), true
    )
    addMetadataOutput(object : MetadataOutput {
      override fun onMetadata(metadata: Metadata) {
        for (n in 0 until metadata.length()) {
          when (val md = metadata[n]) {
            is com.google.android.exoplayer2.metadata.icy.IcyInfo -> {
              Log.d(TAG, "Title: ${md.title} URL: ${md.url}")
            }
            else -> {
              Log.d(TAG, "Some other sort of metadata: $md")
            }
          }
        }
      }
    })
  }
</code>```

Body:
Since switching from Mediaplayer to a simple implementation Exoplayer I have noticed much improved load times but I'm wondering if there is any built in functionality such as a metadata change listener when streaming audio?

I have implemented Exoplayer using a simple example as below:

    Uri uri = Uri.parse(url);
    DefaultSampleSource sampleSource =
            new DefaultSampleSource(new FrameworkSampleExtractor(context, uri, null), 2);
    TrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource);
    mExoPlayerInstance.prepare(audioRenderer);
    mExoPlayerInstance.setPlayWhenReady(true);

Body:
Icy metadata support is now in exoplayer version 2.10:

ExoPlayerFactory.newSimpleInstance(this).apply {
    setAudioAttributes(
      AudioAttributes.Builder()
        .setContentType(C.CONTENT_TYPE_MUSIC)
        .setUsage(C.USAGE_MEDIA)
        .build(), true
    )
    addMetadataOutput(object : MetadataOutput {
      override fun onMetadata(metadata: Metadata) {
        for (n in 0 until metadata.length()) {
          when (val md = metadata[n]) {
            is com.google.android.exoplayer2.metadata.icy.IcyInfo -> {
              Log.d(TAG, "Title: ${md.title} URL: ${md.url}")
            }
            else -> {
              Log.d(TAG, "Some other sort of metadata: $md")
            }
          }
        }
      }
    })
  }


问:
Memset In C Using Sizeof Operator :
Here is a struct :

```<code>typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;
</code>```

For memset, which one should be used from below ?

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

or

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));
</code>```

What are the differences ?

答:
Definitely

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

There are a few cases, if you have:

1) Static array, using sizeof in that context:

```<code>device_sys dev_sys[NUM_DEVICES] = { /* init data * };
...
sizeof(dev_sys);
</code>```

In this case, sizeof operator will give the entire size of the array, so you will essentially end up with:

```<code>NUM_DEVICES * (NUM_DEVICES * sizeof(device_sys))
</code>```

2) or you have a dynamically allocated piece of memory acccessed through a pointer, OR you are in the context of a function call where dev_sys is passed as a function argument. Either way:

sizeof(dev_sys) will give the size of a pointer (in the first, because it IS a pointer, in the second, due to pointer decay), whcih will most likely not be what you are after.

Title: Memset In C Using Sizeof Operator :

Body:
Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?

Body:
Definitely

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

There are a few cases, if you have:

1) Static array, using sizeof in that context:

device_sys dev_sys[NUM_DEVICES] = { /* init data * };
...
sizeof(dev_sys);

In this case, sizeof operator will give the entire size of the array, so you will essentially end up with:

NUM_DEVICES * (NUM_DEVICES * sizeof(device_sys))

2) or you have a dynamically allocated piece of memory acccessed through a pointer, OR you are in the context of a function call where dev_sys is passed as a function argument. Either way:

sizeof(dev_sys) will give the size of a pointer (in the first, because it IS a pointer, in the second, due to pointer decay), whcih will most likely not be what you are after.


问:
Airflow 1.9.0 is queuing but not launching tasks
Airflow is randomly not running queued tasks some tasks dont even get queued status. I keep seeing below in the scheduler logs

```<code> [2018-02-28 02:24:58,780] {jobs.py:1077} INFO - No tasks to consider for execution.
</code>```

I do see tasks in database that either have no status or queued status but they never get started.

The airflow setup is running https://github.com/puckel/docker-airflow on ECS with Redis. There are 4 scheduler threads and 4 Celery worker tasks. For the tasks that are not running are showing in queued state (grey icon) when hovering over the task icon operator is null and task details says:

```<code>    All dependencies are met but the task instance is not running. In most cases this just means that the task will probably be scheduled soon unless:- The scheduler is down or under heavy load
</code>```

Metrics on scheduler do not show heavy load. The dag is very simple with 2 independent tasks only dependent on last run. There are also tasks in the same dag that are stuck with no status (white icon).

Interesting thing to notice is when I restart the scheduler tasks change to running state.

答:
I am facing the issue today and found that bullet point 4 from tobi6 answer below worked out and resolved the issue

```<code>*'Do all the DAGs you want to run have a start date which is in the past?'*
</code>```

I am using airflow version v1.10.3

Body:
Airflow is randomly not running queued tasks some tasks dont even get queued status. I keep seeing below in the scheduler logs

 [2018-02-28 02:24:58,780] {jobs.py:1077} INFO - No tasks to consider for execution.

I do see tasks in database that either have no status or queued status but they never get started.

The airflow setup is running https://github.com/puckel/docker-airflow on ECS with Redis. There are 4 scheduler threads and 4 Celery worker tasks. For the tasks that are not running are showing in queued state (grey icon) when hovering over the task icon operator is null and task details says:

    All dependencies are met but the task instance is not running. In most cases this just means that the task will probably be scheduled soon unless:- The scheduler is down or under heavy load

Metrics on scheduler do not show heavy load. The dag is very simple with 2 independent tasks only dependent on last run. There are also tasks in the same dag that are stuck with no status (white icon).

Interesting thing to notice is when I restart the scheduler tasks change to running state.

Body:
I am facing the issue today and found that bullet point 4 from tobi6 answer below worked out and resolved the issue

*'Do all the DAGs you want to run have a start date which is in the past?'*

I am using airflow version v1.10.3


问:
Akka stream broadcast in java
I am trying to broadcast to 2 sink from a source in java, got stuck in between, any pointer will be helpful</p>

```<code> public static void main(String[] args) {

        ActorSystem system = ActorSystem.create("GraphBasics");
        ActorMaterializer materializer = ActorMaterializer.create(system);

        final Source<Integer, NotUsed> source = Source.range(1, 1000);
         Sink<Integer,CompletionStage<Done>> firstSink = Sink.foreach(x -> System.out.println("first sink "+x));
        Sink<Integer,CompletionStage<Done>> secondsink  = Sink.foreach(x -> System.out.println("second sink "+x));

                RunnableGraph.fromGraph(
                GraphDSL.create(
                        b -> {
                            UniformFanOutShape<Integer, Integer> bcast = b.add(Broadcast.create(2));

                            b.from(b.add(source)).viaFanOut(bcast).to(b.add(firstSink)).to(b.add(secondsink));

                            return ClosedShape.getInstance();
                        }))
                .run(materializer);
    }
</code>```

答:
i am not that much familiar with java api for akka-stream graphs, so i used the official doc. there are 2 errors in your snippet:

when you added source to the graph builder, you need to get Outlet from it. so instead of b.from(b.add(source)) there should smth like this: b.from(b.add(source).out()) according to the official doc

you can't just call two .to method in a row, because .to expects smth with Sink shape, which means kind of dead end. instead you need to attach 2nd sink to the bcast directly, like this:

```<code>(...).viaFanOut(bcast).to(b.add(firstSink));
b.from(bcast).to(b.add(secondSink));

</code>```

all in all the code should look like this:

```<code>ActorSystem system = ActorSystem.create("GraphBasics");
ActorMaterializer materializer = ActorMaterializer.create(system);

final Source<Integer, NotUsed> source = Source.range(1, 1000);
Sink<Integer, CompletionStage<Done>> firstSink = foreach(x -> System.out.println("first sink " + x));
Sink<Integer, CompletionStage<Done>> secondSink = foreach(x -> System.out.println("second sink " + x));

RunnableGraph.fromGraph(
        GraphDSL.create(b -> {
                    UniformFanOutShape<Integer, Integer> bcast = b.add(Broadcast.create(2));

                    b.from(b.add(source).out()).viaFanOut(bcast).to(b.add(firstSink));
                    b.from(bcast).to(b.add(secondSink));

                    return ClosedShape.getInstance();
                }
        )
).run(materializer);

</code>```

Final note - i would think twice whether it makes sense to use graph api. If you case as simple as this one (just 2 sinks), you might want just to use alsoTo or alsoToMat. They give you the possibility to attach multiple sinks to the flow without the need to use graphs.

Title: Akka stream broadcast in java

Body:
I am trying to broadcast to 2 sink from a source in java, got stuck in between, any pointer will be helpful

 public static void main(String[] args) {

        ActorSystem system = ActorSystem.create("GraphBasics");
        ActorMaterializer materializer = ActorMaterializer.create(system);

        final Source<Integer, NotUsed> source = Source.range(1, 1000);
         Sink<Integer,CompletionStage<Done>> firstSink = Sink.foreach(x -> System.out.println("first sink "+x));
        Sink<Integer,CompletionStage<Done>> secondsink  = Sink.foreach(x -> System.out.println("second sink "+x));

                RunnableGraph.fromGraph(
                GraphDSL.create(
                        b -> {
                            UniformFanOutShape<Integer, Integer> bcast = b.add(Broadcast.create(2));

                            b.from(b.add(source)).viaFanOut(bcast).to(b.add(firstSink)).to(b.add(secondsink));

                            return ClosedShape.getInstance();
                        }))
                .run(materializer);
    }

Body:
i am not that much familiar with java api for akka-stream graphs, so i used the official doc. there are 2 errors in your snippet:

when you added source to the graph builder, you need to get Outlet from it. so instead of b.from(b.add(source)) there should smth like this: b.from(b.add(source).out()) according to the official doc

you can't just call two .to method in a row, because .to expects smth with Sink shape, which means kind of dead end. instead you need to attach 2nd sink to the bcast directly, like this:

(...).viaFanOut(bcast).to(b.add(firstSink));
b.from(bcast).to(b.add(secondSink));

all in all the code should look like this:

ActorSystem system = ActorSystem.create("GraphBasics");
ActorMaterializer materializer = ActorMaterializer.create(system);

final Source<Integer, NotUsed> source = Source.range(1, 1000);
Sink<Integer, CompletionStage<Done>> firstSink = foreach(x -> System.out.println("first sink " + x));
Sink<Integer, CompletionStage<Done>> secondSink = foreach(x -> System.out.println("second sink " + x));

RunnableGraph.fromGraph(
        GraphDSL.create(b -> {
                    UniformFanOutShape<Integer, Integer> bcast = b.add(Broadcast.create(2));

                    b.from(b.add(source).out()).viaFanOut(bcast).to(b.add(firstSink));
                    b.from(bcast).to(b.add(secondSink));

                    return ClosedShape.getInstance();
                }
        )
).run(materializer);

Final note - i would think twice whether it makes sense to use graph api. If you case as simple as this one (just 2 sinks), you might want just to use alsoTo or alsoToMat. They give you the possibility to attach multiple sinks to the flow without the need to use graphs.


问:
Big O: Is this FOR loop O(n log(n)) or O(log(n)^2)?
I have a generic function

```<code>for i from 1 to n; i = 2i; {
    for j from 1 to i; {
        (constant time stuff)
    }
}
</code>```

For this function, the first line for i from 1 to n; i = 2i; I know is O(log(n)). The line (constant time stuff) is irrelevant so who cares since it's O(1).

But the middle line for j from 1 to i; is where I'm having trouble.

I'm assuming that the Big O of this line is the same as the first, since it's following the same pattern as the first where the i is doubled after each iteration, which would make it O(log(n)), but could it also be O(n)?

Also, if it is in fact O(log(n)) * O(log(n)), that's just O(log(n)^2) correct?

Sorry, I just started this Big O stuff and unfortunately I've had to rely on the internet so far since my teacher isn't very good :(

答:
Is this FOR loop O(n log(n)) or O(log(n)^2)?

Neither.

The outer loop iterates log n times. If the inner loop had the same number of iterations each time, we could then just multiply the number of iterations of the outer loop by the number of operations of the inner loop. But it doesn't, so we can't.

Instead we actually need to sum up the number of iterations of the inner loop: The first time, it iterates one time. The second time, two times. Then four, then eight and so on until it finally reaches n. So we have the sum 1 + 2 + 4 + ... + n where we know that the sum has log n summands, in other words the sum from k=0 to n of 2^k. This sum happens to be equal to 2n-1. 2n-1 is clearly in O(n), so that's your answer.

Body:
I have a generic function

for i from 1 to n; i = 2i; {
    for j from 1 to i; {
        (constant time stuff)
    }
}

For this function, the first line for i from 1 to n; i = 2i; I know is O(log(n)). The line (constant time stuff) is irrelevant so who cares since it's O(1).

But the middle line for j from 1 to i; is where I'm having trouble.

I'm assuming that the Big O of this line is the same as the first, since it's following the same pattern as the first where the i is doubled after each iteration, which would make it O(log(n)), but could it also be O(n)?

Also, if it is in fact O(log(n)) * O(log(n)), that's just O(log(n)^2) correct?

Sorry, I just started this Big O stuff and unfortunately I've had to rely on the internet so far since my teacher isn't very good :(


问:
Waterfall dialog prompts not working in bot framework
I am still trying to grasp the concepts of bot framework v4 and dialogs. I am trying to create a simple bot which integrates with QnAMaker and LUIS. Both integrations work separately but I am not able to integrate them both. I am using ASP.NET Core for the first time as well. So my problem might be with that too.

So I have created a bot based on this sample.

I have a base dialog which inherits Dialog class. The base class exposes an abstract function which the child dialog class inherits. The child class is called RootDialog.

FunctionDialogBase:

```<code>    public FunctionDialogBase(string dialogId, IConfiguration configuration, ILogger logger) : base(dialogId)
    {
        Configuration = configuration;
        Logger = logger;
    }
    public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dialogContext, object options = null, CancellationToken cancellationToken = default(CancellationToken))
    {
        return await RunStateMachineAsync(dialogContext, cancellationToken).ConfigureAwait(false);
    }
    public override async Task<DialogTurnResult> ContinueDialogAsync(DialogContext dialogContext, CancellationToken cancellationToken = default(CancellationToken))
    {
        return await RunStateMachineAsync(dialogContext, cancellationToken).ConfigureAwait(false);
    }

    //abstract method
    protected abstract Task<(object newState, IEnumerable<Activity> output, object result)> ProcessAsync(object oldState,
        Activity activity,
        DialogContext dialogContext,
        SPEntityDetails spEntityDetails,
        CancellationToken cancellationToken);

    private async Task<DialogTurnResult> RunStateMachineAsync(DialogContext dialogContext, CancellationToken cancellationToken)
        {
            var (newState, output, result) = await ProcessAsync(oldState, dialogContext.Context.Activity, dialogContext, spEntityDetails, cancellationToken).ConfigureAwait(false);
            //do some more logic here
        }
    }
</code>```

The RootDialog calls another dialog called CreateSiteDialog from its abstract method implementation like this:

RootDialog:

```<code>    protected override async Task<(object newState, IEnumerable<Activity> output, object result)> ProcessAsync(
    object oldState,
    Activity activity,
    DialogContext dialogContext,
    SPEntityDetails spEntityDetails,
    CancellationToken cancellationToken)
    {
        dialogContext.Dialogs.Add(new CreateSiteDialog());
        await dialogContext.BeginDialogAsync(nameof(CreateSiteDialog),spEntityDetails, cancellationToken);
        return (null, new Activity[] { activity.CreateReply("Site created successfully.") }, null);
    }
</code>```

And finally the CreateSiteDialog which has the issue. This dialog follows a waterfall model and should in theory move from one waterfall step to the next until the end. This is not happening. When I use the prompt in the first step, it executes and comes out of the waterfall dialog. The next waterfall step is never executed.

CreateSiteDialog:

```<code>public class CreateSiteDialog : CancelAndHelpDialog
{
    public CreateSiteDialog() : base(nameof(CreateSiteDialog))
    {
        AddDialog(new TextPrompt(nameof(TextPrompt)));
        AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            ConfirmStepAsync,
            FinalStepAsync
        }));

        // The initial child Dialog to run.
        InitialDialogId = nameof(WaterfallDialog);
    }

    private async Task<DialogTurnResult> ConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        var spEntityDetails = (SPEntityDetails)stepContext.Options;
        var msg = @"Creating site: http://yoursiteurl/"  + spEntityDetails.SiteName + ". Confirm Yes/No.";
        return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text(msg) }, cancellationToken);
    }
    private async Task<DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        //handle propmt result from user action
    }
}
</code>```

There's no error as well. So I am assuming I am doing something wrong in the usage of the dialogs. Please. Any help will be appreciated.

I am using Visual Studio 2017, Bot Framework Emulator, Bot framework V4 with a Core Bot project.

答:
For the life of me, I can't get Waterfall Dialogs working with that sample as a base (without basically rewriting the whole thing). I recommend you base your bot off of a combination of 11.qnamaker and 13.core-bot (which uses LUIS and is a good example for ComponentDialogs). I make this recommendation for two reasons:

The sample you linked is "experimental" meaning not only is it not ready for production, but it may never be.

The sample you linked uses a State Machine design, which isn't--and hasn't been--used by any other bot samples, so it will be very difficult to get good support.

For getting QnAMaker and LUIS working together, the flow is really going to be based off of your use case. I can't tell from your included code what you're going for. So, this answer is mainly for getting Waterfall Dialogs to work.

Body:
I am still trying to grasp the concepts of bot framework v4 and dialogs. I am trying to create a simple bot which integrates with QnAMaker and LUIS. Both integrations work separately but I am not able to integrate them both. I am using ASP.NET Core for the first time as well. So my problem might be with that too.

So I have created a bot based on this sample.

I have a base dialog which inherits Dialog class. The base class exposes an abstract function which the child dialog class inherits. The child class is called RootDialog.

FunctionDialogBase:

    public FunctionDialogBase(string dialogId, IConfiguration configuration, ILogger logger) : base(dialogId)
    {
        Configuration = configuration;
        Logger = logger;
    }
    public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dialogContext, object options = null, CancellationToken cancellationToken = default(CancellationToken))
    {
        return await RunStateMachineAsync(dialogContext, cancellationToken).ConfigureAwait(false);
    }
    public override async Task<DialogTurnResult> ContinueDialogAsync(DialogContext dialogContext, CancellationToken cancellationToken = default(CancellationToken))
    {
        return await RunStateMachineAsync(dialogContext, cancellationToken).ConfigureAwait(false);
    }

    //abstract method
    protected abstract Task<(object newState, IEnumerable<Activity> output, object result)> ProcessAsync(object oldState,
        Activity activity,
        DialogContext dialogContext,
        SPEntityDetails spEntityDetails,
        CancellationToken cancellationToken);

    private async Task<DialogTurnResult> RunStateMachineAsync(DialogContext dialogContext, CancellationToken cancellationToken)
        {
            var (newState, output, result) = await ProcessAsync(oldState, dialogContext.Context.Activity, dialogContext, spEntityDetails, cancellationToken).ConfigureAwait(false);
            //do some more logic here
        }
    }

The RootDialog calls another dialog called CreateSiteDialog from its abstract method implementation like this:

RootDialog:

    protected override async Task<(object newState, IEnumerable<Activity> output, object result)> ProcessAsync(
    object oldState,
    Activity activity,
    DialogContext dialogContext,
    SPEntityDetails spEntityDetails,
    CancellationToken cancellationToken)
    {
        dialogContext.Dialogs.Add(new CreateSiteDialog());
        await dialogContext.BeginDialogAsync(nameof(CreateSiteDialog),spEntityDetails, cancellationToken);
        return (null, new Activity[] { activity.CreateReply("Site created successfully.") }, null);
    }

And finally the CreateSiteDialog which has the issue. This dialog follows a waterfall model and should in theory move from one waterfall step to the next until the end. This is not happening. When I use the prompt in the first step, it executes and comes out of the waterfall dialog. The next waterfall step is never executed.

CreateSiteDialog:

public class CreateSiteDialog : CancelAndHelpDialog
{
    public CreateSiteDialog() : base(nameof(CreateSiteDialog))
    {
        AddDialog(new TextPrompt(nameof(TextPrompt)));
        AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            ConfirmStepAsync,
            FinalStepAsync
        }));

        // The initial child Dialog to run.
        InitialDialogId = nameof(WaterfallDialog);
    }

    private async Task<DialogTurnResult> ConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        var spEntityDetails = (SPEntityDetails)stepContext.Options;
        var msg = @"Creating site: http://yoursiteurl/"  + spEntityDetails.SiteName + ". Confirm Yes/No.";
        return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text(msg) }, cancellationToken);
    }
    private async Task<DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        //handle propmt result from user action
    }
}

There's no error as well. So I am assuming I am doing something wrong in the usage of the dialogs. Please. Any help will be appreciated.

I am using Visual Studio 2017, Bot Framework Emulator, Bot framework V4 with a Core Bot project.


问:
Failed WordPress Update - This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php
I am trying to update WordPress to the version 5.2.1, but always I am getting the following error:

```<code>Downloading update from https://downloads.wordpress.org/release/wordpress-5.2.1-no-content.zip…

Unpacking the update…

The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php

Installation Failed
</code>```

I saw many other solutions like below, but I am afraid to use them as I am not sure how this will affect the security and the functionality of the plugins.

Reset the permissions of all files to 664:

```<code>find /path/to/site/ -type f -exec chmod 664 {} \;
</code>```

Reset permissions of directories to 775:

```<code>find /path/to/site/ -type d -exec chmod 775 {} \;
</code>```

Reset the group to the wordpress group (or whatever group makes sense for you)

```<code>chgrp -R wordpress /path/to/site/
</code>```

Does any other way for detecting which exact file or folder has the problem so as to avoid making mass changes on the files' and folders' permissions?

答:
Before proceeding I recommend to make a full backup of your files and database just in case, then you should be able to run those commands, they should not affect the security of WordPress as they are documented on Hardening WordPress

Be aware that sometimes file permissions are affected also depending on the group, so in that case find the group WordPress should belong and run:

# replace "www-data" with the group that WordPress has access to.

chown -R www-data:www-data

# Example:

chown -R www-data:www-data /path/to/site/
```

What I do to find sometimes what group is allowed to write onto WordPress is basically just to upload an Image at the media library, if WordPress allows the upload without issues then whatever group the wp-content/uploads/ folder has, should be the correct one, or you can also refresh the permalinks and look up the same group information on the .htaccess to get the correct group information.

Good luck.

Body:
I am trying to update WordPress to the version 5.2.1, but always I am getting the following error:

Downloading update from https://downloads.wordpress.org/release/wordpress-5.2.1-no-content.zip…

Unpacking the update…

The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php

Installation Failed

I saw many other solutions like below, but I am afraid to use them as I am not sure how this will affect the security and the functionality of the plugins.

Reset the permissions of all files to 664:

find /path/to/site/ -type f -exec chmod 664 {} \;

Reset permissions of directories to 775:

find /path/to/site/ -type d -exec chmod 775 {} \;

Reset the group to the wordpress group (or whatever group makes sense for you)

chgrp -R wordpress /path/to/site/

Does any other way for detecting which exact file or folder has the problem so as to avoid making mass changes on the files' and folders' permissions?

Body:
Before proceeding I recommend to make a full backup of your files and database just in case, then you should be able to run those commands, they should not affect the security of WordPress as they are documented on Hardening WordPress

Be aware that sometimes file permissions are affected also depending on the group, so in that case find the group WordPress should belong and run:

# replace "www-data" with the group that WordPress has access to.

chown -R www-data:www-data

# Example:

chown -R www-data:www-data /path/to/site/

What I do to find sometimes what group is allowed to write onto WordPress is basically just to upload an Image at the media library, if WordPress allows the upload without issues then whatever group the wp-content/uploads/ folder has, should be the correct one, or you can also refresh the permalinks and look up the same group information on the .htaccess to get the correct group information.

Good luck.


问:
Using map function instead of for loop
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

```<code>def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)
</code>```

答: function wordcount doesn't return anything, write return numwords  Now your function calcualates numwords and then return None by default, and you erase this global variable

Title: Using map function instead of for loop

Body:
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)


问:
Passing const char* as template argument
Why can't you pass literal strings in here? I made it work with a very slight workaround.</p>

```<code>template<const char* ptr> struct lols {
    lols() : i(ptr) {}
    std::string i;
};
class file {
public:
    static const char arg[];
};
decltype(file::arg) file::arg = __FILE__;
// Getting the right type declaration for this was irritating, so I C++0xed it.

int main() {
    // lols<__FILE__> hi;
    // Error: A template argument may not reference a non-external entity
    lols<file::arg> hi; // Perfectly legal
    std::cout << hi.i;
    std::cin.ignore();
    std::cin.get();
}
</code>```

答:
Good question, thought I'd throw my hat into the ring...  I guess you can pass pointers to static variables as non-type template arguments.  From C++20 it looks like it won't be an issue...  Until then, here is some cheap macro to make it work.

```<code>template <const char *Name, typename T>
struct TaggedValue {
  static constexpr char const *name{Name};
  T value;
  friend ostream &operator<<(ostream &o, const TaggedValue &a) {
    return o << a.name << " = " << a.value;
  }
};

#define ST(name, type)\
  const char ST_name_##name[]{#name};\
  using name = TaggedValue<ST_name_##name,type>;

ST(Foo, int);
ST(Bar, int);
ST(Bax, string);

int main() {
  cout << Foo{3} << endl;
  cout << Bar{5} << endl;
  cout << Bax{"somthing"} << endl;
}
</code>```

C++20 comment (EDIT)

I've not used c++ much lately, so I'm sorry if this isn't 100% correct.  There's a comment about why this wouldn't be an issue in c++20.  According to the reference on template_parameters:

A non-type template parameter must have a structural type, which is one of the following types (optionally cv-qualified, the qualifiers are ignored):

...

a floating-point type;

a literal class type with the following properties:

all base classes and non-static data members are public and non-mutable and

the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof.

This had led me to believe that the following code would work:

```<code>struct conststr
{
    const char * const p;
    template<std::size_t N>
    constexpr conststr(const char(&a)[N]) : p(a)/*, sz(N - 1) */{}
};

template<conststr s>
struct A{};

int main(int argc, char **argv) {
    A<conststr("foo")> x;
}
</code>```

(Again, I'm not 100% sure if that's 100% correct).  But it doesn't, at least not on my machine with g++ -std=c++2a (g++ --version == g++ (Debian 8.3.0-6) 8.3.0).  It doesn't work with double either.  This guy gives a much more detailed account of the history here, and there are probably better references, and I could just be completely incorrect.

ContentLicense: CC BY-SA 2.5

Body:
Why can't you pass literal strings in here? I made it work with a very slight workaround.

template<const char* ptr> struct lols {
    lols() : i(ptr) {}
    std::string i;
};
class file {
public:
    static const char arg[];
};
decltype(file::arg) file::arg = __FILE__;
// Getting the right type declaration for this was irritating, so I C++0xed it.

int main() {
    // lols<__FILE__> hi;
    // Error: A template argument may not reference a non-external entity
    lols<file::arg> hi; // Perfectly legal
    std::cout << hi.i;
    std::cin.ignore();
    std::cin.get();
}

Body:
Good question, thought I'd throw my hat into the ring...  I guess you can pass pointers to static variables as non-type template arguments.  From C++20 it looks like it won't be an issue...  Until then, here is some cheap macro to make it work.

template <const char *Name, typename T>
struct TaggedValue {
  static constexpr char const *name{Name};
  T value;
  friend ostream &operator<<(ostream &o, const TaggedValue &a) {
    return o << a.name << " = " << a.value;
  }
};

#define ST(name, type)\
  const char ST_name_##name[]{#name};\
  using name = TaggedValue<ST_name_##name,type>;

ST(Foo, int);
ST(Bar, int);
ST(Bax, string);

int main() {
  cout << Foo{3} << endl;
  cout << Bar{5} << endl;
  cout << Bax{"somthing"} << endl;
}

C++20 comment (EDIT)

I've not used c++ much lately, so I'm sorry if this isn't 100% correct.  There's a comment about why this wouldn't be an issue in c++20.  According to the reference on template_parameters:

A non-type template parameter must have a structural type, which is one of the following types (optionally cv-qualified, the qualifiers are ignored):

...

a floating-point type;

a literal class type with the following properties:

all base classes and non-static data members are public and non-mutable and

the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof.

This had led me to believe that the following code would work:

struct conststr
{
    const char * const p;
    template<std::size_t N>
    constexpr conststr(const char(&a)[N]) : p(a)/*, sz(N - 1) */{}
};

template<conststr s>
struct A{};

int main(int argc, char **argv) {
    A<conststr("foo")> x;
}

(Again, I'm not 100% sure if that's 100% correct).  But it doesn't, at least not on my machine with g++ -std=c++2a (g++ --version == g++ (Debian 8.3.0-6) 8.3.0).  It doesn't work with double either.  This guy gives a much more detailed account of the history here, and there are probably better references, and I could just be completely incorrect.


问:
How to check for undefined when using find on an javascript array
In my array I am using .find to find an object and set its property to some value.
  I want to set the name only if there is a value. i.e; check for undefined
  Below is my array, am using .find to find the object and set its name.
  I want to set only if the object with id === checkid is found.</p>

```<code> this.myarray.find(colDef => colDef.id === checkid).name = newname;.
</code>```

答:
You need to run find as it's own statement and check if the result is defined. If so, assign the name, otherwise don't:

let myarray = [
    {id: 100},
    {id: 10},
    {id: 5}
]

let found = myarray.find(colDef => colDef.id === 10)

if (found !== undefined){
    found.name = "some name"
}
console.log(found)

// no id 11 found will be undefined
found = myarray.find(colDef => colDef.id === 11)
console.log(found)```
</div>
</div>
</p>

<p>As a single line:</p>

``` this.myarray.find(colDef => colDef.id === checkid).name = newname;
```

there's no chance to check if find() returned undefined and trying to assign a property to undefined will be an error.

Body:
In my array I am using .find to find an object and set its property to some value.
  I want to set the name only if there is a value. i.e; check for undefined
  Below is my array, am using .find to find the object and set its name.
  I want to set only if the object with id === checkid is found.

 this.myarray.find(colDef => colDef.id === checkid).name = newname;.

Body:
You need to run find as it's own statement and check if the result is defined. If so, assign the name, otherwise don't:

let myarray = [
    {id: 100},
    {id: 10},
    {id: 5}
]

let found = myarray.find(colDef => colDef.id === 10)

if (found !== undefined){
    found.name = "some name"
}
console.log(found)

// no id 11 found will be undefined
found = myarray.find(colDef => colDef.id === 11)
console.log(found)

As a single line:

 this.myarray.find(colDef => colDef.id === checkid).name = newname;

there's no chance to check if find() returned undefined and trying to assign a property to undefined will be an error.


问:
Chain of promises in javascript with ajax calls
I have a function (f1) which I want to get called only after two ajax calls (say a1 and a2) are done. a2 should be called only after a1 is done. Following is the sequence of operation =

```<code>$.when(a1 and a2) {
   f1
}
</code>```

I tried the following code snippet -

```<code>$.when(a1a2()).done(function(){
  f1();
}

var a1a2 = function(){
  return $.when(a1()).done(function() {
    if (<check for a few variables a1 sets>) {
      // another ajax call for which f1 should wait
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
}
</code>```

In the above code, f1 is waiting for a1 to finish but it is not waiting for a2 to finish.

I tried the following code snippet as well (but this also just waits for a1 to finish) -

```<code>var a1a2 = function(){
  var retVal = new Promise(function(){
    a1().then(function(){
      if (<check for a few variables a1 sets>) {
        return a2();
      } else {
        // random function for which f1 shouldn't wait
        f2();
      }
    });
  });
}
</code>```

I have looked at other similar questions but an not able to devise a solution. Can someone please help?

答:
Call a1 to get its Promise, then call Promise.all on a1 and a1 chained with a2:

```<code>const a1Prom = a1();
Promise.all([
  a1Prom,
  a1Prom.then(a2)
])
  .then(f1);
</code>```

console.log('script start');

const delay = ms => new Promise(res => setTimeout(res, ms));
const a1 = () => delay(1000).then(() => console.log('a1 done'));
const a2 = () => {
  console.log('a2 starting');
  return delay(1000).then(() => console.log('a2 done'));
};

const f1 = () => console.log('f1 starting');

const a1Prom = a1();
Promise.all([
  a1Prom,
  a1Prom.then(a2)
])
  .then(f1);```

Body:
I have a function (f1) which I want to get called only after two ajax calls (say a1 and a2) are done. a2 should be called only after a1 is done. Following is the sequence of operation =

$.when(a1 and a2) {
   f1
}

I tried the following code snippet -

$.when(a1a2()).done(function(){
  f1();
}

var a1a2 = function(){
  return $.when(a1()).done(function() {
    if (<check for a few variables a1 sets>) {
      // another ajax call for which f1 should wait
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
}

In the above code, f1 is waiting for a1 to finish but it is not waiting for a2 to finish.

I tried the following code snippet as well (but this also just waits for a1 to finish) -

var a1a2 = function(){
  var retVal = new Promise(function(){
    a1().then(function(){
      if (<check for a few variables a1 sets>) {
        return a2();
      } else {
        // random function for which f1 shouldn't wait
        f2();
      }
    });
  });
}

I have looked at other similar questions but an not able to devise a solution. Can someone please help?

Body:
Call a1 to get its Promise, then call Promise.all on a1 and a1 chained with a2:

const a1Prom = a1();
Promise.all([
  a1Prom,
  a1Prom.then(a2)
])
  .then(f1);

console.log('script start');

const delay = ms => new Promise(res => setTimeout(res, ms));
const a1 = () => delay(1000).then(() => console.log('a1 done'));
const a2 = () => {
  console.log('a2 starting');
  return delay(1000).then(() => console.log('a2 done'));
};

const f1 = () => console.log('f1 starting');

const a1Prom = a1();
Promise.all([
  a1Prom,
  a1Prom.then(a2)
])
  .then(f1);


答:
I'm not familiar with the when/done syntax, but this is a correction for your second snippet. A big hint I would give is that using new Promise is 90% of the time a bad idea.

```<code>var a1a2 = function(){
  var retVal = a1().then(function(){
    if (<check for a few variables a1 sets>) {
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
});
</code>```

Title: Chain of promises in javascript with ajax calls

Body:
I'm not familiar with the when/done syntax, but this is a correction for your second snippet. A big hint I would give is that using new Promise is 90% of the time a bad idea.

var a1a2 = function(){
  var retVal = a1().then(function(){
    if (<check for a few variables a1 sets>) {
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
});


问:
How to implement onclick in ResultCard and swap the div with another component
I want to display the details of what's user clicks in the ResultCard.

I want to replace the divs contents (currently displayed results) with rendered html based on the result found in my elastic search cluster(res) when user click the url in the resultcard.

I tried adding onclick properties but nothing happens. Reactivesearch documentation don't list this attribute.

Of course, I could pass argument in the url properties of ResultCard and redirect user to another page but page would be reloaded completely (with the menus defined in index.js and the footer)

I think creating parent component with state mirroring the currently displayed children component in the div is the way to go.

But, how to run a javascript for setting the state when user click in the resultcard?

```<code>
import React, { Component } from 'react';
import { ReactiveBase, CategorySearch, SingleRange, ResultCard } from '@appbaseio/reactivesearch';

class App extends Component {
  render() {
    return (
        <ReactiveBase
        app="artists"
        url="https://admin:xxxxxxx@node1.searchevolution.com:9200"
        type="_doc">
          <div style={{ display: "flex", "flexDirection": "row" }}>
            <div style={{ display: "flex", "flexDirection": "column", "width": "40%" }}>
              <CategorySearch
                componentId="searchbox"
                dataField="nom"
                categoryField="occupations.keyword"
                type="artists"
                placeholder="Search for Artists, Painter, Sculptor, Photographs"
                style={{
                  padding: "5px",
                  "marginTop": "10px"
                }}
              />

            </div>
            <ResultCard
              componentId="result"
              dataField="nom"
              title="Results"
              from={0}
              size={6}
              pagination={true}
              onclick="alert('Message à afficher');"
              react={{
                and: ["searchbox"]
              }}
              onData={(res) => {
                return {
                  image: "data:image/png;base64,iVBORw0KGgoA",
                  title: res.occupations,
                  description: res.nom,
                  url: "/details/" + res
                }
              }}
              style={{
                "width": "60%",
                "textAlign": "center"
              }}
            />
          </div>
        </ReactiveBase>
    );
  }
}

export default App;

</code>```

Expected result is to change the div content with the rendered html from another component (not still coded).

答:
The handler should be called onClick instead of onclick (Even though it looks like HTML, this is JSX, so handlers need to be camelCase).

Also, your code will not call alert unless you put it in curly braces (which tells JSX to execute code). One more thing: you want to wrap it in a function, otherwise the alert will be called when the component mounts, and not on a click.

```<code>onClick={() => alert('Message à afficher')}
</code>```

EDIT: I think I misunderstood your question. If I'm understanding correctly, you're right and you want to handle the click in the App component. Something like this:

```<code>class App extends Component {
  state = {
    showResultCard = true,
  }

  handleClick = () => {
    this.setState({ showResultCard: false });
  }

  render() {
    <ReactiveBase>
      ...
      {this.state.showResultCard ? (
        <ResultCard onClick={this.handleClick} ... />
      ) : (
        <OtherComponent ... />
      )}
    </ReactiveBase>
  }
}
</code>```

Body:
I want to display the details of what's user clicks in the ResultCard.

I want to replace the divs contents (currently displayed results) with rendered html based on the result found in my elastic search cluster(res) when user click the url in the resultcard.

I tried adding onclick properties but nothing happens. Reactivesearch documentation don't list this attribute.

Of course, I could pass argument in the url properties of ResultCard and redirect user to another page but page would be reloaded completely (with the menus defined in index.js and the footer)

I think creating parent component with state mirroring the currently displayed children component in the div is the way to go.

But, how to run a javascript for setting the state when user click in the resultcard?

import React, { Component } from 'react';
import { ReactiveBase, CategorySearch, SingleRange, ResultCard } from '@appbaseio/reactivesearch';

class App extends Component {
  render() {
    return (
        <ReactiveBase
        app="artists"
        url="https://admin:xxxxxxx@node1.searchevolution.com:9200"
        type="_doc">

              <CategorySearch
                componentId="searchbox"
                dataField="nom"
                categoryField="occupations.keyword"
                type="artists"
                placeholder="Search for Artists, Painter, Sculptor, Photographs"
                style={{
                  padding: "5px",
                  "marginTop": "10px"
                }}
              />

            <ResultCard
              componentId="result"
              dataField="nom"
              title="Results"
              from={0}
              size={6}
              pagination={true}
              onclick="alert('Message à afficher');"
              react={{
                and: ["searchbox"]
              }}
              onData={(res) => {
                return {
                  image: "data:image/png;base64,iVBORw0KGgoA",
                  title: res.occupations,
                  description: res.nom,
                  url: "/details/" + res
                }
              }}
              style={{
                "width": "60%",
                "textAlign": "center"
              }}
            />

        </ReactiveBase>
    );
  }
}

export default App;

Expected result is to change the div content with the rendered html from another component (not still coded).

Body:
The handler should be called onClick instead of onclick (Even though it looks like HTML, this is JSX, so handlers need to be camelCase).

Also, your code will not call alert unless you put it in curly braces (which tells JSX to execute code). One more thing: you want to wrap it in a function, otherwise the alert will be called when the component mounts, and not on a click.

onClick={() => alert('Message à afficher')}

EDIT: I think I misunderstood your question. If I'm understanding correctly, you're right and you want to handle the click in the App component. Something like this:

class App extends Component {
  state = {
    showResultCard = true,
  }

  handleClick = () => {
    this.setState({ showResultCard: false });
  }

  render() {
    <ReactiveBase>
      ...
      {this.state.showResultCard ? (
        <ResultCard onClick={this.handleClick} ... />
      ) : (
        <OtherComponent ... />
      )}
    </ReactiveBase>
  }
}


问:
std::vector with nested template argument
i quite new to C++. A'm using std::map with GCC. Since (in my opinion) std::map output with GDB is hard to read. I'd like to export my map to a vector.

Now i already figured out (with some helpful posts from this forum) :) how to export map to a vector. Now i'f i uderstood the c++ reference correctly std::map is not thread safe. So i build a Mutex arround std::map

```<code>template<typename Mutex_Type_T, typename Key_Type_T, typename Mapped_Type_T>
class CConcurrent_Dictionary
{

public:

    CConcurrent_Dictionary();

    class CSingle_Element
    {
    public:

        Key_Type_T key = { };

        Mapped_Type_T mapped_type = { };

    };

    /**
     * Exports all contect of std::map to a vector
     * @param mutex_timeout Mutex timeout
     * @return Vector with all contents of std::map
     */
    std::vector<CSingle_Element> Export(const uint32_t mutex_timeout) const;

private:
    const Mutex_Type_T mutex;

    map<Key_Type_T, Mapped_Type_T> dictionary;
};
</code>```

The implementation of Export() looks like this

```<code>
template<typename Mutex_Type_T, typename Key_Type_T, typename Mapped_Type_T>
std::vector<CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::CSingle_Element> CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::Export(const uint32_t mutex_timeout) const
{
    std::vector<CSingle_Element> res = {};
    CLock_Guard_New<Mutex_Type_T> lock(mutex);
    if(false == lock.Lock(mutex_timeout))
    {
        return res;
    }

    //export all Elements
    for(const auto& single_element : dictionary)
    {
        CSingle_Element single = {};
        single.key = single_element.first;
        single.mapped_type = single_element.second;
        res.push_back(single);
    }

    return res;
}

</code>```

However the problem fails to compile

```<code>note:   expected a type, got 'NDictionary::CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::CSingle_Element'
 error: template argument 2 is invalid
 error: prototype for 'int NDictionary::CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::Export(uint32_t) const' does not match any in class 'NDictionary::CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>'
</code>```

It looks like the vector template argument are not taken correctly.

For my understanding I'd expect

CConcurrent_Dictionary::CSingle_Element
to be the only template argument to std::vector. So could you help me out? What am i missing?

答: Try following: std::vector<typename CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::CSingle_Element>

Body:
i quite new to C++. A'm using std::map with GCC. Since (in my opinion) std::map output with GDB is hard to read. I'd like to export my map to a vector.

Now i already figured out (with some helpful posts from this forum) :) how to export map to a vector. Now i'f i uderstood the c++ reference correctly std::map is not thread safe. So i build a Mutex arround std::map

template<typename Mutex_Type_T, typename Key_Type_T, typename Mapped_Type_T>
class CConcurrent_Dictionary
{

public:

    CConcurrent_Dictionary();

    class CSingle_Element
    {
    public:

        Key_Type_T key = { };

        Mapped_Type_T mapped_type = { };

    };

    /**
     * Exports all contect of std::map to a vector
     * @param mutex_timeout Mutex timeout
     * @return Vector with all contents of std::map
     */
    std::vector<CSingle_Element> Export(const uint32_t mutex_timeout) const;

private:
    const Mutex_Type_T mutex;

    map<Key_Type_T, Mapped_Type_T> dictionary;
};

The implementation of Export() looks like this

template<typename Mutex_Type_T, typename Key_Type_T, typename Mapped_Type_T>
std::vector<CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::CSingle_Element> CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::Export(const uint32_t mutex_timeout) const
{
    std::vector<CSingle_Element> res = {};
    CLock_Guard_New<Mutex_Type_T> lock(mutex);
    if(false == lock.Lock(mutex_timeout))
    {
        return res;
    }

    //export all Elements
    for(const auto& single_element : dictionary)
    {
        CSingle_Element single = {};
        single.key = single_element.first;
        single.mapped_type = single_element.second;
        res.push_back(single);
    }

    return res;
}

However the problem fails to compile

note:   expected a type, got 'NDictionary::CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::CSingle_Element'
 error: template argument 2 is invalid
 error: prototype for 'int NDictionary::CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>::Export(uint32_t) const' does not match any in class 'NDictionary::CConcurrent_Dictionary<Mutex_Type_T, Key_Type_T, Mapped_Type_T>'

It looks like the vector template argument are not taken correctly.

For my understanding I'd expect

CConcurrent_Dictionary::CSingle_Element
to be the only template argument to std::vector. So could you help me out? What am i missing?


问:
Keeping an elements width static after removing another element while still remaining responsive
I have a button with some text in it and when a user presses the button I replace it with a loading symbol. When I remove the text inside of the button and replace it with the spinner, the button shrinks.

I have created a fiddle of the issue.

I know that I can simply add a fixed width to the element, however the page is responsive all the way down to 300 pixels. I also know I can add media queries to address this, but I'm wondering if there is any easier way via LESS or vanilla CSS to handle this without all the media queries?

Here is my basic setup:

```<code><button>
  <span class="hidden-conditionally">
    Click here to perform an action!
  </span>

  <span id="spinner" class="displayed-conditionally">
    Loading...
  </span>
</button>
</code>```

答:
You could set the min-width of that "button" to 100% (or whatever floats your boat really).  That way, the button would be forced to occupy the same amount of available space offered by any parent element regardless of the content within the button:

```<code><button style="min-width:100%">
  <span class="hidden-conditionally">
    Click here to perform an action!
  </span>

  <span id="spinner" class="displayed-conditionally">
    Loading...
  </span>
</button>
</code>```

This fix need not be an inline style attribute, it can also be added in an associated .css file as well.

Body:
I have a button with some text in it and when a user presses the button I replace it with a loading symbol. When I remove the text inside of the button and replace it with the spinner, the button shrinks.

I have created a fiddle of the issue.

I know that I can simply add a fixed width to the element, however the page is responsive all the way down to 300 pixels. I also know I can add media queries to address this, but I'm wondering if there is any easier way via LESS or vanilla CSS to handle this without all the media queries?

Here is my basic setup:

<button>

    Click here to perform an action!

    Loading...

</button>

Body:
You could set the min-width of that "button" to 100% (or whatever floats your boat really).  That way, the button would be forced to occupy the same amount of available space offered by any parent element regardless of the content within the button:

<button style="min-width:100%">
  <span class="hidden-conditionally">
    Click here to perform an action!
  </span>

  <span id="spinner" class="displayed-conditionally">
    Loading...
  </span>
</button>

This fix need not be an inline style attribute, it can also be added in an associated .css file as well.


答:
C-style arrays are sized constructs. You can get the compile-time size of an array via various means. However, when the array decays into a pointer, you lose that compile-time sizing information. Even if the parameter is an "array" type, it's really still just a pointer with no size info. You can use template programming to preserve the size if the array is passed as a function parameter (template<size_t S> void func(T(&param)[S])), but that's it.

This implicit decaying of an array to a pointer is considered by many C++ programmers to be a design flaw in C-style arrays. Indeed, it would hardly be unreasonable to say that lossy conversions are probably not ones which should be implicit. Given that std::array is an attempt to fix as many of the flaws of C-style arrays as possible, allowing it to implicitly decay into a pointer would be counter-productive.

By contrast, C++20's std::span type provides an implicit conversion from a std::array (and C-style arrays, among others). The reason being that such a conversion preserves the information: pointer as well as size. Indeed, the conversion can even preserve the compile-time nature of that size.

Is there any technical reason this operator could not be created?

"Could not"? No.

Title: Why does std::array not have an operator T*?

Body:
With C arrays, it's been the case that simply naming an array has the same effect as writing &foo[0] for something approaching 50 years.

When converting from C style arrays to std::array<> in a project I'm working on, the vast majority of "error"s that appeared were due to the above property of C arrays.

In all cases, the solution was trivial, just append .data().  However it occurred to me that a carefully crafted operator T* ought to directly solve this issue.

Is there any technical reason this operator could not be created?


答:
Here is both ways of approaching.

If you dont care, use fireAndForget style.

If you really want to know, a more verbose check.

const arr = [{id:1}];

const fireAndForget = (arr, id, newName) => (arr.find(i => i.id === id)||{}).name = newName;

const checkAndNotify = (arr, id, newName) => {
  const p = arr.find(i => i.id === id);
  if(!p) return false;
  p.name = newName;
  return true;
};

console.log(checkAndNotify(arr, 2, 'test'));
console.log(checkAndNotify(arr, 1, 'test'));
console.log(arr);

console.log(fireAndForget(arr, 2, 'test2'));
console.log(fireAndForget(arr, 1, 'test2'));
console.log(arr);```

Title: How to check for undefined when using find on an javascript array


问:
POST method not supported when submitting multiple forms through the same JS code. (405)
I have multiple forms on the same page that are submitted through the same JavaScript code.

```<code><form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController@cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="462f2e80-8012-11e9-8b02-65a0a3459d7a">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>

<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController@cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="9b9ef9d0-8012-11e9-aa0f-95ff09733e52">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>
</code>```

There could be any number of forms all of which will have a unique value for each hidden input.

Here is my JavaScript code

```<code>$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".btn-submit-cancelchallenge").click(function(e){e.preventDefault();

    var $form = $('#cancelchallenge');
    var cancel_challengeid = $("input[name=cancel_challengeid]").val();

    $.ajax({
        type:'POST',
    url: $form.attr('action'),
    data:{cancel_challengeid:cancel_challengeid},

    success:function(data){
        if(data.successful) {
            toastr.success(data.successful);
        }
    }
    });

});
</code>```

If I submit any given form using the above code it works but it will always only submit the input value - from the first form - regardless of which form I submit.

Okay So I realise I shouldn't be using the same ID's in multiple forms so I change the form ID from:

id="cancelchallenge" to class="cancelchallenge"

and then update the JS code from:

var $form = $('#cancelchallenge'); to var $form = $(this);

thinking that will allow to submit any given form with the correct input value. However this now results in a 405 error.

"The POST method is not supported for this route. Supported methods: GET, HEAD."

My route looks like this:

```<code>Route::post('cancelChallenge', 'ChallengeController@cancelChallenge');
</code>```

Briefly my controller looks like this:

```<code>public function cancelChallenge(Request $request)
    {
        //Some validation
        $challenge = Challenge::where(['id' => $request->cancel_challengeid,
        'player1' => Auth::user()->id])->first();
        //DB::beginTransaction();
        //Update a row in the challenges table
        //Insert a row into the transactions table
        //Update a row in the users table
        //Commit transaction
    }
</code>```

Anyone able to point me in the right direction? Thanks.

答:
$(this) - current element.

el.parent() - parent of element.

el.find() - find selector inside element.

```<code>$('.btn-submit-cancelchallenge').click(function(e){
    e.preventDefault();

    let $form = $(this).parent();
    let cancel_challengeid = $form.find('input[name=cancel_challengeid]').val();

    $.ajax({
        type:'POST',
        url: $form.attr('action'),
        data: {cancel_challengeid: cancel_challengeid},
        success:function(data){
            if(data.successful) {
                toastr.success(data.successful);
            }
        }
    });
});
</code>```

Or better:

```<code>$('.btn-submit-cancelchallenge').click(function(e){
    e.preventDefault();

    let form = $(this).parent();

    $.ajax({
        type:'POST',
        url: form.attr('action'),
        data: form.serialize(),
        success:function(data){
            if(data.successful) {
                toastr.success(data.successful);
            }
        }
    });
});
</code>```

Body:
I have multiple forms on the same page that are submitted through the same JavaScript code.

<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController@cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="462f2e80-8012-11e9-8b02-65a0a3459d7a">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>

<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController@cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="9b9ef9d0-8012-11e9-aa0f-95ff09733e52">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>

There could be any number of forms all of which will have a unique value for each hidden input.

Here is my JavaScript code

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".btn-submit-cancelchallenge").click(function(e){e.preventDefault();

    var $form = $('#cancelchallenge');
    var cancel_challengeid = $("input[name=cancel_challengeid]").val();

    $.ajax({
        type:'POST',
    url: $form.attr('action'),
    data:{cancel_challengeid:cancel_challengeid},

    success:function(data){
        if(data.successful) {
            toastr.success(data.successful);
        }
    }
    });

});

If I submit any given form using the above code it works but it will always only submit the input value - from the first form - regardless of which form I submit.

Okay So I realise I shouldn't be using the same ID's in multiple forms so I change the form ID from:

id="cancelchallenge" to class="cancelchallenge"

and then update the JS code from:

var $form = $('#cancelchallenge'); to var $form = $(this);

thinking that will allow to submit any given form with the correct input value. However this now results in a 405 error.

"The POST method is not supported for this route. Supported methods: GET, HEAD."

My route looks like this:

Route::post('cancelChallenge', 'ChallengeController@cancelChallenge');

Briefly my controller looks like this:

public function cancelChallenge(Request $request)
    {
        //Some validation
        $challenge = Challenge::where(['id' => $request->cancel_challengeid,
        'player1' => Auth::user()->id])->first();
        //DB::beginTransaction();
        //Update a row in the challenges table
        //Insert a row into the transactions table
        //Update a row in the users table
        //Commit transaction
    }

Anyone able to point me in the right direction? Thanks.

Body:
$(this) - current element.

el.parent() - parent of element.

el.find() - find selector inside element.

$('.btn-submit-cancelchallenge').click(function(e){
    e.preventDefault();

    let $form = $(this).parent();
    let cancel_challengeid = $form.find('input[name=cancel_challengeid]').val();

    $.ajax({
        type:'POST',
        url: $form.attr('action'),
        data: {cancel_challengeid: cancel_challengeid},
        success:function(data){
            if(data.successful) {
                toastr.success(data.successful);
            }
        }
    });
});

Or better:

$('.btn-submit-cancelchallenge').click(function(e){
    e.preventDefault();

    let form = $(this).parent();

    $.ajax({
        type:'POST',
        url: form.attr('action'),
        data: form.serialize(),
        success:function(data){
            if(data.successful) {
                toastr.success(data.successful);
            }
        }
    });
});


问:
effect or animation in UItableVIew
when I click on the tableView it displays something like this to show details

How can I do this?:

答:
I think what you need is an implementation similar to accordion. Here are some sample reference from where you can start

How to implement an accordion view for an iPhone SDK app?

Accordion table cell - How to dynamically expand/contract uitableviewcell?

Accordion sample tutorial

Accordion sample tutorial 2

Title: effect or animation in UItableVIew


问:
How to group by one column and divide the numbers in second column depending from the third
I have frequency (column 1) for SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING (column 3) mutations for a list of genes in the second column.

I need to calculate dN/dS ratio (NON_SYNONYMOUS_CODING / SYNONYMOUS_CODING) for each gene.

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency

```<code>0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING
</code>```

Expected result is smth like this:

```<code>187.95 A1BG
0.3353 A1CF
13.926 A2M
1.565 A2ML1
</code>```

答:
Here is a small awk script:

```<code>cat script.awk

NR%2 { # process odd numbered lines
    readVars(); # read variables from line
    next; # skip processing, goto next line (even numbered line)
}
{ # process even numbered lines
    readVars(); # read variables from line
    print (nonSyn/syn), $2; # print variables division and print code
    syn = nonSyn = 0; # reset variables to 0
}
function readVars() {
    if ($3 ~ "NON_SYNONYMOUS_CODING") # if 3rd field match non_syn
        nonSyn = $1; # set nonSyn value to 1st field
    else syn = $1; # otherwize set syn value to 1st field
}
</code>```

~         Run:

```<code>awk -f script.awk input.txt
</code>```

Output:

```<code>187.954 A1BG
2.98205 A1CF
13.9263 A2M
1.56543 A2ML1
</code>```

Body:
I have frequency (column 1) for SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING (column 3) mutations for a list of genes in the second column.

I need to calculate dN/dS ratio (NON_SYNONYMOUS_CODING / SYNONYMOUS_CODING) for each gene.

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency

0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING

Expected result is smth like this:

187.95 A1BG
0.3353 A1CF
13.926 A2M
1.565 A2ML1

Body:
Here is a small awk script:

cat script.awk

NR%2 { # process odd numbered lines
    readVars(); # read variables from line
    next; # skip processing, goto next line (even numbered line)
}
{ # process even numbered lines
    readVars(); # read variables from line
    print (nonSyn/syn), $2; # print variables division and print code
    syn = nonSyn = 0; # reset variables to 0
}
function readVars() {
    if ($3 ~ "NON_SYNONYMOUS_CODING") # if 3rd field match non_syn
        nonSyn = $1; # set nonSyn value to 1st field
    else syn = $1; # otherwize set syn value to 1st field
}

~         Run:

awk -f script.awk input.txt

Output:

187.954 A1BG
2.98205 A1CF
13.9263 A2M
1.56543 A2ML1