问:
Firebase Cloud Messaging with Android
I want to integrate Firebase cloud messaging with Android. I have created my account on Firebase and integrated with the app and have sent a message from Firebase console. The app received the message. So far, things like this seem working.

My question is that how can I connect Firebase with my own database server, which is consisting of MongoDB, to check for the data of users against to whom a notification is to be sent? Can some one guide me please?

答:
There are quite a number of steps, it is probably too long to post here, but since you just asked for guidance, I'll try to run through the steps involved.

Your Android app will need to send its FCM token the server running your MongoDB instance. Referencing this FCM documentation page, you'll need to implement sendRegistrationToServer(refreshedToken); in the onTokenRefresh() method.

Your server will need to be listening for clients sending their FCM token. This could be an HTTP endpoint listening for POST requests with a client token and username. It can then store the details in your database. (Remember to use HTTPS where possible.)

Enable the Cloud Messaging API: https://console.developers.google.com/apis/api/fcm.googleapis.com/overview?project=insert-project-id-here

You can send FCM messages from the server running MongoDB using the Firebase HTTP v1 API, but first you'll need to authorize your server to do so. Instructions here. You will get an authorisation token that needs to be included in the HTTP header of all API requests.

Once you have a valid token you can send an HTTP POST request to https://fcm.googleapis.com/v1/{parent=projects/*}/messages:send, where the body contains details of the message. This page contains a description of the API endpoint. This page contains a description of the message body to send.

As a brief (currently untested) example of a POST request. If you're project id was fcm-test-12345, you would make a POST request to:

https://fcm.googleapis.com/v1/projects/fcm-test-12345/messages:send

The header should contain:

```<code>Authorization: Bearer <your access token>
Content-Type: application/json
</code>```

And the body would be something like this:

```<code>{
  "message": {
    "data": { "key": "value" }, // optional data to send to client.
    "notification": {
        "title": "Notification title",
        "body": "Notification body"
    },
    "token": "<client device token from MongoDB>"
  }
}
</code>```

Title: Firebase Cloud Messaging with Android

Body:
There are quite a number of steps, it is probably too long to post here, but since you just asked for guidance, I'll try to run through the steps involved.

Your Android app will need to send its FCM token the server running your MongoDB instance. Referencing this FCM documentation page, you'll need to implement sendRegistrationToServer(refreshedToken); in the onTokenRefresh() method.

Your server will need to be listening for clients sending their FCM token. This could be an HTTP endpoint listening for POST requests with a client token and username. It can then store the details in your database. (Remember to use HTTPS where possible.)

Enable the Cloud Messaging API: https://console.developers.google.com/apis/api/fcm.googleapis.com/overview?project=insert-project-id-here

You can send FCM messages from the server running MongoDB using the Firebase HTTP v1 API, but first you'll need to authorize your server to do so. Instructions here. You will get an authorisation token that needs to be included in the HTTP header of all API requests.

Once you have a valid token you can send an HTTP POST request to https://fcm.googleapis.com/v1/{parent=projects/*}/messages:send, where the body contains details of the message. This page contains a description of the API endpoint. This page contains a description of the message body to send.

As a brief (currently untested) example of a POST request. If you're project id was fcm-test-12345, you would make a POST request to:

https://fcm.googleapis.com/v1/projects/fcm-test-12345/messages:send

The header should contain:

Authorization: Bearer <your access token>
Content-Type: application/json

And the body would be something like this:

{
  "message": {
    "data": { "key": "value" }, // optional data to send to client.
    "notification": {
        "title": "Notification title",
        "body": "Notification body"
    },
    "token": "<client device token from MongoDB>"
  }
}


来源: stackexchange

问:
using django model outside of the django framework
I have a django application that is working fine.  I want to be able to leverage the model to access the database from another (standalone) python app.  Here is what I have (that doesn't work.)

```<code>import sys
import os

sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor"))
os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings'
import models
    config = models.SystemConfiguration.objects.filter(idSystemConfiguration=1)
    config = config[0]
    for x in config.__dict__:
      print x
</code>```

Here is the error I get:

```<code>  File "/home/pi/garageMonitor/django/lib/webWatcher.py", line 14, in <module>
    import models
  File "/home/pi/garageMonitor/django/garageMonitor/models.py", line 11, in <module>
    class DoorClosing(models.Model):
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 131, in __new__
    'app.' % (new_class.__name__, model_module.__name__)
django.core.exceptions.ImproperlyConfigured: Unable to detect the app label for model "DoorClosing
</code>```

DoorClosing is a class in my models.py file.  Similar code works within the django framework.  What am I missing?

答:
Please refer to this post for working version for this problem in latest Django version.
see https://stackoverflow.com/a/46050808/1698030

Quoting the solution here:

```<code>import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)
</code>```

Put your app name and any other apps you have on your project under 'INSTALLED_APPS'

ContentLicense: CC BY-SA 3.0

Body:
I have a django application that is working fine.  I want to be able to leverage the model to access the database from another (standalone) python app.  Here is what I have (that doesn't work.)

import sys
import os

sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor"))
os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings'
import models
    config = models.SystemConfiguration.objects.filter(idSystemConfiguration=1)
    config = config[0]
    for x in config.__dict__:
      print x

Here is the error I get:

  File "/home/pi/garageMonitor/django/lib/webWatcher.py", line 14, in <module>
    import models
  File "/home/pi/garageMonitor/django/garageMonitor/models.py", line 11, in <module>
    class DoorClosing(models.Model):
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 131, in __new__
    'app.' % (new_class.__name__, model_module.__name__)
django.core.exceptions.ImproperlyConfigured: Unable to detect the app label for model "DoorClosing

DoorClosing is a class in my models.py file.  Similar code works within the django framework.  What am I missing?

Body:
Please refer to this post for working version for this problem in latest Django version.
see https://stackoverflow.com/a/46050808/1698030

Quoting the solution here:

import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)

Put your app name and any other apps you have on your project under 'INSTALLED_APPS'


问:
RecyclerView vs. ListView
From android developer (Creating Lists and Cards):

The RecyclerView widget is a more advanced and flexible version of
  ListView.

Okay, it sounds cool, but when I saw this example picture, I got really confused about the difference between these two.

The picture above can be easily created by ListView using custom adapter.

So, in what situation should one use RecyclerView?

答:
Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.

You find it harder because you are thinking just with the Android library in mind.

Today there exists a lot of options that help you build your own adapters, making it easy to build lists and grids of dynamic items that you can pick, reorder, use animation, dividers, add footers, headers, etc, etc.

Don't get scared and give a try to RecyclerView, you can starting to love it making a list of 100 items downloaded from the web (like facebook news) in a ListView and a RecyclerView, you will see the difference in the UX (user experience) when you try to scroll, probably the test app will stop before you can even do it.

I recommend you to check this two libraries for making easy adapters:

FastAdapter by mikepenz

FlexibleAdapter by davideas

ContentLicense: CC BY-SA 4.0

Title: RecyclerView vs. ListView


问:
Eclipse - Add Server - Next Button is disabled when I select a specific Tomcat (e.g tomcat8)
I open Servers view, right click and go to new->server menu.

When I select Tomcat 6 or Tomcat 7 the next button works well however when I select Tomcat 8 the next button is greyed out.

How can I add a tomcat 8 in this case?

答:
It is a bug in Eclipse.
You can follow following steps for overcome this problem.

Close Eclipse

Go {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings

delete the following two files:

org.eclipse.wst.server.core.prefs

org.eclipse.jst.server.tomcat.core.prefs

Restart Eclipse


问:
Consul cluster automatic bootstrap on docker
I am working on conf management tools like etcd and consul. As I know etcd has discovery mechanism. I wonder does consul have something like that?

I am working on official consul docker image and when I set advertise IP's and join IP's there is no problem but I don't want to do this manually. Docker containers' Ip could change or some nodes could crash and you need new node to replace it. The situations like that how could I manage? I mean is there a possibility to join cluster without exactly know the nodes' Ip in the cluster?

答:
You could start consul with docker swarm inside a subnet. Like this:

```<code>docker network create --driver overlay --subnet 172.20.0.0/24 consul-net

docker service create \
  --name consul \
  --publish 8500:8500 \
  --network consul-net \
  --replicas 3 \
  -e 'CONSUL_BIND_INTERFACE=eth0' \
  -e ‘CONSUL_LOCAL_CONFIG={“skip_leave_on_interrupt”:true}’ \
consul agent -server -ui \
-client=0.0.0.0 \
-bootstrap-expect=3 \
-data-dir=consul/data \
-retry-join 172.20.0.3 \
-retry-join 172.20.0.4 \
-retry-join 172.20.0.5 \
-retry-interval 5s
</code>```

You can also see this consul issue #66

Body:
You could start consul with docker swarm inside a subnet. Like this:

docker network create --driver overlay --subnet 172.20.0.0/24 consul-net

docker service create \
  --name consul \
  --publish 8500:8500 \
  --network consul-net \
  --replicas 3 \
  -e 'CONSUL_BIND_INTERFACE=eth0' \
  -e ‘CONSUL_LOCAL_CONFIG={“skip_leave_on_interrupt”:true}’ \
consul agent -server -ui \
-client=0.0.0.0 \
-bootstrap-expect=3 \
-data-dir=consul/data \
-retry-join 172.20.0.3 \
-retry-join 172.20.0.4 \
-retry-join 172.20.0.5 \
-retry-interval 5s

You can also see this consul issue #66


问:
Find if the machine is multi homed via Java
Is there an in-built programmatic way to find out if the machine is multi-homed or not? I have the snippet below which can do the task but looks cumbersome. Is there a better way to do this?

```<code>int count = 0;
    try {
          InetAddress localhost = InetAddress.getLocalHost();
          InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
          if (allMyIps != null && allMyIps.length > 1) {
              for (int i = 0; i < allMyIps.length; i++) {
                  if (allMyIps[i].isLoopbackAddress() == false) count++;
              }
          }
          if (count > 1) System.out.println("Multihomed");
        } catch (UnknownHostException e) {
          e.printStackTrace();
        }
</code>```

I am skeptical about this since all hybrid NIC have a IpV6 and an IPv4 configured on it (at least in windows 7) by default. Hence these come out as an multi homed. Is there an effective way to do this?

答:
You could use the "NetworkInterface" class in java. If there are more than one interfaces other than loopback interface, its multi-homed.</p>

```<code>Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
int count = 0;
while (ifs.hasMoreElements()) {
    if (count > 1) {
       break;
    }

    if(!ifs.nextElement().isLoopback()) {
        count++;
    }
 }

 System.out.println(count > 1 ? "Multi-homed" : "Not Multi-homed");
</code>```

Body:
Is there an in-built programmatic way to find out if the machine is multi-homed or not? I have the snippet below which can do the task but looks cumbersome. Is there a better way to do this?

int count = 0;
    try {
          InetAddress localhost = InetAddress.getLocalHost();
          InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
          if (allMyIps != null && allMyIps.length > 1) {
              for (int i = 0; i < allMyIps.length; i++) {
                  if (allMyIps[i].isLoopbackAddress() == false) count++;
              }
          }
          if (count > 1) System.out.println("Multihomed");
        } catch (UnknownHostException e) {
          e.printStackTrace();
        }

I am skeptical about this since all hybrid NIC have a IpV6 and an IPv4 configured on it (at least in windows 7) by default. Hence these come out as an multi homed. Is there an effective way to do this?

Body:
You could use the "NetworkInterface" class in java. If there are more than one interfaces other than loopback interface, its multi-homed.

Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
int count = 0;
while (ifs.hasMoreElements()) {
    if (count > 1) {
       break;
    }

    if(!ifs.nextElement().isLoopback()) {
        count++;
    }
 }

 System.out.println(count > 1 ? "Multi-homed" : "Not Multi-homed");


问:
C#: How to access an Excel cell?
I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.

Currently I am at this stage with the following code but still I am getting errors:

```<code>Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
                new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
    // is there already such a file ?
    if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
    {
        // then go and load this into excel
        Microsoft.Office.Interop.Excel.Workbooks.Open(
            "C:\\csharp\\errorreport1.xls", true, false,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    }
    else
    {
        // if not go and create a workbook:
        newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
            (Microsoft.Office.Interop.Excel._Worksheet)
                newWorkBook.Worksheets.get_Item(1);
    }
i++;
j = 1;

j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
                                + rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";
</code>```

These are the top 2 errors I am getting:

```<code>Error 1 An object reference is required for the nonstatic field, method, or
        property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
        object, object, object, object, object, object, object, object, object,
        object, object, object, object)'

Error 2 The name 'newWorkbook' does not exist in the current context
</code>```

答:
I think, that you have to declare the associated sheet!

Try something like this

```<code>objsheet(1).Cells[i,j].Value;
</code>```

OwnerDisplayName: tksy

ContentLicense: CC BY-SA 2.5

Title: C#: How to access an Excel cell?

Body:
I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.

Currently I am at this stage with the following code but still I am getting errors:

Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
                new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
    // is there already such a file ?
    if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
    {
        // then go and load this into excel
        Microsoft.Office.Interop.Excel.Workbooks.Open(
            "C:\\csharp\\errorreport1.xls", true, false,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    }
    else
    {
        // if not go and create a workbook:
        newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
            (Microsoft.Office.Interop.Excel._Worksheet)
                newWorkBook.Worksheets.get_Item(1);
    }
i++;
j = 1;

j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
                                + rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";

These are the top 2 errors I am getting:

Error 1 An object reference is required for the nonstatic field, method, or
        property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
        object, object, object, object, object, object, object, object, object,
        object, object, object, object)'

Error 2 The name 'newWorkbook' does not exist in the current context

LastEditorDisplayName: tksy

Body:
I think, that you have to declare the associated sheet!

Try something like this

objsheet(1).Cells[i,j].Value;


问:
How do I concatenate strings within an array of objects nested inside another array of objects?
Here's the JSON object I'm working with:

```<code>var object = {
    "units": [
        { "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
        { "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
    ]
}
</code>```

What's the most performative way of concatenating all of the fuelDesc strings into one string, separated by ,?

NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.

The result would be "Coal,Pipeline Natural Gas".

I did this:

```<code>var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
    var mergedFuels = [].concat.apply([], units[i].fuels)
    var unitFuelStr = mergedFuels.map(function (mergedFuels) {
        return mergedFuels["fuelDesc"];
    }).join(",");
    fuelsStr += unitFuelStr;
}
</code>```

答:
Based on assumption that you always have one element inside the fuels array. you can use .map and .join together

var myobject = {"units":[{"unitNum": "1","fuels":[{"fuelDesc":"Coal"}]},
{"unitNum": "2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]};

var result = myobject.units.map(function(elem){
    return elem.fuels[0].fuelDesc;
}).join(",");

console.log(result);```

Body:
Here's the JSON object I'm working with:

var object = {
    "units": [
        { "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
        { "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
    ]
}

What's the most performative way of concatenating all of the fuelDesc strings into one string, separated by ,?

NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.

The result would be "Coal,Pipeline Natural Gas".

I did this:

var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
    var mergedFuels = [].concat.apply([], units[i].fuels)
    var unitFuelStr = mergedFuels.map(function (mergedFuels) {
        return mergedFuels["fuelDesc"];
    }).join(",");
    fuelsStr += unitFuelStr;
}


问:
Publishing .NET Core web api/angular application to IIS
I am having issues deploying my .NET Core 2.0 project to IIS

I followed the instructions listed here:
https://learn.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x#common-errors

I publish using Visual  Studios

When I try to access my published project via the browser I get this error
message

Looking at the Event Viewer on my IIS server I see the following error

I installed the .NET SDK so the dotnet command is available at the terminal.

I added a global.json file that specifies the correct dotnet SDK per the instructions found in this link: https://github.com/aspnet/JavaScriptServices/issues/495 but that did not resolve the issue.

How can I publish my .NET Core 2.0 WebAPI+Angular4 project to IIS?

EDIT:

I can launch the application manually with dotnet MPMWebsiteLogins.dll

EDIT 2:

I updated my web.config and explicitly specified my path for dotnet.exe and MPMWebsiteLogins.dll

<aspNetCore processPath="C:\Program Files\dotnet\dotnet.exe" arguments="C:\inetpub\WebApps\HPIssuesUtilityV2\MPMWebsiteLogins.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

I am now getting this error in my event viewer:

Application 'MACHINE/WEBROOT/APPHOST/MPMWEBSITELOGINS' with physical root 'C:\inetpub\WebApps\HPIssuesUtilityV2\' created process with commandline 'C:\Program Files\dotnet\dotnet.exe C:\inetpub\WebApps\HPIssuesUtilityV2\MPMWebsiteLogins.dll' but failed to listen on the given port '1989'

答: Seems like you are missing the ACNM module for reverse proxy. If you install the .Net core windows server hosting bundle it should install all the require components for you. You can double check by checking your IIS modules, it should have ASPnetcore.</p>


问:
Keyframe animating border-bottom color
I've read over other questions/answers that address keyframes (as well as articles online) and it really seems to me my code should work...but nothing happens. I'm not using any vendor prefixes because from caniuse it seems they aren't necessary anymore.
`</p>

```<code>@keyframe colorWash {
  from{border-bottom:25px solid #111;}
  50%{border-bottom: 25px solid #333;}
  to{border-bottom:25px solid #777;}
}

#bro {
  padding:2rem;
  background-color:#999;
  border-bottom: 25px solid #111;
  animation: colorWash 10s infinite;
}
</code>```

答:
Except for one minor detail (which, in CSS, matters) your animation works:

it's not @keyframe, but @keyframes

Now, since you specified it should loop infinitely, I assume you want it smooth. Therefore, you probably want to match from with to (so the transition between end and start is seamless. I also shortened the duration, so it's easier to observe.

It's also advisable to only specify the property to be animated in @keyframes. In your case, border-bottom-color:

@keyframes colorWash {
  from {border-bottom-color: #111;}
  42%{border-bottom-color: #777;}
  to {border-bottom-color: #111;}
}

#bro {
  padding:2rem;
  background-color:#999;
  border-bottom: 25px solid;
  animation: colorWash 3s infinite;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bro"></div></code>```

Title: Keyframe animating border-bottom color

Body:
I've read over other questions/answers that address keyframes (as well as articles online) and it really seems to me my code should work...but nothing happens. I'm not using any vendor prefixes because from caniuse it seems they aren't necessary anymore.
`

@keyframe colorWash {
  from{border-bottom:25px solid #111;}
  50%{border-bottom: 25px solid #333;}
  to{border-bottom:25px solid #777;}
}

#bro {
  padding:2rem;
  background-color:#999;
  border-bottom: 25px solid #111;
  animation: colorWash 10s infinite;
}

Body:
Except for one minor detail (which, in CSS, matters) your animation works:

it's not @keyframe, but @keyframes

Now, since you specified it should loop infinitely, I assume you want it smooth. Therefore, you probably want to match from with to (so the transition between end and start is seamless. I also shortened the duration, so it's easier to observe.

It's also advisable to only specify the property to be animated in @keyframes. In your case, border-bottom-color:

@keyframes colorWash {
  from {border-bottom-color: #111;}
  42%{border-bottom-color: #777;}
  to {border-bottom-color: #111;}
}

#bro {
  padding:2rem;
  background-color:#999;
  border-bottom: 25px solid;
  animation: colorWash 3s infinite;
  }

<div id="bro"></div>


问:
dynamic invoke throws error "Object of type 'myObject' can not be converted to type 'myObject' "
I created an object of a dynamically created type and i'm attempting to invoke a runtime loaded function.

The invoke call exceptions with:
{System.ArgumentException: Object of type 'UserClasses.re_Constituent' cannot be converted to type 'UserClasses.re_Constituent'.}

(yes those 2 classes are the same)

the code for the class, and the code for the invoked function been previously generated and compiled as per https://stackoverflow.com/a/3024112/432976

Does anyone know the source of the error?

The following code exceptions at the magicValue Invoke()

```<code>namespace myTest
{
  internal class Program
  {
    Main(){
      //pseudoCode
        BuildTypes();
        {Type myType,MethodInfo myMethod} = factory.getType("re_Constituent");

      //actual code that exceptions
        Node result = (Node) JSON.Deserialize(textstream,myType);
        object magicValue = myMethodInfo.Invoke(null,new object[]{result});
    }
}
namespace UserClasses
{
  public abstract class Node
  {}
}
</code>```

inspecing when paused at the invoke line of code reveals:

myMethodInfo is:
{System.Collections.Generic.List`1[UserClasses.Node] ConvertToCore(UserClasses.re_Constituent)}

the type of the parameter expected by the methodInfo is :
"UserClasses.re_Constituent, dynamicGen_reApi_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

the type passed to the JSON de-serializer (Jil) is listed as:
"UserClasses.re_Constituent, dynamicGen_reApi_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

result.GetType().AssemblyQualifiedName:
"UserClasses.re_Constituent, dynamicGen_reApi_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

re_Constituent is defined in a separate dynamically loaded dll.

```<code>namespace UserClasses
{
  public class re_Constituent : Node
  {
    public string id;
    ... other fields
  }
}
</code>```

the code for the function is found in another runtime loaded dll:

```<code>namespace UserClasses
{
  public static class MyExtensions
  {
    public static List<Node> ConvertToCore(this re_Constituent node)
    {
      return new List<Node>()
      {
        new Node(); // actual code is more complex here
      };
    }
  }
}
</code>```

I noticed something funny with my dynamic generation / loading by iterating all classes in all assemblies loaded, which shows that there were 2 copies of the built assembly in memory:

```<code>foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
    if(!assembly.GetName().Name.StartsWith("System"))
    foreach (Type type in assembly.GetTypes())
    {
        if(type.FullName.Name.StartsWith("System"))
            Console.WriteLine(type+":"+assembly.GetName().Name);
    }
}
</code>```

答:
When you compile code, the classes are not made available to the general type resolution system until they are loaded. To resolve this issue  https://stackoverflow.com/a/3024112/432976
has the code for compiling end with:

```<code>    AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName());
    return results.CompiledAssembly;
</code>```

The problem is that the assembly read returned from the .Load call is not the same object as the already in-memory assembly from the compilation results.

My problem was that i was examining the returned assembly for types, and caching them for future use, which meant that my version of re_constituent was indeed different from the version of re_constituent that the type system knew about.

To fix this problem, make sure that there is only 1 assembly version exposed to the user code by returning the Loaded version:

```<code> return AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName());
</code>```

Body:
I created an object of a dynamically created type and i'm attempting to invoke a runtime loaded function.

The invoke call exceptions with:
{System.ArgumentException: Object of type 'UserClasses.re_Constituent' cannot be converted to type 'UserClasses.re_Constituent'.}

(yes those 2 classes are the same)

the code for the class, and the code for the invoked function been previously generated and compiled as per https://stackoverflow.com/a/3024112/432976

Does anyone know the source of the error?

The following code exceptions at the magicValue Invoke()

namespace myTest
{
  internal class Program
  {
    Main(){
      //pseudoCode
        BuildTypes();
        {Type myType,MethodInfo myMethod} = factory.getType("re_Constituent");

      //actual code that exceptions
        Node result = (Node) JSON.Deserialize(textstream,myType);
        object magicValue = myMethodInfo.Invoke(null,new object[]{result});
    }
}
namespace UserClasses
{
  public abstract class Node
  {}
}

inspecing when paused at the invoke line of code reveals:

myMethodInfo is:
{System.Collections.Generic.List`1[UserClasses.Node] ConvertToCore(UserClasses.re_Constituent)}

the type of the parameter expected by the methodInfo is :
"UserClasses.re_Constituent, dynamicGen_reApi_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

the type passed to the JSON de-serializer (Jil) is listed as:
"UserClasses.re_Constituent, dynamicGen_reApi_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

result.GetType().AssemblyQualifiedName:
"UserClasses.re_Constituent, dynamicGen_reApi_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

re_Constituent is defined in a separate dynamically loaded dll.

namespace UserClasses
{
  public class re_Constituent : Node
  {
    public string id;
    ... other fields
  }
}

the code for the function is found in another runtime loaded dll:

namespace UserClasses
{
  public static class MyExtensions
  {
    public static List<Node> ConvertToCore(this re_Constituent node)
    {
      return new List<Node>()
      {
        new Node(); // actual code is more complex here
      };
    }
  }
}

I noticed something funny with my dynamic generation / loading by iterating all classes in all assemblies loaded, which shows that there were 2 copies of the built assembly in memory:

foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
    if(!assembly.GetName().Name.StartsWith("System"))
    foreach (Type type in assembly.GetTypes())
    {
        if(type.FullName.Name.StartsWith("System"))
            Console.WriteLine(type+":"+assembly.GetName().Name);
    }
}

Body:
When you compile code, the classes are not made available to the general type resolution system until they are loaded. To resolve this issue  https://stackoverflow.com/a/3024112/432976
has the code for compiling end with:

    AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName());
    return results.CompiledAssembly;

The problem is that the assembly read returned from the .Load call is not the same object as the already in-memory assembly from the compilation results.

My problem was that i was examining the returned assembly for types, and caching them for future use, which meant that my version of re_constituent was indeed different from the version of re_constituent that the type system knew about.

To fix this problem, make sure that there is only 1 assembly version exposed to the user code by returning the Loaded version:

 return AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName());


问:
How can i repeat a script?
i've search for command or solution to repeat a script after n times but i can't find it.
This is my rusty script:

```<code>#!/bin/csh -f
rm -rf result120
rm -rf result127
rm -rf result126
rm -rf result125
rm -rf result128
rm -rf result129
rm -rf result122
rm -rf output
rm -rf aaa
### Get job id from user name
foreach file ( `cat name` )
        echo `bjobs -u $file | awk '$1 ~ /^[0-9]+/ {print $1}' >> aaa`
        echo "loading"
end
### Read in job id
foreach file ( `cat aaa` )
    echo `bjobs -l $file >> result120`
    echo "loading"
end
### Get pattern in < >
awk '{\
gsub(/                     /,"",$0)}\
BEGIN {\
RS =""\
FS=","\
}\
{\
s=1\
e=150\
if ($1 ~/Job/){\
for(i=s;i<=e;i++){\
    printf("%s", $(i))}\
}\
}' result120 > result126
grep -oE '<[^>]+>' result126 > result125
### Get Current Work Location
awk '$1 ~ /<lsf_login..>/ {getline; print $1}' result125 >result122 #result127
### Get another information and paste it with CWD
foreach file1 ( `cat aaa` )
    echo `bjobs $file1 >> result128`
    echo "getting data"
end
awk '$1 ~ /JOBID/ {getline; printf "%-15s %-15s %-15s %-15s %-20s\n", $1, $2, $3, $4, $5}' result128 >> result129
paste result129 result122 >> output
### Summary
awk '{count1[$2]++}{count2[$4]++}{count3[$3]++}\
END{\
print "\n"\
print "##########################################################################"\
print "There are: ", NR " Jobs"\
for(name in count1){ print name, count1[name]}\
print "\n"\
for(queqe in count2){ print queqe, count2[queqe]}\
print "\n"\
for(stt in count3){ print stt, count3[stt]}\
}' output >> output
</code>```

And my desire is run it again per 15 minutes to get report. Someone told me use Wait but i've searched for it in man wait and can't find any
useful example. That's why i need yours help to solve this problem.
Thanks a lot.

答:
run the script every 15 mins

```<code>while true; do ./script.sh; sleep 900; done
</code>```

or set a cron job or use watch

For c shell you have to write

```<code>while (1)
   ./script.sh
   sleep 900
end
</code>```

but why use csh since you have bash?  Double check the syntax, since I don't remember it much anymore...

Title: How can i repeat a script?

Body:
i've search for command or solution to repeat a script after n times but i can't find it.
This is my rusty script:

#!/bin/csh -f
rm -rf result120
rm -rf result127
rm -rf result126
rm -rf result125
rm -rf result128
rm -rf result129
rm -rf result122
rm -rf output
rm -rf aaa
### Get job id from user name
foreach file ( `cat name` )
        echo `bjobs -u $file | awk '$1 ~ /^[0-9]+/ {print $1}' >> aaa`
        echo "loading"
end
### Read in job id
foreach file ( `cat aaa` )
    echo `bjobs -l $file >> result120`
    echo "loading"
end
### Get pattern in < >
awk '{\
gsub(/                     /,"",$0)}\
BEGIN {\
RS =""\
FS=","\
}\
{\
s=1\
e=150\
if ($1 ~/Job/){\
for(i=s;i<=e;i++){\
    printf("%s", $(i))}\
}\
}' result120 > result126
grep -oE '<[^>]+>' result126 > result125
### Get Current Work Location
awk '$1 ~ /<lsf_login..>/ {getline; print $1}' result125 >result122 #result127
### Get another information and paste it with CWD
foreach file1 ( `cat aaa` )
    echo `bjobs $file1 >> result128`
    echo "getting data"
end
awk '$1 ~ /JOBID/ {getline; printf "%-15s %-15s %-15s %-15s %-20s\n", $1, $2, $3, $4, $5}' result128 >> result129
paste result129 result122 >> output
### Summary
awk '{count1[$2]++}{count2[$4]++}{count3[$3]++}\
END{\
print "\n"\
print "##########################################################################"\
print "There are: ", NR " Jobs"\
for(name in count1){ print name, count1[name]}\
print "\n"\
for(queqe in count2){ print queqe, count2[queqe]}\
print "\n"\
for(stt in count3){ print stt, count3[stt]}\
}' output >> output

And my desire is run it again per 15 minutes to get report. Someone told me use Wait but i've searched for it in man wait and can't find any
useful example. That's why i need yours help to solve this problem.
Thanks a lot.

Body:
run the script every 15 mins

while true; do ./script.sh; sleep 900; done

or set a cron job or use watch

For c shell you have to write

while (1)
   ./script.sh
   sleep 900
end

but why use csh since you have bash?  Double check the syntax, since I don't remember it much anymore...


问:
How to update python in Google Datalab (from google cloud platform)
How can I upgrade my python version in google datalab?

I tried already:

```<code>!pip install python --upgrade
</code>```

And i get the response of "Requirement already up-to-date: python in /usr/lib/python2.7/lib-dynload", however if I type "!python2 --version" , I still get "Python 2.7.12"

答:
You likely can't upgrade this using pip.  You probably need to use apt-get, but I could be wrong here.

That said, Google Cloud Datalab currently uses an Ubuntu 16.04 (LTS) base image, and I think 2.7.12 might be the latest version that works with that OS.  (Specifically it has 2.7.12-1ubuntu0~16.04.1, which is listed as the 16.04 version here: https://packages.ubuntu.com/search?keywords=python2.7)

Body:
How can I upgrade my python version in google datalab?

I tried already:

!pip install python --upgrade

And i get the response of "Requirement already up-to-date: python in /usr/lib/python2.7/lib-dynload", however if I type "!python2 --version" , I still get "Python 2.7.12"


问:
Speed up Linq Query
I have my class structure as follows

```<code>public class Email
{
    public string Subject {get;set;}
    public string Message {get;set;}
    public Contact Sender {get;set;}
    public string SenderEmail {get;set;}
}
public class Contact
{
    public string Email {get;set;}
    public string Name {get;set;}
}
</code>```

and I run my Linq query in two parts
First i select all the emails.

```<code>var query = from msg in context.Email
            select msg;
</code>```

Then i assign the Contact details to the Email Class

```<code>List<Email> outputList = new List<Email>();
foreach (var item in query.ToList())
{
    var q = from contact in context.Contact
            where contact.Email = item.SenderEmail
            select contact;
    item.Sender = q.SingleOrDefault();
    outputList.Add(item);
}

return outputList;
</code>```

Is there anyway i can run a join query and simply output the List without having to run multiple queries

答:
I think this would do the trick (warning: untested code):</p>

```<code>    var qry = from email in context.Email
              join contact in context.Contact
              on email.SenderEmail equals contact.Email
              into contacts
              select new { eml = email, sender = contacts.FirstOrDefault() };

    var items = qry.ToList();

    foreach (var item in items)
    {
        item.eml.Sender = item.sender;
        outputList.Add(item.eml);
    }

    return outputList;
</code>```

Title: Speed up Linq Query

Body:
I have my class structure as follows

public class Email
{
    public string Subject {get;set;}
    public string Message {get;set;}
    public Contact Sender {get;set;}
    public string SenderEmail {get;set;}
}
public class Contact
{
    public string Email {get;set;}
    public string Name {get;set;}
}

and I run my Linq query in two parts
First i select all the emails.

var query = from msg in context.Email
            select msg;

Then i assign the Contact details to the Email Class

List<Email> outputList = new List<Email>();
foreach (var item in query.ToList())
{
    var q = from contact in context.Contact
            where contact.Email = item.SenderEmail
            select contact;
    item.Sender = q.SingleOrDefault();
    outputList.Add(item);
}

return outputList;

Is there anyway i can run a join query and simply output the List without having to run multiple queries

Body:
I think this would do the trick (warning: untested code):

    var qry = from email in context.Email
              join contact in context.Contact
              on email.SenderEmail equals contact.Email
              into contacts
              select new { eml = email, sender = contacts.FirstOrDefault() };

    var items = qry.ToList();

    foreach (var item in items)
    {
        item.eml.Sender = item.sender;
        outputList.Add(item.eml);
    }

    return outputList;


问:
Bandpass FIR filter labview
I am trying to make a bandpass FIR filter in Labview. I have created two sine waves (one with freq = 1Hz, amplitude = 1 and the second with freq=50, amplitude = 0.1) that I added together.

And now I want to create a bandpass filter to filter out the 50Hz signal (I know that its possible use just low pass filter, but I need to use bandpass filter). I set the low cutoff freq to 0.01 and high cutoff freq to 3, but the result is witout any change.

On top of that when I change the parameters I get no change.

When I use the butterworth filter I get the result that I am looking for.

This is my code:

What am I missing?

答:
Most probably you just need to play with the settings to find the ones that suite you the most.

See the example bellow:

And its snippet (drag and drop the image into a blank VI):

Title: Bandpass FIR filter labview


问:
Markdown - imported file not writing escaped characters in fences
Imported md files seem to not be rendering escaped characters in fences (keeping in mind that assemble notes md as a renderer out of the box). Below is a test I ran with assemble built into a node API renderer. While building out the base system I noticed that markdown fences aren't working when in an imported md file but do work when written directly in the hbs file. I've looked all over the assemble documentation, as well as the 'markdown' and 'helpers-markdown' docs but, have had no luck.

Am I missing a step in the pipeline or is this a bug that needs to be filed against assemble/markdown?

test.hbs

```<code>---
docSrc: src/ to/ doc.md
---
{{md docSrc}}

{{#markdown}}
    ``` html
    anchor
    ```
{{/markdown}}
</code>```

doc.md

```<code># Anchor

### best practices

    ``` html
    anchor
    ```
</code>```

RENDERED HTML

```<code>```

        anchor

```

```

        anchor

```
</code>```

答: The {{md}} helper is coming from helper-md and its decoding html elements after rendering the markdown. If you open an issue there (or submit a PR) we can discuss it there.

Body:
Imported md files seem to not be rendering escaped characters in fences (keeping in mind that assemble notes md as a renderer out of the box). Below is a test I ran with assemble built into a node API renderer. While building out the base system I noticed that markdown fences aren't working when in an imported md file but do work when written directly in the hbs file. I've looked all over the assemble documentation, as well as the 'markdown' and 'helpers-markdown' docs but, have had no luck.

Am I missing a step in the pipeline or is this a bug that needs to be filed against assemble/markdown?

test.hbs

---
docSrc: src/ to/ doc.md
---
{{md docSrc}}

{{#markdown}}
    ``` html
    <a href="">anchor</a>
    ```
{{/markdown}}

doc.md

# Anchor

### best practices

    ``` html
    <a href="#">anchor</a>
    ```

RENDERED HTML

        anchor

        anchor


问:
use color from a class's static field xamarin.forms
Let's say I have a static class as follows

```<code>namespace MyNameSpace {
    static class MyClass {
        public static Color MyColor = Color.Red;

    }
}
</code>```

I am creating a class with these fields to use them within other c# classes. Is it also possible to use the same static them within xaml. something like this?

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:Cols="clr-namespace:MyNameSpace"
         BackgroundColor="{Cols:MyClass.MyColor}" />
</code>```

Or some other way using static resources?

答:
You can use the x:Static markup extension.

```<code><ContentPage ...
     BackgroundColor="{x:Static Cols:MyClass.MyColor}"..
</code>```

x:Static can access one of the following:

a public static field

a public static property

a public constant field

an enumeration member.

Body:
Let's say I have a static class as follows

namespace MyNameSpace {
    static class MyClass {
        public static Color MyColor = Color.Red;

    }
}

I am creating a class with these fields to use them within other c# classes. Is it also possible to use the same static them within xaml. something like this?

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:Cols="clr-namespace:MyNameSpace"
         BackgroundColor="{Cols:MyClass.MyColor}" />

Or some other way using static resources?

Body:
You can use the x:Static markup extension.

<ContentPage ...
     BackgroundColor="{x:Static Cols:MyClass.MyColor}"..

x:Static can access one of the following:

a public static field

a public static property

a public constant field

an enumeration member.


问:
While reading line by line from input file.txt, how to implement the code corresponding to each line
I use Python3.5

I already created 3 functions:

```<code> def Insert(self, key):
 def Report(self, node, a, b)
 def Print(self, node)
</code>```

But I need to read a lot of lines from input file.txt as:

```<code>I 20
...
...
R 17 27
...
...
P
...
...
E
</code>```

To read the file.txt above, I use the following code

```<code>filepath = 'file.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line))
       ine = fp.readline()
       cnt += 1
</code>```

Question: While reading each line, I need to run the corresponding function and turn the result, before running the next line. But I don't know how to implement it in Python.

For example, when I read line I 20, I have to run function Insert(20) and it will turn me a result. Then I continue to read next line  R 17 27, to run function Report(node,17,27). Then, I will read P, to run function Print(node). Finally, when I read E, I need to print ("end of file").

I am really appreciated for your answer.

答:
Here's a basic example (Python 3.x).  I dropped node and self since they weren't defined in your example:

```<code>import sys

def Insert(key):
    print('Insert',key)

def Report(a, b):
    print('Report',a,b)

def Print():
    print('Print')

def Exit():
    sys.exit(0)

# Dictionary lookup of what function to call for each letter
dispatch = {'I':Insert,
            'R':Report,
            'P':Print,
            'E':Exit}

with open('file.txt') as fp:

    # Iterate and return the line number and line data for each line
    for cnt,line in enumerate(fp,1):

        # `line` already contains a newline so end is used to suppress a newline.
        print('Line {}: {}'.format(cnt,line),end='')

        # strip leading/trailing whitespace and split on whitespace.
        # First item to `cmd`, the rest to `data`
        cmd,*data = line.strip().split()

        # Lookup function based on command, then call it with data expanded as arguments.
        dispatch[cmd](*data)
</code>```

Input file:

```<code>I 20
R 17 27
P
E
</code>```

Output:

```<code>Line 1: I 20
Insert 20
Line 2: R 17 27
Report 17 27
Line 3: P
Print
Line 4: E
</code>```

If you expect errors in the data file, write your functions to take variable arguments.  Example:

```<code>def Report(*args):
    if len(args) == 2:
        a,b = args
        print('Report',a,b)
    else:
        print('Report: invalid arguments')
</code>```

Body:
I use Python3.5

I already created 3 functions:

 def Insert(self, key):
 def Report(self, node, a, b)
 def Print(self, node)

But I need to read a lot of lines from input file.txt as:

I 20
...
...
R 17 27
...
...
P
...
...
E

To read the file.txt above, I use the following code

filepath = 'file.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line))
       ine = fp.readline()
       cnt += 1

Question: While reading each line, I need to run the corresponding function and turn the result, before running the next line. But I don't know how to implement it in Python.

For example, when I read line I 20, I have to run function Insert(20) and it will turn me a result. Then I continue to read next line  R 17 27, to run function Report(node,17,27). Then, I will read P, to run function Print(node). Finally, when I read E, I need to print ("end of file").

I am really appreciated for your answer.

Body:
Here's a basic example (Python 3.x).  I dropped node and self since they weren't defined in your example:

import sys

def Insert(key):
    print('Insert',key)

def Report(a, b):
    print('Report',a,b)

def Print():
    print('Print')

def Exit():
    sys.exit(0)

# Dictionary lookup of what function to call for each letter
dispatch = {'I':Insert,
            'R':Report,
            'P':Print,
            'E':Exit}

with open('file.txt') as fp:

    # Iterate and return the line number and line data for each line
    for cnt,line in enumerate(fp,1):

        # `line` already contains a newline so end is used to suppress a newline.
        print('Line {}: {}'.format(cnt,line),end='')

        # strip leading/trailing whitespace and split on whitespace.
        # First item to `cmd`, the rest to `data`
        cmd,*data = line.strip().split()

        # Lookup function based on command, then call it with data expanded as arguments.
        dispatch[cmd](*data)

Input file:

I 20
R 17 27
P
E

Output:

Line 1: I 20
Insert 20
Line 2: R 17 27
Report 17 27
Line 3: P
Print
Line 4: E

If you expect errors in the data file, write your functions to take variable arguments.  Example:

def Report(*args):
    if len(args) == 2:
        a,b = args
        print('Report',a,b)
    else:
        print('Report: invalid arguments')


问:
I want to return html in a flask route
Instead of using send_static_file, I want to use something like html('
content
'), sort of like jsonify.

```<code>@app.route('/incorrect_pass')
def incorrect_pass():
    return html('Incorrect password. <a href="/">Go back?</a>')
</code>```

Is what I want to do.

答: Never mind. Should've checked. Flask returns strings as html, so the html() isn't necessary above.

Title: I want to return html in a flask route

Body:
Instead of using send_static_file, I want to use something like html('
content
'), sort of like jsonify.

@app.route('/incorrect_pass')
def incorrect_pass():
    return html('Incorrect password. Go back?')

Is what I want to do.


问:
UWP PreLoaded SQLite
I am trying to copy a preloaded SQLite db into my UWP app.  On the initial installation it copies the "test.db", but the size is 0 bytes and there are no tables or data.  The original db is 1300 bytes with data and tables.

Another factoid...when I create the app Using Visual Studio 2017 and compile and run/debug the app it works fine, but when I sideload the appx file or download from the Windows Store the db is empty.

Here is the code that I am using:

```<code>  Task task = CopyDatabase();

 private async Task CopyDatabase()
    {
        bool isDatabaseExisting = false;

        try
        {
            StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Express.db");
            isDatabaseExisting = true;
        }
        catch
        {
            isDatabaseExisting = false;
        }

        if (!isDatabaseExisting)
        {
            StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Express.db");
            await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, "Express.db", NameCollisionOption.ReplaceExisting);
        }
    }
</code>```

I'm not getting any error messages.

答:
Does the your database file deployed correctly to the target system?
To confirm it, see your deployed - "Package" - folder. Open command prompt with administrative previleges, and see the directory

c:\Program Files\WindowsApps\your-app-id

If your database file deployed successfully, you can see it in the directory. If not, you may need to change the deploy settings.

To deploy the file to target machine, you should set the property of the one as ...

'BuildAction=Contents'

'Copy to output directory'='Always Copy'

You can set it from solution explorer and right-click the your database file.

If you succeeded the deploying file, your code will copy your database file to app local folder.

c:\Users\YOUR-USER-ID\AppData\Local\Packages\YOUR-APP-ID\LocalState

Title: UWP PreLoaded SQLite

Body:
I am trying to copy a preloaded SQLite db into my UWP app.  On the initial installation it copies the "test.db", but the size is 0 bytes and there are no tables or data.  The original db is 1300 bytes with data and tables.

Another factoid...when I create the app Using Visual Studio 2017 and compile and run/debug the app it works fine, but when I sideload the appx file or download from the Windows Store the db is empty.

Here is the code that I am using:

  Task task = CopyDatabase();

 private async Task CopyDatabase()
    {
        bool isDatabaseExisting = false;

        try
        {
            StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Express.db");
            isDatabaseExisting = true;
        }
        catch
        {
            isDatabaseExisting = false;
        }

        if (!isDatabaseExisting)
        {
            StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Express.db");
            await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, "Express.db", NameCollisionOption.ReplaceExisting);
        }
    }

I'm not getting any error messages.


答:
Why not just:</p>

```<code>def html(content):  # Also allows you to set your own <head></head> etc
   return '<html><head>custom head stuff here</head><body>' + content + '</body></html>'

@app.route('/incorrect_pass')
def incorrect_pass():
    return html('Incorrect password. <a href="/">Go back?</a>')
    # OR return  'Incorrect password. <a href="/">Go back?</a>
</code>```

Title: I want to return html in a flask route

Body:
Why not just:

def html(content):  # Also allows you to set your own <head></head> etc
   return '<html><head>custom head stuff here</head><body>' + content + '</body></html>'

@app.route('/incorrect_pass')
def incorrect_pass():
    return html('Incorrect password. <a href="/">Go back?</a>')
    # OR return  'Incorrect password. <a href="/">Go back?</a>


答:
How about splitting the line and making the function choice based on the first word on each line. Something like:

```<code>tokens = line.split()
if tokens[0] == 'I':
    # call insert
elif tokens[0] == 'R':
    # call report
</code>```

and so on. The args will be in the other tokens, for example, the insert call could look like Insert(tokens[1]).

Title: While reading line by line from input file.txt, how to implement the code corresponding to each line

Body:
How about splitting the line and making the function choice based on the first word on each line. Something like:

tokens = line.split()
if tokens[0] == 'I':
    # call insert
elif tokens[0] == 'R':
    # call report

and so on. The args will be in the other tokens, for example, the insert call could look like Insert(tokens[1]).


问:
XSD attribute cannot equal value?
How can I restrict an attribute to not allow a particular value?

For instance, I have an <xs:key/> on an Id attribute of an element, but some yahoo has gone and thrown a magic number in there so now I cannot allow 3, but 1, 2, and 5 are perfectly acceptable.

答: You can specify restrictions using regular expressions. Take a look at this tutorial

Title: XSD attribute cannot equal value?


问:
Swift accessing response from function
I am producing a GET request, which gives me JSON object of array within dictionaries in this format:

```<code>Array<Dictionary<String,String>>
</code>```

I have a class:

```<code>class foodMenu: UITableViewController{

    var jsonData:Array<Dictionary<String,String>>! // Here is set an empty global variable(Not sure if I am doing this right either)

    func getFoodRequest(){
        Alamofire.request("http://127.0.0.1:5000/get_food").responseJSON {
            response in
            print("This response", response.result)
            let result = response.result.value
            self.jsonData = result as! Array<Dictionary<String,String>>
        }
   }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   getFoodRequest()
   return jsonData!.count
  }
}
</code>```

jsonData returns nil. My goal is to  have an array of jsonData so i can use .count method on it.

答:
The problem is that you are trying to network synchronously, and you can't. Actually, you are networking asynchronously, which is correct, but you are forgetting that networking is asynchronous.

Let's look at your code:

```<code>func getFoodRequest(){
    Alamofire.request("http://127.0.0.1:5000/get_food").responseJSON {
        response in
        let result = response.result.value
        self.jsonData = result as! Array<Dictionary<String,String>> // B
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    getFoodRequest() // A
    return jsonData!.count // C
}
</code>```

 Look at the letter comments I've added. You seem to think that the code executes in the order A,B,C. It doesn't. It executes in the order A,C,B. That's because getting your response takes time and happens on a background thread, and meanwhile your numberOfRowsInSection has gone right ahead and executed the next line and finished.

Title: Swift accessing response from function

Body:
I am producing a GET request, which gives me JSON object of array within dictionaries in this format:

Array<Dictionary<String,String>>

I have a class:

class foodMenu: UITableViewController{

    var jsonData:Array<Dictionary<String,String>>! // Here is set an empty global variable(Not sure if I am doing this right either)

    func getFoodRequest(){
        Alamofire.request("http://127.0.0.1:5000/get_food").responseJSON {
            response in
            print("This response", response.result)
            let result = response.result.value
            self.jsonData = result as! Array<Dictionary<String,String>>
        }
   }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   getFoodRequest()
   return jsonData!.count
  }
}

jsonData returns nil. My goal is to  have an array of jsonData so i can use .count method on it.

Body:
The problem is that you are trying to network synchronously, and you can't. Actually, you are networking asynchronously, which is correct, but you are forgetting that networking is asynchronous.

Let's look at your code:

func getFoodRequest(){
    Alamofire.request("http://127.0.0.1:5000/get_food").responseJSON {
        response in
        let result = response.result.value
        self.jsonData = result as! Array<Dictionary<String,String>> // B
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    getFoodRequest() // A
    return jsonData!.count // C
}

 Look at the letter comments I've added. You seem to think that the code executes in the order A,B,C. It doesn't. It executes in the order A,C,B. That's because getting your response takes time and happens on a background thread, and meanwhile your numberOfRowsInSection has gone right ahead and executed the next line and finished.


问:
Django. Using multiple settings files with Heroku
I am trying to follow the advice of the book "Two Scoops of Django" and although it is a really good book, I think it this section is unclear.
So, I split my settings file and created a folder like this:

```<code>settings/
 __init__.py
 base.py (allmost everything there)
 local.py (dev. specific settings)
 production.py (settings for Heroku)
</code>```

most of the settings are in the base.py file

in local.py I have this:

```<code># settings/local.py
from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
INSTALLED_APPS += ("debug_toolbar", "django_extensions", "south",)
</code>```

in production.py I have this:

```<code>from .base import *
INSTALLED_APPS += ("gunicorn",)
</code>```

When I run locally:

```<code>python manage.py runserver 7000 --settings=appname.settings.local
python manage.py runserver 7000 --settings=appname.settings.production
</code>```

everything works fine.

But when I push changes to Heroku, I get the log:

```<code>  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app

 raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
</code>```

So, I guess Heroku is not finding my settings files, I don't know how to fix this (it might be very simple).

Two Scoops of Django is kind of ironic here, it writes "Platform as Service - See section 25.2" and then in that section it just writes "read Platform Documentation" : /

答:
After you have logged into heroku with heroku login you can check your configs by running:
heroku config.
 If you dont see a SECRET_KEY and DJANGO_SETTINGS_MODULE you can set them by running:

```<code>heroku config:set SECRET_KEY='secret_key_goes_here'
</code>```

and

```<code>heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings.production
</code>```

Finally, make sure that you have the following syntax inside of your production setting file:

```<code>SECRET_KEY = os.environ['SECRET_KEY']
</code>```

The above intstructions are for the following project structure

```<code>-myproject
  -app1
  -app2
  -mysite
    -settings
      __init__.py
      base.py
      dev.py
      production.py
-manage.py
-Pipfile
-Procfile
-requirements.txt
</code>```

Body:
I am trying to follow the advice of the book "Two Scoops of Django" and although it is a really good book, I think it this section is unclear.
So, I split my settings file and created a folder like this:

settings/
 __init__.py
 base.py (allmost everything there)
 local.py (dev. specific settings)
 production.py (settings for Heroku)

most of the settings are in the base.py file

in local.py I have this:

# settings/local.py
from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
INSTALLED_APPS += ("debug_toolbar", "django_extensions", "south",)

in production.py I have this:

from .base import *
INSTALLED_APPS += ("gunicorn",)

When I run locally:

python manage.py runserver 7000 --settings=appname.settings.local
python manage.py runserver 7000 --settings=appname.settings.production

everything works fine.

But when I push changes to Heroku, I get the log:

  File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app

 raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

So, I guess Heroku is not finding my settings files, I don't know how to fix this (it might be very simple).

Two Scoops of Django is kind of ironic here, it writes "Platform as Service - See section 25.2" and then in that section it just writes "read Platform Documentation" : /

Body:
After you have logged into heroku with heroku login you can check your configs by running:
heroku config.
 If you dont see a SECRET_KEY and DJANGO_SETTINGS_MODULE you can set them by running:

heroku config:set SECRET_KEY='secret_key_goes_here'

and

heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings.production

Finally, make sure that you have the following syntax inside of your production setting file:

SECRET_KEY = os.environ['SECRET_KEY']

The above intstructions are for the following project structure

-myproject
  -app1
  -app2
  -mysite
    -settings
      __init__.py
      base.py
      dev.py
      production.py
-manage.py
-Pipfile
-Procfile
-requirements.txt


问:
(Ionic) Cordova-file-plugin error when trying to read file
So, I'm currently trying to read an Audio file I just saved on the App's directory (Android) through the cordova file-plugin, but I keep getting the same error code 5, which stands for "ENCODING_ERR".

This is how I create the file and start recording

```<code>start() {
    this.filename = this.file.externalDataDirectory.replace(/file:\/\//g, '');
    this.mediaobject = this.media.create(this.filename + 'audioprofile' + '.3gp');
    this.mediaobject.startRecord();
}
</code>```

This is how I stop recording and save the file

```<code>stop() {
 this.mediaobject.stopRecord();
 this.mediaobject.release();
...
</code>```

And this is where I'm stuck: right after saving it, I need to have it as a String, so I'm try to read it ( alert(content) should show me that string)

```<code>stop() {
this.mediaobject.stopRecord();
this.mediaobject.release();

this.storage.get("uid").then((id) => {

  try{
  this.file.readAsDataURL(this.filename,'audioprofile'+'.3gp').then((filecontent)=>{
  alert(filecontent);
},(err)=>{
    alert(err.code);
  })
  } `
</code>```

After some research I found out it PROBABLY means I'm not giving the right path for it, but I've tried everything, any combinations of 'filename' and 'filepath' were made, even adding the prefix removed on start().

I want to know if someone managed to read a file with this cordova plugin and if you did, please help me out.

Thanks in advance, this is my first post here \o/ (although I've always used the website, love u guys).

答: Well i managed to do this with the File-Path Plugin, it resolves the Path for your file in a way the File Plugin understands and is able to reach the file, then you just have to manipulate it the way you want.</p>

Body:
So, I'm currently trying to read an Audio file I just saved on the App's directory (Android) through the cordova file-plugin, but I keep getting the same error code 5, which stands for "ENCODING_ERR".

This is how I create the file and start recording

start() {
    this.filename = this.file.externalDataDirectory.replace(/file:\/\//g, '');
    this.mediaobject = this.media.create(this.filename + 'audioprofile' + '.3gp');
    this.mediaobject.startRecord();
}

This is how I stop recording and save the file

stop() {
 this.mediaobject.stopRecord();
 this.mediaobject.release();
...

And this is where I'm stuck: right after saving it, I need to have it as a String, so I'm try to read it ( alert(content) should show me that string)

stop() {
this.mediaobject.stopRecord();
this.mediaobject.release();

this.storage.get("uid").then((id) => {

  try{
  this.file.readAsDataURL(this.filename,'audioprofile'+'.3gp').then((filecontent)=>{
  alert(filecontent);
},(err)=>{
    alert(err.code);
  })
  } `

After some research I found out it PROBABLY means I'm not giving the right path for it, but I've tried everything, any combinations of 'filename' and 'filepath' were made, even adding the prefix removed on start().

I want to know if someone managed to read a file with this cordova plugin and if you did, please help me out.

Thanks in advance, this is my first post here \o/ (although I've always used the website, love u guys).


问:
Process interval tick based on condition RXJS
I have the following interval in my code, where I want to run some logic, however I need to do some queries before knowing if I can process the logic developed or not:

```<code>This is my observable:
const interval$ = Observable.interval(120000).startWith(0);
</code>```

I need to map to this observable and only let it process if the return from a service call is not equal 1:

```<code>documentRepository.getProcedureLock().then(data => {
                if (data !== null && data !=== '1') {
</code>```

I have tried many things without success... the logic that process my interval is a .mergeMap and I don't have enough experience with it...can u guys help out?

答:
See if that's what u looking for </p>

```<code>Rx.Observable.fromPromise(documentRepository.getProcedureLock()).flatMap(data
=> {
            if (data !== null && data !=== '1') return interval$
// i assume you want data if condition not met
return Rx.Observable.of(data)
}).subscribe(console.log)
</code>```

Body:
I have the following interval in my code, where I want to run some logic, however I need to do some queries before knowing if I can process the logic developed or not:

This is my observable:
const interval$ = Observable.interval(120000).startWith(0);

I need to map to this observable and only let it process if the return from a service call is not equal 1:

documentRepository.getProcedureLock().then(data => {
                if (data !== null && data !=== '1') {

I have tried many things without success... the logic that process my interval is a .mergeMap and I don't have enough experience with it...can u guys help out?

Body:
See if that's what u looking for

Rx.Observable.fromPromise(documentRepository.getProcedureLock()).flatMap(data
=> {
            if (data !== null && data !=== '1') return interval$
// i assume you want data if condition not met
return Rx.Observable.of(data)
}).subscribe(console.log)


问:
Reset/Change Picker(Dropdown) selectedValue with setNativeProps
I have a form with a TextInput, a Picker and a TouchableHiglight.

User will enter something into the TextInput, pick an item from the Picker and submit with the TouchableHighlight.

I am able to use ref to reset the TextInput but I can't figure out how to change/reset the Picker value to default.

Possible Unhandled Promise Rejection

  TypeError: this.value2ref.setNativeProps is not a function

React-Native

```<code>constructor(props) {
  super(props);
  this.state = {
    value1: '',
    value1ref: '',
    value2: '',
    value2ref: ''
  }
}

<TextInput
  onChangeText={(text) => this.setState({value1:text})}
  ref={input => {this.value1ref=input}}
/>

<View>
  <Picker
    selectedValue={this.state.value1}
    onValueChange={(itemValue, itemIndex) => this.setState({value2: itemValue})}
    ref={input => {this.value2ref=input}}>
    <Picker.Item label="Pick an item" value="" />
    <Picker.Item label="Item 1" value="Item1" />
    <Picker.Item label="Item 2" value="Item2" />
    <Picker.Item label="Item 3" value="Item3" />
  </Picker>
</View>

<View>
  <TouchableOpacity onPress={this.onSubmit.bind(this)}>
    <View>
      <Text>SUBMIT</Text>
    </View>
  </TouchableOpacity>
</View>
</code>```

I've also tried with this type of reference but to no avail.

```<code>ref={component => this._exampleref=component}>
</code>```

JavaScript

```<code>onSubmit() {
  this.value1ref.setNativeProps({ //This one works
    text: "",
  });
  this.value2ref.setNativeProps({ // This one does NOT work
    selectedValue: "",
  });
}
</code>```

I know I can use this.value1ref.clear() but i'm doing it this way to prove a point, and also, there is no clear() for the Picker.

答:
I don't think you are supposed to be using refs for that.

You are correctly updating the state with the callbacks in onChangeText and onValueChange but you are not rendering from the state, for that you need to add the value prop to the TextInput you were already using a selectedValue for the picker hence the different behavior (the value used in the prop was probably the wrong one though).

```<code><TextInput
  onChangeText={(text) => this.setState({value1:text})}
  value={this.state.value1}
/>
</code>```

and

```<code><Picker
  selectedValue={this.state.value2}
  onValueChange={(itemValue) => this.setState({value2: itemValue})}
  >
  {/* ... */}
</Picker>
</code>```

With that set you just need this in your onSubmit.

```<code>onSubmit() {
  this.setState({value1: '', value2: ''});
}
</code>```

Body:
I have a form with a TextInput, a Picker and a TouchableHiglight.

User will enter something into the TextInput, pick an item from the Picker and submit with the TouchableHighlight.

I am able to use ref to reset the TextInput but I can't figure out how to change/reset the Picker value to default.

Possible Unhandled Promise Rejection

  TypeError: this.value2ref.setNativeProps is not a function

React-Native

constructor(props) {
  super(props);
  this.state = {
    value1: '',
    value1ref: '',
    value2: '',
    value2ref: ''
  }
}

<TextInput
  onChangeText={(text) => this.setState({value1:text})}
  ref={input => {this.value1ref=input}}
/>

<View>
  <Picker
    selectedValue={this.state.value1}
    onValueChange={(itemValue, itemIndex) => this.setState({value2: itemValue})}
    ref={input => {this.value2ref=input}}>
    <Picker.Item label="Pick an item" value="" />
    <Picker.Item label="Item 1" value="Item1" />
    <Picker.Item label="Item 2" value="Item2" />
    <Picker.Item label="Item 3" value="Item3" />
  </Picker>
</View>

<View>
  <TouchableOpacity onPress={this.onSubmit.bind(this)}>
    <View>
      <Text>SUBMIT</Text>
    </View>
  </TouchableOpacity>
</View>

I've also tried with this type of reference but to no avail.

ref={component => this._exampleref=component}>

JavaScript

onSubmit() {
  this.value1ref.setNativeProps({ //This one works
    text: "",
  });
  this.value2ref.setNativeProps({ // This one does NOT work
    selectedValue: "",
  });
}

I know I can use this.value1ref.clear() but i'm doing it this way to prove a point, and also, there is no clear() for the Picker.

Body:
I don't think you are supposed to be using refs for that.

You are correctly updating the state with the callbacks in onChangeText and onValueChange but you are not rendering from the state, for that you need to add the value prop to the TextInput you were already using a selectedValue for the picker hence the different behavior (the value used in the prop was probably the wrong one though).

<TextInput
  onChangeText={(text) => this.setState({value1:text})}
  value={this.state.value1}
/>

and

<Picker
  selectedValue={this.state.value2}
  onValueChange={(itemValue) => this.setState({value2: itemValue})}
  >
  {/* ... */}
</Picker>

With that set you just need this in your onSubmit.

onSubmit() {
  this.setState({value1: '', value2: ''});
}


问:
how to start and stop HostapduService
I am a begginer in android studio, but i am working in a hce Project. I am bulding an app that works like a key, and when my reader detects the correct aid open a door. I extends a host apdu Service and declares the aid. I want to stop the service or the android nfc permission, because the propuse of my app is that first you introduce your name and password. But the nfc in my app works in background and idon’t know the way for stop nfc before I put the password.

```<code>public class HceService extends HostApduService {

    private static final byte[] SELECT_AID = {0x00, (byte) 0xA4, 0x04, 0x00, 0x07, (byte) 0xBB, 0x52, 0x61, 0x75, 0x6c, 0x0d, 0x0a,};
    private static final byte[] MY_UID = {0x01, 0x02, 0x03, 0x04, (byte) 0x90, 0x00};
    private static final byte[] MY_ERROR = {0x6f, 0x00};

    @Override
    public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
        if (Arrays.equals(SELECT_AID, apdu))
            return MY_UID;
        else return MY_ERROR;

    }

    @Override
    public void onDeactivated(int reason){
    }
}
</code>```

<service
            android:name=".HceService"
            android:exported="true"
            android:permission="android.permission.BIND_NFC_SERVICE">
            <intent-filter>
                <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
            </intent-filter>
            <meta-data
                android:name="android.nfc.cardemulation.host_apdu_service"
                android:resource="@xml/apduservice" />
        </service>

        <?xml version="1.0" encoding="utf-8"?>
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:requireDeviceUnlock="false" >
    <aid-group
        android:category="other">
        <aid-filter android:name="BB5261756c0d0a"/>
    </aid-group>
</host-apdu-service>
```

答: You shouldn't stop the NFC transmission for user input. Keep an authorization record for your user and just send all the commands at once. Otherwise, launch the app with the first tap, then have a user authenticate, then tap again.</p>

Title: how to start and stop HostapduService

Body:
I am a begginer in android studio, but i am working in a hce Project. I am bulding an app that works like a key, and when my reader detects the correct aid open a door. I extends a host apdu Service and declares the aid. I want to stop the service or the android nfc permission, because the propuse of my app is that first you introduce your name and password. But the nfc in my app works in background and idon’t know the way for stop nfc before I put the password.

public class HceService extends HostApduService {

    private static final byte[] SELECT_AID = {0x00, (byte) 0xA4, 0x04, 0x00, 0x07, (byte) 0xBB, 0x52, 0x61, 0x75, 0x6c, 0x0d, 0x0a,};
    private static final byte[] MY_UID = {0x01, 0x02, 0x03, 0x04, (byte) 0x90, 0x00};
    private static final byte[] MY_ERROR = {0x6f, 0x00};

    @Override
    public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
        if (Arrays.equals(SELECT_AID, apdu))
            return MY_UID;
        else return MY_ERROR;

    }

    @Override
    public void onDeactivated(int reason){
    }
}

<service
            android:name=".HceService"
            android:exported="true"
            android:permission="android.permission.BIND_NFC_SERVICE">
            <intent-filter>
                <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
            </intent-filter>
            <meta-data
                android:name="android.nfc.cardemulation.host_apdu_service"
                android:resource="@xml/apduservice" />
        </service>

        <?xml version="1.0" encoding="utf-8"?>
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:requireDeviceUnlock="false" >
    <aid-group
        android:category="other">
        <aid-filter android:name="BB5261756c0d0a"/>
    </aid-group>
</host-apdu-service>


问:
How to fix warning with %ms in scanf
I need to do something like this:

```<code>scanf("%ms", ...)
</code>```

and compile it with

```<code>g++ -Wall -pedantic -std=c++11
</code>```

also with

```<code>gcc -Wall -pedantic -std=c99
</code>```

And it prints warning: ISO C does not support the 'm' scanf flag.
How can i fix it?

答:
The %ms format is specified by POSIX, not by ISO C.

By using -Wall -pedantic -std=c99, you've requested diagnostics for code that violates the C99 standard, as yours does (its behavior is undefined).

If you want your code to be portable to ISO C99 (or C11) implementations, don't use %ms.

If you need to use %ms (making your code less portable, but it should work with any POSIX-conforming implementation),  don't use those options. Dropping the -pedantic option seems to be sufficient to inhibit the warning. Compilers other than gcc are likely to have different options to achieve this (though clang copies gcc fairly closely).

Title: How to fix warning with %ms in scanf

Body:
I need to do something like this:

scanf("%ms", ...)

and compile it with

g++ -Wall -pedantic -std=c++11

also with

gcc -Wall -pedantic -std=c99

And it prints warning: ISO C does not support the 'm' scanf flag.
How can i fix it?


问:
docker stack deploy got error code 3 and "driver name: if driver is specified name is required"
I was following the Docker tutorial and on Part 3: Services (link)

When I ran this command, I got the shown error:

```<code>[root@pecan-9A firstDocker]# docker-latest stack deploy -c docker-compose.yml getstartedlab
Creating network getstartedlab_webnet
Error response from daemon: rpc error: code = 3
desc = driver name: if driver is specified name is required
</code>```

Version:

```<code>[root@pecan-9A firstDocker]# docker-latest --version
Docker version 1.13.1, build 6774275/1.13.1
</code>```

Updated 1: My docker-compose.yml

I was using the same docker-compose.yml as suggested in the
tutorial:

```<code>[root@pecan-9A firstDocker]# cat docker-compose.yml
version: "3"
services:
  web:
    # replace username/repo:tag with your name and image details
    image: localhost:5000/leeyuiwah/get-started:part2
    deploy:
      replicas: 5
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
      restart_policy:
        condition: on-failure
    ports:
      - "80:80"
    networks:
      - webnet
networks:
  webnet:
</code>```

Update 2: Another variant of the file

Based on some discussion on this thread, I also tweaked the file
to use a slightly different definition of network.  But this
file got the same error as the above.

```<code>[root@pecan-9A firstDocker]# cat docker-compose.v2.yml
version: "3.0"
services:
  web:
    image: localhost:5000/leeyuiwah/get-started:part2
    deploy:
      replicas: 5
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
      restart_policy:
        condition: on-failure
    ports:
      - "80:80"
    networks: [hello]

networks:
  hello:
    driver: overlay
    ipam:
      config:
        - subnet: 172.17.0.0/16
</code>```

答:
I ran into the same issue while following the same guide you are using. The problem seems to be from using the 'docker' package from the OS and not the package from the docker repository. During the setup guide they ask you to add their repository, remove docker and docker.io packages, and then install 'docker-ce'.

See: https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/#set-up-the-repository

Once I did this, I no longer ran into the error.

Body:
I was following the Docker tutorial and on Part 3: Services (link)

When I ran this command, I got the shown error:

[root@pecan-9A firstDocker]# docker-latest stack deploy -c docker-compose.yml getstartedlab
Creating network getstartedlab_webnet
Error response from daemon: rpc error: code = 3
desc = driver name: if driver is specified name is required

Version:

[root@pecan-9A firstDocker]# docker-latest --version
Docker version 1.13.1, build 6774275/1.13.1

Updated 1: My docker-compose.yml

I was using the same docker-compose.yml as suggested in the
tutorial:

[root@pecan-9A firstDocker]# cat docker-compose.yml
version: "3"
services:
  web:
    # replace username/repo:tag with your name and image details
    image: localhost:5000/leeyuiwah/get-started:part2
    deploy:
      replicas: 5
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
      restart_policy:
        condition: on-failure
    ports:
      - "80:80"
    networks:
      - webnet
networks:
  webnet:

Update 2: Another variant of the file

Based on some discussion on this thread, I also tweaked the file
to use a slightly different definition of network.  But this
file got the same error as the above.

[root@pecan-9A firstDocker]# cat docker-compose.v2.yml
version: "3.0"
services:
  web:
    image: localhost:5000/leeyuiwah/get-started:part2
    deploy:
      replicas: 5
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
      restart_policy:
        condition: on-failure
    ports:
      - "80:80"
    networks: [hello]

networks:
  hello:
    driver: overlay
    ipam:
      config:
        - subnet: 172.17.0.0/16


问:
Timeout Mechanism for Hashtable
I have a hashtable that under heavy-traffic. I want to add timeout mechanism to hashtable, remove too old records. My concerns are,
- It should be lightweight
- Remove operation has not time critical. I mean (timeout value is 1 hour) remove operation can be after 1 hour or and 1 hour 15 minute. There is no problem.

My opinion is,
I create a big array (as ring buffer)that store put time and hashtable key,
When adding to hashtable, using array index find a next slot on array put time,
  if array slot empty, put insertion time and HT key,
  if array slot is not empty, compare insertion time for timeout occured.

     if timeout occured remove from Hashtable (if not removed yet)
     it not timeout occured, increment index till to find empty slot or timeouted array slot.
When removing from hashtable there is no operation on big array.

Shortly, for every add operation to Hashtable, may remove 1 timeouted element from hashtable  or do nothing.

What is your the more elegant and more lightweight solution ?

Thanks for helps,

答: Under the assumption that the currently most heavily accessed items in your cache structure are in the significant minority, you may well get by with randomly selecting items for removal (you have a low probability of removing something very useful).  I've used this technique and, in this particular application, it worked very well and took next to no implementation effort.</p>

Title: Timeout Mechanism for Hashtable


问:
React functional component is called on every parent state change
I'm new in React and I found thing that makes me confused.

Almost every tutorial suggests using functional (stateless) components.
But recently I discovered that if functional component is a child component, it is rendered every time when parent component state or props changed even if I don't pass any props to it.
It doesn't happen with class-based component.
What is the reason for this situation?

Should I use only class-based components in order to get the highest performance?

答:
Here are your options out of the box:

Use a pure function like you did:

[+] Easy to write and to understand

[-] Rerenders each time the parent component rerenders (might not be an issue if you don't pass it any props though)

Use a class component and implement shouldComponentUpdate

[+] you have full control over the rerendering conditions.

[-] Takes a lot more code to write

Use a PureComponent

[+] uses a shallow shouldComponentUpdate automagically so less code to write

[-] can have undesirable side effects (false negative for complex objects and non pure child components not rendering properly)

In your particular case, since you are not passing any props to your child component, using a pure function is perfectly acceptable. Because that means its just pure static HTML and would rerender each time anyways even if it was part of the parent.

Lastly, for more advanced uses, have a look at https://github.com/acdlite/recompose


问:
Push notification in Web pages
Can a web notification be implemented in web sites? I'm using a environment of jsp's with jquery, vue and angular.js for the front side. There's a way to implement web notifications with this environment?</p>

答: you can use web socket, which has integrated in Angular already.</p>

Title: Push notification in Web pages


问:
How do I merge elements in my array of strings in which there are leading and trailing parens?
In Ruby, let's say I have an array of strings

```<code>["a", "(b", "c)", "d", "e"]
</code>```

How do I merge (with a space in between) strings in my array where the first character of one is a "(" and the last character of another one is ")"?  In the above example, I would want the resulting array to be

```<code>["a", "(b c)", "d", "e"]
</code>```

Similarly, if my array were

```<code>["a", "(b", "e", "c)", "d"]
</code>```

I would want the result to be

```<code>["a", "(b e c)", "d"]
</code>```

However if the array were

```<code>["(a", "c"]
</code>```

or

```<code>["c)", "e", "(b"]
</code>```

I would want the arrays to be unchanged b/c in the first instance, there is no element with a ")" and in the second instance the element with the ")" is before the element beginning with the "(".  I hope this makes sense.

答:
The other answer probably fits you better, but just in case, here's an alternate approach, using string parsing:</p>

```<code>def parse(str)
  str.scan(/
    (?<token> \g<paren> | \g<word>)
    (?<word> \w+){0}
    (?<paren> \( \g<token> (?:\s+ \g<token>)* \) ){0}
  /x).map(&:first)
end

arr = ["a", "(b", "c)", "d", "e"]
str = arr.join(' ')
parse(str)
# => ["a", "(b c)", "d", "e"]
parse("(a (b c) d) (e (f g)) (h i)")
# => ["(a (b c) d)", "(e (f g))", "(h i)"]
</code>```

Body:
In Ruby, let's say I have an array of strings

["a", "(b", "c)", "d", "e"]

How do I merge (with a space in between) strings in my array where the first character of one is a "(" and the last character of another one is ")"?  In the above example, I would want the resulting array to be

["a", "(b c)", "d", "e"]

Similarly, if my array were

["a", "(b", "e", "c)", "d"]

I would want the result to be

["a", "(b e c)", "d"]

However if the array were

["(a", "c"]

or

["c)", "e", "(b"]

I would want the arrays to be unchanged b/c in the first instance, there is no element with a ")" and in the second instance the element with the ")" is before the element beginning with the "(".  I hope this makes sense.

Body:
The other answer probably fits you better, but just in case, here's an alternate approach, using string parsing:

def parse(str)
  str.scan(/
    (?<token> \g<paren> | \g<word>)
    (?<word> \w+){0}
    (?<paren> \( \g<token> (?:\s+ \g<token>)* \) ){0}
  /x).map(&:first)
end

arr = ["a", "(b", "c)", "d", "e"]
str = arr.join(' ')
parse(str)
# => ["a", "(b c)", "d", "e"]
parse("(a (b c) d) (e (f g)) (h i)")
# => ["(a (b c) d)", "(e (f g))", "(h i)"]


问:
git undo deleted files
I am new to git. I have checkout files from remote. I had to delete few files from the git repo. Instead of doing git rm command, I issued unix rm -rf folder command. I need to revert the delete command and then perform git rm command. How to revert to the latest code?

Note: I have not yet committed the staged files.The out out of git status is the list of files deleted in the below format:

```<code>#   deleted:    i18n/angular-locale_sl.js
#   deleted:    i18n/angular-locale_in.js
</code>```

答:
If you have staged the deletion, first unstage it:

```<code>git reset HEAD path/to/deleted/file
</code>```

Then restore the file:

```<code>git checkout path/to/deleted/file
</code>```

Title: git undo deleted files

Body:
I am new to git. I have checkout files from remote. I had to delete few files from the git repo. Instead of doing git rm command, I issued unix rm -rf folder command. I need to revert the delete command and then perform git rm command. How to revert to the latest code?

Note: I have not yet committed the staged files.The out out of git status is the list of files deleted in the below format:

#   deleted:    i18n/angular-locale_sl.js
#   deleted:    i18n/angular-locale_in.js

Body:
If you have staged the deletion, first unstage it:

git reset HEAD path/to/deleted/file

Then restore the file:

git checkout path/to/deleted/file


问:
How do I do two has_many/belongs_to relationships between two models?
I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

```<code>class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end
</code>```

How do I make two relationships here?

答:
Its similar to the way belongs_to is defined in the other class.

So Basically

```<code>class Contact < ActiveRecord::Base
  has_many :projects_owned, :class_name => "Project", :foreign_key => "owner_id"
  has_many :projects_as_client, :class_name  => "Project", :foreign_key => "client_id"
end
</code>```

names of associations could be better. The Single Table inheritance approach described before me is also a neat way, but go for it if you have a lot of different behaviour for each of the OwnerContact and ClientContact class, otherwise it might be just a useless overhead.

Body:
I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end

How do I make two relationships here?

Body:
Its similar to the way belongs_to is defined in the other class.

So Basically

class Contact < ActiveRecord::Base
  has_many :projects_owned, :class_name => "Project", :foreign_key => "owner_id"
  has_many :projects_as_client, :class_name  => "Project", :foreign_key => "client_id"
end

names of associations could be better. The Single Table inheritance approach described before me is also a neat way, but go for it if you have a lot of different behaviour for each of the OwnerContact and ClientContact class, otherwise it might be just a useless overhead.


问:
Google One-tap declares global variable L
The Google One-tap library causes errors when used with other libraries because it declares a global variable L.

I see this in the minified code but I am not sure what it is doing.

```<code>var L = 0;
function K(g) {
  return "jscomp_symbol_" + (g || "") + L++
}
</code>```

That conflicts with other libraries like LeafletJS that also define a global L
https://github.com/Leaflet/Leaflet

I can't find an open source project for Google's One-tap code to submit a patch. How do I work around this?

答:
Until the bug is corrected in Google One-tap file, you can simply use Leaflet's noConflict mode so that you can reassign Leaflet to any other global variable name you like, and avoid those used by Google library. Since the latter is a minified file, most variables and functions will be 1 or 2 characters long.

// Should actually be BELOW the HTML part,
// but SO insists on displaying the JS part first.

var map = Leaflet.map("map").setView([48.86, 2.35], 12);

Leaflet.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<script>
  // Re-assign L from Leaflet to any other global variable, and avoid conflict
  // with other libraries, like Google One-tap in this case.
  var Leaflet = L.noConflict();
</script>

<script src="https://smartlock.google.com/client"></script>

<div id="map" style="height: 200px;"></div></code>```

Body:
The Google One-tap library causes errors when used with other libraries because it declares a global variable L.

I see this in the minified code but I am not sure what it is doing.

var L = 0;
function K(g) {
  return "jscomp_symbol_" + (g || "") + L++
}

That conflicts with other libraries like LeafletJS that also define a global L
https://github.com/Leaflet/Leaflet

I can't find an open source project for Google's One-tap code to submit a patch. How do I work around this?

Body:
Until the bug is corrected in Google One-tap file, you can simply use Leaflet's noConflict mode so that you can reassign Leaflet to any other global variable name you like, and avoid those used by Google library. Since the latter is a minified file, most variables and functions will be 1 or 2 characters long.

// Should actually be BELOW the HTML part,
// but SO insists on displaying the JS part first.

var map = Leaflet.map("map").setView([48.86, 2.35], 12);

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

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<script>
  // Re-assign L from Leaflet to any other global variable, and avoid conflict
  // with other libraries, like Google One-tap in this case.
  var Leaflet = L.noConflict();
</script>

<script src="https://smartlock.google.com/client"></script>

<div id="map" style="height: 200px;"></div>