问:
Google NLP api gives Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available
I am trying to use google natural language processing api. I add libraries using Maven and add the GOOGLE_APPLICATION_CREDENTIALSas environment variable which is having the path to a JSON file that contains my service account key.

It is giving me an error;   Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available

```<code>try (LanguageServiceClient language = LanguageServiceClient.create()) {

            // The text to analyze
            String text = "Hello, world!";
            Document doc = Document.newBuilder()
                    .setContent(text).setType(Type.PLAIN_TEXT).build();

            // Detects the sentiment of the text
            Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

            System.out.printf("Text: %s%n", text);
            System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());
        }catch(Exception e){
            System.out.println("Gevindu Error "+ e.getMessage());
        }
</code>```

答:
There isn't much data to be sure about correct answer, but in my case error was because I was using java version 1.8, I change compile properties to 1.9 and error gone:</p>

```<code><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
            <source>1.9</source>
            <target>1.9</target>
            <optimize>true</optimize>
            <debug>true</debug>
            <encoding>UTF-8</encoding>
        </configuration>
    </plugin>
</code>```

Body:
I am trying to use google natural language processing api. I add libraries using Maven and add the GOOGLE_APPLICATION_CREDENTIALSas environment variable which is having the path to a JSON file that contains my service account key.

It is giving me an error;   Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available

try (LanguageServiceClient language = LanguageServiceClient.create()) {

            // The text to analyze
            String text = "Hello, world!";
            Document doc = Document.newBuilder()
                    .setContent(text).setType(Type.PLAIN_TEXT).build();

            // Detects the sentiment of the text
            Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

            System.out.printf("Text: %s%n", text);
            System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());
        }catch(Exception e){
            System.out.println("Gevindu Error "+ e.getMessage());
        }

Body:
There isn't much data to be sure about correct answer, but in my case error was because I was using java version 1.8, I change compile properties to 1.9 and error gone:

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
            <source>1.9</source>
            <target>1.9</target>
            <optimize>true</optimize>
            <debug>true</debug>
            <encoding>UTF-8</encoding>
        </configuration>
    </plugin>


来源: stackexchange

问:
Connecting two promises in a Firebase web app
I am using a Realtime Database to handle some data in a Firebase web app.
In the code hereafter, I want to insert a record in the DB only if fieldOne and fieldTwo aren't going to be duplicated.

```<code>dbReference.orderByChild("fieldOne").equalTo(fieldOneVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This fieldOne has already been used.')
    reject();
  }
}).then( // What is the correct way to connect this line and the following ??
dbReference.orderByChild("fieldTwo").equalTo(fieldTwoVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This NAME has already been used.')
    reject();
  }

  // All is now OK.
  .... do the final things here .....
}).catch(function(error) {
  // An error happened.
  alert('This record cannot be inserted.')
});
</code>```

At this point, I am able to tweak the code to make things work the way I wish. But my issue is that I am not doing things the proper way (I know that due to some messages I can see in the console). The comment in my code shows where I need to know the correct way to connect the two parts.
What is the .... the following ??

For information the DB looks like this:

```<code>MyList
  + -M93j....443cxYYDSN
      fieldOne: "asdc..."
      fieldTwo: "Gkk...."
  + -M94j.........OZS6FL
      fieldOne: "afc..."
      fieldTwo: "SDFSk...."
</code>```

答:
The following Promises chaining combined with errors throwing should do the trick.

```<code>  dbReference
    .orderByChild('fieldOne')
    .equalTo(fieldOneVal)
    .once('value')
    .then(function (snapshot) {
      if (snapshot.exists()) {
        throw new Error('fieldOneExists');
      }
      return dbReference
        .orderByChild('fieldTwo')
        .equalTo(fieldTwoVal)
        .once('value');
    })
    .then(function (snapshot) {
      if (snapshot.exists()) {
        throw new Error('fieldTwoExists');
      }

      // All is now OK.
      //.... do the final things here .....
    })
    .catch(function (error) {
      if (
        error.message === 'fieldOneExists' ||
        error.message === 'fieldTwoExists'
      ) {
        console.log('This record cannot be inserted');
      } else {
        console.log('other error');
      }
    });
</code>```

However, it would probably be better to use a Transaction for checking the existence of the two values for the fieldOne and fieldTwo fields.

The problem is that the Realtime Database transactions don't work with queries: you need to exactly know the location of the data to be modified (or to be checked for existence/non-existence). So you would need to adapt your data model if it appears that you really need a transaction (which depends on your exact global requirements).

For example you could create database nodes with the concatenation of the values of fieldOne and fieldTwo values and check the existence of such a node in a Transaction. But, again, the feasibility of this approach depends on your exact global requirements, which we don't know.

ContentLicense: CC BY-SA 4.0

Body:
I am using a Realtime Database to handle some data in a Firebase web app.
In the code hereafter, I want to insert a record in the DB only if fieldOne and fieldTwo aren't going to be duplicated.

dbReference.orderByChild("fieldOne").equalTo(fieldOneVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This fieldOne has already been used.')
    reject();
  }
}).then( // What is the correct way to connect this line and the following ??
dbReference.orderByChild("fieldTwo").equalTo(fieldTwoVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This NAME has already been used.')
    reject();
  }

  // All is now OK.
  .... do the final things here .....
}).catch(function(error) {
  // An error happened.
  alert('This record cannot be inserted.')
});

At this point, I am able to tweak the code to make things work the way I wish. But my issue is that I am not doing things the proper way (I know that due to some messages I can see in the console). The comment in my code shows where I need to know the correct way to connect the two parts.
What is the .... the following ??

For information the DB looks like this:

MyList
  + -M93j....443cxYYDSN
      fieldOne: "asdc..."
      fieldTwo: "Gkk...."
  + -M94j.........OZS6FL
      fieldOne: "afc..."
      fieldTwo: "SDFSk...."

Body:
The following Promises chaining combined with errors throwing should do the trick.

  dbReference
    .orderByChild('fieldOne')
    .equalTo(fieldOneVal)
    .once('value')
    .then(function (snapshot) {
      if (snapshot.exists()) {
        throw new Error('fieldOneExists');
      }
      return dbReference
        .orderByChild('fieldTwo')
        .equalTo(fieldTwoVal)
        .once('value');
    })
    .then(function (snapshot) {
      if (snapshot.exists()) {
        throw new Error('fieldTwoExists');
      }

      // All is now OK.
      //.... do the final things here .....
    })
    .catch(function (error) {
      if (
        error.message === 'fieldOneExists' ||
        error.message === 'fieldTwoExists'
      ) {
        console.log('This record cannot be inserted');
      } else {
        console.log('other error');
      }
    });

However, it would probably be better to use a Transaction for checking the existence of the two values for the fieldOne and fieldTwo fields.

The problem is that the Realtime Database transactions don't work with queries: you need to exactly know the location of the data to be modified (or to be checked for existence/non-existence). So you would need to adapt your data model if it appears that you really need a transaction (which depends on your exact global requirements).

For example you could create database nodes with the concatenation of the values of fieldOne and fieldTwo values and check the existence of such a node in a Transaction. But, again, the feasibility of this approach depends on your exact global requirements, which we don't know.


问:
Saving object in React.useState
I have a form in my react project, and I want the value of each field to be stored in the state.
instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)</p>

```<code>import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}
</code>```

答:
You should create an initial state value if you want to store the form values as an object using useState, so you can rollback to the initial state after an error. Example,

const initialState = {
  name: "",
  email: ""
};

export const UserData = () => {
  const [formState, setFormState] = useState(initialState);

  const submitHandler = event => {
    event.preventDefault();
    console.log(formState);
  };

  return (
    <form onSubmit={submitHandler}>
      <input
        type="text"
        placeholder="Name"
        value={formState.name}
        onChange={e => {
          setFormState({ ...formState, name: e.target.value });
        }}
      />
      <input
        type="email"
        placeholder="Email"
        value={formState.email}
        onChange={e => {
          setFormState({ ...formState, email: e.target.value });
        }}
      />
      <button>Confirm</button>
    </form>
  );
};

```

Working demo in codesandbox.

Title: Saving object in React.useState

Body:
I have a form in my react project, and I want the value of each field to be stored in the state.
instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)

import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}

Body:
You should create an initial state value if you want to store the form values as an object using useState, so you can rollback to the initial state after an error. Example,

const initialState = {
  name: "",
  email: ""
};

export const UserData = () => {
  const [formState, setFormState] = useState(initialState);

  const submitHandler = event => {
    event.preventDefault();
    console.log(formState);
  };

  return (
    <form onSubmit={submitHandler}>
      <input
        type="text"
        placeholder="Name"
        value={formState.name}
        onChange={e => {
          setFormState({ ...formState, name: e.target.value });
        }}
      />
      <input
        type="email"
        placeholder="Email"
        value={formState.email}
        onChange={e => {
          setFormState({ ...formState, email: e.target.value });
        }}
      />
      <button>Confirm</button>
    </form>
  );
};

Working demo in codesandbox.


问:
Kotlin coroutine in lifecycleScope doesn't block main thread
I am confused about coroutines in ViewModels.

My question is pretty simple: why does it seem like the following coroutine doesn't block UIThread? (UI is still smooth while coroutine is running)

My fragment right here:

```<code>class FragmentSeePaths : Fragment(R.layout.fragment_see_paths),
        PathRecyclerAdapter.OnSetPathForWidgetListener {
    private val pathViewModel: PathViewModel by activityViewModels()
    private lateinit var binding: FragmentSeePathsBinding
    private lateinit var listener: OnAddLineRequestListener

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        ...
    }

    private fun observeWidgetPath() {
        pathViewModel.getUserWidgetPath().observe(viewLifecycleOwner, Observer {
            if (it != null) {
                lifecycleScope.launch {
                    val times = pathViewModel.fetchBusTime(it)
                    updateUI(it, times)
                }
            }
        })
    }
</code>```

And here are the shotened ViewModel with the fetchBusTime method:

```<code>suspend fun fetchBusTime(path: Path): Pair<List<Time>?, List<Time>?> {
        Log.v("fetchBusTimeUI", Thread.currentThread().name) // Main

        // Some network requests made with Retrofit
        val timesResponseStartPoint: GinkoTimesResponse? = repository.getTimes(
                path.startingPoint.startName,
                path.line.lineId,
                path.isStartPointNaturalWay
        )

        val timesResponseEndPoint: GinkoTimesResponse? = repository.getTimes(
                path.endingPoint.endName,
                path.line.lineId,
                path.isStartPointNaturalWay
        )

        return timesResponseStartPoint to timesResponseEndPoint
}
</code>```

答:
launch allows us to start a coroutine in the background and keep working in the meantime. Suspending functions may suspend the execution of the current coroutine without blocking the current thread. We can start a coroutine under any of the below dispatchers.

dipatcher.IO -> Network operation

dispatcher.Main -> On main thread

dispatcher.Default -> for CPU intensive operation

To explain you in detail, I am taking an example from the documentation :-

```<code>fun main() {
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L)
        println("World!")
    }
    println("Hello,") // main thread continues here immediately
    runBlocking {     // but this expression blocks the main thread
        delay(2000L)  // ... while we delay for 2 seconds to keep JVM alive
    }
}
</code>```

The comments should speak for themselves. This will print “Hello,” immediately, and add “World!” after a second.
This is the same thing that will work with your code, the suspend function fetchBusTime() will be executed without blocking the thread and after the operation completed inside this method, it will execute updateUI(it, times).

For more details on this please go through this article here

Body:
I am confused about coroutines in ViewModels.

My question is pretty simple: why does it seem like the following coroutine doesn't block UIThread? (UI is still smooth while coroutine is running)

My fragment right here:

class FragmentSeePaths : Fragment(R.layout.fragment_see_paths),
        PathRecyclerAdapter.OnSetPathForWidgetListener {
    private val pathViewModel: PathViewModel by activityViewModels()
    private lateinit var binding: FragmentSeePathsBinding
    private lateinit var listener: OnAddLineRequestListener

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        ...
    }

    private fun observeWidgetPath() {
        pathViewModel.getUserWidgetPath().observe(viewLifecycleOwner, Observer {
            if (it != null) {
                lifecycleScope.launch {
                    val times = pathViewModel.fetchBusTime(it)
                    updateUI(it, times)
                }
            }
        })
    }

And here are the shotened ViewModel with the fetchBusTime method:

suspend fun fetchBusTime(path: Path): Pair<List<Time>?, List<Time>?> {
        Log.v("fetchBusTimeUI", Thread.currentThread().name) // Main

        // Some network requests made with Retrofit
        val timesResponseStartPoint: GinkoTimesResponse? = repository.getTimes(
                path.startingPoint.startName,
                path.line.lineId,
                path.isStartPointNaturalWay
        )

        val timesResponseEndPoint: GinkoTimesResponse? = repository.getTimes(
                path.endingPoint.endName,
                path.line.lineId,
                path.isStartPointNaturalWay
        )

        return timesResponseStartPoint to timesResponseEndPoint
}

Body:
launch allows us to start a coroutine in the background and keep working in the meantime. Suspending functions may suspend the execution of the current coroutine without blocking the current thread. We can start a coroutine under any of the below dispatchers.

dipatcher.IO -> Network operation

dispatcher.Main -> On main thread

dispatcher.Default -> for CPU intensive operation

To explain you in detail, I am taking an example from the documentation :-

fun main() {
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L)
        println("World!")
    }
    println("Hello,") // main thread continues here immediately
    runBlocking {     // but this expression blocks the main thread
        delay(2000L)  // ... while we delay for 2 seconds to keep JVM alive
    }
}

The comments should speak for themselves. This will print “Hello,” immediately, and add “World!” after a second.
This is the same thing that will work with your code, the suspend function fetchBusTime() will be executed without blocking the thread and after the operation completed inside this method, it will execute updateUI(it, times).

For more details on this please go through this article here


问:
How do i make it so that my bot autoamtticly kicks people when they have 3 warnings in discord.py rewrite
So here is my code for the warning system:

```<code>@commands.has_permissions(manage_messages=True)
async def warn(ctx,user:discord.User,*reason:str):
  if not reason:
    await ctx.send("Du skal lige give mig en grund til din Advarsel!")
    return
  reason = ' '.join(reason)
  for current_user in report['users']:
    if current_user['name'] == user.name:
      current_user['reasons'].append(reason)
      break
  else:
    await ctx.send(f"{user.name} er blevet advaret med grunden: '{reason}'")
    report['users'].append({
      'name':user.name,
      'reasons': [reason,]
    })

  with open('reports.json','w+') as f:
    json.dump(report,f)

@client.command()
@commands.has_permissions(manage_messages=True)
async def warnings(ctx,user:discord.User):
  for current_user in report['users']:
    if user.name == current_user['name']:
      await ctx.send(f"{user.name} er blevet advaret {len(current_user['reasons'])} gange : {','.join(current_user['reasons'])}")
      break
  else:
    await ctx.send(f"{user.name} er aldrig blevet advaret!")
</code>```

all i'm asking is help with making so when they have 3 warnings in my reports.json file that they get kicked..

and i little disclaimer.. i didn't write all that code myself, i took it off stack and modified

答:
Check for 3 warnings whenever you warn someone, and use discord.Member instead of discord.User.

@commands.has_permissions(manage_messages=True)
async def warn(ctx,user:discord.Member,*reason:str):
  if not reason:
    await ctx.send("Du skal lige give mig en grund til din Advarsel!")
    return
  reason = ' '.join(reason)
  for current_user in report['users']:
    if current_user['name'] == user.name:
      current_user['reasons'].append(reason)
      break
  else:
    await ctx.send(f"{user.name} er blevet advaret med grunden: '{reason}'")
    report['users'].append({
      'name':user.name,
      'reasons': [reason,]
    })

  with open('reports.json','w+') as f:
    json.dump(report,f)
  if len(report['users']) >= 3:
    await user.kick(reason='You reached 3 warnings')

@client.command()
@commands.has_permissions(manage_messages=True)
async def warnings(ctx,user:discord.Member):
  for current_user in report['users']:
    if user.name == current_user['name']:
      await ctx.send(f"{user.name} er blevet advaret {len(current_user['reasons'])} gange : {','.join(current_user['reasons'])}")
      break
  else:
    await ctx.send(f"{user.name} er aldrig blevet advaret!")
```

Body:
So here is my code for the warning system:

@commands.has_permissions(manage_messages=True)
async def warn(ctx,user:discord.User,*reason:str):
  if not reason:
    await ctx.send("Du skal lige give mig en grund til din Advarsel!")
    return
  reason = ' '.join(reason)
  for current_user in report['users']:
    if current_user['name'] == user.name:
      current_user['reasons'].append(reason)
      break
  else:
    await ctx.send(f"{user.name} er blevet advaret med grunden: '{reason}'")
    report['users'].append({
      'name':user.name,
      'reasons': [reason,]
    })

  with open('reports.json','w+') as f:
    json.dump(report,f)

@client.command()
@commands.has_permissions(manage_messages=True)
async def warnings(ctx,user:discord.User):
  for current_user in report['users']:
    if user.name == current_user['name']:
      await ctx.send(f"{user.name} er blevet advaret {len(current_user['reasons'])} gange : {','.join(current_user['reasons'])}")
      break
  else:
    await ctx.send(f"{user.name} er aldrig blevet advaret!")

all i'm asking is help with making so when they have 3 warnings in my reports.json file that they get kicked..

and i little disclaimer.. i didn't write all that code myself, i took it off stack and modified


问:
Houdini, Python: range, randomize and timeshift keyframes
I have a simple model object_A that has 10 keyframes.

Frames 1-5 have rotation only on X, frames 6-10 have rotation only on Y.

Per copy to point (Houdini) I copy object_A as an instance on every point on a grid.

Now I would like to range, randomize and timeshift the keyframes for each instance.

In a range from 1-5, chose a random key and timeshift that keyframe to frame 1.

I also want to define the keyframes in a dropdown list.
The dropdown has two tokens and two labels ((1, 5), (rotation_x)) and ((6, 10), (rotation_y))

My first lines look like that:

```<code>import random

def retime_frames():

    # values from dropdown tokens
    fr_get = hou.evalParm('choose_frame_set')

    for frX in range(fr_get):
        fRandom = (random.choice(frX))
        hou.parm('retime_frame').set(str(fRandom))
        print fRandom
</code>```

I get an error that way and dont know where.
If I use a list like [1, 2, 3, 4, 5] it works.
But as soon as I try to use range(var) it does not work anymore.

```<code>TypeError: range() integer end argument expected, got str.
</code>```

答:
I found a solution for the random frames.

```<code>import random

""" Give out randomized, single frame
from given frame sequence preset. To add more presets
modify 'Choose Frame Set' menu in parameters.
'token' example1: '1-5' = frames 1 till 5.
'token' example2: '1-3, 7, 10-12' = 1 till 3 + 7 + 10 till 12
"""

def retime_frames():

    fr_range = hou.evalParm("choose_frame_set")
    fr_sequence = []

    for frames in fr_range.split(','):
        if '-' in frames:
            a, b = frames.split('-')
            a, b = int(a), int(b)
            fr_sequence.extend(range(a, b + 1))
        else:
            a = int(part)

    # random frame from frame_sequence, stepping (frame_range, step)
    random_frame = random.sample(fr_sequence, 1)

    hou.parm('retime_frame').set(str(random_frame)[1])
    print str(random_frame)[1]
</code>```

Body:
I have a simple model object_A that has 10 keyframes.

Frames 1-5 have rotation only on X, frames 6-10 have rotation only on Y.

Per copy to point (Houdini) I copy object_A as an instance on every point on a grid.

Now I would like to range, randomize and timeshift the keyframes for each instance.

In a range from 1-5, chose a random key and timeshift that keyframe to frame 1.

I also want to define the keyframes in a dropdown list.
The dropdown has two tokens and two labels ((1, 5), (rotation_x)) and ((6, 10), (rotation_y))

My first lines look like that:

import random

def retime_frames():

    # values from dropdown tokens
    fr_get = hou.evalParm('choose_frame_set')

    for frX in range(fr_get):
        fRandom = (random.choice(frX))
        hou.parm('retime_frame').set(str(fRandom))
        print fRandom

I get an error that way and dont know where.
If I use a list like [1, 2, 3, 4, 5] it works.
But as soon as I try to use range(var) it does not work anymore.

TypeError: range() integer end argument expected, got str.

Body:
I found a solution for the random frames.

import random

""" Give out randomized, single frame
from given frame sequence preset. To add more presets
modify 'Choose Frame Set' menu in parameters.
'token' example1: '1-5' = frames 1 till 5.
'token' example2: '1-3, 7, 10-12' = 1 till 3 + 7 + 10 till 12
"""

def retime_frames():

    fr_range = hou.evalParm("choose_frame_set")
    fr_sequence = []

    for frames in fr_range.split(','):
        if '-' in frames:
            a, b = frames.split('-')
            a, b = int(a), int(b)
            fr_sequence.extend(range(a, b + 1))
        else:
            a = int(part)

    # random frame from frame_sequence, stepping (frame_range, step)
    random_frame = random.sample(fr_sequence, 1)

    hou.parm('retime_frame').set(str(random_frame)[1])
    print str(random_frame)[1]


问:
Automatic tooltip when text is trimmed in DataGrid
My application runs with C# and WPF (.net framework 4.0). My goal is to have a DataGrid in which the text in the cells is trimmed with an ellipsis, and automatically has a tooltip with the full text displayed only if the text in the cell is actually trimmed.

Solution 1: I'm currently using this to know if the text is trimmed or not: http://tranxcoder.wordpress.com/2008/10/12/customizing-lookful-wpf-controls-take-2/
The problem is that it only works when I resize the columns. The tooltips don't show up when the DataGrid is first loaded, when the columns are sorted, or when the ItemSource of the DataGrid is updated.

Solution 2: I've also tried this:http://www.scottlogic.com/blog/2011/01/31/automatically-showing-tooltips-on-a-trimmed-textblock-silverlight-wpf.html
But the tooltips never appear on my DataGrid cells, while it works fine with isolated textblocks.

I'm looking for simple ways to improve Solution 1 and make it work in my DataGrid in all cases, or maybe a different approach.

The style for Solution 1:

```<code><UserControl.Resources>
    <Style x:Key="TextColumnElementStyle" TargetType="TextBlock" BasedOn="{StaticResource TextBlockService}">
        <Style.Setters>
            <Setter Property="TextWrapping" Value="NoWrap" />
            <Setter Property="TextTrimming" Value="WordEllipsis" />
        </Style.Setters>
    </Style>
</UserControl.Resources>
</code>```

The source code of the TextBlockService

The DataGrid for Solution 1:

```<code><DataGrid ItemsSource="{Binding IssueList}" tbs:TextBlockService.AutomaticToolTipEnabled="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Description" Binding="{Binding Description}"
            ElementStyle="{StaticResource TextColumnElementStyle}">
    </DataGrid.Columns>
</DataGrid>
</code>```

Thanks

答:
I can't comment yet, I lack points needed for it.

But I just want to add an extra tip to the accepted answer code, for noobs like me who want to use it.

If you want to link your Converter to its code, make sure to create a link in your Window/UserControl Resources as mentioned below:

<Window.Resources>
    <local:TrimmedTextBlockVisibilityConverter x:Key="TrimToVisConverter" />
</Window.Resources>
```

Additional thought on accepted answer: You also have to rewrite any style that comes with default DataGridCell template as DataGridCell States. Otherwise you lose clean view on row select and other stuff...

ContentLicense: CC BY-SA 3.0

Body:
My application runs with C# and WPF (.net framework 4.0). My goal is to have a DataGrid in which the text in the cells is trimmed with an ellipsis, and automatically has a tooltip with the full text displayed only if the text in the cell is actually trimmed.

Solution 1: I'm currently using this to know if the text is trimmed or not: http://tranxcoder.wordpress.com/2008/10/12/customizing-lookful-wpf-controls-take-2/
The problem is that it only works when I resize the columns. The tooltips don't show up when the DataGrid is first loaded, when the columns are sorted, or when the ItemSource of the DataGrid is updated.

Solution 2: I've also tried this:http://www.scottlogic.com/blog/2011/01/31/automatically-showing-tooltips-on-a-trimmed-textblock-silverlight-wpf.html
But the tooltips never appear on my DataGrid cells, while it works fine with isolated textblocks.

I'm looking for simple ways to improve Solution 1 and make it work in my DataGrid in all cases, or maybe a different approach.

The style for Solution 1:

<UserControl.Resources>

    </Style>
</UserControl.Resources>

The source code of the TextBlockService

The DataGrid for Solution 1:

<DataGrid ItemsSource="{Binding IssueList}" tbs:TextBlockService.AutomaticToolTipEnabled="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Description" Binding="{Binding Description}"
            ElementStyle="{StaticResource TextColumnElementStyle}">
    </DataGrid.Columns>
</DataGrid>

Thanks

Body:
I can't comment yet, I lack points needed for it.

But I just want to add an extra tip to the accepted answer code, for noobs like me who want to use it.

If you want to link your Converter to its code, make sure to create a link in your Window/UserControl Resources as mentioned below:

<Window.Resources>
    <local:TrimmedTextBlockVisibilityConverter x:Key="TrimToVisConverter" />
</Window.Resources>

Additional thought on accepted answer: You also have to rewrite any style that comes with default DataGridCell template as DataGridCell States. Otherwise you lose clean view on row select and other stuff...


问:
Concatenate three inputs of different dimensions in Keras
I have two inputs of same size and then applied word embeddings of vector size 128 and then reshape it giving both inputs shape of (none,1,128), another input which is context has dimension (none,1,18), I want to concatenate these three inputs and then feed the combined output to an LSTM layer. But I am unable to concatenate the inputs as dimensions are different with this error:

A Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 1, 128), (None, 1, 128), (None, 1, 18)]

```<code>   combined= Concatenate(axis=-2)([input_1,input_2, input_3])
</code>```

The two inputs of shape (none,1,128) are word embeddings while third input of shape(none,1,18) is one hot encoding of some categorial variable.

Does anyone know how to do concatenate this? Any help would be greatly appreciated!

答:
concatenate them on the last dimension

```<code>input_1 = Input((1,128))
input_2 = Input((1,128))
input_3 = Input((1,18))

combined = Concatenate(axis=-1)([input_1,input_2, input_3])
</code>```

this produces a combined tensor of shape (batch_dim, 1, 274)

Body:
I have two inputs of same size and then applied word embeddings of vector size 128 and then reshape it giving both inputs shape of (none,1,128), another input which is context has dimension (none,1,18), I want to concatenate these three inputs and then feed the combined output to an LSTM layer. But I am unable to concatenate the inputs as dimensions are different with this error:

A Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 1, 128), (None, 1, 128), (None, 1, 18)]

   combined= Concatenate(axis=-2)([input_1,input_2, input_3])

The two inputs of shape (none,1,128) are word embeddings while third input of shape(none,1,18) is one hot encoding of some categorial variable.

Does anyone know how to do concatenate this? Any help would be greatly appreciated!

Body:
concatenate them on the last dimension

input_1 = Input((1,128))
input_2 = Input((1,128))
input_3 = Input((1,18))

combined = Concatenate(axis=-1)([input_1,input_2, input_3])

this produces a combined tensor of shape (batch_dim, 1, 274)


问:
Iridescence effect in OpenGL ES 2.0/3.0. Replacing the black area
I am trying to apply an iridescence effect to an object. For this, I used the following shaders:

Vertex shader:

```<code>#version 300 es
uniform mat4 u_mvpMatrix;
uniform mat4 u_mvMatrix;
uniform mat4 u_vMatrix;

in vec4 a_position;
in vec2 a_textureCoordinates;
in vec3 a_normal;

out vec2 v_textureCoordinates;
out float v_CosViewAngle;
out float v_LightIntensity;

void main() {
    // transform normal orientation into eye space
    vec3 modelViewNormal = mat3(u_mvMatrix) * a_normal;
    vec3 modelViewVertex = vec3(u_mvMatrix * a_position);
    mediump vec3 eyeDirection = normalize(-modelViewVertex);

    vec3 lightVector = normalize(lightPosition - modelViewVertex);
    lightVector = mat3(u_vMatrix) * lightVector;

    v_LightIntensity = max(dot(lightVector, modelViewNormal), 0.0);
    v_CosViewAngle = max(dot(eyeDirection, modelViewNormal), 0.1);
    ...
}
</code>```

Fragment shader:

```<code>#version 300 es
precision lowp float;

in vec2 v_textureCoordinates;
in float v_CosViewAngle;
in float v_LightIntensity;
out vec4 outColor;
uniform sampler2D s_texture;

// wave numbers for the iridescence effect: k = 2.0 * pi / wavelength (nm).
const mediump float PI = 3.141592654;
const mediump vec3 rgbK = 2.0 * PI * vec3(1.0/475.0, 1.0/510.0, 1.0/650.0);
const mediump float iridescence = 4.4;
const mediump float minThickness = 80.0;
const mediump float maxVariation = 50.0;

void main() {
    float thickness = texture(s_texture, v_textureCoordinates).r
        * maxVariation + minThickness; // or texture2D() - in OpenGL ES 2.0
    float delta = (thickness / v_LightIntensity) + (thickness / v_CosViewAngle);
    lowp vec3 color = cos(delta * rgbK) * iridescence * v_LightIntensity;
    vec4 resultColor = vec4(color, 1.0);
    outColor = resultColor;
}
</code>```

Result:

Question: How to replace a black area with a common texture? In other words, to have a common texture instead of black color.

Note: I tryid as:

```<code>vec4 resultColor = texture(s_texture, v_textureCoordinates) * (vec4(color, 1.0) + 0.5);
</code>```

And so:

```<code>if (color == vec3(0.0, 0.0, 0.0)) { // if black color
    resultColor = texture(s_texture, v_textureCoordinates);
} else {
    resultColor = texture(s_texture, v_textureCoordinates) * (vec4(color, 1.0) + 0.5);
}
</code>```

But this did not solve the problem.

Thanks in advance!

The code of the shaders is partially taken from PVRShamanGUI.

Update:
Based on the Rabbid76 answer, I also used delta, but only to check the wavelength (in nm):

```<code>...
if (delta > 1700.0 || delta < 370.0) {
    resultColor = texture(s_texture, v_textureCoordinates) * v_commonLight;
} else {
    resultColor = vec4(color, 1.0);
}
outColor = resultColor;
</code>```

Result:

答:
The color is not completely black, the values of the color channels is not exactly 0.0. Compute the average color (gray scale) and mix the color and the texture color dependent on the gray scale:

vec4  texturColor = texture(s_texture, v_textureCoordinates);
float gray_scale  = (color.r + color.g + color.b) / 3.0;
resultColor = mix(texturColor, color, gray_scale);
```

<p>Another possibility is to mix the color dependent on the value of <code>delta</code>:</p>

<pre class="lang-c prettyprint-override"><code>vec4 texturColor = texture(s_texture, v_textureCoordinates);
resultColor = mix(texturColor, color, delta);
</code>```

Body:
I am trying to apply an iridescence effect to an object. For this, I used the following shaders:

Vertex shader:

#version 300 es
uniform mat4 u_mvpMatrix;
uniform mat4 u_mvMatrix;
uniform mat4 u_vMatrix;

in vec4 a_position;
in vec2 a_textureCoordinates;
in vec3 a_normal;

out vec2 v_textureCoordinates;
out float v_CosViewAngle;
out float v_LightIntensity;

void main() {
    // transform normal orientation into eye space
    vec3 modelViewNormal = mat3(u_mvMatrix) * a_normal;
    vec3 modelViewVertex = vec3(u_mvMatrix * a_position);
    mediump vec3 eyeDirection = normalize(-modelViewVertex);

    vec3 lightVector = normalize(lightPosition - modelViewVertex);
    lightVector = mat3(u_vMatrix) * lightVector;

    v_LightIntensity = max(dot(lightVector, modelViewNormal), 0.0);
    v_CosViewAngle = max(dot(eyeDirection, modelViewNormal), 0.1);
    ...
}

Fragment shader:

#version 300 es
precision lowp float;

in vec2 v_textureCoordinates;
in float v_CosViewAngle;
in float v_LightIntensity;
out vec4 outColor;
uniform sampler2D s_texture;

// wave numbers for the iridescence effect: k = 2.0 * pi / wavelength (nm).
const mediump float PI = 3.141592654;
const mediump vec3 rgbK = 2.0 * PI * vec3(1.0/475.0, 1.0/510.0, 1.0/650.0);
const mediump float iridescence = 4.4;
const mediump float minThickness = 80.0;
const mediump float maxVariation = 50.0;

void main() {
    float thickness = texture(s_texture, v_textureCoordinates).r
        * maxVariation + minThickness; // or texture2D() - in OpenGL ES 2.0
    float delta = (thickness / v_LightIntensity) + (thickness / v_CosViewAngle);
    lowp vec3 color = cos(delta * rgbK) * iridescence * v_LightIntensity;
    vec4 resultColor = vec4(color, 1.0);
    outColor = resultColor;
}

Result:

Question: How to replace a black area with a common texture? In other words, to have a common texture instead of black color.

Note: I tryid as:

vec4 resultColor = texture(s_texture, v_textureCoordinates) * (vec4(color, 1.0) + 0.5);

And so:

if (color == vec3(0.0, 0.0, 0.0)) { // if black color
    resultColor = texture(s_texture, v_textureCoordinates);
} else {
    resultColor = texture(s_texture, v_textureCoordinates) * (vec4(color, 1.0) + 0.5);
}

But this did not solve the problem.

Thanks in advance!

The code of the shaders is partially taken from PVRShamanGUI.

Update:
Based on the Rabbid76 answer, I also used delta, but only to check the wavelength (in nm):

...
if (delta > 1700.0 || delta < 370.0) {
    resultColor = texture(s_texture, v_textureCoordinates) * v_commonLight;
} else {
    resultColor = vec4(color, 1.0);
}
outColor = resultColor;

Result:

Body:
The color is not completely black, the values of the color channels is not exactly 0.0. Compute the average color (gray scale) and mix the color and the texture color dependent on the gray scale:

vec4  texturColor = texture(s_texture, v_textureCoordinates);
float gray_scale  = (color.r + color.g + color.b) / 3.0;
resultColor = mix(texturColor, color, gray_scale);

Another possibility is to mix the color dependent on the value of delta:

vec4 texturColor = texture(s_texture, v_textureCoordinates);
resultColor = mix(texturColor, color, delta);


问:
Is + operator overloaded for primitive types?
Already overloaded operators <<,>>,= etc are used many times.

An example that i was thinking of is when we add strings say :

string name = string("munish") + "kumar";

the + operator is overloaded in the string class.

but when we add numbers like 1 + 2( doesn't seem like an overloaded operator call)

I was just wondering how does it happens does the compiler does a binary additon.

I don't need to worry about it much though if the compiler does it so, just a matter of curiosity for me.

答:
I think you're confusing two things: operator overloading, and how you
define an operator for a user defined type.  Operator overloading isn't
new; it exists already in C, where + is overloaded on int, unsigned
int, long, unsigned long, float, double and long double.  In
C++, you can add operators for user defined types, by defining a
function named operator+, so the list of overloads is longer.  And to
make things more coherent, the way the compiler resolves the overload is
to add synthesized signatures along the lines of operator+(int, int)
to the list of overloads.  If the overload resolution then ends up
choosing one of these synthesized signatures, it uses the built-in
operator, generating whatever machine code is necessary (which may
involve a function call at the machine code level).  The fact that it
chooses one of the "build-in" overloads does have repercussions in the
rest of the code: a user defined operator is considered a function call,
with the corresponding sequence points and all of the rest, and the
compiler is not allowed to make any assumptions concerning its
semantics—in particular, the compiler cannot assume that a user
defined operator+ is associative or commutative.  A build-in operator
(with a very few exceptions) does not introduce any sequence points, and
the compiler knows its semantics, and can optimize in consequence.

Note that the generated machine code may not be that different.  I've
used machines where the compiler had to call a function to multiply
ints, and the compiler can (and often will) inline a user defined
operator.  What changes is the rules I mentionned above: the presence of
sequence points in user defined operators, and the fact that the
compiler cannot make assumptions concerning the various mathematical
laws which might apply.


问:
If filename matches pattern do something (for-loop, case-statement)
The local file tree:

```<code>/pdf/Insurance.January.2020.pdf
/pdf/Insurance.February.2020.pdf
/pdf/Provider1.March.2020.pdf
/pdf/Provider2.April.2020.pdf
</code>```

The remote file tree:

```<code>/invoice/Insurance/2019/January/Insurance.January.2019.pdf
/invoice/Insurance/2020/February/Insurance.February.2020.pdf
/invoice/Provider1/.....
</code>```

What I want:
I want to (r)sync my local PDF-files with the remote folders by matching patterns like Name, Year and maybe Month.

I thought I can solve this with a for-loop and case-statements:

```<code>for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME=${FILE##*/}          # cut only filename
    case "$FILENAME" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done
</code>```

But now I think this is not the fastest way because I've to write a lot of lines to find a match. And I also need to "re-match" Year and Month.

Has someone another idea? Thanks!

答:
Assuming there are no newlines in filenames.

Big problems are sum of small problems. The small problems are:

find all files.

Transform the list of files.

Run rsyncs.

The hardest part is the transformation, applying the list on rsync. As usual transforming can be easily done with a regex with sed and applying the output on a command can be done with xargs.

```<code># recreate state
mkdir -p pdf
touch ./pdf/Insurance.January.2020.pdf
touch ./pdf/Insurance.February.2020.pdf
touch ./pdf/Provider1.March.2020.pdf
touch ./pdf/Provider2.April.2020.pdf

# list all files, ex.
# /pdf/Insurance.January.2020.pdf
# /pdf/Provider2.April.2020.pdf
find "./pdf" -maxdepth 1 -type f -name '*.pdf' |
# tranform the list of srcs\ntarget list
# match /pdf/<anything1>.<anything2>.<anything3>.pdf
# and output the original line
# with another line that has ./invoice/<anything1>/<anything3>/<anything1>.<anything2>.<anything3>.pdf
# the star is taken literally
sed 's@/pdf/\([^\.]*\)\.\([^\.]*\)\.\([^\.]*\)\.pdf$@&\n./invoice/\1/\3/\1.\2.\3.pdf@' |
# run rsync for each two arguments (why rsync?)
xargs -d'\n' -n2 echo rsync
</code>```

The code outputs on repl:

```<code>rsync ./pdf/Insurance.January.2020.pdf ./invoice/Insurance/2020/Insurance.January.2020.pdf
rsync ./pdf/Insurance.February.2020.pdf ./invoice/Insurance/2020/Insurance.February.2020.pdf
rsync ./pdf/Provider1.March.2020.pdf ./invoice/Provider1/2020/Provider1.March.2020.pdf
rsync ./pdf/Provider2.April.2020.pdf ./invoice/Provider2/2020/Provider2.April.2020.pdf
</code>```

The star is taken literally as a star.

Body:
The local file tree:

/pdf/Insurance.January.2020.pdf
/pdf/Insurance.February.2020.pdf
/pdf/Provider1.March.2020.pdf
/pdf/Provider2.April.2020.pdf

The remote file tree:

/invoice/Insurance/2019/January/Insurance.January.2019.pdf
/invoice/Insurance/2020/February/Insurance.February.2020.pdf
/invoice/Provider1/.....

What I want:
I want to (r)sync my local PDF-files with the remote folders by matching patterns like Name, Year and maybe Month.

I thought I can solve this with a for-loop and case-statements:

for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME=${FILE##*/}          # cut only filename
    case "$FILENAME" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done

But now I think this is not the fastest way because I've to write a lot of lines to find a match. And I also need to "re-match" Year and Month.

Has someone another idea? Thanks!

Body:
Assuming there are no newlines in filenames.

Big problems are sum of small problems. The small problems are:

find all files.

Transform the list of files.

Run rsyncs.

The hardest part is the transformation, applying the list on rsync. As usual transforming can be easily done with a regex with sed and applying the output on a command can be done with xargs.

# recreate state
mkdir -p pdf
touch ./pdf/Insurance.January.2020.pdf
touch ./pdf/Insurance.February.2020.pdf
touch ./pdf/Provider1.March.2020.pdf
touch ./pdf/Provider2.April.2020.pdf

# list all files, ex.
# /pdf/Insurance.January.2020.pdf
# /pdf/Provider2.April.2020.pdf
find "./pdf" -maxdepth 1 -type f -name '*.pdf' |
# tranform the list of srcs\ntarget list
# match /pdf/<anything1>.<anything2>.<anything3>.pdf
# and output the original line
# with another line that has ./invoice/<anything1>/<anything3>/<anything1>.<anything2>.<anything3>.pdf
# the star is taken literally
sed 's@/pdf/\([^\.]*\)\.\([^\.]*\)\.\([^\.]*\)\.pdf$@&\n./invoice/\1/\3/\1.\2.\3.pdf@' |
# run rsync for each two arguments (why rsync?)
xargs -d'\n' -n2 echo rsync

The code outputs on repl:

rsync ./pdf/Insurance.January.2020.pdf ./invoice/Insurance/2020/Insurance.January.2020.pdf
rsync ./pdf/Insurance.February.2020.pdf ./invoice/Insurance/2020/Insurance.February.2020.pdf
rsync ./pdf/Provider1.March.2020.pdf ./invoice/Provider1/2020/Provider1.March.2020.pdf
rsync ./pdf/Provider2.April.2020.pdf ./invoice/Provider2/2020/Provider2.April.2020.pdf

The star is taken literally as a star.


问:
Improve the usecase of a template-based library
I'm creating a lib in c++, using templates.

The problem I'm trying to resolve, the use case of itself is annoying.

First creates a container "Q_fun" with templates and the rest of classes use it, so all the classes have the same template parameters.

main.cpp

```<code>       lib::Discrete<unsigned> status(3),actions(21);
       lib::Q_fun<double,1,1> q(status, actions);
       lib::Agent<double,1,1> a(q);
       lib::Trainer_TD<double,1,1> tr(a);
</code>```

Lib:

```<code>template<typename T, unsigned st, unsigned ac>
class Agent
{
  public:
    Q_fun<T,st,ac> *q;
...
}

... other file ...

template<typename T, unsigned st, unsigned ac>
class Trainer_TD
{
  public:
    Agent<T,st,ac> *a;
...
}
</code>```

Do you know a better way to improve this(what can I change of the lib)?

Thanks 4 your time.
P.A.C.

答:
Use a type-trait:

```<code>template <typename T,unsigned st, unsigned ac>
struct my_types {
    using Agent_t = Agent<T,st,ac>;
    using Q_fun_t = Q_fun<T,st,ac>;
    using Trainer_TD_t = Trainer_TD<T,st,ac>;
};
</code>```

Now the template parameters need not be repeated:

```<code>using types = my_types<double,1,1>;
types::Agent_t agent;
types::Q_fun_t q_fun;
types::Trainer_TD_t trainer_qd;
</code>```

Body:
I'm creating a lib in c++, using templates.

The problem I'm trying to resolve, the use case of itself is annoying.

First creates a container "Q_fun" with templates and the rest of classes use it, so all the classes have the same template parameters.

main.cpp

       lib::Discrete<unsigned> status(3),actions(21);
       lib::Q_fun<double,1,1> q(status, actions);
       lib::Agent<double,1,1> a(q);
       lib::Trainer_TD<double,1,1> tr(a);

Lib:

template<typename T, unsigned st, unsigned ac>
class Agent
{
  public:
    Q_fun<T,st,ac> *q;
...
}

... other file ...

template<typename T, unsigned st, unsigned ac>
class Trainer_TD
{
  public:
    Agent<T,st,ac> *a;
...
}

Do you know a better way to improve this(what can I change of the lib)?

Thanks 4 your time.
P.A.C.

Body:
Use a type-trait:

template <typename T,unsigned st, unsigned ac>
struct my_types {
    using Agent_t = Agent<T,st,ac>;
    using Q_fun_t = Q_fun<T,st,ac>;
    using Trainer_TD_t = Trainer_TD<T,st,ac>;
};

Now the template parameters need not be repeated:

using types = my_types<double,1,1>;
types::Agent_t agent;
types::Q_fun_t q_fun;
types::Trainer_TD_t trainer_qd;


问:
How to pass method with arguments to thread to execution?
I have a method

```<code>void RobocopyCopy::monitoring_thread_method(std::string path_to_monior)
{
    while (!m_bMonitorThreadShouldExit)
    {
        printf("HERE WE ARE!!!! Path is :: %s\n", path_to_monior.c_str());
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}
</code>```

I need to start it in the background, so I create a thread and would like to pass this method as an argument

```<code>void RobocopyCopy::start_monitoring_thread(std::string path_to_monior)
{
    m_bMonitorThreadShouldExit = false;
    m_pMonitoringThread = std::unique_ptr<std::thread>(new std::thread(&RobocopyCopy::monitoring_thread_method, path_to_monior, this));
}
</code>```

I am getting such an error

```<code>>RobocopyCopy.cpp
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): error C2672: 'std::invoke': no matching overloaded function found
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(246): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0,1,2>(std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *> &,std::integer_sequence<_Ty,0,1,2>)' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>,
1>            _Ty=size_t
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(245): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0,1,2>(std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *> &,std::integer_sequence<_Ty,0,1,2>)' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>,
1>            _Ty=size_t
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(242): note: while compiling class template member function 'void std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *) noexcept'
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(230): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *) noexcept' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(257): note: see reference to class template instantiation 'std::_LaunchPad<_Target>' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thread(49): note: see reference to function template instantiation 'void std::_Launch<std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<_Ty>>>(_Thrd_t *,_Target &&)' being compiled
1>        with
1>        [
1>            _Ty=std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\tetavi_main2\tv_apps\tv_world2\tv_logic_cpp\robocopycopy.cpp(73): note: see reference to function template instantiation 'std::thread::thread<void(__cdecl RobocopyCopy::* )(std::string),std::string&,RobocopyCopy*,void>(_Fn &&,std::string &,RobocopyCopy *&&)' being compiled
1>        with
1>        [
1>            _Fn=void (__cdecl RobocopyCopy::* )(std::string)
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): note: With the following template arguments:
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): note: '_Callable=void (__cdecl RobocopyCopy::* )(std::string)'
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): note: '_Types={std::basic_string<char,std::char_traits<char>,std::allocator<char>>, RobocopyCopy *}'
1>Done building project "TV_Logic_CPP.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

</code>```

What am I doing wrong?

答:
```<code> m_pMonitoringThread = std::make_unique<std::thread>(&RobocopyCopy::monitoring_thread_method, this, path_to_monior);
</code>```

Body:
I have a method

void RobocopyCopy::monitoring_thread_method(std::string path_to_monior)
{
    while (!m_bMonitorThreadShouldExit)
    {
        printf("HERE WE ARE!!!! Path is :: %s\n", path_to_monior.c_str());
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

I need to start it in the background, so I create a thread and would like to pass this method as an argument

void RobocopyCopy::start_monitoring_thread(std::string path_to_monior)
{
    m_bMonitorThreadShouldExit = false;
    m_pMonitoringThread = std::unique_ptr<std::thread>(new std::thread(&RobocopyCopy::monitoring_thread_method, path_to_monior, this));
}

I am getting such an error

>RobocopyCopy.cpp
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): error C2672: 'std::invoke': no matching overloaded function found
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(246): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0,1,2>(std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *> &,std::integer_sequence<_Ty,0,1,2>)' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>,
1>            _Ty=size_t
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(245): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0,1,2>(std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *> &,std::integer_sequence<_Ty,0,1,2>)' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>,
1>            _Ty=size_t
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(242): note: while compiling class template member function 'void std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *) noexcept'
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(230): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *) noexcept' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(257): note: see reference to class template instantiation 'std::_LaunchPad<_Target>' being compiled
1>        with
1>        [
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thread(49): note: see reference to function template instantiation 'void std::_Launch<std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<_Ty>>>(_Thrd_t *,_Target &&)' being compiled
1>        with
1>        [
1>            _Ty=std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,
1>            _Target=std::unique_ptr<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>,std::default_delete<std::tuple<void (__cdecl RobocopyCopy::* )(std::string),std::basic_string<char,std::char_traits<char>,std::allocator<char>>,RobocopyCopy *>>>
1>        ]
1>c:\tetavi_main2\tv_apps\tv_world2\tv_logic_cpp\robocopycopy.cpp(73): note: see reference to function template instantiation 'std::thread::thread<void(__cdecl RobocopyCopy::* )(std::string),std::string&,RobocopyCopy*,void>(_Fn &&,std::string &,RobocopyCopy *&&)' being compiled
1>        with
1>        [
1>            _Fn=void (__cdecl RobocopyCopy::* )(std::string)
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): note: With the following template arguments:
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): note: '_Callable=void (__cdecl RobocopyCopy::* )(std::string)'
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\thr\xthread(238): note: '_Types={std::basic_string<char,std::char_traits<char>,std::allocator<char>>, RobocopyCopy *}'
1>Done building project "TV_Logic_CPP.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

What am I doing wrong?


问:
Flutter - How to download files in WebView?
I am using flutter_webview_plugin: ^0.3.8 but I have the same problem with webview_flutter: ^0.3.13.

In webview, I want to make use of a website which triggers a file download on successful completion of a captcha. However, I complete the captcha and nothing happens, no download.

Is there something in Flutter like a webview download listener ("webview.setDownloadListener")? I only need this for Android.

If not, is there a way of downloading files from a webview in Flutter?

答:
A similar issue can be found here!

You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews. It can recognize downloadable files in both Android (using setDownloadListener) and iOS platforms!

I report here the same answer that I gave to the similar issue:

To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen the onDownloadStart event!

Also, for example, on Android you need to add write permission inside your AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```

<p>Then, you need to ask permission using the permission_handler plugin. Instead, to effectively download your file, you can use the flutter_downloader plugin.</p>

<p>Here is a complete example using http://ovh.net/files/ (in particular, the http://ovh.net/files/1Mio.dat as URL) to test the download:</p>

<pre class="lang-dart prettyprint-override"><code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: true // optional: set false to disable printing logs to console
  );
  await Permission.storage.request();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "http://ovh.net/files/1Mio.dat",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useOnDownloadStart: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) {

            },
            onDownloadStart: (controller, url) async {
              print("onDownloadStart $url");
              final taskId = await FlutterDownloader.enqueue(
                url: url,
                savedDir: (await getExternalStorageDirectory()).path,
                showNotification: true, // show download progress in status bar (for Android)
                openFileFromNotification: true, // click on notification to open downloaded file (for Android)
              );
            },
          ))
        ])),
      ),
    );
  }
}
</code>```

Here, as you can see, I'm using also the path_provider plugin to get the folder where I want to save the file.

Body:
A similar issue can be found here!

You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews. It can recognize downloadable files in both Android (using setDownloadListener) and iOS platforms!

I report here the same answer that I gave to the similar issue:

To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen the onDownloadStart event!

Also, for example, on Android you need to add write permission inside your AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then, you need to ask permission using the permission_handler plugin. Instead, to effectively download your file, you can use the flutter_downloader plugin.

Here is a complete example using http://ovh.net/files/ (in particular, the http://ovh.net/files/1Mio.dat as URL) to test the download:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: true // optional: set false to disable printing logs to console
  );
  await Permission.storage.request();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "http://ovh.net/files/1Mio.dat",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useOnDownloadStart: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) {

            },
            onDownloadStart: (controller, url) async {
              print("onDownloadStart $url");
              final taskId = await FlutterDownloader.enqueue(
                url: url,
                savedDir: (await getExternalStorageDirectory()).path,
                showNotification: true, // show download progress in status bar (for Android)
                openFileFromNotification: true, // click on notification to open downloaded file (for Android)
              );
            },
          ))
        ])),
      ),
    );
  }
}

Here, as you can see, I'm using also the path_provider plugin to get the folder where I want to save the file.


问:
How to display array data from json field to the blade view?
I created a json field produce_stored to store array data.

Warehouse Table Structure

In the Warehouse Model I'm using $casts to store the array data

```<code>protected $casts = [
    'produce_stored' => 'array'
];
</code>```

In the WarehouseController - index method

```<code>$warehouses = DB::table('warehouses')
                ->join('regions', 'regions.id', '=', 'warehouses.region_id')
                ->join('districts', 'districts.id', '=', 'warehouses.district_id')
                ->join('users', 'users.id', '=', 'warehouses.agent_assigned')
                ->select(
                    'warehouses.id',
                    'warehouses.name as warehouseName',
                    'warehouses.ownership_type',
                    'warehouses.capacity',
                    'warehouses.produce_stored',  // json field with array data
                    'regions.name as regionName',
                    'districts.name as districtName',
                    'users.name as agent_assigned',
                    'warehouses.status'
                    )
                ->get();

return view('admin.warehouses.index', compact('warehouses'));
</code>```

In the blade view

```<code>{{ $warehouse->produce_stored }}
</code>```

This is the output in the browser

```<code>["1", "2"]
</code>```

When I try looping through the array to get the produce ids to load the produce names

```<code>@foreach ($warehouse->produceStored as $produce)
    {{$produce}}
@endforeach
</code>```

The above throws an error

```<code>Invalid argument supplied for foreach()
</code>```

How do I get the produce ids from the produce_stored field?

答:
you have two choices:

```<code> <?php $warehouse->produceStored = json_decode($warehouse->produceStored, false); ?>
</code>```

and then try

```<code>@foreach ($warehouse->produceStored as $produce)
    {{$produce}}
@endforeach
</code>```

2- like Autista_z said in comment:

```<code>$warehouses = Warehouse::query()
                ->join('regions', 'regions.id', '=', 'warehouses.region_id')
                ->join('districts', 'districts.id', '=', 'warehouses.district_id')
                ->join('users', 'users.id', '=', 'warehouses.agent_assigned')
                ->select(
                    'warehouses.id',
                    'warehouses.name as warehouseName',
                    'warehouses.ownership_type',
                    'warehouses.capacity',
                    'warehouses.produce_stored',  // json field with array data
                    'regions.name as regionName',
                    'districts.name as districtName',
                    'users.name as agent_assigned',
                    'warehouses.status'
                    )
                ->get();
</code>```

note: replace Warehouse with your model name if they are not the same...

Body:
I created a json field produce_stored to store array data.

Warehouse Table Structure

In the Warehouse Model I'm using $casts to store the array data

protected $casts = [
    'produce_stored' => 'array'
];

In the WarehouseController - index method

$warehouses = DB::table('warehouses')
                ->join('regions', 'regions.id', '=', 'warehouses.region_id')
                ->join('districts', 'districts.id', '=', 'warehouses.district_id')
                ->join('users', 'users.id', '=', 'warehouses.agent_assigned')
                ->select(
                    'warehouses.id',
                    'warehouses.name as warehouseName',
                    'warehouses.ownership_type',
                    'warehouses.capacity',
                    'warehouses.produce_stored',  // json field with array data
                    'regions.name as regionName',
                    'districts.name as districtName',
                    'users.name as agent_assigned',
                    'warehouses.status'
                    )
                ->get();

return view('admin.warehouses.index', compact('warehouses'));

In the blade view

{{ $warehouse->produce_stored }}

This is the output in the browser

["1", "2"]

When I try looping through the array to get the produce ids to load the produce names

@foreach ($warehouse->produceStored as $produce)
    {{$produce}}
@endforeach

The above throws an error

Invalid argument supplied for foreach()

How do I get the produce ids from the produce_stored field?

Body:
you have two choices:

 <?php $warehouse->produceStored = json_decode($warehouse->produceStored, false); ?>

and then try

@foreach ($warehouse->produceStored as $produce)
    {{$produce}}
@endforeach

2- like Autista_z said in comment:

$warehouses = Warehouse::query()
                ->join('regions', 'regions.id', '=', 'warehouses.region_id')
                ->join('districts', 'districts.id', '=', 'warehouses.district_id')
                ->join('users', 'users.id', '=', 'warehouses.agent_assigned')
                ->select(
                    'warehouses.id',
                    'warehouses.name as warehouseName',
                    'warehouses.ownership_type',
                    'warehouses.capacity',
                    'warehouses.produce_stored',  // json field with array data
                    'regions.name as regionName',
                    'districts.name as districtName',
                    'users.name as agent_assigned',
                    'warehouses.status'
                    )
                ->get();

note: replace Warehouse with your model name if they are not the same...


问:
Silence "Views without any layout constraints may clip their content" on a specific view controller that has preferredContentSize set
I have a view controller that's fixed size (it can not be resized). This specific view controller is presented as a sheet in a window, I disabled the resizing by setting preferredContentSize. Since it can't be resized anymore, I left the view without any constraint. However, when I build the app, I got a lot of warnings that says :

```<code>Views without any layout constraints may clip their content or overlap other views.
</code>```

I do know that if you don't add any constraints in a standard window it will clip when it is resized. However, resizing is disabled on my specific window so that I know it won't happen. Is there a way to silence this warning? There are a lot of views on this specific view controller and it's blocking other useful warnings that I may encounter in the issues navigator.

This view controller is presented through a "Sheet" segue.

答: Since no one answered this, here is how I fixed it. For each view on the form change the Layout option from Automatic to "Translates Mask Into Contraints". If you want it anchored to the upper left corner, select the top an left red handles and leave the lower and right unchecked.</p>

Body:
I have a view controller that's fixed size (it can not be resized). This specific view controller is presented as a sheet in a window, I disabled the resizing by setting preferredContentSize. Since it can't be resized anymore, I left the view without any constraint. However, when I build the app, I got a lot of warnings that says :

Views without any layout constraints may clip their content or overlap other views.

I do know that if you don't add any constraints in a standard window it will clip when it is resized. However, resizing is disabled on my specific window so that I know it won't happen. Is there a way to silence this warning? There are a lot of views on this specific view controller and it's blocking other useful warnings that I may encounter in the issues navigator.

This view controller is presented through a "Sheet" segue.


问:
Data warehouse - OLAP vs OLTP vs Dimentional model vs Relational model
I kind of know the difference between OLAP and OLTP, and the difference between Dimentional data model vs Relational data model. But how are these 4 terms related with each other? Is OLAP usually "applied" with dimentaional data model design? I'm struggled to link these terms toghether..

Thanks!

答:
In a nutshell, and without going into much detail, it boils down to:

OLAP: analytical queries. Usually related to Kimball's dimensional model, as well as other data warehousing models (Inmon, for example). It usually fetches large volumes of data, which are then aggregated into a report. Response times are long, usually seconds or even minutes. That's ok, as users are usually ok with waiting for a report to finish rendering.

OLTP: transactional queries. Usually row by row queries used by applications (fetch profile information for current user; insert 1 row into messages table, etc). Low latency, quick response times, but not suitable for large volumes of data. Often used against 3rd normal form databases.


问:
Should GC.SuppressFinalize be called on objects that do not have a finalizer?
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not. </p>

<p>Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined? </p>

答:
There is always a finalizer in IL - System.Object.Finalize() exists in every class, so if you make a custom class, it has a finalizer you want to suppress.  That being said, not all objects are put on the finalization queue, so you only techncially should need to suppress finalization if you implement your own finalizer.

If you're implementing IDisposable to wrap unmanaged resources, you should include a finalizer, and you should prevent this from running, since in theory you're doing the cleanup already when Dispose is called.

ContentLicense: CC BY-SA 2.5

Body:
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not.

Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined?

LastEditorDisplayName: Mitch Wheat


问:
How to achieve authentication with Twitter in Kivy App without manual intervention
I am trying to build a simple kivy app for mobiles / desktops which uses Twitter to authenticate users at the login screen. I am using Tweepy with Python to authenticate the users.

The authentication process works fine when I run the code from command line.  It generates a redirect url which I open in a browser to authenticate the user and then it generates a pin. The pin is copied and entered into the command line interface of the parent Python program as an input and the authentication process completes successfully.

Is there a way to copy the generated pin from the browser's html content and directly use it as an input in the program without any human intervention? This would enhance the user experience and people would not get confused as to what to do with the PIN. I was playing around with the weburl, urllib and htmlparser libraries in Python and was wondering if there any way to achieve this behaviour?

Please help.

答: You need to create an intermediate web app which runs on a server with a static ip address. The authentication code / PIN should be returned by Twitter to this intermediate app, which in turn can exchange it with your mobile/desktop app.</p>


问:
Ansible copy files with wildcard?
In my files directory I have various files, with a similar name structure:

```<code>data-example.zip
data-precise.zip
data-arbitrary.zip
data-collected.zip
</code>```

I would like to transfer all of these files in the /tmp directory of my remote machine using Ansible without specifying each file name explicitly.
In other words I would like to transfer every file that stars with "data-".

What is the correct way to do that? In a similar thread, someone suggested the with_fileglob keyword, - but I couldn't get that to work.
Can someone provide me an example on how to accomplish said task?

答:
Method 1: Find all files, store them in a variable and copy them to destination.

```<code>- hosts: lnx
  tasks:
    - find: paths="/source/path" recurse=yes patterns="data*"
      register: files_to_copy
    - copy: src={{ item.path }} dest=/dear/dir
      owner: root
      mode: 0775
      with_items: "{{ files_to_copy.files }}"
</code>```

Use remote_src: yes to copy file in remote machine from one path to another.

Ansible documentation

Method 2: Fileglob

Fileglob allows using patterns to match files and directories

```<code>- name: Copy each file over that matches the given pattern
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: "root"
    mode: 0600
  with_fileglob:
    - "/playbooks/files/fooapp/*"
</code>```

Ansible documentation

Title: Ansible copy files with wildcard?

Body:
In my files directory I have various files, with a similar name structure:

data-example.zip
data-precise.zip
data-arbitrary.zip
data-collected.zip

I would like to transfer all of these files in the /tmp directory of my remote machine using Ansible without specifying each file name explicitly.
In other words I would like to transfer every file that stars with "data-".

What is the correct way to do that? In a similar thread, someone suggested the with_fileglob keyword, - but I couldn't get that to work.
Can someone provide me an example on how to accomplish said task?

Body:
Method 1: Find all files, store them in a variable and copy them to destination.

- hosts: lnx
  tasks:
    - find: paths="/source/path" recurse=yes patterns="data*"
      register: files_to_copy
    - copy: src={{ item.path }} dest=/dear/dir
      owner: root
      mode: 0775
      with_items: "{{ files_to_copy.files }}"

Use remote_src: yes to copy file in remote machine from one path to another.

Ansible documentation

Method 2: Fileglob

Fileglob allows using patterns to match files and directories

- name: Copy each file over that matches the given pattern
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: "root"
    mode: 0600
  with_fileglob:
    - "/playbooks/files/fooapp/*"

Ansible documentation


问:
Access-Control-Allow-Origin error on axios request even after enabling express CORS middleware
I am recently deployed my API on Heroku, and I'm having some CORS related issues. I've seen many other posts that  talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

The actual post request from the frontend looks like this:

```<code>const axiosConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      };
  await axios
    .post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
    .then((_) => Message.success("Successfully registered! "))
    .catch((error) => Message.error(error.message));
</code>```

and my app.js on the backend looks like this.

```<code>const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");

const app = express();
app.use(
  cors({
    allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
    exposedHeaders: ["authorization"], // you can change the headers
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
  })
);

// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");

const port = process.env.PORT || 8080;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
      cb(null, "temp-storage/cover/");
    } else {
      cb(null, "temp-storage/");
    }
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
  },
});

const upload = multer({
  // dest: "temp-storage/",
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
  },
});

// view engine setup

app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ error: err.message });
});

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "build", "index.html"));
});

app.listen(port, console.log(`MyApp backend started on port ${port}!`));

module.exports = app;
</code>```

I'd really appreciate it if someone could help me out!

答:
I generally use CORS module for cross origin requests how ever below code also works fine of you dont't want to add cors</p>

```<code>app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin",*");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});
</code>```

Body:
I am recently deployed my API on Heroku, and I'm having some CORS related issues. I've seen many other posts that  talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

The actual post request from the frontend looks like this:

const axiosConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      };
  await axios
    .post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
    .then((_) => Message.success("Successfully registered! "))
    .catch((error) => Message.error(error.message));

and my app.js on the backend looks like this.

const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");

const app = express();
app.use(
  cors({
    allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
    exposedHeaders: ["authorization"], // you can change the headers
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
  })
);

// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");

const port = process.env.PORT || 8080;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
      cb(null, "temp-storage/cover/");
    } else {
      cb(null, "temp-storage/");
    }
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
  },
});

const upload = multer({
  // dest: "temp-storage/",
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
  },
});

// view engine setup

app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ error: err.message });
});

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "build", "index.html"));
});

app.listen(port, console.log(`MyApp backend started on port ${port}!`));

module.exports = app;

I'd really appreciate it if someone could help me out!

Body:
I generally use CORS module for cross origin requests how ever below code also works fine of you dont't want to add cors

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin",*");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});


问:
Button click issue
I am trying to refer the button to another page using :to. It doesn't do anything at the moment. For testing purposes I'm now trying to refer to the existing /learn page.

My code:

```<code>  <b-navbar-item tag="div">
                <div class="buttons">
                    <a class="button is-primary"
                v-for="item in menuItems"
                :key="item.title"
                :to="item.link">
                        {{item.title}}
                        </a>
                </div>
            </b-navbar-item>
</code>```

```<code>export default {
    data() {
      return {
           menuItems: [
       { title: 'Login', link: '/learn'},
       { title: 'Sign up', link: '/learn'},
       { title: 'Logout', link: '/learn'},

      ]
      }
</code>```

答:
Are you using Vue Router? I'm not a Vue.js expert, but I believe the v-bind:to attribute is used on <router-link> components. For regular links using the  tag, you can use v-bind:href or :href to assign the link:

new Vue({
  el: '#app',
  data: {
    menuItems: [{
        title: 'Login',
        link: '/link1'
      },
      {
        title: 'Sign up',
        link: '/link2'
      },
      {
        title: 'Logout',
        link: '/link3'
      },
    ]
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue"></script>
<div id="app">
  <div class="buttons">

      {{item.title}}

  </div>
</div></code>```

Title: Button click issue

Body:
I am trying to refer the button to another page using :to. It doesn't do anything at the moment. For testing purposes I'm now trying to refer to the existing /learn page.

My code:

                        {{item.title}}

export default {
    data() {
      return {
           menuItems: [
       { title: 'Login', link: '/learn'},
       { title: 'Sign up', link: '/learn'},
       { title: 'Logout', link: '/learn'},

      ]
      }

Body:
Are you using Vue Router? I'm not a Vue.js expert, but I believe the v-bind:to attribute is used on <router-link> components. For regular links using the <a> tag, you can use v-bind:href or :href to assign the link:

new Vue({
  el: '#app',
  data: {
    menuItems: [{
        title: 'Login',
        link: '/link1'
      },
      {
        title: 'Sign up',
        link: '/link2'
      },
      {
        title: 'Logout',
        link: '/link3'
      },
    ]
  }
})

<script src="https://unpkg.com/vue"></script>
<div id="app">
  <div class="buttons">
    <a class="button is-primary" v-for="item in menuItems" :key="item.title" :href="item.link">
      {{item.title}}
    </a>
  </div>
</div>


问:
How can I extract links using R from a webpage that is javascript enabled
I am trying to extract all the links on a webpage: "https://coronavirus.data.gov.uk/archive/"

For other webpages, I have used the following approach with the rvest pacakge, that has worked well:

```<code>url_page<-"https://coronavirus.data.gov.uk/archive/"
webpage<-read_html(url_page)
all_links<-html_attr(html_nodes(webpage, "a"), "href")
</code>```

However this produces a null value for this webpage. For example, it works well for "https://www.gov.uk/guidance/coronavirus-covid-19-information-for-the-public"

I think it might have something to do with the webpage being javascript enabled. Does anyone know how to extract the links for a webpage like this using R?

答:
I believe you are using rvest package.

```<code>url = read_html("https://coronavirus.data.gov.uk/archive/")
url %>%
  html_nodes('.govuk-template__body') %>%
  html_text()
</code>```

Returns error message on running javascript.

You might  use RSelenium package as solution which enables to scrape data with browser use to load the table first.

Body:
I am trying to extract all the links on a webpage: "https://coronavirus.data.gov.uk/archive/"

For other webpages, I have used the following approach with the rvest pacakge, that has worked well:

url_page<-"https://coronavirus.data.gov.uk/archive/"
webpage<-read_html(url_page)
all_links<-html_attr(html_nodes(webpage, "a"), "href")

However this produces a null value for this webpage. For example, it works well for "https://www.gov.uk/guidance/coronavirus-covid-19-information-for-the-public"

I think it might have something to do with the webpage being javascript enabled. Does anyone know how to extract the links for a webpage like this using R?

Body:
I believe you are using rvest package.

url = read_html("https://coronavirus.data.gov.uk/archive/")
url %>%
  html_nodes('.govuk-template__body') %>%
  html_text()

Returns error message on running javascript.

You might  use RSelenium package as solution which enables to scrape data with browser use to load the table first.