问:
Subsonic Join issue
For those of you who are decent with subsonic!

```<code>        TblNewsCollection col =
            new Select().From(Tables.TblNews)
                .InnerJoin(Tables.TblContent)
                .Paged(currentPage, pageSize)
                .OrderDesc(TblContent.Columns.PubDate)
                .ExecuteAsCollection<TblNewsCollection>();
</code>```

The above works, no problem, but when I try to add a where clause

```<code>        TblNewsCollection col =
            new Select().From(Tables.TblNews)
                .InnerJoin(Tables.TblContent)
                .Where(TblContent.Columns.UserFK)
                .IsEqualTo(guidUserFK)
                .Paged(currentPage, pageSize)
                .OrderDesc(TblContent.Columns.PubDate)
                .ExecuteAsCollection<TblNewsCollection>();
</code>```

I get this message

```<code>System.InvalidCastException: Object must implement IConvertible.
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
System.InvalidCastException: Failed to convert parameter value from a Guid to a String.
</code>```

I've tried it from other fields, for example a bit field in a database it says it can't convert from bool to bit!

Seems to only be an issue on where statements after joins

答: I found that joins work better using the TableColumnSchema as in the above Northwind example as opposed to the column name.</p>

OwnerDisplayName: Shahin

Title: Subsonic Join issue

Body:
For those of you who are decent with subsonic!

        TblNewsCollection col =
            new Select().From(Tables.TblNews)
                .InnerJoin(Tables.TblContent)
                .Paged(currentPage, pageSize)
                .OrderDesc(TblContent.Columns.PubDate)
                .ExecuteAsCollection<TblNewsCollection>();

The above works, no problem, but when I try to add a where clause

        TblNewsCollection col =
            new Select().From(Tables.TblNews)
                .InnerJoin(Tables.TblContent)
                .Where(TblContent.Columns.UserFK)
                .IsEqualTo(guidUserFK)
                .Paged(currentPage, pageSize)
                .OrderDesc(TblContent.Columns.PubDate)
                .ExecuteAsCollection<TblNewsCollection>();

I get this message

System.InvalidCastException: Object must implement IConvertible.
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
System.InvalidCastException: Failed to convert parameter value from a Guid to a String.

I've tried it from other fields, for example a bit field in a database it says it can't convert from bool to bit!

Seems to only be an issue on where statements after joins

LastEditorDisplayName: Remou

OwnerDisplayName: ptutt

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
How to rename properties of objects in array in javascript?
I have this javascript objects:

```<code>var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]
</code>```

I need to rename properties with name in arr1 to title:

```<code>var arr = [{id:'124',title:'qqq'},
           {id:'589',title:'www'},
           {id:'45',title:'eee'},
           {id:'567',title:'rrr'}]
</code>```

What is elegant way to implement it in Javascript?

答:
it is not possible to change the name of property, but add a new one and delete the old one, i also got the code from somewhere dont remeber the exact source</p>

```<code>function changeKey(originalKey, newKey, arr)
{
  var newArr = [];
  for(var i = 0; i < arr.length; i++)
  {
    var obj = arr[i];
    obj[newKey] = obj[originalKey];
    delete(obj[originalKey]);
    newArr.push(obj);
  }
  return newArr;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this javascript objects:

var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]

I need to rename properties with name in arr1 to title:

var arr = [{id:'124',title:'qqq'},
           {id:'589',title:'www'},
           {id:'45',title:'eee'},
           {id:'567',title:'rrr'}]

What is elegant way to implement it in Javascript?

Body:
it is not possible to change the name of property, but add a new one and delete the old one, i also got the code from somewhere dont remeber the exact source

function changeKey(originalKey, newKey, arr)
{
  var newArr = [];
  for(var i = 0; i < arr.length; i++)
  {
    var obj = arr[i];
    obj[newKey] = obj[originalKey];
    delete(obj[originalKey]);
    newArr.push(obj);
  }
  return newArr;
}


问:
Transpose lists to form object
What is the most Pythonic way to convert this:

```<code>{'a': ['apple1', 'apple2', 'apple3'], 'b': ['banana1', 'banana2', 'banana3']}
</code>```

into this?

```<code>[{'a': 'apple1', 'b': 'banana1'}, {'a': 'apple2', 'b': 'banana2'}, {'a': 'apple3', 'b': 'banana3'}]
</code>```

I would prefer a solution that doesn't use array comprehensions.

This is my current approach

```<code>d = {
    'a': ['apple1', 'apple2', 'apple3'],
    'b': ['banana1', 'banana2', 'banana3']
}

r = []
for k,v in d.items():
    for i in range(len(v)):
        if len(r) <= i:
            r.append({})
        r[i][k] = v[i]
</code>```

答:
You can use the following approach:

```<code>[dict(zip(d.keys(),vs)) for vs in zip(*d.values())]
</code>```

With d the original dictionary.

This generates:

```<code>>>> [dict(zip(d.keys(),vs)) for vs in zip(*d.values())]
[{'b': 'banana1', 'a': 'apple1'}, {'b': 'banana2', 'a': 'apple2'}, {'b': 'banana3', 'a': 'apple3'}]
</code>```

The code works as follows, it is guaranteed that - given a dictionary is not changed - d.keys() and d.values() generate the keys/values in the same order: so you can dict(zip(d.keys(),d.values())) back into the original dictionary.

Now what we do is we make a transpose of the .values() of the dictionary, by using zip(*d.values()). For each such "column" (of the tranpose), we zip the column with the d.keys() and convert that into a dictionary (with dict(..)), by using list comprehension, we will eventually iterate over all rows.

Mind that the iteration stops from the moment one of the lists in the values is exhausted.

Title: Transpose lists to form object

Body:
What is the most Pythonic way to convert this:

{'a': ['apple1', 'apple2', 'apple3'], 'b': ['banana1', 'banana2', 'banana3']}

into this?

[{'a': 'apple1', 'b': 'banana1'}, {'a': 'apple2', 'b': 'banana2'}, {'a': 'apple3', 'b': 'banana3'}]

I would prefer a solution that doesn't use array comprehensions.

This is my current approach

d = {
    'a': ['apple1', 'apple2', 'apple3'],
    'b': ['banana1', 'banana2', 'banana3']
}

r = []
for k,v in d.items():
    for i in range(len(v)):
        if len(r) <= i:
            r.append({})
        r[i][k] = v[i]

Body:
You can use the following approach:

[dict(zip(d.keys(),vs)) for vs in zip(*d.values())]

With d the original dictionary.

This generates:

>>> [dict(zip(d.keys(),vs)) for vs in zip(*d.values())]
[{'b': 'banana1', 'a': 'apple1'}, {'b': 'banana2', 'a': 'apple2'}, {'b': 'banana3', 'a': 'apple3'}]

The code works as follows, it is guaranteed that - given a dictionary is not changed - d.keys() and d.values() generate the keys/values in the same order: so you can dict(zip(d.keys(),d.values())) back into the original dictionary.

Now what we do is we make a transpose of the .values() of the dictionary, by using zip(*d.values()). For each such "column" (of the tranpose), we zip the column with the d.keys() and convert that into a dictionary (with dict(..)), by using list comprehension, we will eventually iterate over all rows.

Mind that the iteration stops from the moment one of the lists in the values is exhausted.


问:
Access external project static web resources from Struts2.5 web server
I have some files in a lib package that I am currently working on. It needs to be used by multiple projects so I can't put the files directly within my web server.

I want my Struts2.5 web server to be able to serve some static files from my Lib package. I was looking into using a web-fragment.xml solution, but from what I gather from oracle, this is only going to work if I compile my library package and put it in my META-INF directory somewhere. That's fine and all, but really inconvenient for any sort of development or testing, as I will need to make a new build and copy it there every time I make changes to the html/js. This sounds to me like the wrong solution.

If there is a way to do this with the xml configuration, it hasn't been made clear from what I've read. If I could be pointed in the right direction, that would be helpful.

Otherwise, if there's a way to do this in Eclipse somehow that would also be acceptable. For the record, this project is referenced by the other project in eclipse as a required project in my Java Build Path.

答:
Put static files under Web Content Root (/). If you want Struts to serve your static content then put it under /static. Struts can also serve static content from the classpath, but it seems not an option for you.

Read my answer for Load image in jsp from different URL but same domain:

You can read more about static content loader and configuration settings in the docs for Static Content.

You can reuse the same static files from other web applications if you package and deploy static files in another .war file and specify a context path to access these files from your application. It could be served from the same domain or different domain.

You can deploy a web application with static files as web archive exploded, so you don't need to package them every time you deploy the application, and if it's a different application you don't need to redeploy other applications, unless they are affected by the access path to files.

Another approach is that you share the project with static content with other projects in Eclipse, because Eclipse copies the project files to the final .war during the building, and every web app will have its own copy of the shared files. If you want to modify some shared files, then you need to rebuild/redeploy only the project you working on. Other projects that has this project as dependency could be rebuilt/redeployed on demand. It seems most reliable solution, because modifying some web app doesn't affect other web apps running.

ContentLicense: CC BY-SA 4.0


问:
how to go to previouse lines of an algorithm in matlab
I have an algorithm that I want go to previouse lines of it in MATLAB.

for example: 4-14- Correct the value of i from Equation i = i+1 and go to step 3–4.
Or I want to do: Step 5-Correct the value of k from the equation k = k + 1. If k>a-b, go to step 6; otherwise, go to step 4.

in this cases how can I go to step 3-4 from 4-14 ? or in second example how can I go to Step 4 after Step 6?

答:
It is hard to say without more information, but why don't you structure your code in different functions and use "switch case" to control the logic? This would make your code more modular, easier to read and debug (which usually a nightmare in codes using "goto" clauses).
In any case, there is at least one "goto" function in the Matlab file exchange repository.</p>


问:
Check if ALL elements of list A within list B
I have done my research, however all these techniques return true, i need them to return false.

```<code>print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True
</code>```

The lists I'm comparing have duplicate numbers

答:
Mathematically answers by python functions are correct. It seems you also want to check the the number of elements. So, a user defined function will look like

```<code>def compare(listsuper,listsub):
   stat=None
   for element in listsuper:
       if listsuper.count(element)==listsub.count(element):
          pass
       else:
          stat=False
   if stat==None:
       for element in listsub:
           if element in listsub and element in listsuper:
               pass
           else:
               stat=False
   if stat==None:
       stat=True
   return stat
print compare([2,3,3],[2, 2])
</code>```

Hope this function works as you want

Body:
I have done my research, however all these techniques return true, i need them to return false.

print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True

The lists I'm comparing have duplicate numbers

Body:
Mathematically answers by python functions are correct. It seems you also want to check the the number of elements. So, a user defined function will look like

def compare(listsuper,listsub):
   stat=None
   for element in listsuper:
       if listsuper.count(element)==listsub.count(element):
          pass
       else:
          stat=False
   if stat==None:
       for element in listsub:
           if element in listsub and element in listsuper:
               pass
           else:
               stat=False
   if stat==None:
       stat=True
   return stat
print compare([2,3,3],[2, 2])

Hope this function works as you want


问:
Disclosure indicator to specific cell in static TableView in Swift
I created a static TableView and I would like to add or remove a disclosure indicator depending if we are consulting our own account or a guest account.

This is what I would like :

```<code>let index = IndexPath(row: 4, section: 0)

let cell = tableView.cellForRow(at: index)
if currentUser {
   cell.accessoryType = .none
   //cell.backgroundColor = UIColor.red
}
</code>```

I tried to put it in the viewDidLoad function but it didn't work. I tried cellForRowAt indexPath also and same result.

How could I do that?

答:
Please use below code in cellForRowTableView code

It will work for you

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    if currentUser {
     // Own Account
       cell.accessoryType = .none
       //cell.backgroundColor = UIColor.red
    }else{
     //Guest Account
     cell.accessoryType =.checkmark
    }
}
</code>```

Body:
I created a static TableView and I would like to add or remove a disclosure indicator depending if we are consulting our own account or a guest account.

This is what I would like :

let index = IndexPath(row: 4, section: 0)

let cell = tableView.cellForRow(at: index)
if currentUser {
   cell.accessoryType = .none
   //cell.backgroundColor = UIColor.red
}

I tried to put it in the viewDidLoad function but it didn't work. I tried cellForRowAt indexPath also and same result.

How could I do that?

Body:
Please use below code in cellForRowTableView code

It will work for you

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    if currentUser {
     // Own Account
       cell.accessoryType = .none
       //cell.backgroundColor = UIColor.red
    }else{
     //Guest Account
     cell.accessoryType =.checkmark
    }
}


问:
Converting SSIS packages into Cloud Azure
how to convert SSIS packages into Cloud azure.

Also please can you tell me something about SSIS packages and what is not supported in CLoud.

答:
SSIS is not supported in SQL Azure at all for now.

If you have to run it, you have 3 options that I can see:

Install SQL Server standard on a VM role in the cloud and run it on that.

Put your database in the cloud, but run the package on a local machine and just connect to the remote database.

Rewrite your SSIS logic as an Azure worker role


问:
Android application restarts if homescreen icon clicked after opened from folder and vice versa but only if downloaded from Play Market
Maybe someone has come across this error. It is a mindbreaker.

I have developed an app. If I sideload it to my android device Samsung J1 it works fine. I mean debug or load from my website via browser. It installs into the applications folder. I create a shortcut for the homescreen the usual way after it is intalled by simply holding down the icon in the applications folder and we get the expected behaviour which was experienced during the debug.

Expected behaviour (which is also the behaviour if sideloaded, dowloaded from website via browser onto device) works fine!

1) Open app from application folder, do anyhting with the app. Go to homescreen, do whatever and re open app from homescreen shortcut or from applications folder the app RESUMES. That is totally fine. We can start from where we finished.

Unexpected behaviour if downloaded from google play store

1) Start app from homescreen. Go to app folder, press on app icon, app starts again and bad things happen because ot the business logic inside app. Vice versa same thing. Start app from app folder, go to homescreen and click on app icon app restarts, doesn't resume.

Play Store makes changes to the app and this happens. Also I have noticed that the package size is significantly smaller when downloading from the store so it is definetly doing something to the files.

Anyway there seems to be quite a few posts that address this issue but I couldn't find the exact same situation described so hopefully a solvation to this instance could provide a valuble contribution to the community. Thanks!

答:
So after a little research, I have figured out the answer that worked for me. In the Xamarin Anroid project in MainActivity.cs add LaunchMode = LaunchMode.SingleInstance to the activity label.

The manifesto is compiled automaticaly so you can't change the xml directly, instead you just work with the class file. So in the end it looks something like this.

Paste the below code above the main activity class code. Notice the added LaunchMode = LaunchMode.SingleInstance tag which actually adds

<activity android:launchMode="singleInstanc>e"  to the Manifesto.xml

```<code>[Activity(Label = "LavkaLavka",
    Icon = "@drawable/icon",
    Theme = "@style/MainTheme",
    MainLauncher = true,
    LaunchMode = LaunchMode.SingleInstance,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{

    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
    }
}
</code>```

Body:
So after a little research, I have figured out the answer that worked for me. In the Xamarin Anroid project in MainActivity.cs add LaunchMode = LaunchMode.SingleInstance to the activity label.

The manifesto is compiled automaticaly so you can't change the xml directly, instead you just work with the class file. So in the end it looks something like this.

Paste the below code above the main activity class code. Notice the added LaunchMode = LaunchMode.SingleInstance tag which actually adds

<activity android:launchMode="singleInstanc>e"  to the Manifesto.xml

[Activity(Label = "LavkaLavka",
    Icon = "@drawable/icon",
    Theme = "@style/MainTheme",
    MainLauncher = true,
    LaunchMode = LaunchMode.SingleInstance,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{

    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
    }
}


问:
Send data from java mail in HTML Table
I am trying to send data from my Java mail application in the form of a HTML table. The problem is that when I receive the mail, the data is in simple text format and not in a table form. Please suggest a solution</p>

```<code>StringBuilder sb1 = new StringBuilder(200);
sb1.append("<html><body>"+ "<table style='border:2px solid black'>");
for(SCSINPojo cat : ar){

    sb1.append("<tr>");
    sb1.append(cat.getINNumber())
       .append("<td>")
       .append(cat.getDescription())
       .append("</td><td>")
       .append(cat.getStatus())
       .append("</td><td>")
       .append(cat.getStatus())
       .append("</td><td>")
       .append(cat.getOwner())
       .append("</td><td>")
       .append(cat.getOwnerGroup())
       .append("</td><td>")
       .append(cat.getSeverity());
    sb1.append("</tr>");
    String in = sb1.toString();

}
sb1.append("</table></body></html>");

message.setText(sb1.toString());

Transport.send(message);
</code>```

答:
Try this...you can even print it out to an HTML file and so I have added some break lines for appearance.</p>

```<code>sb1.append("<html><body><br/>"+ "<table style='border:2px solid black'><br/>");
    for(SCSINPojo cat : ar){

        sb1.append("<tr><br/><td>");
        sb1.append(cat.getINNumber())
           .append("</td><br/><td>")
           .append(cat.getDescription())
           .append("</td><br/><td>")
           .append(cat.getStatus())
           .append("</td><br/><td>")
           .append(cat.getStatus())
           .append("</td><br/><td>")
           .append(cat.getOwner())
           .append("</td><br/><td>")
           .append(cat.getOwnerGroup())
           .append("</td><br/><td>")
           .append(cat.getSeverity());
        sb1.append("</td><br/><td>");
        String in = sb1.toString();

    }
    sb1.append("</table></br></body></html>");
</code>```

Title: Send data from java mail in HTML Table

Body:
I am trying to send data from my Java mail application in the form of a HTML table. The problem is that when I receive the mail, the data is in simple text format and not in a table form. Please suggest a solution

StringBuilder sb1 = new StringBuilder(200);
sb1.append(""+ "
");
for(SCSINPojo cat : ar){

    sb1.append("
");
    sb1.append(cat.getINNumber())
       .append("")
       .append(cat.getDescription())
       .append("	")
       .append(cat.getStatus())
       .append("	")
       .append(cat.getStatus())
       .append("	")
       .append(cat.getOwner())
       .append("	")
       .append(cat.getOwnerGroup())
       .append("	")
       .append(cat.getSeverity());
    sb1.append("
");
    String in = sb1.toString();

}
sb1.append("
");

message.setText(sb1.toString());

Transport.send(message);

Body:
Try this...you can even print it out to an HTML file and so I have added some break lines for appearance.

sb1.append("<html><body><br/>"+ "<table style='border:2px solid black'><br/>");
    for(SCSINPojo cat : ar){

        sb1.append("<tr><br/><td>");
        sb1.append(cat.getINNumber())
           .append("</td><br/><td>")
           .append(cat.getDescription())
           .append("</td><br/><td>")
           .append(cat.getStatus())
           .append("</td><br/><td>")
           .append(cat.getStatus())
           .append("</td><br/><td>")
           .append(cat.getOwner())
           .append("</td><br/><td>")
           .append(cat.getOwnerGroup())
           .append("</td><br/><td>")
           .append(cat.getSeverity());
        sb1.append("</td><br/><td>");
        String in = sb1.toString();

    }
    sb1.append("</table></br></body></html>");


问:
LINQ and column with Null
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

```<code>MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

答:
Try Code:</p>

```<code>var query = from  tbl in dt.AsEnumerable()
        where tbl.Field<dynamic>("A") == parentId
        &&    tbl.Field<dynamic>("B") == languageId
        select tbl;
</code>```

Title: LINQ and column with Null

Body:
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

Body:
Try Code:

var query = from  tbl in dt.AsEnumerable()
        where tbl.Field<dynamic>("A") == parentId
        &&    tbl.Field<dynamic>("B") == languageId
        select tbl;


问:
Order Automated TFS Builds (Mac)
I am using TFS 2015 to perform automated builds of my libraries in a cross-platform environment. I just added support for building my libraries on macOS but I am unable to figure out how to order the builds. Here is my situation:

I have libraries A, B, and C (in separate build definitions). Library B depends on library A, and library C depends on library B. Libraries A, B, and C have a small bit of overlap in terms of shared files in TFS, so when a user checks in files from these overlapped directories, all of the libraries are built, but in random order. I need to be able to build library A first, then library B, then library C.

Any help in configuring this (in a way other than creating a single build definition)?

答:
Unfortunately, there is no such feature to control the order of vNext build and  move items up / down in the queue.

There is no logical order and without any configuration to control this.

I have created a uservoice for you, you could vote up and monitor it. TFS PM and Admin will kindly review the suggestion.

Order TFS vNext Builds

https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/19960372-order-tfs-vnext-builds

For now you have to use the workaround, creating a new single build definition to combine them.

Title: Order Automated TFS Builds (Mac)


问:
can we instrument UPC code with PAPI API calls
I want to instrument my UPC program with PAPI APIs to get information on hardware counters during the execution of UPC program.

But i keep getting linking errors for eg, "undefined reference to PAPI_read" undefined reference to PAPI_library_init etc

The command I'm giving is
upcc -L/full/path/to/libpapi.a -o upcMatrxMultplction upcMatrxMultplction.o

Any suggestions ?

Does PAPI support UPC compiler ?

答:
-L provides a directory, not a think to link with.  you should either provide the /full/path/to/libpapi.a as a link argument (along with *.o), or else use "-L/full/path/to -lpapi".  the latter is a bit more conventional.

also, linking can be order-dependent, so I prefer to list all to-link objects first and end the line with -o whatever.


问:
how to remove common elements between two cell arrays from the first one in MATLAB?
How to remove common elements between two cell arrays from the first one in MATLAB?

for example:

```<code> A={[1 3 2],[2 3 1],[3 1 2]} & B={[1 3 2],[3 2 1]}
</code>```

A & B are two cell arrays. I want to find A-B. for this purpose I want to remove common elements between A & B from A. How can I do that?

答:
I wrote a small function that works when A and B both are vectors:

```<code>function A = celldiff(A, B)
for ii = 1:length(B)
    inA = arrayfun(@(x) isequal(A{x}, B{ii}), 1:length(A));
    A = A(~inA);
end
end
</code>```

Example with your defined inputs:

```<code>>> A={[1 3 2],[2 3 1],[3 1 2]};
>> B={[1 3 2],[3 2 1]};
>> C = celldiff(A, B);
>> C{:}
ans =
     2     3     1
ans =
     3     1     2
</code>```

Body:
How to remove common elements between two cell arrays from the first one in MATLAB?

for example:

 A={[1 3 2],[2 3 1],[3 1 2]} & B={[1 3 2],[3 2 1]}

A & B are two cell arrays. I want to find A-B. for this purpose I want to remove common elements between A & B from A. How can I do that?

Body:
I wrote a small function that works when A and B both are vectors:

function A = celldiff(A, B)
for ii = 1:length(B)
    inA = arrayfun(@(x) isequal(A{x}, B{ii}), 1:length(A));
    A = A(~inA);
end
end

Example with your defined inputs:

>> A={[1 3 2],[2 3 1],[3 1 2]};
>> B={[1 3 2],[3 2 1]};
>> C = celldiff(A, B);
>> C{:}
ans =
     2     3     1
ans =
     3     1     2


答:
Here's how you delete key and value and assign to new key:

var arr = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]

arr.forEach(function(o) {
    Object.defineProperty(o, 'title',
        Object.getOwnPropertyDescriptor(o, 'name'));
    delete o['name'];
});
console.log(arr);```

Title: How to rename properties of objects in array in javascript?


问:
Faster way of checking if dialog has closed?
I'm automating an application (pywinauto ver 0.6.2) in which I:

search for a record

open a dialog

make changes

click an OK button

wait for the dialog to close

when closed, search for the next record, repeat

In the 'wait for the dialog to close' step I am using:

```<code>dlg.wait_not("visible", timeout=60)
</code>```

This works most of the time, but sometimes it not only doesn't detect that the dialog has closed, but it also doesn't appear to do anything at the 60 second mark.

Is there a better way to detect the close of a window?

答: The bug with timings is fixed in pywinauto 0.6.3. Please update it with pip install -U pywinauto. Method wait_not is also affected.

Body:
I'm automating an application (pywinauto ver 0.6.2) in which I:

search for a record

open a dialog

make changes

click an OK button

wait for the dialog to close

when closed, search for the next record, repeat

In the 'wait for the dialog to close' step I am using:

dlg.wait_not("visible", timeout=60)

This works most of the time, but sometimes it not only doesn't detect that the dialog has closed, but it also doesn't appear to do anything at the 60 second mark.

Is there a better way to detect the close of a window?


问:
How to Change one controller value into another Control
```<code>var getAgentBalanceAmount = function (ClientId, UserId) {
    $http({
        method: 'GET',
        url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
    })
    .then(function success(response) {
        $scope.getBalAmount = response.data[0].BalanceAmount;
    }, function error(response) {
        alert('Error');
    });
};
</code>```

In this method  $scope.getBalAmount have some value and bind into index.html page.here index page act as a master page.i want to change this value on other pages(in content page.) is it possible.Thanks in advance.

答:
Use a factory. If you want to use factory, inject factory(UserService) in controller.

For getting amount value in index.html, inject factory in appropriate controller and use get method.

```<code>$scope.amount = UserService.getBalAmount();
</code>```

JS

```<code>var getAgentBalanceAmount = function (ClientId, UserId) {
  $http({
    method: 'GET',
    url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId;
  })
  .then(function success(response) {
    UserService.setBalAmount(response.data[0].BalanceAmount);
  }, function error(response) {
    alert('Error');
  });
};
</code>```

Factory

```<code>app.factory("UserService", function() {
  var balAmount;
  return {
    getBalAmount: function() {
      return balAmount;
    },
    setBalAmount: function(amount) {
      balAmount = amount;
    }
  };
</code>```

Body:
var getAgentBalanceAmount = function (ClientId, UserId) {
    $http({
        method: 'GET',
        url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
    })
    .then(function success(response) {
        $scope.getBalAmount = response.data[0].BalanceAmount;
    }, function error(response) {
        alert('Error');
    });
};

In this method  $scope.getBalAmount have some value and bind into index.html page.here index page act as a master page.i want to change this value on other pages(in content page.) is it possible.Thanks in advance.

Body:
Use a factory. If you want to use factory, inject factory(UserService) in controller.

For getting amount value in index.html, inject factory in appropriate controller and use get method.

$scope.amount = UserService.getBalAmount();

JS

var getAgentBalanceAmount = function (ClientId, UserId) {
  $http({
    method: 'GET',
    url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId;
  })
  .then(function success(response) {
    UserService.setBalAmount(response.data[0].BalanceAmount);
  }, function error(response) {
    alert('Error');
  });
};

Factory

app.factory("UserService", function() {
  var balAmount;
  return {
    getBalAmount: function() {
      return balAmount;
    },
    setBalAmount: function(amount) {
      balAmount = amount;
    }
  };


问:
Duplicate edges with same properties neo4j
I have two nodes between which, same edge with same property is being created over and over again. How can I avoid this? If the edges have different properties, its ok and it needs to be kept but if the properties are same, there should be one edge only.

EDIT: I'm using rails and I want to do this through application and not Cypher query.

EDIT: Sharing some code for relevance:

```<code>dis = Disease.where(disease: params[:disease]).first
fac = Factor.where(factor: params[:factor])
dis.factors.create(fac, prop: "p1")
</code>```

So, what I want is if I input same disease and factor, it not duplicate the edge (which it is currently doing) as property being set is also same. However, if in future, this p1 changes to p2, then the edge should be added.

Refer post Neo4j inconsistent behaviour of model classes for model classes (Disease and factor).

答:
You need to use MERGE keyword in cypher : it Match a pattern or create it if it does not exist.

This is an example based on the movie graph :

```<code>MATCH (neo:Person { name:"Keanu Reeves"})
MATCH (matrix:Matrix { title:"The Matrix"})
MERGE (neo)-[:ACTED_IN {roles:['neo']}]->(matrix)
</code>```

You can execute this query multi-times, you will only have one edge between Neo & Matrix.

Cheers

Body:
I have two nodes between which, same edge with same property is being created over and over again. How can I avoid this? If the edges have different properties, its ok and it needs to be kept but if the properties are same, there should be one edge only.

EDIT: I'm using rails and I want to do this through application and not Cypher query.

EDIT: Sharing some code for relevance:

dis = Disease.where(disease: params[:disease]).first
fac = Factor.where(factor: params[:factor])
dis.factors.create(fac, prop: "p1")

So, what I want is if I input same disease and factor, it not duplicate the edge (which it is currently doing) as property being set is also same. However, if in future, this p1 changes to p2, then the edge should be added.

Refer post Neo4j inconsistent behaviour of model classes for model classes (Disease and factor).

Body:
You need to use MERGE keyword in cypher : it Match a pattern or create it if it does not exist.

This is an example based on the movie graph :

MATCH (neo:Person { name:"Keanu Reeves"})
MATCH (matrix:Matrix { title:"The Matrix"})
MERGE (neo)-[:ACTED_IN {roles:['neo']}]->(matrix)

You can execute this query multi-times, you will only have one edge between Neo & Matrix.

Cheers


问:
update sql database with ContentValues and the update-method
I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.

```<code>ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{
    db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
    String error =  e.getMessage().toString();
}
</code>```

but I get following error:

android.database.sqlite.SQLiteException: near "15": syntax error: ,
  while compiling: UPDATE mytable SET location=?, name=? WHERE
  id=2010-09-21 15:05:36.995

I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.

答:
I have an other approach</p>

```<code>    public boolean updateEmployee(TalebeDataUser fav) {

    SQLiteDatabase database = dbHelper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(DBHelper.COLUMN_ID, fav.getId());
    contentValues.put(DBHelper.COLUM_AD, fav.getAd());
    contentValues.put(DBHelper.COLUMN_NUMARA, fav.getNumara());
    contentValues.put(DBHelper.COLUMN_YURD_ID, fav.getYurtID());
    contentValues.put(DBHelper.COLUMN_EGITIM_ID, fav.getEgitimTur());
    contentValues.put(DBHelper.COLUMN_TEL, fav.getTel());
    contentValues.put(DBHelper.COLUMN_EMAIL, fav.getEmail());
    contentValues.put(DBHelper.COLUMN_ADDRESS, fav.getAdres());

    String whereClause = DBHelper.COLUM_AD + " = ? AND " + DBHelper.COLUMN_NUMARA + " = ? ";
    final String whereArgs[] = {fav.getAd(), String.valueOf(fav.getNumara())};// old nameler taranıyor
    int affectedRows = database.update(DBHelper.TABLE_NAME_OGR, contentValues, whereClause, whereArgs);
    return affectedRows > 0;
}
</code>```

Body:
I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.

ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{
    db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
    String error =  e.getMessage().toString();
}

but I get following error:

android.database.sqlite.SQLiteException: near "15": syntax error: ,
  while compiling: UPDATE mytable SET location=?, name=? WHERE
  id=2010-09-21 15:05:36.995

I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.

Body:
I have an other approach

    public boolean updateEmployee(TalebeDataUser fav) {

    SQLiteDatabase database = dbHelper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(DBHelper.COLUMN_ID, fav.getId());
    contentValues.put(DBHelper.COLUM_AD, fav.getAd());
    contentValues.put(DBHelper.COLUMN_NUMARA, fav.getNumara());
    contentValues.put(DBHelper.COLUMN_YURD_ID, fav.getYurtID());
    contentValues.put(DBHelper.COLUMN_EGITIM_ID, fav.getEgitimTur());
    contentValues.put(DBHelper.COLUMN_TEL, fav.getTel());
    contentValues.put(DBHelper.COLUMN_EMAIL, fav.getEmail());
    contentValues.put(DBHelper.COLUMN_ADDRESS, fav.getAdres());

    String whereClause = DBHelper.COLUM_AD + " = ? AND " + DBHelper.COLUMN_NUMARA + " = ? ";
    final String whereArgs[] = {fav.getAd(), String.valueOf(fav.getNumara())};// old nameler taranıyor
    int affectedRows = database.update(DBHelper.TABLE_NAME_OGR, contentValues, whereClause, whereArgs);
    return affectedRows > 0;
}


问:
Kafka Streams API: KStream to KTable 1
I have a cluster kafka with 3 brokers and  I have 300 topics.

I want to start processing using API kafka streams on each topic independently with others and write the results  of each input topic to specific topic

```<code>inputtopic1 to outputtopic1
inputtopic2  to outputtopic2
inputtopic3 to outputtopic3
inputtopic4 to outputtopic4
</code>```

etc

Any ideas ?

答:
http://docs.confluent.io/current/streams/developer-guide.html#writing-streams-back-to-kafka

To() -> Terminal operation. Write the records to a Kafka topic. (KStream details, KTable details)

When to provide serdes explicitly:

If you do not specify serdes explicitly, the default serdes from the configuration are used.
You must specificy serdes explicitly if the key and/or value types of the KStream or KTable do not match the configured default serdes.
See Data types and serialization for information about configuring default serdes, available serdes, and implementing your own custom serdes.
Several variants of to exist to e.g. specify a custom StreamPartitioner that gives you control over how output records are distributed across the partitions of the output topic.

Title: Kafka Streams API: KStream to KTable 1

Body:
I have a cluster kafka with 3 brokers and  I have 300 topics.

I want to start processing using API kafka streams on each topic independently with others and write the results  of each input topic to specific topic

inputtopic1 to outputtopic1
inputtopic2  to outputtopic2
inputtopic3 to outputtopic3
inputtopic4 to outputtopic4

etc

Any ideas ?


问:
Disable comment generation in public class method snippet
Right now VScode automatically inserts a comment before the public class method, which is kind of annoying since I often don't need the comment right away (I'd better use JSDoc snippets to have a nice documentation generated later).

How can I disable this behavior?

答:
The public method completion is a snippet. If you do not wish to use the snippets, simply set:

```<code>"editor.snippetSuggestions": "none"
</code>```

You can also create your own snippets to customize the text that is inserted

Body:
The public method completion is a snippet. If you do not wish to use the snippets, simply set:

"editor.snippetSuggestions": "none"

You can also create your own snippets to customize the text that is inserted


问:
Using multithreading to speed up web crawler written by beautifulsoup4 and python
I am writing a web crawler to extract the information of a website. However, since I am using Beautiful Soup 4 to extract large amount of data on window, the crawling speed is extremely slow. Can Anyone tell me how to use multi threading in my case. Thank you so much if you wanna help me. My code is as below:</p>

```<code>import requests
from html.parser import HTMLParser
from bs4 import BeautifulSoup
import re
import time
import sys
import json

HTML_PARSER = "html.parser"

def get_shop_link_list(links):
global food_id
list_req=requests.get(links)
if list_req.status_code == requests.codes.ok:
    soup = BeautifulSoup(list_req.content, HTML_PARSER)
    link_tag=soup.find_all('h2',{'class':'heavy break-word'})
    for h2 in link_tag:
        print(food_id,end="@")
        link=h2.find('a')
        parse_shop_information(link['href'])
        food_id=food_id+1
        print("")
#turn next page
    try:
        next_page=soup.find('a',{'class':'button -small'})
        get_shop_link_list(next_page['href'])
    except KeyError:
        pass

def parse_shop_information(shop_link):
req=requests.get(shop_link)
if req.status_code == requests.codes.ok:
    soup = BeautifulSoup(req.content, HTML_PARSER)

    #restaurant name
    shop_header_tags = soup.find('div',{'class' : 'cassette'})
    japname_tag=shop_header_tags.find('p',{'class':'small'})
    print(japname_tag.get_text(" ",strip=True).encode(encoding="utf-8",errors="strict").decode(sys.stdin.encoding).strip(),end="@")
    name_tag = shop_header_tags.find('h1',{'class' : 'jumbo break-word'})
    print(name_tag.get_text(" ",strip=True).encode(encoding="utf-8",errors="strict").decode(sys.stdin.encoding).strip(),end="@")
    #Basic information
    shop_body_tags = soup.find('ul',{'class' : 'icon-list -space sentence'})
    information = shop_body_tags.find_all('li')
    for li in information:
        print((li.get_text("|",strip=True).encode(encoding="utf-8",errors="strict")).strip(),end="{")
    #Detail information
    restaurant_detail = soup.find_all("table", {"class":"table sentence"})
    basic_detail=restaurant_detail[0].find_all('tr')
    address="No record"
    address_pic="No record"
    access="No record"
    parking="No record"
    service="No record"
    cards="No record"
    for tr in basic_detail:
        if tr.find('th').get_text(" ",strip=True)=='Address':
            address=((tr.find('p').get_text(" ",strip=True)))
            address_pic=((tr.find('img')["src"]))
        if tr.find('th').get_text(" ",strip=True)=='Access':
            access=((tr.find('td').get_text(" ",strip=True)))
        if tr.find('th').get_text(" ",strip=True)=='Parking':
            parking=((tr.find('td').get_text(" ",strip=True)))
        if tr.find('th').get_text(" ",strip=True)=='Service charge':
            service=((tr.find('td').get_text(" ",strip=True)))
        if tr.find('th').get_text(" ",strip=True)=='Cards Accepted':
            cards=((tr.find('td').get_text(" ",strip=True)))
    print(address.strip(),end="@")
    print(address_pic.strip(),end="@")
    print(access.strip(),end="@")
    print(parking.strip(),end="@")
    print(service.strip(),end="@")
    print(cards.strip(),end="@")

    try:
        facility_detail=restaurant_detail[1].find_all('tr')
        seating="No record"
        MPS="No record"
        RMPS="No record"
        Smoking="No record"
        WAR="No record"
        KF="No record"
        LS="No record"
        WP="No record"
        Other="No record"
        for tr in facility_detail:
            if tr.find('th').get_text(" ",strip=True)=='Seating Capacity':
                seating=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Banquet Maximum Party Size':
                MPS=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Reservation Maximum Party Size':
                RMPS=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Smoking':
                Smoking=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Wheelchair Accessible Restrooms':
                WAR=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Kid Friendly':
                KF=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Language Support':
                LS=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Wi-Fi  /  Plug-in':
                WP=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Other':
                Other=((tr.find('td').get_text(" ",strip=True)))
        print(seating.strip(),end="@")
        print(MPS.strip(),end="@")
        print(RMPS.strip(),end="@")
        print(Smoking.strip(),end="@")
        print(WAR.strip(),end="@")
        print(KF.strip(),end="@")
        print(LS.strip(),end="@")
        print(WP.strip(),end="@")
        print(Other.strip(),end="@")

    except IndexError:
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")

    try:
        other_detail=restaurant_detail[2].find_all('tr')
        menu="No record"
        lunch="No record"
        dress_code="No record"
        Delivery="No record"
        for tr in other_detail:
            if tr.find('th').get_text(" ",strip=True)=='Lunch Service':
                lunch=(tr.find('td').get_text(" ",strip=True))
            if tr.find('th').get_text(" ",strip=True)=='Dress Code':
                dress_code=(tr.find('td').get_text(" ",strip=True))

            if tr.find('th').get_text(" ",strip=True)=='Menu':
                lunch=(tr.find('td').get_text(" ",strip=True))
            if tr.find('th').get_text(" ",strip=True)=='Delivery / Catering':
                dress_code=(tr.find('td').get_text(" ",strip=True))
        print(menu.strip(),end="@")
        print(lunch.strip(),end="@")
        print(dress_code.strip(),end="@")
        print(Delivery.strip(),end="@")
    except IndexError:
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")

    try:
        main_col_tag=soup.find('div',{'class':'global-navigation'})
        main_col=main_col_tag.find_all('li')
        for li in main_col:
            if li.find('a').get_text()=="Menu":
                print("{",end="")
                sub_menu(shop_link)
                print("}",end="")
    except (IndexError, AttributeError):
        print("No record",end="@")

def sub_menu(link):
list_req=requests.get(link)
if list_req.status_code == requests.codes.ok:
    soup=BeautifulSoup(list_req.content,HTML_PARSER)
    all_menu_tag=soup.find('ul',{'class':'-sub-menu hide'})
    menus=all_menu_tag.find_all('li')
    for i, li in enumerate(menus):
        type=li.find('a').get_text()
        print("\"",end="")
        print(type,end="\":[")
        link=li.find('a')
        sub_menu_json(link['href'])
        if i != len(menus)-1:
            print("]",end=",")
        else:
            print("]",end="")

def sub_menu_json(link):
list_req=requests.get(link)
if list_req.status_code == requests.codes.ok:
    soup = BeautifulSoup(list_req.content, HTML_PARSER)
    eachfood=soup.find_all('div',{'class':'cassette normal-colored'})
    for i,div in enumerate(eachfood):
        food_jap_name="No record"
        food_eng_name="No record"
        food_price="No record"
        tax_inclusion="No record"
        description="No record"
        if div.find('div',{'class':'small'}):
            food_jap_name=div.find('div',{'class':'small'}).get_text(" ",strip=True)
        if div.find('h3',{'class':'huge'}):
            food_eng_name=div.find('h3',{'class':'huge'}).get_text(" ",strip=True)
        if div.find('h3',{'class':'huge abit-spacing'}):
            food_eng_name=div.find('h3',{'class':'huge'}).get_text(" ",strip=True)
        if div.find('p',{'class':'small spacing'}):
            food_price=div.find('p',{'class':'small spacing'}).get_text(" ",strip=True)
        if div.find('span',{'class':'-value'}):
            food_price=div.find('span',{'class':'-value'}).get_text(" ",strip=True)
        if div.find('p',{'class':'text-right small'}):
            tax_inclusion=div.find('p',{'class':'text-right small'}).get_text(" ",strip=True)
        if div.find('div',{'class':'panel -light-silver -in'}):
            description=div.find('div',{'class':'panel -light-silver -in'}).get_text(" ",strip=True)
        if div.find('div',{'class':'sake-detail'}):
            description=div.find('div',{'class':'sake-detail'}).get_text(" ",strip=True)
        print("{\"JpnFoodname:\":",end="\"")
        print(food_jap_name.encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"EngFoodname\":",end="\"")
        print(food_eng_name.encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"Price\":",end="\"")
        print(food_price.strip().encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"TaxIncludeExclude\":",end="\"")
        print(tax_inclusion.strip().encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"Description\":",end="\"")
        print(description.strip().encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        if div.find('a') or div.find('img'):
            print("\"ImgUrl:\":",end="\"")
            if div.find('img'):
                food_pic=div.find('img')["src"]
            if div.find('a'):
                food_pic=div.find('a')['href']
            print(food_pic,end="\"}")
        else:
            print("\"ImgUrl:\":\"No record\"",end="}")
        if i != len(eachfood)-1:
            print(',',end="")

if __name__ == '__main__':
global food_id
food_id=1
get_shop_link_list("https://gurunavi.com/en/reg/pf_tokyo/rs/srh/?p=461")
</code>```

答:
Here's an outline of what you can do; split the work into individual jobs, add the jobs to a jobQueue and start as many processes as you need (you pass the jobQueue to each one)

Each process takes one job from the queue as log as there are still jobs to process.

This way the number of workers is configurable

```<code>import multiprocessing,Queue

def getData(tasksQ):
    while (True):
        try:
            job=tasksQ.get(block = False)
        except Queue.Empty:
            break;
        else:
            <do_work>

tasks = multiprocessing.Queue()

for job in getJob():
  tasks.put(job)

noOfProcesses = 10
processes = []
for i in range(noOfProcesses):
  p = multiprocessing.Process(target = getData, args=(tasks,))
        processes.append(p)

for p in processes:
    p.start()

for p in processes:
    p.join()
</code>```

Hope this helps.

Body:
I am writing a web crawler to extract the information of a website. However, since I am using Beautiful Soup 4 to extract large amount of data on window, the crawling speed is extremely slow. Can Anyone tell me how to use multi threading in my case. Thank you so much if you wanna help me. My code is as below:

import requests
from html.parser import HTMLParser
from bs4 import BeautifulSoup
import re
import time
import sys
import json

HTML_PARSER = "html.parser"

def get_shop_link_list(links):
global food_id
list_req=requests.get(links)
if list_req.status_code == requests.codes.ok:
    soup = BeautifulSoup(list_req.content, HTML_PARSER)
    link_tag=soup.find_all('h2',{'class':'heavy break-word'})
    for h2 in link_tag:
        print(food_id,end="@")
        link=h2.find('a')
        parse_shop_information(link['href'])
        food_id=food_id+1
        print("")
#turn next page
    try:
        next_page=soup.find('a',{'class':'button -small'})
        get_shop_link_list(next_page['href'])
    except KeyError:
        pass

def parse_shop_information(shop_link):
req=requests.get(shop_link)
if req.status_code == requests.codes.ok:
    soup = BeautifulSoup(req.content, HTML_PARSER)

    #restaurant name
    shop_header_tags = soup.find('div',{'class' : 'cassette'})
    japname_tag=shop_header_tags.find('p',{'class':'small'})
    print(japname_tag.get_text(" ",strip=True).encode(encoding="utf-8",errors="strict").decode(sys.stdin.encoding).strip(),end="@")
    name_tag = shop_header_tags.find('h1',{'class' : 'jumbo break-word'})
    print(name_tag.get_text(" ",strip=True).encode(encoding="utf-8",errors="strict").decode(sys.stdin.encoding).strip(),end="@")
    #Basic information
    shop_body_tags = soup.find('ul',{'class' : 'icon-list -space sentence'})
    information = shop_body_tags.find_all('li')
    for li in information:
        print((li.get_text("|",strip=True).encode(encoding="utf-8",errors="strict")).strip(),end="{")
    #Detail information
    restaurant_detail = soup.find_all("table", {"class":"table sentence"})
    basic_detail=restaurant_detail[0].find_all('tr')
    address="No record"
    address_pic="No record"
    access="No record"
    parking="No record"
    service="No record"
    cards="No record"
    for tr in basic_detail:
        if tr.find('th').get_text(" ",strip=True)=='Address':
            address=((tr.find('p').get_text(" ",strip=True)))
            address_pic=((tr.find('img')["src"]))
        if tr.find('th').get_text(" ",strip=True)=='Access':
            access=((tr.find('td').get_text(" ",strip=True)))
        if tr.find('th').get_text(" ",strip=True)=='Parking':
            parking=((tr.find('td').get_text(" ",strip=True)))
        if tr.find('th').get_text(" ",strip=True)=='Service charge':
            service=((tr.find('td').get_text(" ",strip=True)))
        if tr.find('th').get_text(" ",strip=True)=='Cards Accepted':
            cards=((tr.find('td').get_text(" ",strip=True)))
    print(address.strip(),end="@")
    print(address_pic.strip(),end="@")
    print(access.strip(),end="@")
    print(parking.strip(),end="@")
    print(service.strip(),end="@")
    print(cards.strip(),end="@")

    try:
        facility_detail=restaurant_detail[1].find_all('tr')
        seating="No record"
        MPS="No record"
        RMPS="No record"
        Smoking="No record"
        WAR="No record"
        KF="No record"
        LS="No record"
        WP="No record"
        Other="No record"
        for tr in facility_detail:
            if tr.find('th').get_text(" ",strip=True)=='Seating Capacity':
                seating=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Banquet Maximum Party Size':
                MPS=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Reservation Maximum Party Size':
                RMPS=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Smoking':
                Smoking=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Wheelchair Accessible Restrooms':
                WAR=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Kid Friendly':
                KF=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Language Support':
                LS=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Wi-Fi  /  Plug-in':
                WP=((tr.find('td').get_text(" ",strip=True)))
            if tr.find('th').get_text(" ",strip=True)=='Other':
                Other=((tr.find('td').get_text(" ",strip=True)))
        print(seating.strip(),end="@")
        print(MPS.strip(),end="@")
        print(RMPS.strip(),end="@")
        print(Smoking.strip(),end="@")
        print(WAR.strip(),end="@")
        print(KF.strip(),end="@")
        print(LS.strip(),end="@")
        print(WP.strip(),end="@")
        print(Other.strip(),end="@")

    except IndexError:
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")

    try:
        other_detail=restaurant_detail[2].find_all('tr')
        menu="No record"
        lunch="No record"
        dress_code="No record"
        Delivery="No record"
        for tr in other_detail:
            if tr.find('th').get_text(" ",strip=True)=='Lunch Service':
                lunch=(tr.find('td').get_text(" ",strip=True))
            if tr.find('th').get_text(" ",strip=True)=='Dress Code':
                dress_code=(tr.find('td').get_text(" ",strip=True))

            if tr.find('th').get_text(" ",strip=True)=='Menu':
                lunch=(tr.find('td').get_text(" ",strip=True))
            if tr.find('th').get_text(" ",strip=True)=='Delivery / Catering':
                dress_code=(tr.find('td').get_text(" ",strip=True))
        print(menu.strip(),end="@")
        print(lunch.strip(),end="@")
        print(dress_code.strip(),end="@")
        print(Delivery.strip(),end="@")
    except IndexError:
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")
        print("No record",end="@")

    try:
        main_col_tag=soup.find('div',{'class':'global-navigation'})
        main_col=main_col_tag.find_all('li')
        for li in main_col:
            if li.find('a').get_text()=="Menu":
                print("{",end="")
                sub_menu(shop_link)
                print("}",end="")
    except (IndexError, AttributeError):
        print("No record",end="@")

def sub_menu(link):
list_req=requests.get(link)
if list_req.status_code == requests.codes.ok:
    soup=BeautifulSoup(list_req.content,HTML_PARSER)
    all_menu_tag=soup.find('ul',{'class':'-sub-menu hide'})
    menus=all_menu_tag.find_all('li')
    for i, li in enumerate(menus):
        type=li.find('a').get_text()
        print("\"",end="")
        print(type,end="\":[")
        link=li.find('a')
        sub_menu_json(link['href'])
        if i != len(menus)-1:
            print("]",end=",")
        else:
            print("]",end="")

def sub_menu_json(link):
list_req=requests.get(link)
if list_req.status_code == requests.codes.ok:
    soup = BeautifulSoup(list_req.content, HTML_PARSER)
    eachfood=soup.find_all('div',{'class':'cassette normal-colored'})
    for i,div in enumerate(eachfood):
        food_jap_name="No record"
        food_eng_name="No record"
        food_price="No record"
        tax_inclusion="No record"
        description="No record"
        if div.find('div',{'class':'small'}):
            food_jap_name=div.find('div',{'class':'small'}).get_text(" ",strip=True)
        if div.find('h3',{'class':'huge'}):
            food_eng_name=div.find('h3',{'class':'huge'}).get_text(" ",strip=True)
        if div.find('h3',{'class':'huge abit-spacing'}):
            food_eng_name=div.find('h3',{'class':'huge'}).get_text(" ",strip=True)
        if div.find('p',{'class':'small spacing'}):
            food_price=div.find('p',{'class':'small spacing'}).get_text(" ",strip=True)
        if div.find('span',{'class':'-value'}):
            food_price=div.find('span',{'class':'-value'}).get_text(" ",strip=True)
        if div.find('p',{'class':'text-right small'}):
            tax_inclusion=div.find('p',{'class':'text-right small'}).get_text(" ",strip=True)
        if div.find('div',{'class':'panel -light-silver -in'}):
            description=div.find('div',{'class':'panel -light-silver -in'}).get_text(" ",strip=True)
        if div.find('div',{'class':'sake-detail'}):
            description=div.find('div',{'class':'sake-detail'}).get_text(" ",strip=True)
        print("{\"JpnFoodname:\":",end="\"")
        print(food_jap_name.encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"EngFoodname\":",end="\"")
        print(food_eng_name.encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"Price\":",end="\"")
        print(food_price.strip().encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"TaxIncludeExclude\":",end="\"")
        print(tax_inclusion.strip().encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        print("\"Description\":",end="\"")
        print(description.strip().encode(sys.stdin.encoding, "replace").decode(sys.stdin.encoding).strip(),end="\",")
        if div.find('a') or div.find('img'):
            print("\"ImgUrl:\":",end="\"")
            if div.find('img'):
                food_pic=div.find('img')["src"]
            if div.find('a'):
                food_pic=div.find('a')['href']
            print(food_pic,end="\"}")
        else:
            print("\"ImgUrl:\":\"No record\"",end="}")
        if i != len(eachfood)-1:
            print(',',end="")

if __name__ == '__main__':
global food_id
food_id=1
get_shop_link_list("https://gurunavi.com/en/reg/pf_tokyo/rs/srh/?p=461")

Body:
Here's an outline of what you can do; split the work into individual jobs, add the jobs to a jobQueue and start as many processes as you need (you pass the jobQueue to each one)

Each process takes one job from the queue as log as there are still jobs to process.

This way the number of workers is configurable

import multiprocessing,Queue

def getData(tasksQ):
    while (True):
        try:
            job=tasksQ.get(block = False)
        except Queue.Empty:
            break;
        else:
            <do_work>

tasks = multiprocessing.Queue()

for job in getJob():
  tasks.put(job)

noOfProcesses = 10
processes = []
for i in range(noOfProcesses):
  p = multiprocessing.Process(target = getData, args=(tasks,))
        processes.append(p)

for p in processes:
    p.start()

for p in processes:
    p.join()

Hope this helps.


问:
is it possible to connect to mongodb from SparklyR
i can connect to MongoDB from SparkR (i am using R Studio, Spark 2.x.x, Mongo connector v2.0) as described here https://docs.mongodb.com/spark-connector/current/r-api/. I would like to do the same using SparklyR, is that possible? Could not find any examples for it.</p>

答:
Finally it seems it's possible but there is an easier way by installing the development version of sparklyr:

devtools::install_github("rstudio/sparklyr")

followed by:

```<code>config <- spark_config()
config$sparklyr.defaultPackages <- c("org.mongodb.spark:mongo-spark-connector_2.10:1.1.0")
sc <- spark_connect(master = "local", config = config)
uri <- "mongodb://localhost/nasa.eva"
spark_read_source(
      sc,
      "spark-table-name",
      "com.mongodb.spark.sql.DefaultSource",
      list(
        spark.mongodb.input.uri = uri,
        keyspace = "nasa",
        table = "eva"),
      memory = FALSE)
</code>```

"nasa" and "eva" are the mongo database and the mongo collection, respectively. You can find more information here, at the sparklyr github forum.
I hope this helps!

Body:
Finally it seems it's possible but there is an easier way by installing the development version of sparklyr:

devtools::install_github("rstudio/sparklyr")

followed by:

config <- spark_config()
config$sparklyr.defaultPackages <- c("org.mongodb.spark:mongo-spark-connector_2.10:1.1.0")
sc <- spark_connect(master = "local", config = config)
uri <- "mongodb://localhost/nasa.eva"
spark_read_source(
      sc,
      "spark-table-name",
      "com.mongodb.spark.sql.DefaultSource",
      list(
        spark.mongodb.input.uri = uri,
        keyspace = "nasa",
        table = "eva"),
      memory = FALSE)

"nasa" and "eva" are the mongo database and the mongo collection, respectively. You can find more information here, at the sparklyr github forum.
I hope this helps!


问:
How to receive an array of 16-bit integer tuples from a socket, in Python?
My Python app needs to receive an array of 16-bit integer tuples from a C++ application.

The data consists of an array of 32-bit unsigned integers, where each integer represents an IQ complex number. I and Q are each signed 16-bit numbers.

The array size is constant (6000).

The apps run on similar architectures so I don’t need to worry about endianness.

Please suggest a Python code snippet to read the data from a socket into a list of IQ tuples.  (I know how to create and connect a socket).

Best regards

David

答:
Python has several options to process binary data; in this case, you start out by reading from a socket, producing an immutable bytes buffer (bytes in Python 3, str in Python 2). This can be parsed as 16-bit words using either struct.unpack or array.array:

```<code>tuple_of_ints = struct.unpack('=12000h', data)
array_of_s16s = array.array('h', data)
</code>```

From there, you still have only a one-dimensional structure, where odd and even items are your I and Q values. If using numpy, you could use ndarray.fromstring or ndarray.frombuffer to create a similar array, then reshape it.

We could also convert items individually, which is a bit slower:

```<code>list_of_complex_numbers = [complex(*struct.unpack('hh',data[i:i+4]))
    for i in range(0,len(data),4)]
</code>```

numpy is also capable of reading from file, so with a file-like socket you might be able to use numpy.fromfile(socket, numpy.int16, 2*6000).

Body:
Python has several options to process binary data; in this case, you start out by reading from a socket, producing an immutable bytes buffer (bytes in Python 3, str in Python 2). This can be parsed as 16-bit words using either struct.unpack or array.array:

tuple_of_ints = struct.unpack('=12000h', data)
array_of_s16s = array.array('h', data)

From there, you still have only a one-dimensional structure, where odd and even items are your I and Q values. If using numpy, you could use ndarray.fromstring or ndarray.frombuffer to create a similar array, then reshape it.

We could also convert items individually, which is a bit slower:

list_of_complex_numbers = [complex(*struct.unpack('hh',data[i:i+4]))
    for i in range(0,len(data),4)]

numpy is also capable of reading from file, so with a file-like socket you might be able to use numpy.fromfile(socket, numpy.int16, 2*6000).


问:
Case Statement Not Working - VBA
In my project I have a list of clients that have unique commission calculations (ex. Client_1 has a 0.1% commission rate, whereas Client_2 has a 0.25% commission rate).

In my VBA code I made special cases, that vary by the client_id. The problem I'm getting with this code is that even though I put in a special ID, it jumps over the case (ex. if klienta_nr = 100, it skips over the Case klienta_nr = 100 and returns the Case Else). How can I fix this issue?

```<code>Private Sub CommandButton1_Click()

Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double
Dim vk As String

Set kSheet = ThisWorkbook.Sheets("komisijas")

klienta_nr = Range("B2").Value
ISIN = Range("E2").Value
Cena = Range("H2").Value
Skaits = Range("I2").Value
vk = Range("B2").Value

Select Case klienta_nr

Case klienta_nr = 100

            If klienta_nr = 100 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                Komisija = (Cena * Skaits) * 0.01
                Range("K2").Value = Komisija
                End If
            If klienta_nr = 100 And Komisija <= 30 Then
                Range("K2").Value = 30
                End If

            'Case where klient is special, but ISIN doesn't apply
            If klienta_nr = 100 And (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
                Komisija = (Cena * Skaits) * 0.003
                If Komisija >= 40 Then
                    Range("K2").Value = 40
                    End If
            End If

 Case klienta_nr = 105

            If klienta_nr = 105 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                Komisija = (Cena * Skaits) * 0.01
                Range("K2").Value = Komisija
                End If
            'Set 30 EUR Min
            If klienta_nr = 105 And Komisija <= 30 Then
                Range("K2").Value = 30
                End If

    'End If

 Case klienta_nr = 110

            If klienta_nr = 110 And (Left(ISIN, 2) = "NO" Or Left(ISIN, 2) = "SE" Or Left(ISIN, 2) = "DK" Or Left(ISIN, 2) = "FI" Or Left(ISIN, 2) = "IS" Or Left(ISIN, 2) = "LT" Or Left(ISIN, 2) = "EE" Or Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE" Or Left(ISIN, 2) = "AT" Or Left(ISIN, 2) = "BE" Or Left(ISIN, 2) = "ES" Or Left(ISIN, 2) = "PT") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.002
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "UK") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "CH") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If
            'Set 20 [valūte] MIN
            If klienta_nr = 110 And Komisija <= 20 Then
                Range("K2").Value = 20
                End If

Case klienta_nr = 115

            If klienta_nr = 115 And (Left(ISIN, 2) = "NO" Or Left(ISIN, 2) = "SE" Or Left(ISIN, 2) = "DK" Or Left(ISIN, 2) = "FI" Or Left(ISIN, 2) = "IS" Or Left(ISIN, 2) = "LT" Or Left(ISIN, 2) = "EE" Or Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE" Or Left(ISIN, 2) = "AT" Or Left(ISIN, 2) = "BE" Or Left(ISIN, 2) = "ES" Or Left(ISIN, 2) = "PT") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.002
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "UK") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "CH") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If
            'Set 20 [valūte] MIN
            If klienta_nr = 115 And Komisija <= 20 Then
                Range("K2").Value = 20
                End If

 Case klienta_nr = 120

            If klienta_nr = 120 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.0027
                Range("K2").Value = Komisija
                End If
            'Set 40 USD MIN
            If klienta_nr = 120 And Komisija <= 40 Then
                Range("K2").Value = 40
                End If

'Non-special klient cases
Case Else
    If Not Application.Match(klienta_nr, kSheet.Range("A2:A100")) Then

         If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
            Komisija = (Cena * Skaits) * 0.003
            Range("K2").Value = Komisija
            End If

        If Right(vk, 1) = 7 Then
            Komisija = (Cena * Skaits) * 0.01
            Range("K2").Value = Komisija
            End If
        'Komisija MAX is 40, so anything >=40 equals 40
        If Komisija >= 40 Then
            Range("K2").Value = 40
            End If
    End If
   End Select
  End Sub
</code>```

答:
Once you have your Select Case klienta_nr , and then the first case is Case 100, you don't repeat underneath If klienta_nr = 100 , since you already checked that in your Case.

Change your Select Case structure to:

```<code>Select Case klienta_nr

Case 100

    If (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
        Komisija = (Cena * Skaits) * 0.01
        Range("K2").Value = Komisija
    End If
    If Komisija <= 30 Then
        Range("K2").Value = 30
    End If

    'Case where klient is special, but ISIN doesn't apply
    If (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
        Komisija = (Cena * Skaits) * 0.003
        If Komisija >= 40 Then
            Range("K2").Value = 40
        End If
    End If

Case 105

    If (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
        Komisija = (Cena * Skaits) * 0.01
        Range("K2").Value = Komisija
    End If
    'Set 30 EUR Min
    If Komisija <= 30 Then
        Range("K2").Value = 30
    End If

' add here your other cases...

End Select
</code>```

Title: Case Statement Not Working - VBA

Body:
In my project I have a list of clients that have unique commission calculations (ex. Client_1 has a 0.1% commission rate, whereas Client_2 has a 0.25% commission rate).

In my VBA code I made special cases, that vary by the client_id. The problem I'm getting with this code is that even though I put in a special ID, it jumps over the case (ex. if klienta_nr = 100, it skips over the Case klienta_nr = 100 and returns the Case Else). How can I fix this issue?

Private Sub CommandButton1_Click()

Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double
Dim vk As String

Set kSheet = ThisWorkbook.Sheets("komisijas")

klienta_nr = Range("B2").Value
ISIN = Range("E2").Value
Cena = Range("H2").Value
Skaits = Range("I2").Value
vk = Range("B2").Value

Select Case klienta_nr

Case klienta_nr = 100

            If klienta_nr = 100 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                Komisija = (Cena * Skaits) * 0.01
                Range("K2").Value = Komisija
                End If
            If klienta_nr = 100 And Komisija <= 30 Then
                Range("K2").Value = 30
                End If

            'Case where klient is special, but ISIN doesn't apply
            If klienta_nr = 100 And (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
                Komisija = (Cena * Skaits) * 0.003
                If Komisija >= 40 Then
                    Range("K2").Value = 40
                    End If
            End If

 Case klienta_nr = 105

            If klienta_nr = 105 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                Komisija = (Cena * Skaits) * 0.01
                Range("K2").Value = Komisija
                End If
            'Set 30 EUR Min
            If klienta_nr = 105 And Komisija <= 30 Then
                Range("K2").Value = 30
                End If

    'End If

 Case klienta_nr = 110

            If klienta_nr = 110 And (Left(ISIN, 2) = "NO" Or Left(ISIN, 2) = "SE" Or Left(ISIN, 2) = "DK" Or Left(ISIN, 2) = "FI" Or Left(ISIN, 2) = "IS" Or Left(ISIN, 2) = "LT" Or Left(ISIN, 2) = "EE" Or Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE" Or Left(ISIN, 2) = "AT" Or Left(ISIN, 2) = "BE" Or Left(ISIN, 2) = "ES" Or Left(ISIN, 2) = "PT") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.002
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "UK") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "CH") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If
            'Set 20 [valūte] MIN
            If klienta_nr = 110 And Komisija <= 20 Then
                Range("K2").Value = 20
                End If

Case klienta_nr = 115

            If klienta_nr = 115 And (Left(ISIN, 2) = "NO" Or Left(ISIN, 2) = "SE" Or Left(ISIN, 2) = "DK" Or Left(ISIN, 2) = "FI" Or Left(ISIN, 2) = "IS" Or Left(ISIN, 2) = "LT" Or Left(ISIN, 2) = "EE" Or Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE" Or Left(ISIN, 2) = "AT" Or Left(ISIN, 2) = "BE" Or Left(ISIN, 2) = "ES" Or Left(ISIN, 2) = "PT") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.002
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "UK") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "CH") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If
            'Set 20 [valūte] MIN
            If klienta_nr = 115 And Komisija <= 20 Then
                Range("K2").Value = 20
                End If

 Case klienta_nr = 120

            If klienta_nr = 120 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.0027
                Range("K2").Value = Komisija
                End If
            'Set 40 USD MIN
            If klienta_nr = 120 And Komisija <= 40 Then
                Range("K2").Value = 40
                End If

'Non-special klient cases
Case Else
    If Not Application.Match(klienta_nr, kSheet.Range("A2:A100")) Then

         If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
            Komisija = (Cena * Skaits) * 0.003
            Range("K2").Value = Komisija
            End If

        If Right(vk, 1) = 7 Then
            Komisija = (Cena * Skaits) * 0.01
            Range("K2").Value = Komisija
            End If
        'Komisija MAX is 40, so anything >=40 equals 40
        If Komisija >= 40 Then
            Range("K2").Value = 40
            End If
    End If
   End Select
  End Sub

Body:
Once you have your Select Case klienta_nr , and then the first case is Case 100, you don't repeat underneath If klienta_nr = 100 , since you already checked that in your Case.

Change your Select Case structure to:

Select Case klienta_nr

Case 100

    If (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
        Komisija = (Cena * Skaits) * 0.01
        Range("K2").Value = Komisija
    End If
    If Komisija <= 30 Then
        Range("K2").Value = 30
    End If

    'Case where klient is special, but ISIN doesn't apply
    If (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
        Komisija = (Cena * Skaits) * 0.003
        If Komisija >= 40 Then
            Range("K2").Value = 40
        End If
    End If

Case 105

    If (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
        Komisija = (Cena * Skaits) * 0.01
        Range("K2").Value = Komisija
    End If
    'Set 30 EUR Min
    If Komisija <= 30 Then
        Range("K2").Value = 30
    End If

' add here your other cases...

End Select


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

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

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
```<code>if (a.nextInt()=='+'){
    float result = x + y;
    System.out.println("result: " + result);
}
</code>```

a.nextInt() expect an "int", but you're passing to it a char.
You have two possibilities.

Create another scanner which will take "char"

Use the method "next()". Like this : a.next();
In the second case, use .equals("your operation"), cause you can't compare strings with "==".

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
if (a.nextInt()=='+'){
    float result = x + y;
    System.out.println("result: " + result);
}

a.nextInt() expect an "int", but you're passing to it a char.
You have two possibilities.

Create another scanner which will take "char"

Use the method "next()". Like this : a.next();
In the second case, use .equals("your operation"), cause you can't compare strings with "==".


问:
i want to sorting hashmap (decending) in java
I want to sort this HashMap:

```<code>HashMap<Integer,Integer> hp=new HashMap<Integer,Integer>();

TreeMap<Integer,Integer> stm = new TreeMap<Integer,Integer>();
stm.putAll(hp);
</code>```

In value reverse sorting.

If the values are the same, I will use key as the next condition.
Value is reverse but key is not.

答:
We can implement the sort of HashMap by referring to TreeMap's value sort.
I tried to write a sample to share with you.

```<code>public class HashMapTest {
public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("c", "ccccc");
    map.put("a", "aaaaa");
    map.put("b", "bbbbb");
    map.put("d", "ddddd");

    List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
    Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
        //Ascending order
        public int compare(Entry<String, String> o1,
                Entry<String, String> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });

    for(Map.Entry<String,String> mapping:list){
           System.out.println(mapping.getKey()+":"+mapping.getValue());
      }
 }
</code>```

the resule is

a:aaaaa

b:bbbbb

c:ccccc

d:ddddd

Body:
I want to sort this HashMap:

HashMap<Integer,Integer> hp=new HashMap<Integer,Integer>();

TreeMap<Integer,Integer> stm = new TreeMap<Integer,Integer>();
stm.putAll(hp);

In value reverse sorting.

If the values are the same, I will use key as the next condition.
Value is reverse but key is not.

Body:
We can implement the sort of HashMap by referring to TreeMap's value sort.
I tried to write a sample to share with you.

public class HashMapTest {
public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("c", "ccccc");
    map.put("a", "aaaaa");
    map.put("b", "bbbbb");
    map.put("d", "ddddd");

    List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
    Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
        //Ascending order
        public int compare(Entry<String, String> o1,
                Entry<String, String> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });

    for(Map.Entry<String,String> mapping:list){
           System.out.println(mapping.getKey()+":"+mapping.getValue());
      }
 }

the resule is

a:aaaaa

b:bbbbb

c:ccccc

d:ddddd


问:
admin-on-rest: How use <Resource /> component with custom API end points
I'm using the Loopback REST Client for admin-on-rest successfully with no issues. It's easy to use and works very well for the standard CRUD operations, however I quickly found myself in the need of using non-conventional REST calls like the following:

```<code>http://www.remoteurl.com/api/getUsersWithRolesInfo
</code>```

I also want in some situations to make use of Loopback's in-URL filters, like such:

```<code>http://www.remoteurl.com/api/Users?filter=[include][profile]&filter=[include][posts]
</code>```

How can I achieve this with the <Resource /> component?

Initially I thought of modifying the REST client in order to map the above end points. However the REST client maps its calls to types like GET_ONE, GET_MANY, etc.. while what I want to map is an URL (like ../getUserWithRolesInfo).

Thanks for your help.

答:
You can pass a permanent filter with your List component as well as a one time filter with the ReferenceInput component. For more specific modifications to the call to your API you can use a RestWrapper that will intercept some of the calls to your API and pass the rest to the Loopback Rest Client.

https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

The Loopback REST client does not account for the include filter. You will have to manually construct the URL query. Something like below. Most of this is from the AOR-Loopback Code as is the queryParameters function used below. You can find it all there and modify it to your needs.

```<code>function getListQueryConstructor(params, apiResource) {
  const page =  params.pagination.page
  const perPage = params.pagination.perPage
  const {field, order} = params.sort
  const query = {}
  if (params.filter.include) {
    query['include'] = params.filter.include
    delete params.filter.include
  }
  query['where'] = {...params.filter}
  if (field) {query['order'] = [field + ' ' + order]}
  if (perPage > 0) {
      query['limit'] = perPage;
      if (page >= 0) {
          query['skip'] = (page - 1) * perPage
      }
  }
  return (config.host + '/' + apiResource + '?' +  queryParameters({filter: JSON.stringify(query)}))
}
</code>```

Body:
I'm using the Loopback REST Client for admin-on-rest successfully with no issues. It's easy to use and works very well for the standard CRUD operations, however I quickly found myself in the need of using non-conventional REST calls like the following:

http://www.remoteurl.com/api/getUsersWithRolesInfo

I also want in some situations to make use of Loopback's in-URL filters, like such:

http://www.remoteurl.com/api/Users?filter=[include][profile]&filter=[include][posts]

How can I achieve this with the <Resource /> component?

Initially I thought of modifying the REST client in order to map the above end points. However the REST client maps its calls to types like GET_ONE, GET_MANY, etc.. while what I want to map is an URL (like ../getUserWithRolesInfo).

Thanks for your help.

Body:
You can pass a permanent filter with your List component as well as a one time filter with the ReferenceInput component. For more specific modifications to the call to your API you can use a RestWrapper that will intercept some of the calls to your API and pass the rest to the Loopback Rest Client.

https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

The Loopback REST client does not account for the include filter. You will have to manually construct the URL query. Something like below. Most of this is from the AOR-Loopback Code as is the queryParameters function used below. You can find it all there and modify it to your needs.

function getListQueryConstructor(params, apiResource) {
  const page =  params.pagination.page
  const perPage = params.pagination.perPage
  const {field, order} = params.sort
  const query = {}
  if (params.filter.include) {
    query['include'] = params.filter.include
    delete params.filter.include
  }
  query['where'] = {...params.filter}
  if (field) {query['order'] = [field + ' ' + order]}
  if (perPage > 0) {
      query['limit'] = perPage;
      if (page >= 0) {
          query['skip'] = (page - 1) * perPage
      }
  }
  return (config.host + '/' + apiResource + '?' +  queryParameters({filter: JSON.stringify(query)}))
}


问:
Receive and send msgs from C client to nodejs server
I have made a TCP client in C, and Im looking to make the server side in nodejs for simplicity and for easy integration into a existing app...

Well in my C code I receive and send msgs in the next way:

```<code>numBytes = send( sock, &timeStamp, sizeof( timeStamp ), 0 );
if( numBytes < 0 )
    DieWithSystemMessage( "send( ) failed" );
</code>```

After reading a little about the "net" and "socket.io" packages for nodejs I haven't found the way to make it work... I apologize if this is somethog simple but it is my first time working with nodejs.
If you have some blog or github link that have made something similar I will be glad to take a look, Thanks!!!

答: You can use argv for passing ip or you can modify with hexadecimal editor like Hxd.</p>

Body:
I have made a TCP client in C, and Im looking to make the server side in nodejs for simplicity and for easy integration into a existing app...

Well in my C code I receive and send msgs in the next way:

numBytes = send( sock, &timeStamp, sizeof( timeStamp ), 0 );
if( numBytes < 0 )
    DieWithSystemMessage( "send( ) failed" );

After reading a little about the "net" and "socket.io" packages for nodejs I haven't found the way to make it work... I apologize if this is somethog simple but it is my first time working with nodejs.
If you have some blog or github link that have made something similar I will be glad to take a look, Thanks!!!


问:
Different between keyword "new" and "default" in create instance of class
I have class like:

```<code> class foo
    {
        public foo(string Text)
        {
        }
    }
</code>```

After run this code for create instance of class the obj1 set to null:

```<code>foo obj1 = default(foo);
</code>```

And by blow code everything work fine:

```<code>foo obj2= new foo("bla bla");
</code>```

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.

答:
In essence default(T) only reserves the minimum memory required to hold a reference to, or instance of the type, it does not call any constructors.

For primitive types like int and bool the value returned would be 0 or false respectively.

For reference types (classes) the only reservation made is for the reference, which will be null

For structs, the memory for the struct will be reserved according to the rules above, so reference fields will be initialized to null, even if they cannot normally be null because of a constructor! Value fields will have their default set (0, false, etc).

For enum types, values will be initialized to their first (0 value) field unless you have manually assigned values to the enum labels, in which case the value will still be 0 and might be invalid.

Body:
I have class like:

 class foo
    {
        public foo(string Text)
        {
        }
    }

After run this code for create instance of class the obj1 set to null:

foo obj1 = default(foo);

And by blow code everything work fine:

foo obj2= new foo("bla bla");

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.


问:
How to change Primary Language of already approved app in new version?
In App Information -> Primary Language option is not actionable. But when I view at top right 2 Languages is coming, marked english as primary. And also if I check Prepare for submission both language are coming there as well.

答:
You have to replacing your app with a New Version.

See this link

See this image