问:
"Invalid procedure Call or Argument" when importing access query into excel table
I have an excel workbook that has pivot tables and charts linked to a excel table. I want to create a button that when pressed, deletes any data in the table and replaces it with updates data from a saved query in an access database. I have written the  below code but i'm getting an "invalid procedure call or argument" error when i run the procedure. Does anyone know where i've gone wrong?</p>

```<code>   'button on excel form runs procedure to remove current data in table then
   'import data from query in MS access database

Sub ImportData()
    Call CleanTheTable("MMPres_MainData", "MainData")
    Call ImportAccessData("qry_MMPres_Main", "MMPres_MainData", "MainData"
End Sub

   'procedure finds database file and imports query into excel table

Sub ImportAccessData(qry As String, sht As String, tbl As String)

On Error GoTo ErrorHandler

    Const dbLoc As String = "D:\AccessPractice\CTDB\CardiothoracicDB_v2_Current.accdb"
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim bk As Workbook
    Dim Wsht As Worksheet

    Set bk = ActiveWorkbook
    Set Wsht = bk.Worksheets(sht)
    Set db = DBEngine.OpenDatabase(dbLoc)
    Set rs = db.OpenRecordset(qry, dbOpenSnapshot)

    Wsht.ListObjects(tbl).Range("A1").CopyFromRecordset (rs)

    rs.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing
    Set Wsht = Nothing
    Set bk = Nothing
    Exit Sub

ErrorHandler:
    Application.StatusBar = ""
    MsgBox ("Error: " & Err.Number & " " & Err.Description)
    rs.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing
    Set Wsht = Nothing
    Set bk = Nothing

End Sub
</code>```

答:
Assuming you had set the necessary library references for DAO, the error you get is on this line:

```<code>Wsht.ListObjects(tbl).Range("A1").CopyFromRecordset (rs)
</code>```

Change it into this:

```<code>Wsht.ListObjects(tbl).Range(2, 1).CopyFromRecordset rs
</code>```

also possible:

```<code>Wsht.ListObjects(tbl).HeaderRowRange.Offset(1).CopyFromRecordset rs
</code>```

In summary:

1- remove the parenthesis around (rs)

2- Dont overwrite the table's header (which is row 1), copy the recordset starting at second row.

3- The method Range of the ListObject is a bit confusing, it returns the table's whole range, but cannot be fed directly a "A1-style" reference, it works more like the the Cells method of worksheets.

Body:
I have an excel workbook that has pivot tables and charts linked to a excel table. I want to create a button that when pressed, deletes any data in the table and replaces it with updates data from a saved query in an access database. I have written the  below code but i'm getting an "invalid procedure call or argument" error when i run the procedure. Does anyone know where i've gone wrong?

   'button on excel form runs procedure to remove current data in table then
   'import data from query in MS access database

Sub ImportData()
    Call CleanTheTable("MMPres_MainData", "MainData")
    Call ImportAccessData("qry_MMPres_Main", "MMPres_MainData", "MainData"
End Sub

   'procedure finds database file and imports query into excel table

Sub ImportAccessData(qry As String, sht As String, tbl As String)

On Error GoTo ErrorHandler

    Const dbLoc As String = "D:\AccessPractice\CTDB\CardiothoracicDB_v2_Current.accdb"
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim bk As Workbook
    Dim Wsht As Worksheet

    Set bk = ActiveWorkbook
    Set Wsht = bk.Worksheets(sht)
    Set db = DBEngine.OpenDatabase(dbLoc)
    Set rs = db.OpenRecordset(qry, dbOpenSnapshot)

    Wsht.ListObjects(tbl).Range("A1").CopyFromRecordset (rs)

    rs.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing
    Set Wsht = Nothing
    Set bk = Nothing
    Exit Sub

ErrorHandler:
    Application.StatusBar = ""
    MsgBox ("Error: " & Err.Number & " " & Err.Description)
    rs.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing
    Set Wsht = Nothing
    Set bk = Nothing

End Sub

Body:
Assuming you had set the necessary library references for DAO, the error you get is on this line:

Wsht.ListObjects(tbl).Range("A1").CopyFromRecordset (rs)

Change it into this:

Wsht.ListObjects(tbl).Range(2, 1).CopyFromRecordset rs

also possible:

Wsht.ListObjects(tbl).HeaderRowRange.Offset(1).CopyFromRecordset rs

In summary:

1- remove the parenthesis around (rs)

2- Dont overwrite the table's header (which is row 1), copy the recordset starting at second row.

3- The method Range of the ListObject is a bit confusing, it returns the table's whole range, but cannot be fed directly a "A1-style" reference, it works more like the the Cells method of worksheets.


来源: stackexchange

问:
libgcc_s.so: Error adding symbols: File in wrong format
When using GCC like gcc -march i486 -m32 -e Harimain -o bootpack.hrb bootpack.c hankaku.c naskfunc.o, the compiler worked well. But when I add -T link.ls it told me:

libgcc_s.so:Error adding symbols:File in wrong format

I am creating 32bit binary on 64bit PC. This is my linker script:

```<code>OUTPUT_FORMAT("binary");
SECTIONS
{
    .head 0x0 : {
        LONG(0x64 * 1024)  /*  0 : stack+.data+heap の大きさ（4KBの倍数） */
        LONG(0x69726148)      /*  4 : シグネチャ "Hari" */
        LONG(0)               /*  8 : mmarea の大きさ（4KBの倍数） */
        LONG(0x310000)        /* 12 : スタック初期値＆.data転送先 */
        LONG(SIZEOF(.data))   /* 16 : .dataサイズ */
        LONG(LOADADDR(.data)) /* 20 : .dataの初期値列のファイル位置 */
        LONG(0xE9000000)      /* 24 : 0xE9000000 */
        LONG(main - 0x20) /* 28 : エントリアドレス - 0x20 */
        LONG(0)               /* 32 : heap領域（malloc領域）開始アドレス */
}
   .text : { *(.text) }
   .data 0x310000 : AT ( ADDR(.text) + SIZEOF(.text) ) {
        *(.data)
        *(.rodata*)
        *(.bss)
}   /DISCARD/ : { *(.eh_frame) }
}
</code>```

The OS is Ubuntu 16.04 64-bit and GCC version is 5.4.0.

What is the problem, and how do I fix it?

答:
GCC builds shared programs by default. So try adding -static to your command line. You will probably want also -ffreestanding.

My advice when doing these kind of things is to separate the compile and the linker commands, and do the linker using ld, not gcc. gcc assumes too many things when doing the linker phase.

ContentLicense: CC BY-SA 3.0

Body:
When using GCC like gcc -march i486 -m32 -e Harimain -o bootpack.hrb bootpack.c hankaku.c naskfunc.o, the compiler worked well. But when I add -T link.ls it told me:

libgcc_s.so:Error adding symbols:File in wrong format

I am creating 32bit binary on 64bit PC. This is my linker script:

OUTPUT_FORMAT("binary");
SECTIONS
{
    .head 0x0 : {
        LONG(0x64 * 1024)  /*  0 : stack+.data+heap の大きさ（4KBの倍数） */
        LONG(0x69726148)      /*  4 : シグネチャ "Hari" */
        LONG(0)               /*  8 : mmarea の大きさ（4KBの倍数） */
        LONG(0x310000)        /* 12 : スタック初期値＆.data転送先 */
        LONG(SIZEOF(.data))   /* 16 : .dataサイズ */
        LONG(LOADADDR(.data)) /* 20 : .dataの初期値列のファイル位置 */
        LONG(0xE9000000)      /* 24 : 0xE9000000 */
        LONG(main - 0x20) /* 28 : エントリアドレス - 0x20 */
        LONG(0)               /* 32 : heap領域（malloc領域）開始アドレス */
}
   .text : { *(.text) }
   .data 0x310000 : AT ( ADDR(.text) + SIZEOF(.text) ) {
        *(.data)
        *(.rodata*)
        *(.bss)
}   /DISCARD/ : { *(.eh_frame) }
}

The OS is Ubuntu 16.04 64-bit and GCC version is 5.4.0.

What is the problem, and how do I fix it?


问:
How to plot vertical scatter using only matplotlib
I need to plot vertical scatters in matplotlib but I couldn't find anything in matplotlib.org/examples or StackOverflow.

I tried something of my own but I am missing Jitter. Jitter changes X component slightly for the points having same (or very similar) Y components so they won't overlap. Is there anything which I can use or will I have to change x components manually?

```<code>import numpy as np
from matplotlib import pyplot as plt

x = np.array([1,2,3])
l = ['A','B','C']
a = np.array([2,2,3])
b = np.array([3,3,4])
c = np.array([7,7,5])
d = (np.array(a) + np.array(b) + np.array(c)) / 3

plt.subplot(111)
plt.margins(0.2)
plt.xticks(x,l)
plt.plot(x, a, 'ro', label='a')
plt.plot(x, b, 'ro', label='b')
plt.plot(x, c, 'ro', label='c')
plt.plot(x, d, 'k_', markersize=15, label='avg')
plt.tight_layout()
plt.savefig('vertical_scatter')
plt.close()
</code>```

which gave me following

I found this on Seaborn.

which is what I want but only using matplotlib.

答:
An example with jitter using only matplotlib would be the following. The idea is basically to add some random noise to the x values.

```<code>import numpy as np
import matplotlib.pyplot as plt

data = np.random.rayleigh(scale=1, size=(30,4))
labels = list("ABCD")
colors = ["crimson", "purple", "limegreen", "gold"]

width=0.4
fig, ax = plt.subplots()
for i, l in enumerate(labels):
    x = np.ones(data.shape[0])*i + (np.random.rand(data.shape[0])*width-width/2.)
    ax.scatter(x, data[:,i], color=colors[i], s=25)
    mean = data[:,i].mean()
    ax.plot([i-width/2., i+width/2.],[mean,mean], color="k")

ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels)

plt.show()
</code>```

Body:
I need to plot vertical scatters in matplotlib but I couldn't find anything in matplotlib.org/examples or StackOverflow.

I tried something of my own but I am missing Jitter. Jitter changes X component slightly for the points having same (or very similar) Y components so they won't overlap. Is there anything which I can use or will I have to change x components manually?

import numpy as np
from matplotlib import pyplot as plt

x = np.array([1,2,3])
l = ['A','B','C']
a = np.array([2,2,3])
b = np.array([3,3,4])
c = np.array([7,7,5])
d = (np.array(a) + np.array(b) + np.array(c)) / 3

plt.subplot(111)
plt.margins(0.2)
plt.xticks(x,l)
plt.plot(x, a, 'ro', label='a')
plt.plot(x, b, 'ro', label='b')
plt.plot(x, c, 'ro', label='c')
plt.plot(x, d, 'k_', markersize=15, label='avg')
plt.tight_layout()
plt.savefig('vertical_scatter')
plt.close()

which gave me following

I found this on Seaborn.

which is what I want but only using matplotlib.

Body:
An example with jitter using only matplotlib would be the following. The idea is basically to add some random noise to the x values.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rayleigh(scale=1, size=(30,4))
labels = list("ABCD")
colors = ["crimson", "purple", "limegreen", "gold"]

width=0.4
fig, ax = plt.subplots()
for i, l in enumerate(labels):
    x = np.ones(data.shape[0])*i + (np.random.rand(data.shape[0])*width-width/2.)
    ax.scatter(x, data[:,i], color=colors[i], s=25)
    mean = data[:,i].mean()
    ax.plot([i-width/2., i+width/2.],[mean,mean], color="k")

ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels)

plt.show()


问:
Spring Data JPA, dynamic sorting based upon possible entry in nested collection
As the codebase is already using Spring Data JPA, I would like to create a Sort
object, which will be based upon the presence (or lack thereof) of a particular element
being present in a Collection, collection itself which is one of the element in the
primary table.  The Sort object's property would need to be dynamic, as a user might want to sort
records once one way and the next time another way.

Explicitly, if multiple PrimaryEntity objects have a SecondaryEntity with 'type' set to a particular
value, I would then want to sort them based upon the corresponding 'notes' field in the corresponding
SecondaryEntity.  Also, while I would want to retrieve all SecondaryEntity objects, I would want the
sorting to be based solely upon the SecondaryEntity records where 'type' is equal to, say, 'Important'.

The classes look like the following (I also redefined 'equals' & 'hashCode' for SecondaryEntity):

```<code>public class PrimaryEntity
{

@OneToMany(mappedBy = "primary", cascade = CascadeType.ALL)
@MapKey(name = "type")
private Map<String, SecondaryEntity> myMap = new HashMap<>();

@Column(name = "name")
private String name;

}

public class SecondaryEntity
{

@Column(name = "type", length = 200)
private String type;

@Column(name = "notes", length = 2000)
private String notes;

@ManyToOne
@JoinColumn(name = "primary_id", referencedColumnName = "id")
private PrimaryEntity primary;

 }
</code>```

I would then want to create a Sort with a syntax similar to he following:

Sort sort = new Sort("myMap[important].notes")

Finally, while I am striving to sort the PrimaryEntity records as per above, it does not matter to
me how, for a given PrimaryEntity, its SecondaryEntity records are displayed.

For example,

```<code><html>
<head>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style>
</head>
<body>
<table>
  <tr>
    <th>Name</th>
    <th>Type</th>
    <th>Notes</th>
  </tr>
  <tr>
    <td>Second primary</td>
    <td>Important</td>
    <td>1</td>
  </tr>
  <tr>
    <td>Second primary</td>
    <td>Other</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Second primary</td>
    <td>Miscellaneous</td>
    <td></td>
  </tr>
  <tr>
    <td>Third primary</td>
    <td>Important</td>
    <td>2</td>
  </tr>
  <tr>
    <td>First primary</td>
    <td>Important</td>
    <td>3</td>
  </tr>
</table>
</body>
</html>
</code>```

Thank you.

答:
You can optionally override findAll(Sort sort) method in the SecondaryRepo with @EntityGraph annotation:

```<code>public interface SecondaryRepo extends JpaRepository<Secondary, Long> {

    @EntityGraph(attributePaths = {"primary"})
    @Override
    List<Secondary> findAll(Sort sort);
}
</code>```

to fetch associated Primaries eagerly.

Then just define Sort with type and note and fetch Secondaries (that will contain also their Primaries) like this:

```<code>Sort sort = new Sort(new Sort.Order("type"), new Sort.Order("note"));
List<Secondary> list = secondaryRepo.findAll(sort);
</code>```

See example and test.

Body:
As the codebase is already using Spring Data JPA, I would like to create a Sort
object, which will be based upon the presence (or lack thereof) of a particular element
being present in a Collection, collection itself which is one of the element in the
primary table.  The Sort object's property would need to be dynamic, as a user might want to sort
records once one way and the next time another way.

Explicitly, if multiple PrimaryEntity objects have a SecondaryEntity with 'type' set to a particular
value, I would then want to sort them based upon the corresponding 'notes' field in the corresponding
SecondaryEntity.  Also, while I would want to retrieve all SecondaryEntity objects, I would want the
sorting to be based solely upon the SecondaryEntity records where 'type' is equal to, say, 'Important'.

The classes look like the following (I also redefined 'equals' & 'hashCode' for SecondaryEntity):

public class PrimaryEntity
{

@OneToMany(mappedBy = "primary", cascade = CascadeType.ALL)
@MapKey(name = "type")
private Map<String, SecondaryEntity> myMap = new HashMap<>();

@Column(name = "name")
private String name;

}

public class SecondaryEntity
{

@Column(name = "type", length = 200)
private String type;

@Column(name = "notes", length = 2000)
private String notes;

@ManyToOne
@JoinColumn(name = "primary_id", referencedColumnName = "id")
private PrimaryEntity primary;

 }

I would then want to create a Sort with a syntax similar to he following:

Sort sort = new Sort("myMap[important].notes")

Finally, while I am striving to sort the PrimaryEntity records as per above, it does not matter to
me how, for a given PrimaryEntity, its SecondaryEntity records are displayed.

For example,

    Name
    Type
    Notes

    Second primary
    Important
    1

    Second primary
    Other
    2

    Second primary
    Miscellaneous

    Third primary
    Important
    2

    First primary
    Important
    3

Thank you.

Body:
You can optionally override findAll(Sort sort) method in the SecondaryRepo with @EntityGraph annotation:

public interface SecondaryRepo extends JpaRepository<Secondary, Long> {

    @EntityGraph(attributePaths = {"primary"})
    @Override
    List<Secondary> findAll(Sort sort);
}

to fetch associated Primaries eagerly.

Then just define Sort with type and note and fetch Secondaries (that will contain also their Primaries) like this:

Sort sort = new Sort(new Sort.Order("type"), new Sort.Order("note"));
List<Secondary> list = secondaryRepo.findAll(sort);

See example and test.


问:
How to sparsely checkout only one single file from a git repository?
How do I checkout just one file from a git repo?</p>

答:
If you need a specific file from a specific branch from a remote Git repository the command is:

```<code>git archive --remote=git://git.example.com/project.git refs/heads/mybranch path/to/myfile |tar xf -
</code>```

The rest can be derived from @VonC's answer:

If you need a specific file from the master branch it is:

```<code>git archive --remote=git://git.example.com/project.git HEAD path/to/myfile |tar xf -
</code>```

If you need a specific file from a tag it is:

```<code>git archive --remote=git://git.example.com/project.git mytag path/to/myfile |tar xf -
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you need a specific file from a specific branch from a remote Git repository the command is:

git archive --remote=git://git.example.com/project.git refs/heads/mybranch path/to/myfile |tar xf -

The rest can be derived from @VonC's answer:

If you need a specific file from the master branch it is:

git archive --remote=git://git.example.com/project.git HEAD path/to/myfile |tar xf -

If you need a specific file from a tag it is:

git archive --remote=git://git.example.com/project.git mytag path/to/myfile |tar xf -


问:
How to construct properly a html string in C#
I need to create this html string :

```<code><table cellspacing="2" style="width:100%">
    <tr height="30" nowrap="NOWRAP" width="200" bgcolor="#f4f4f4">
      <th>Product</th>
      <th>Category</th>
      <th>Price</th>
   </tr>
   <tr>
      <td>Replace</td>
      <td>Replace</td>
      <td>Replace</td>
  </tr>
</table>
</code>```

And I have a List of items that I intend to replace. I Was trying to do with StringBuilder but it wasn't working!

答:
You can use the @ for verbatim string and double the " marks to escape them. Also you can use string.Format with {} placeholders to inject values although they are not html encoded so if you have characters like < in the string they would need to be escaped. This is 1 variant of many and without you sharing what you have so far it is as good as any answer you might get.

```<code>var html = string.Format(
@"<table cellspacing=""2"" style=""width:100%"">
    <tr height=""30"" nowrap=""NOWRAP"" width=""200"" bgcolor=""#f4f4f4"">
      <th>Product</th>
      <th>Category</th>
      <th>Price</th>
   </tr>
   <tr>
      <td>{0}</td>
      <td>{1}</td>
      <td>{2}</td>
  </tr>
</table>", listItem[0], listItem[1], listItem[2]);
</code>```

Body:
I need to create this html string :

      Product
      Category
      Price

      Replace
      Replace
      Replace

And I have a List of items that I intend to replace. I Was trying to do with StringBuilder but it wasn't working!

Body:
You can use the @ for verbatim string and double the " marks to escape them. Also you can use string.Format with {} placeholders to inject values although they are not html encoded so if you have characters like < in the string they would need to be escaped. This is 1 variant of many and without you sharing what you have so far it is as good as any answer you might get.

var html = string.Format(
@"<table cellspacing=""2"" style=""width:100%"">
    <tr height=""30"" nowrap=""NOWRAP"" width=""200"" bgcolor=""#f4f4f4"">
      <th>Product</th>
      <th>Category</th>
      <th>Price</th>
   </tr>
   <tr>
      <td>{0}</td>
      <td>{1}</td>
      <td>{2}</td>
  </tr>
</table>", listItem[0], listItem[1], listItem[2]);


问:
Get Autoscaling groups of ElasticBeanstalk environments
How can I get a list of ElasticBeanstalk environments together with their AutoScaling groups information via SDK?

I want to do an API for users to scale down the instances to 0, to save costs after office hours.

I could use DescribeEnvironments then for each environment call DescribeEnvironmentResources but I think this is less ideal? I am making O(n) calls to DescribeEnvironmentResources which maybe slow?

答:
You probably want to describe the ElasticBeanstalk environments, and get the names of the auto-scaling groups from the response. Then query the information for the auto-scaling groups. You will probably want to change the desired capacity of the Autoscaling group, from here. You should be able to put that into an API for users.

With the ruby sdk:
Get information about the ElasticBeanStalk:
http://docs.aws.amazon.com/sdkforruby/api/Aws/ElasticBeanstalk/Client.html#describe_environment_resources-instance_method

Get information about the AutoScaling group:
http://docs.aws.amazon.com/sdkforruby/api/Aws/AutoScaling/Client.html#describe_auto_scaling_groups-instance_method

Set desired capacity of the AutoScaling group:
http://docs.aws.amazon.com/sdkforruby/api/Aws/AutoScaling/Client.html#set_desired_capacity-instance_method

The code should look something like:

```<code>elasticbeanstalk = Aws::ElasticBeanstalk::Client.new(
    region: region_name,
    credentials: credentials,
)

# assuming you know the environment names
resp = elasticbeanstalk.describe_environment_resources({
  environment_name: "my-env",
})

auto_scaling_groups_array = resp.to_hash['environment_resources']['auto_scaling_groups']
# auto_scaling_groups_array[0].name should give the name of the first autoscaling group

autoscaling = Aws::AutoScaling::Client.new(
  region: region_name,
  credentials: credentials,
  # ...
)

# get the resources of an AutoScaling Group, you probably want to do this for each group
resp = autoscaling.describe_auto_scaling_groups({
  auto_scaling_group_names: [
   "my-auto-scaling-group", # or auto_scaling_groups_array[0].name
  ]
})

# set the desired capacity, you probably want to do this for each group
resp = autoscaling.set_desired_capacity({
  auto_scaling_group_name: "my-auto-scaling-group", # or auto_scaling_groups_array[0].name
  desired_capacity: 2,
  honor_cooldown: true,
})
</code>```

You probably want to do this for each region. I haven't tested this. I hope that helps.

Body:
You probably want to describe the ElasticBeanstalk environments, and get the names of the auto-scaling groups from the response. Then query the information for the auto-scaling groups. You will probably want to change the desired capacity of the Autoscaling group, from here. You should be able to put that into an API for users.

With the ruby sdk:
Get information about the ElasticBeanStalk:
http://docs.aws.amazon.com/sdkforruby/api/Aws/ElasticBeanstalk/Client.html#describe_environment_resources-instance_method

Get information about the AutoScaling group:
http://docs.aws.amazon.com/sdkforruby/api/Aws/AutoScaling/Client.html#describe_auto_scaling_groups-instance_method

Set desired capacity of the AutoScaling group:
http://docs.aws.amazon.com/sdkforruby/api/Aws/AutoScaling/Client.html#set_desired_capacity-instance_method

The code should look something like:

elasticbeanstalk = Aws::ElasticBeanstalk::Client.new(
    region: region_name,
    credentials: credentials,
)

# assuming you know the environment names
resp = elasticbeanstalk.describe_environment_resources({
  environment_name: "my-env",
})

auto_scaling_groups_array = resp.to_hash['environment_resources']['auto_scaling_groups']
# auto_scaling_groups_array[0].name should give the name of the first autoscaling group

autoscaling = Aws::AutoScaling::Client.new(
  region: region_name,
  credentials: credentials,
  # ...
)

# get the resources of an AutoScaling Group, you probably want to do this for each group
resp = autoscaling.describe_auto_scaling_groups({
  auto_scaling_group_names: [
   "my-auto-scaling-group", # or auto_scaling_groups_array[0].name
  ]
})

# set the desired capacity, you probably want to do this for each group
resp = autoscaling.set_desired_capacity({
  auto_scaling_group_name: "my-auto-scaling-group", # or auto_scaling_groups_array[0].name
  desired_capacity: 2,
  honor_cooldown: true,
})

You probably want to do this for each region. I haven't tested this. I hope that helps.


问:
How tensorflow tf.contrib.learn.SVM reload trained model and use predict to classify new data
Training svm model with tensorflow tf.contrib.learn.SVM and saveing model; the codes

```<code>feature_columns = [tf.contrib.layers.real_valued_column(feat) for feat in self.feature_columns]
model_dir = os.path.join(define.root, 'src', 'static_data', 'svm_model_dir')
model = svm.SVM(example_id_column='example_id',
                feature_columns=feature_columns,
                 model_dir=model_dir,
                            config=tf.contrib.learn.RunConfig(save_checkpoints_secs=10))
model.fit(input_fn=lambda: self.input_fun(self.df_train), steps=10000)
results = model.evaluate(input_fn=lambda: self.input_fun(self.df_test), steps=5, metrics=validation_metrics)
for key in sorted(results):
    print('% s: % s' % (key, results[key]))
</code>```

hwo to reload trained model and use predict to classify new data?

答:
When training

You call svm.SVM(..., model_dir) and then call the fit() and evaluate() method.

When testing

You call svm.SVM(..., model_dir) and then can call predict() methods. Your model will find a trained model in the model_dir and will load the trained model params.

Reference

Issue #3340 of TF

Body:
Training svm model with tensorflow tf.contrib.learn.SVM and saveing model; the codes

feature_columns = [tf.contrib.layers.real_valued_column(feat) for feat in self.feature_columns]
model_dir = os.path.join(define.root, 'src', 'static_data', 'svm_model_dir')
model = svm.SVM(example_id_column='example_id',
                feature_columns=feature_columns,
                 model_dir=model_dir,
                            config=tf.contrib.learn.RunConfig(save_checkpoints_secs=10))
model.fit(input_fn=lambda: self.input_fun(self.df_train), steps=10000)
results = model.evaluate(input_fn=lambda: self.input_fun(self.df_test), steps=5, metrics=validation_metrics)
for key in sorted(results):
    print('% s: % s' % (key, results[key]))

hwo to reload trained model and use predict to classify new data?


问:
How to convert wstring to wchar_t*? C++
I would like to convert wstring to wchar_t*. I have tried everything what i know, please help.
I would like to convert wstring to wchar_t*.</p>

答:
Did you try reading the reference</p>

```<code>const wchar_t* wcs = s.c_str();
</code>```

Title: How to convert wstring to wchar_t*? C++

Body:
Did you try reading the reference

const wchar_t* wcs = s.c_str();


问:
R services in SQL server - since which version?
Since which version does SQL server (non-Azure) support the R language? </p>

<p>What are good doc resources to get an overview of that support? </p>

答: R Services was introduced in SQL Server 2016. The SQL Server 2017 version under development, adds support for Python and renamed the feature to Machine Learning Services.</p>

Body:
Since which version does SQL server (non-Azure) support the R language?

What are good doc resources to get an overview of that support?


问:
SQL: simplify and, or query on multiple columns
I have a table named employe with following content

```<code>id A B C D E F G
1  8 4 6 3 2 5 2
1  7 3 1 2 1 3 7
3  9 2 3 3 2 6 1
4  6 1 2 4 5 5 7
4  6 4 6 3 2 5 2
</code>```

I do a query like this

```<code>employe.where(
   A > 7 &
(

 (C<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & F<3)

)
)
</code>```

Is there any way to simplify the above query? Because I have more than 20 columns in my table and I have do the above query for all columns. It looks ugly and same code in every line. Even if I could something like this would look nice

```<code>q1 = [C, D, E, F, G]
q2 = [B, D, E, F, G]
q3 = [B, C, E, F, G]
q4 = [B, C, D, F, G]
q5 = [B, C, D, E, G]
q6 = [B, C, D, E, F]
employe.where(
   A > 7 &
(
  q1<3 | q2<3 | q4<4 | q5<3 | q6<3
)
)
</code>```

答:
I don't have MySQL to check, but is it possible to do something like:

```<code>SELECT * FROM @employee e
INNER JOIN (SELECT id, A,
CASE WHEN a < 3 THEN 0 ELSE 1 END +
CASE WHEN b < 3 THEN 0 ELSE 1 END +
CASE WHEN c < 3 THEN 0 ELSE 1 END +
CASE WHEN d < 3 THEN 0 ELSE 1 END +
CASE WHEN e < 3 THEN 0 ELSE 1 END +
CASE WHEN f < 3 THEN 0 ELSE 1 END +
CASE WHEN g < 3 THEN 0 ELSE 1 END as cnt from @employee) c
on e.id = c.id
WHERE e.A > 7 AND c.cnt < 3
</code>```

If I understand you correctly you are trying to find instances of one column where it is greater than 7, where at least four of the other five columns are less than three.  My example achieves this (for all columns) by a simple trick of logic.  If you count all the instances of A-G that are not less than 3 and check that for any column this is less than 3 where that column is > 7, then you know the others are maximally one not less than 3, since the column itself is one of the 2 that are not less than 3.

Expanding the example for all columns you then get

```<code>SELECT * FROM @employee e
INNER JOIN (SELECT id,
CASE WHEN a < 3 THEN 0 ELSE 1 END +
CASE WHEN b < 3 THEN 0 ELSE 1 END +
CASE WHEN c < 3 THEN 0 ELSE 1 END +
CASE WHEN d < 3 THEN 0 ELSE 1 END +
CASE WHEN e < 3 THEN 0 ELSE 1 END +
CASE WHEN f < 3 THEN 0 ELSE 1 END +
CASE WHEN g < 3 THEN 0 ELSE 1 END as cnt from @employee) c
on e.id = c.id
WHERE (e.A > 7 OR e.B > 7 OR e.C > 7 OR e.D > 7 OR e.F > 7 or e.G > 7)
AND c.cnt < 3
</code>```

Body:
I have a table named employe with following content

id A B C D E F G
1  8 4 6 3 2 5 2
1  7 3 1 2 1 3 7
3  9 2 3 3 2 6 1
4  6 1 2 4 5 5 7
4  6 4 6 3 2 5 2

I do a query like this

employe.where(
   A > 7 &
(

 (C<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & F<3)

)
)

Is there any way to simplify the above query? Because I have more than 20 columns in my table and I have do the above query for all columns. It looks ugly and same code in every line. Even if I could something like this would look nice

q1 = [C, D, E, F, G]
q2 = [B, D, E, F, G]
q3 = [B, C, E, F, G]
q4 = [B, C, D, F, G]
q5 = [B, C, D, E, G]
q6 = [B, C, D, E, F]
employe.where(
   A > 7 &
(
  q1<3 | q2<3 | q4<4 | q5<3 | q6<3
)
)

Body:
I don't have MySQL to check, but is it possible to do something like:

SELECT * FROM @employee e
INNER JOIN (SELECT id, A,
CASE WHEN a < 3 THEN 0 ELSE 1 END +
CASE WHEN b < 3 THEN 0 ELSE 1 END +
CASE WHEN c < 3 THEN 0 ELSE 1 END +
CASE WHEN d < 3 THEN 0 ELSE 1 END +
CASE WHEN e < 3 THEN 0 ELSE 1 END +
CASE WHEN f < 3 THEN 0 ELSE 1 END +
CASE WHEN g < 3 THEN 0 ELSE 1 END as cnt from @employee) c
on e.id = c.id
WHERE e.A > 7 AND c.cnt < 3

If I understand you correctly you are trying to find instances of one column where it is greater than 7, where at least four of the other five columns are less than three.  My example achieves this (for all columns) by a simple trick of logic.  If you count all the instances of A-G that are not less than 3 and check that for any column this is less than 3 where that column is > 7, then you know the others are maximally one not less than 3, since the column itself is one of the 2 that are not less than 3.

Expanding the example for all columns you then get

SELECT * FROM @employee e
INNER JOIN (SELECT id,
CASE WHEN a < 3 THEN 0 ELSE 1 END +
CASE WHEN b < 3 THEN 0 ELSE 1 END +
CASE WHEN c < 3 THEN 0 ELSE 1 END +
CASE WHEN d < 3 THEN 0 ELSE 1 END +
CASE WHEN e < 3 THEN 0 ELSE 1 END +
CASE WHEN f < 3 THEN 0 ELSE 1 END +
CASE WHEN g < 3 THEN 0 ELSE 1 END as cnt from @employee) c
on e.id = c.id
WHERE (e.A > 7 OR e.B > 7 OR e.C > 7 OR e.D > 7 OR e.F > 7 or e.G > 7)
AND c.cnt < 3


问:
WCF service, how to mapp the objects runtime
I have to design a wcf service which gives outut in a standard model(which i think its better to give as string/XML).But this standard model is/may be subjected to change its format.So every time its changed we need to change the code.My service should also accomadte the same with configurable change. How to do it without code change and exernal configurable entities.

Is there any way to create and mapp  the class in runtime.

My primary idea is to keep a format internally and an XML which would be the standard format and to mapp the class properties and XML nodes using a database table.

Please suggest ....Appreciate the help from GURUS !!!

Thanks in advance

答: I don't fully understand the question, so perhaps you could elaborate upon it, perhaps with some simplified code? However, if you need to map between XML formats, have you considered an XSL Transform?</p>

ContentLicense: CC BY-SA 2.5


问:
Parsing Decoded JSON in PHP (blokchain API)
Hello I am trying to extract some info from a json format page

The page is : https://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF

this link allows to get all bitcoin transactions from an address.
All the quotation marks confuse me, I can not see clearly

I want to display everything like the original blockchain website
Blockchain Display view
The beginning will be something like that

```<code>$json = file_get_contents("https://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
var_dump(json_decode($json));
</code>```

I can extract basic info from JSO to php, but here there is too much transactions and I think we need to use a loop to display everything but I don't know how to do that
If someone can display for me in php the 5 first transactions it will be very sympathic.

Thanks a lot in advance youw ill really help me if you can do that !

答:
If you goal is to display all Tx info you want to do that.

```<code>$json = file_get_contents("http://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
$txs = json_decode($json,1)['txs'];
echo"```"; //just to get a human readable display
foreach($txs as $txinfo){
    echo"A new tx";
    //will display the full tx data
    print_r($txinfo);
}

echo"```";
</code>```

Note a blockchain transaction can be a little complexe since one transaction can have multiple input and multiple outputs.
you might want to cycle trough outputs as well to display all addresses who received bitcoin from a transaction
in that case you can simply add another foreach output

```<code>$json = file_get_contents("http://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
$txs = json_decode($json,1)['txs'];
echo"```"; //just to get a human readable display
foreach($txs as $txinfo){
    echo"A new tx";
    //will display the full tx data
    print_r($txinfo);
    // will cycle trough all output for each tx
    foreach ($txinfo['out'] as $outgoingTransaction)
    {
        //Will display the receiving address
       $receivingAddress = $outgoingTransaction['addr'];
       //will get the amount sent in satoshis
       $receivingAmountInSatoshi = $outgoingTransaction['value'];

       echo"
1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF sent to $receivingAddress  $receivingAmountInSatoshi satoshis
";

    }

}
```

<p>a more advanced code to add tx understanding logic</p>

```$walletAddress = '1AWKFrvFYuCC7ef2m2zX73pWu1C15FRGjR' ;
$json = file_get_contents("http://blockchain.info/fr/rawaddr/$walletAddress");
$txs = json_decode($json,1)['txs'];
echo"```"; //just to get a human readable display

foreach($txs as $txinfo){

    $spendingTx = false ;
    $totalSpent = 0 ;
    $totalReceived = 0;

    echo"<p>Txid = $txinfo[hash]<br>";
    //print_r($txinfo);

    // we need to find out if the address is the sender or the receiver
    $senderData = reset($txinfo['inputs']); //using reset to get only the first input
    if ($senderData['prev_out']['addr'] ==$walletAddress ){
        //the address is the sender meaning the address is spending
        $spendingTx = true ;

    }

   //it's a spend tx then we cycle trough receivers
    if ($spendingTx) {

        foreach ($txinfo['out'] as $outgoingTransaction) {
            //Will display the receiving address
            $receivingAddress = $outgoingTransaction['addr'];
            //will get the amount sent in satoshis
            $receivingAmountInSatoshi = $outgoingTransaction['value'];
            $totalSpent = $totalSpent + $receivingAmountInSatoshi ;
            echo "<br>$walletAddress sent to $receivingAddress  $receivingAmountInSatoshi satoshis <br>";

        }

        echo "<br>Total spent = $totalSpent" ;

    }
        //it is not a spending tx so it's a receceiving tx
        else {

            foreach ($txinfo['out'] as $outgoingTransaction) {

                //We keep only receiving data concerning current wallet
                if ($outgoingTransaction['addr'] == $walletAddress) {
                    //Will display the receiving address
                    $receivingAddress = $outgoingTransaction['addr'];
                    //will get the amount sent in satoshis
                    $receivingAmountInSatoshi = $outgoingTransaction['value'];
                    $senderAddress = $senderData['prev_out']['addr'];
                    $totalReceived = $receivingAmountInSatoshi;
                    echo "<br>$walletAddress received $receivingAmountInSatoshi satoshis from $senderAddress<br>";

                }

            }
            echo "<br>Total received = $totalReceived" ;

        }

        echo"<br>end tx </p>";
}

echo"```";
```

Body:
Hello I am trying to extract some info from a json format page

The page is : https://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF

this link allows to get all bitcoin transactions from an address.
All the quotation marks confuse me, I can not see clearly

I want to display everything like the original blockchain website
Blockchain Display view
The beginning will be something like that

$json = file_get_contents("https://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
var_dump(json_decode($json));

I can extract basic info from JSO to php, but here there is too much transactions and I think we need to use a loop to display everything but I don't know how to do that
If someone can display for me in php the 5 first transactions it will be very sympathic.

Thanks a lot in advance youw ill really help me if you can do that !

Body:
If you goal is to display all Tx info you want to do that.

$json = file_get_contents("http://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
$txs = json_decode($json,1)['txs'];
echo"<pre>"; //just to get a human readable display
foreach($txs as $txinfo){
    echo"A new tx";
    //will display the full tx data
    print_r($txinfo);
}

echo"</pre>";

Note a blockchain transaction can be a little complexe since one transaction can have multiple input and multiple outputs.
you might want to cycle trough outputs as well to display all addresses who received bitcoin from a transaction
in that case you can simply add another foreach output

$json = file_get_contents("http://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
$txs = json_decode($json,1)['txs'];
echo"<pre>"; //just to get a human readable display
foreach($txs as $txinfo){
    echo"A new tx";
    //will display the full tx data
    print_r($txinfo);
    // will cycle trough all output for each tx
    foreach ($txinfo['out'] as $outgoingTransaction)
    {
        //Will display the receiving address
       $receivingAddress = $outgoingTransaction['addr'];
       //will get the amount sent in satoshis
       $receivingAmountInSatoshi = $outgoingTransaction['value'];

       echo"<br>1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF sent to $receivingAddress  $receivingAmountInSatoshi satoshis <br>";

    }

}

a more advanced code to add tx understanding logic

$walletAddress = '1AWKFrvFYuCC7ef2m2zX73pWu1C15FRGjR' ;
$json = file_get_contents("http://blockchain.info/fr/rawaddr/$walletAddress");
$txs = json_decode($json,1)['txs'];
echo"<pre>"; //just to get a human readable display

foreach($txs as $txinfo){

    $spendingTx = false ;
    $totalSpent = 0 ;
    $totalReceived = 0;

    echo"<p>Txid = $txinfo[hash]<br>";
    //print_r($txinfo);

    // we need to find out if the address is the sender or the receiver
    $senderData = reset($txinfo['inputs']); //using reset to get only the first input
    if ($senderData['prev_out']['addr'] ==$walletAddress ){
        //the address is the sender meaning the address is spending
        $spendingTx = true ;

    }

   //it's a spend tx then we cycle trough receivers
    if ($spendingTx) {

        foreach ($txinfo['out'] as $outgoingTransaction) {
            //Will display the receiving address
            $receivingAddress = $outgoingTransaction['addr'];
            //will get the amount sent in satoshis
            $receivingAmountInSatoshi = $outgoingTransaction['value'];
            $totalSpent = $totalSpent + $receivingAmountInSatoshi ;
            echo "<br>$walletAddress sent to $receivingAddress  $receivingAmountInSatoshi satoshis <br>";

        }

        echo "<br>Total spent = $totalSpent" ;

    }
        //it is not a spending tx so it's a receceiving tx
        else {

            foreach ($txinfo['out'] as $outgoingTransaction) {

                //We keep only receiving data concerning current wallet
                if ($outgoingTransaction['addr'] == $walletAddress) {
                    //Will display the receiving address
                    $receivingAddress = $outgoingTransaction['addr'];
                    //will get the amount sent in satoshis
                    $receivingAmountInSatoshi = $outgoingTransaction['value'];
                    $senderAddress = $senderData['prev_out']['addr'];
                    $totalReceived = $receivingAmountInSatoshi;
                    echo "<br>$walletAddress received $receivingAmountInSatoshi satoshis from $senderAddress<br>";

                }

            }
            echo "<br>Total received = $totalReceived" ;

        }

        echo"<br>end tx </p>";
}

echo"</pre>";


问:
Center image in ul
Tried to google this but didn't find anything that helped me.
So I have button-text on the left and right but I want to center an image inside the top bar.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #f3f3f3;
    }

    li {
    float: left;
    }

    li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }

    li a:hover:not(.active) {
    background-color: #ddd;
    }

    li a.active {
    color: white;
    background-color: #3744a2;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>home</li>
    <li>news</li>
    <li>services</li>
    <li>prices</li>
    <li>contat</li>
    <li><img src="https://dummyimage.com/150X38/000/fff"></li>
    <li style="float:right"><i class="fa fa-envelope" aria-hidden="true"></i>  enter@email.here</li>
    <li style="float:right"><i class="fa fa-phone" aria-hidden="true"></i>  123 123 123</li>
    </ul></code>```

so what I basicly want is the image (class="image") to be centered, but the rest as it is.

Thanks alot!

答:
Do it like this

Remove image class from a tag and give image class to it's parent li and try this with this example. it will helps you

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f3f3f3;
text-align: center;
}

li {
float: left;
}

li a {
display: block;
color: #666;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

li a:hover:not(.active) {
background-color: #ddd;
}

li a.active {
color: white;
background-color: #3744a2;
}
li.image {
    float: none;
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>home</li>
<li>news</li>
<li>services</li>
<li>prices</li>
<li>contat</li>
<li class='image'><img src="../image/image.png"></li>
<li style="float:right"><i class="fa fa-envelope" aria-hidden="true"></i>  enter@email.here</li>
<li style="float:right"><i class="fa fa-phone" aria-hidden="true"></i>  123 123 123</li>
</ul></code>```

Title: Center image in ul

Body:
Tried to google this but didn't find anything that helped me.
So I have button-text on the left and right but I want to center an image inside the top bar.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #f3f3f3;
    }

    li {
    float: left;
    }

    li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }

    li a:hover:not(.active) {
    background-color: #ddd;
    }

    li a.active {
    color: white;
    background-color: #3744a2;
    }

home

news

services

prices

contat

  enter@email.here

  123 123 123

so what I basicly want is the image (class="image") to be centered, but the rest as it is.

Thanks alot!

Body:
Do it like this

Remove image class from a tag and give image class to it's parent li and try this with this example. it will helps you

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f3f3f3;
text-align: center;
}

li {
float: left;
}

li a {
display: block;
color: #666;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

li a:hover:not(.active) {
background-color: #ddd;
}

li a.active {
color: white;
background-color: #3744a2;
}
li.image {
    float: none;
    display: inline-block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="../index.html">home</a></li>
<li><a href="../news/news.html">news</a></li>
<li><a href="../services/services.html">services</a></li>
<li><a class="active" href="#">prices</a></li>
<li><a href="../contat/contat.html">contat</a></li>
<li class='image'><a class="" href="#"><img src="../image/image.png"></a></li>
<li style="float:right"><a href="mailto:enter@email.here"><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp; enter@email.here</a></li>
<li style="float:right"><a href="#"><i class="fa fa-phone" aria-hidden="true"></i>&nbsp; 123 123 123</a></li>
</ul>


问:
Can't import .json file to Firebase database.x
I'm trying to import my json file (called users.json), this is the file content:

```<code>{
  users:{

  },
  friends:{

  }
}
</code>```

I'm trying to import it to the firebase but it says "invalid json file".
What am I doing wrong?

答:
Every key in JSON file has to be surrounded by quotation marks.</p>

```<code>{
  "users":{

  },
  "friends":{

  }
}
</code>```

Body:
I'm trying to import my json file (called users.json), this is the file content:

{
  users:{

  },
  friends:{

  }
}

I'm trying to import it to the firebase but it says "invalid json file".
What am I doing wrong?

Body:
Every key in JSON file has to be surrounded by quotation marks.

{
  "users":{

  },
  "friends":{

  }
}


问:
Unable to run Python code
I have installed Python 3.5 in the directory c:\users\rshukla\desktop\python\python35

I have downloaded a simple Python code that I have saved in Atom.io also in the same folder c:\users\rshukla\desktop\python\happy_hour.py
And I am trying to it run through Powershell

```<code>import random

bars = ["Shoolbred's",
    "The Wren",
    "The Scratcher",
    "ACME",
    "Blind Barber"]

people = ["Mattan",
      "Chris",
      "Pooje",
      "that person you forgot to text back",
      "Kanye West",
      "Samuel L. Jackson"]

random_bar = random.choice(bars)
random_person_1 = random.choice(people)
random_person_2 = ramndon.choice(people)

print(f"How about you go to {random_bar} with {random_person_1} and {random_person_2}")
</code>```

When I try running this in Powershell, I get the output below - what am I doing    wrong?

```<code>PS C:\Users\rshukla\desktop\python> python happy_hour.py
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python happy_hour.py
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
Try doing:
c:\users\rshukla\desktop\python\python35 c:\users\rshukla\desktop\python\happy_hour.py

If you don't want to type complete path of python executable(python35) add this path c:\users\rshukla\desktop\python to PATH variable in your PS shell.

PATH variable is the location where powershell searches for executables you're try to executes any CMD line utility, right now it(powershell) is not able to find python35, so either you can give whole path of python35 exe or add the directory into path variable.

ps. ignore typos, written via mobile

Title: Unable to run Python code

Body:
I have installed Python 3.5 in the directory c:\users\rshukla\desktop\python\python35

I have downloaded a simple Python code that I have saved in Atom.io also in the same folder c:\users\rshukla\desktop\python\happy_hour.py
And I am trying to it run through Powershell

import random

bars = ["Shoolbred's",
    "The Wren",
    "The Scratcher",
    "ACME",
    "Blind Barber"]

people = ["Mattan",
      "Chris",
      "Pooje",
      "that person you forgot to text back",
      "Kanye West",
      "Samuel L. Jackson"]

random_bar = random.choice(bars)
random_person_1 = random.choice(people)
random_person_2 = ramndon.choice(people)

print(f"How about you go to {random_bar} with {random_person_1} and {random_person_2}")

When I try running this in Powershell, I get the output below - what am I doing    wrong?

PS C:\Users\rshukla\desktop\python> python happy_hour.py
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python happy_hour.py
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


问:
How can I use GDB from inside Visual Studio C++ (Express) to debug my GCC Makefile projects?
I've a couple of Makefile projects on my visual studio (express) 2005/2008 (doesn't matter for now) to compile some application using the MinGW GCC compiler. I don't want to use the MS compiler because there are features that only are available on GCC.

Now I'd like to debug from inside VS since I'm coding from it but this requires me to use GDB (it works from the command line) but i prefer to use the IDE tools.

Is there a way to do this? Even if the Express version is limited and doesn't support it can it be done using the full version?

答: As far as I know, you can only debug from within the IDE if you have compiled your code with the Microsoft compiler. Otherwise, the Visual Studio debugger doesn't have a clue what to do with the GDB debug information.</p>

OwnerDisplayName: Paulo Lopes

OwnerDisplayName: Greg Hewgill


问:
Jquery check for integer?
I have this code:

```<code>    jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

    // Move the damn autocue

 $('a.goDown').click(function(){
        alert($moveSpeed);
  $.scrollTo('#footer', $moveSpeed);
  return false;
 });

    $('a.goUp').click(function(){
        alert($moveSpeed);
  $.scrollTo('#header', $moveSpeed);
  return false;
 });

    // Speed settings for autocue

    $('a.changeSpeed').click(function(){
  $moveSpeed = $(this).attr('speed');
  return false;
 });
});

</script>
</code>```

and if the changeSpeed is clicked, the alert box shows it is changed to the given number but it aint an integer, is there a way to convert a variable in to an integer?

thx :)

答:
```<code>$('a.changeSpeed').click(function(){
  $moveSpeed = parseInt($(this).attr('speed'),10);
  return false;
 });
</code>```

Javascript parseInt Function

Title: Jquery check for integer?

Body:
I have this code:

    jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

    // Move the damn autocue

 $('a.goDown').click(function(){
        alert($moveSpeed);
  $.scrollTo('#footer', $moveSpeed);
  return false;
 });

    $('a.goUp').click(function(){
        alert($moveSpeed);
  $.scrollTo('#header', $moveSpeed);
  return false;
 });

    // Speed settings for autocue

    $('a.changeSpeed').click(function(){
  $moveSpeed = $(this).attr('speed');
  return false;
 });
});

</script>

and if the changeSpeed is clicked, the alert box shows it is changed to the given number but it aint an integer, is there a way to convert a variable in to an integer?

thx :)

Body:
$('a.changeSpeed').click(function(){
  $moveSpeed = parseInt($(this).attr('speed'),10);
  return false;
 });

Javascript parseInt Function


问:
Separate strings by word to a separate line in Python
I have a line in my textfile like the line below:

```<code>hi   everyone  this is good
the weather is good     yes
</code>```

I want to write each string in one line like this:

```<code>  hi
  everyone
  this
</code>```

What should i do? I dont know the number of spaces between each string.

Thank you

I used this method but it didn´t work

```<code>text_file = open("1.txt","r")
for line in text_file :
    lline = list(line)
    lline.replace(" ", "")
    line1 = lline.join()
    file.write(line1)
</code>```

答:
You can split the lines by whitespaces and flatten the list:

```<code>lines = ['hi there', 'how    are you   today']
tokens = [token for line in lines for token in line.split()]
# tokens: ['hi', 'there', 'how', 'are', 'you', 'today']
</code>```

When reading from file the code should be:

```<code>with open('1.txt', 'rt') as text_file:
    tokens = [token for line in text_file for token in line.split()]
    target_file.write('\n'.join(tokens))
</code>```

Edit thanks to officialaimm's comment the example was simplified from re.split(r'\s+', line) to line.split().

Body:
I have a line in my textfile like the line below:

hi   everyone  this is good
the weather is good     yes

I want to write each string in one line like this:

  hi
  everyone
  this

What should i do? I dont know the number of spaces between each string.

Thank you

I used this method but it didn´t work

text_file = open("1.txt","r")
for line in text_file :
    lline = list(line)
    lline.replace(" ", "")
    line1 = lline.join()
    file.write(line1)

Body:
You can split the lines by whitespaces and flatten the list:

lines = ['hi there', 'how    are you   today']
tokens = [token for line in lines for token in line.split()]
# tokens: ['hi', 'there', 'how', 'are', 'you', 'today']

When reading from file the code should be:

with open('1.txt', 'rt') as text_file:
    tokens = [token for line in text_file for token in line.split()]
    target_file.write('\n'.join(tokens))

Edit thanks to officialaimm's comment the example was simplified from re.split(r'\s+', line) to line.split().


答:
Using re.sub:

```<code>In [227]: import re

In [228]: line = '''hi   everyone  this is good
     ...:   the weather is good     yes'''

In [233]: print(re.sub('\s+', '\n', line, re.M | re.DOTALL))
hi
everyone
this
is
good
the
weather
is
good
yes
</code>```

Title: Separate strings by word to a separate line in Python

Body:
Using re.sub:

In [227]: import re

In [228]: line = '''hi   everyone  this is good
     ...:   the weather is good     yes'''

In [233]: print(re.sub('\s+', '\n', line, re.M | re.DOTALL))
hi
everyone
this
is
good
the
weather
is
good
yes


问:
How to turn columns into rows without available library functions (Python)
So I have this, which only works when the number of columns (number of elements in my sublist) is equal to the number of rows I want to create.

```<code>list1 = [[2, 1, 2, 6],[1, 5, 4, 9],[4, 2, 3, 2],[1, 4, 5, 7]

for i in range(len(list1)):
    columns.append([row[i] for row in list1])
</code>```

I tried this to make it universal, meaning it'll accept any combination of list length and sublist length (ex. [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]) but the error I got was that j wasn't defined.

```<code>for i,j in range(len(list1[i][j])):
    columns.append([row[i] for row in list1])
</code>```

How can I change this to make it work?
My list has to be a NxM matrix, and I can't use any shortcuts like min, max, zip, etc.

答:
This will work. The main ideas are to create an empty over-all result list and empty sub-lists at the proper time and append to them. Note that the input matrix has size m x n, m rows and n columns, which is the standard way to state matrix size. The result has size n x m. You may swap the m and n names to correspond with your lessons or book, if you like.

```<code>m, n = len(list1), len(list1[0])
result = []
for col in range(n):
    result.append([])
    for row in range(m):
        result[col].append(list1[row][col])
</code>```

If you do not like the temporarily-empty lists or appends, an alternative approach that is often used in languages other than Python is to create a temporary result matrix of the proper size then fill in the correct entries, like this:

```<code>m, n = len(list1), len(list1[0])
result = [[None] * m for col in range(n)]
for col in range(n):
    for row in range(m):
        result[col][row] = list1[row][col]
</code>```

Also, there is also the briefer but harder-to-understand list comprehension:

```<code>[[list1[row][col] for row in range(len(list1))] for col in range(len(list1[0]))]
</code>```

All that said, the better way in Python is

```<code>result = list(map(list, (zip(*list1))))
</code>```

(That last includes a correction by @cᴏʟᴅsᴘᴇᴇᴅ.)

Body:
So I have this, which only works when the number of columns (number of elements in my sublist) is equal to the number of rows I want to create.

list1 = [[2, 1, 2, 6],[1, 5, 4, 9],[4, 2, 3, 2],[1, 4, 5, 7]

for i in range(len(list1)):
    columns.append([row[i] for row in list1])

I tried this to make it universal, meaning it'll accept any combination of list length and sublist length (ex. [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]) but the error I got was that j wasn't defined.

for i,j in range(len(list1[i][j])):
    columns.append([row[i] for row in list1])

How can I change this to make it work?
My list has to be a NxM matrix, and I can't use any shortcuts like min, max, zip, etc.

Body:
This will work. The main ideas are to create an empty over-all result list and empty sub-lists at the proper time and append to them. Note that the input matrix has size m x n, m rows and n columns, which is the standard way to state matrix size. The result has size n x m. You may swap the m and n names to correspond with your lessons or book, if you like.

m, n = len(list1), len(list1[0])
result = []
for col in range(n):
    result.append([])
    for row in range(m):
        result[col].append(list1[row][col])

If you do not like the temporarily-empty lists or appends, an alternative approach that is often used in languages other than Python is to create a temporary result matrix of the proper size then fill in the correct entries, like this:

m, n = len(list1), len(list1[0])
result = [[None] * m for col in range(n)]
for col in range(n):
    for row in range(m):
        result[col][row] = list1[row][col]

Also, there is also the briefer but harder-to-understand list comprehension:

[[list1[row][col] for row in range(len(list1))] for col in range(len(list1[0]))]

All that said, the better way in Python is

result = list(map(list, (zip(*list1))))

(That last includes a correction by @cᴏʟᴅsᴘᴇᴇᴅ.)


问:
Getting error while using parameterised like query in Python
I am getting the following error while trying to use like query for sqlite3 db using python.

Error:

```<code>Request Method: POST
Request URL:    http://127.0.0.1:8000/search/
Django Version: 1.11.2
Exception Type: ProgrammingError
Exception Value:Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.
</code>```

I am explaining my query below.

```<code>rname = request.POST.get('rname')
keyword = '%' + rname + '%'
cursor.execute("SELECT * FROM booking_meeting WHERE room_name LIKE ? ",(keyword))
</code>```

Here I need to fetch value from table as per keyword. Please help me to resolve this error.

答:
try:

```<code>keyword = '%"' + rname + '"%'
</code>```

or

```<code>keyword = '%\'' + rname + '\'%'
</code>```

spaces in your keyword might cause the 3 parameters recognized.

Body:
I am getting the following error while trying to use like query for sqlite3 db using python.

Error:

Request Method: POST
Request URL:    http://127.0.0.1:8000/search/
Django Version: 1.11.2
Exception Type: ProgrammingError
Exception Value:Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.

I am explaining my query below.

rname = request.POST.get('rname')
keyword = '%' + rname + '%'
cursor.execute("SELECT * FROM booking_meeting WHERE room_name LIKE ? ",(keyword))

Here I need to fetch value from table as per keyword. Please help me to resolve this error.

Body:
try:

keyword = '%"' + rname + '"%'

or

keyword = '%\'' + rname + '\'%'

spaces in your keyword might cause the 3 parameters recognized.


问:
Problems with case-when-value-between something -formula
I have a case in where I have product codes, which are 4 symbol long. Then in some cases products are basically same no mather of the first symbol, for example one product code would be 7456 and another 8456 and these products would still have same function. So only difference is the first symbol and three symbols from rigth remains same.

My problem is that I would like to compare two data table with each other and in the first table could be used code 7456 and in the second one code 8456. I would like to mach these two data together but I dunno know how to tell for SQL that if code start with 7 or 8 use three last symbols.

I think that possible solution would be some kind of case when value between 7000-8999 then use 3 right, but I can't get this code to work? Would someone has a solution for me??? Thanks!

答:
Are you looking for something like this</p>

```<code>CASE
    WHEN value BETWEEN '7000' AND '8999'
        THEN RIGHT(value, 3)
    ELSE value
END
</code>```

Body:
Are you looking for something like this

CASE
    WHEN value BETWEEN '7000' AND '8999'
        THEN RIGHT(value, 3)
    ELSE value
END


问:
User Name is not taking from Dataabase
I'm new to php. I've some problem. I get the value of username with ($_GET) variable. Let's suppose if some one enter (mehwish) in url. I want to check if the username entered by user is available or not in the database. My code below doesn't work. Correct my mistake if there's any. Thank you for your support.</p>

```<code><?php include("header.php");
    include("classes/db.php");
    session_start();
    $username="";
    if(isset($_GET['username']))
    {
        $user=$_GET['username'];
        if("SELECT user_name FROM user_reg WHERE user_name='$user'")
        {
            $username="SELECT user_name FROM user_reg WHERE user_name='$user'";
            $run_username=mysqli_query($con,$username);
            $row=mysqli_fetch_array($run_username);
            $username=$row['user_name'];
        }
        else
        {
            die("User does nto exist");
        }
    }
    ?>
</code>```

答:
You've many mistakes in your code.Try something like this: </p>

```<code>    <?php include("header.php");
        include("classes/db.php");
        session_start();
        $username="";
        if(isset($_GET['username']))
        {
            $user=$_GET['username'];
            $q = "SELECT user_name FROM user_reg WHERE user_name='$user'";
            $res = mysqli_query($con, q);
            if(mysqli_num_rows($res) > 0)
            {
                while ($row = mysqli_fetch_array($res, $con)) {
                     //Show what you want here..
                }
            }
            else
            {
                echo "User does nto exist";
            }
        }
 ?>
</code>```

Title: User Name is not taking from Dataabase

Body:
I'm new to php. I've some problem. I get the value of username with ($_GET) variable. Let's suppose if some one enter (mehwish) in url. I want to check if the username entered by user is available or not in the database. My code below doesn't work. Correct my mistake if there's any. Thank you for your support.

<?php include("header.php");
    include("classes/db.php");
    session_start();
    $username="";
    if(isset($_GET['username']))
    {
        $user=$_GET['username'];
        if("SELECT user_name FROM user_reg WHERE user_name='$user'")
        {
            $username="SELECT user_name FROM user_reg WHERE user_name='$user'";
            $run_username=mysqli_query($con,$username);
            $row=mysqli_fetch_array($run_username);
            $username=$row['user_name'];
        }
        else
        {
            die("User does nto exist");
        }
    }
    ?>

Body:
You've many mistakes in your code.Try something like this:

    <?php include("header.php");
        include("classes/db.php");
        session_start();
        $username="";
        if(isset($_GET['username']))
        {
            $user=$_GET['username'];
            $q = "SELECT user_name FROM user_reg WHERE user_name='$user'";
            $res = mysqli_query($con, q);
            if(mysqli_num_rows($res) > 0)
            {
                while ($row = mysqli_fetch_array($res, $con)) {
                     //Show what you want here..
                }
            }
            else
            {
                echo "User does nto exist";
            }
        }
 ?>


问:
How to get current element with mousOver React
I'm new in React, but I have some experience in JS.

My question is:

I have a function and I put this functions to onMouseOver event to element

```<code><td> in current situation.
</code>```

I want to get this current dom element and get index of this element next.

My code is bellow:

var Cell = function(k) {

  function getIndex(cell){
   console.log(cell)
  }

  return (

  )

}```

In js it works something like this. But now in React it returns me null.

If I put in console.log "1" for example it also works. So function is woks and I have only problem to get information about current element

Please help to find out how to do it.
Thanks.

答:
```<code>You have to bind the function instead of creating new function so the context scope of component remains same

var Cell = function(k) {
        function getIndex(cell){
            console.log(cell)
        }
        return (

            <td key ={k} onMouseOver={this.getIndex.bind(this,k)}}>
                <div className="square__cell" ></div>
            </td>

        )
}
</code>```

Body:
I'm new in React, but I have some experience in JS.

My question is:

I have a function and I put this functions to onMouseOver event to element

 in current situation.

I want to get this current dom element and get index of this element next.

My code is bellow:

var Cell = function(k) {

  function getIndex(cell){
   console.log(cell)
  }

  return (

  )

}

In js it works something like this. But now in React it returns me null.

If I put in console.log "1" for example it also works. So function is woks and I have only problem to get information about current element

Please help to find out how to do it.
Thanks.


答:
I used display:flex and flex property. by setting display: flex:0 I'm telling the browser I want this element take just the place he need, and with flex:1 on a single element I'm telling that I want it to take all the possible place

div.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f3f3f3;
  display: flex;
  }

  div.left-part, div.right-part {
    flex: 0;
    display:inline-block;
    white-space: nowrap;
  }

  div.center-part {
    flex: 1;
    text-align: center;
  }

  div.nav-button {
  display:inline-block;
  }

  div.nav-button a {
  display: block;
  color: #666;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  }

  div.nav-button a:hover:not(.active) {
  background-color: #ddd;
  }

  div.nav-button a.active {
  color: white;
  background-color: #3744a2;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <div class="left-part"><div class="nav-button">home</div>
    <div class="nav-button">news</div>
    <div class="nav-button">services</div>
    <div class="nav-button">prices</div>
    <div class="nav-button">contat</div>
  </div>
  <div class="center-part">
    <div class="nav-button"><img src="../image/image.png"></div>
  </div>
  <div class="right-part">
    <div class="nav-button"><i class="fa fa-envelope" aria-hidden="true"></i>  enter@email.here</div>
    <div class="nav-button"><i class="fa fa-phone" aria-hidden="true"></i>  123 123 123</div>
  </div>
</div></code>```

Title: Center image in ul

Body:
Tried to google this but didn't find anything that helped me.
So I have button-text on the left and right but I want to center an image inside the top bar.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #f3f3f3;
    }

    li {
    float: left;
    }

    li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }

    li a:hover:not(.active) {
    background-color: #ddd;
    }

    li a.active {
    color: white;
    background-color: #3744a2;
    }

home

news

services

prices

contat

  enter@email.here

  123 123 123

so what I basicly want is the image (class="image") to be centered, but the rest as it is.

Thanks alot!

Body:
I used display:flex and flex property. by setting display: flex:0 I'm telling the browser I want this element take just the place he need, and with flex:1 on a single element I'm telling that I want it to take all the possible place

div.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f3f3f3;
  display: flex;
  }

  div.left-part, div.right-part {
    flex: 0;
    display:inline-block;
    white-space: nowrap;
  }

  div.center-part {
    flex: 1;
    text-align: center;
  }

  div.nav-button {
  display:inline-block;
  }

  div.nav-button a {
  display: block;
  color: #666;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  }

  div.nav-button a:hover:not(.active) {
  background-color: #ddd;
  }

  div.nav-button a.active {
  color: white;
  background-color: #3744a2;
  }

<div class="nav">
  <div class="left-part"><div class="nav-button"><a href="../index.html">home</a></div>
    <div class="nav-button"><a href="../news/news.html">news</a></div>
    <div class="nav-button"><a href="../services/services.html">services</a></div>
    <div class="nav-button"><a class="active" href="#">prices</a></div>
    <div class="nav-button"><a href="../contat/contat.html">contat</a></div>
  </div>
  <div class="center-part">
    <div class="nav-button"><a class="image" href="#"><img src="../image/image.png"></a></div>
  </div>
  <div class="right-part">
    <div class="nav-button"><a href="mailto:enter@email.here"><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp; enter@email.here</a></div>
    <div class="nav-button"><a href="#"><i class="fa fa-phone" aria-hidden="true"></i>&nbsp; 123 123 123</a></div>
  </div>
</div>


问:
Python - comparison between 2 apps with a very similar codebase - 'TypeError: change_name() takes exactly 2 arguments (1 given)' only in one
The starting point of the discussion is the answer to my question here.

The subject was "How to call the Android keyboard from a Kivy application"

The answer provided me with works perfectly if alone, but I have tried to reuse the code provided me with into a more complex app and it is not working.

In details: the app is running but when i click on the Button that has to run the function change_name I receive the following error TypeError: change_name() takes exactly 2 arguments (1 given)

This is the Button

```<code>Button:
    text: "Me"
    font_size: '20sp'
    pos_hint: {'x':.0, 'y':.3}
    size_hint: .4, .8
    on_release: root.change_name()
</code>```

This is the change_name function inside the related class LifeCounter

```<code>class LifeCounter(BoxLayout):

    def __init__(self, **kwargs):
        super(LifeCounter, self).__init__(**kwargs)
        self.hide_input = TextInput(size_hint=(None, None),
                                    size=(0, 0),
                                    multiline=False)
        self.hide_input_bind = None

    def change_name(self, instance):
        if self.hide_input_bind:
            self.hide_input.unbind_uid('text', self.hide_input_bind)
        self.hide_input.text = instance.text
        self.hide_input.focus = True
        self.hide_input_bind = self.hide_input.fbind('text', self._update_text, instance)

    def _update_text(self, button, instance, value):
        button.text = value
</code>```

Below the full traceback

```<code> Traceback (most recent call last):
   File "app.py", line 182, in <module>
     MtgLifeCounter().run()
   File "C:\Python27\lib\site-packages\kivy\app.py", line 828, in run
     runTouchApp()
   File "C:\Python27\lib\site-packages\kivy\base.py", line 504, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Python27\lib\site-packages\kivy\core\window\window_sdl2.py", line 663, in mainloop
     self._mainloop()
   File "C:\Python27\lib\site-packages\kivy\core\window\window_sdl2.py", line 405, in _mainloop
     EventLoop.idle()
   File "C:\Python27\lib\site-packages\kivy\base.py", line 342, in idle
     self.dispatch_input()
   File "C:\Python27\lib\site-packages\kivy\base.py", line 327, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Python27\lib\site-packages\kivy\base.py", line 293, in post_dispatch_input
     wid.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Python27\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
     self.dispatch('on_release')
   File "kivy\_event.pyx", line 714, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8146)
   File "kivy\_event.pyx", line 1225, in kivy._event.EventObservers.dispatch (kivy\_event.c:14035)
   File "kivy\_event.pyx", line 1109, in kivy._event.EventObservers._dispatch (kivy\_event.c:12816)
   File "C:\Python27\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "<string>", line 21, in <module>
 TypeError: change_name() takes exactly 2 arguments (1 given)
</code>```

Consider that I am new to programming, and some concepts are not totally clear to me and this case is an example: I have two apps with the same main class (only the name is different) but in one case is running and in the other no.

Could you please help me understanding what is the difference from the two apps and why I am receiving an error in the case below if the function change_name that I am calling with a Button is the same?

答:
In the first example you have

```<code>on_release: root.change_name(self)
</code>```

In the second example you have this instead:

```<code>on_release: root.change_name()
</code>```

You have to call change_name() with the required number of arguments. Presumably, you want to use root.change_name(self) there as well.

Body:
The starting point of the discussion is the answer to my question here.

The subject was "How to call the Android keyboard from a Kivy application"

The answer provided me with works perfectly if alone, but I have tried to reuse the code provided me with into a more complex app and it is not working.

In details: the app is running but when i click on the Button that has to run the function change_name I receive the following error TypeError: change_name() takes exactly 2 arguments (1 given)

This is the Button

Button:
    text: "Me"
    font_size: '20sp'
    pos_hint: {'x':.0, 'y':.3}
    size_hint: .4, .8
    on_release: root.change_name()

This is the change_name function inside the related class LifeCounter

class LifeCounter(BoxLayout):

    def __init__(self, **kwargs):
        super(LifeCounter, self).__init__(**kwargs)
        self.hide_input = TextInput(size_hint=(None, None),
                                    size=(0, 0),
                                    multiline=False)
        self.hide_input_bind = None

    def change_name(self, instance):
        if self.hide_input_bind:
            self.hide_input.unbind_uid('text', self.hide_input_bind)
        self.hide_input.text = instance.text
        self.hide_input.focus = True
        self.hide_input_bind = self.hide_input.fbind('text', self._update_text, instance)

    def _update_text(self, button, instance, value):
        button.text = value

Below the full traceback

 Traceback (most recent call last):
   File "app.py", line 182, in <module>
     MtgLifeCounter().run()
   File "C:\Python27\lib\site-packages\kivy\app.py", line 828, in run
     runTouchApp()
   File "C:\Python27\lib\site-packages\kivy\base.py", line 504, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Python27\lib\site-packages\kivy\core\window\window_sdl2.py", line 663, in mainloop
     self._mainloop()
   File "C:\Python27\lib\site-packages\kivy\core\window\window_sdl2.py", line 405, in _mainloop
     EventLoop.idle()
   File "C:\Python27\lib\site-packages\kivy\base.py", line 342, in idle
     self.dispatch_input()
   File "C:\Python27\lib\site-packages\kivy\base.py", line 327, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Python27\lib\site-packages\kivy\base.py", line 293, in post_dispatch_input
     wid.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Python27\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
     self.dispatch('on_release')
   File "kivy\_event.pyx", line 714, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8146)
   File "kivy\_event.pyx", line 1225, in kivy._event.EventObservers.dispatch (kivy\_event.c:14035)
   File "kivy\_event.pyx", line 1109, in kivy._event.EventObservers._dispatch (kivy\_event.c:12816)
   File "C:\Python27\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "<string>", line 21, in <module>
 TypeError: change_name() takes exactly 2 arguments (1 given)

Consider that I am new to programming, and some concepts are not totally clear to me and this case is an example: I have two apps with the same main class (only the name is different) but in one case is running and in the other no.

Could you please help me understanding what is the difference from the two apps and why I am receiving an error in the case below if the function change_name that I am calling with a Button is the same?

Body:
In the first example you have

on_release: root.change_name(self)

In the second example you have this instead:

on_release: root.change_name()

You have to call change_name() with the required number of arguments. Presumably, you want to use root.change_name(self) there as well.


问:
Command prompt won't change directory to another drive
I'm trying to compile some java (learning java currently), and to do so I need to change command-prompt's directory.

```<code>C:\...\Admin> cd D:\Docs\Java
C:\...\Admin> cd
C:\...\Admin
</code>```

It doesn't change the directory. I try again using quotes:

```<code>C:\...\Admin> cd "D:\Docs\Java"
C:\...\Admin>
</code>```

Again it doesn't change the directory. What am I doing wrong?

答:
The short answer

The correct way to go from C:\...\Adminto D:\Docs\Java drive, is the following command :

```<code>cd /d d:\Docs\Java
</code>```

More details

If you're somewhere random on your D:\ drive, and you want to go to the root of your drive, you can use this command :

```<code>cd d:\
</code>```

If you're somewhere random on your D:\ drive, and you want to go to a specific folder on your drive, you can use this command :

```<code>cd d:\Docs\Java
</code>```

If you're on a different drive, and you want to go to the root of your D:\ drive, you can use this command :

```<code>cd /d d:\
</code>```

If you're on a different drive, and you want to go to a specific folder on your D: drive, you can use this command :

```<code>cd /d d:\Docs\Java
</code>```

If you're on a different drive, and you want to go to the last open folder of you D: drive, you can use this command :

```<code>cd /d d:
</code>```

As a shorthand for cd /d d:, you can also use this command :

```<code>d:
</code>```

Body:
I'm trying to compile some java (learning java currently), and to do so I need to change command-prompt's directory.

C:\...\Admin> cd D:\Docs\Java
C:\...\Admin> cd
C:\...\Admin

It doesn't change the directory. I try again using quotes:

C:\...\Admin> cd "D:\Docs\Java"
C:\...\Admin>

Again it doesn't change the directory. What am I doing wrong?

Body:
The short answer

The correct way to go from C:\...\Adminto D:\Docs\Java drive, is the following command :

cd /d d:\Docs\Java

More details

If you're somewhere random on your D:\ drive, and you want to go to the root of your drive, you can use this command :

cd d:\

If you're somewhere random on your D:\ drive, and you want to go to a specific folder on your drive, you can use this command :

cd d:\Docs\Java

If you're on a different drive, and you want to go to the root of your D:\ drive, you can use this command :

cd /d d:\

If you're on a different drive, and you want to go to a specific folder on your D: drive, you can use this command :

cd /d d:\Docs\Java

If you're on a different drive, and you want to go to the last open folder of you D: drive, you can use this command :

cd /d d:

As a shorthand for cd /d d:, you can also use this command :

d:


问:
VBA RegEx Continuous Matching
I am trying to get a RegEx to identify when multiple names appear in succession inside a string. The names all have the same pattern of [0-9]{1,2}-[A-Z]\.[A-Z][a-z]*. So, for example using the test string of: '22-A.Albert missing. Added 1-D.Barnes with 50FTE. 1-D.Barnes 99-W.Grogan is created new.' I want to match '1-D.Barnes 99-W.Grogan'... so here's what I tried:

```<code>Dim regEx As VBScript_RegExp_55.RegExp
Dim matches As VBScript_RegExp_55.MatchCollection
Set regEx = New VBScript_RegExp_55.RegExp
With regEx
    .Global = True
    .IgnoreCase = False
    .MultiLine = True
    .pattern = "\G[0-9]{1,2}-[A-Z]\.[A-Z][a-z]*"
End With
Set matches = regEx.Execute(exampleStr)
</code>```

But the matches count always come back = 0... I tried multiple iterations of adding spaces before and after the name pattern string, I tried multiple iterations of various noncapturing groups... Nothing.

Then I decided to try Microsoft's own example on how to use the continuous matching anchor '\G'... on their own support website they say the pattern '\G(\d)' should match "(1)", "(3)", "(5)" in "(1)(3)(5)7"...
However when I set that example up as simply as possible:

```<code>Dim regEx As VBScript_RegExp_55.RegExp
Dim matches As VBScript_RegExp_55.MatchCollection
Set regEx = New VBScript_RegExp_55.RegExp
With regEx
    .Global = True
    .IgnoreCase = False
    .MultiLine = True
    .pattern = "\G\(\d\)"
End With
Set matches = regEx.Execute("(1)(3)(5)[7](9)")
</code>```

I STILL GET NOTHING! I can't even get MSDN's own example to work for me.

答:
You are usin VBScript_RegExp_55.RegExp, not the NET regex engine. It does not support \G anchor as VBA regex engine is ECMA-5 standard compliant.

To only match 2 or more names separated with whitespace, use

```<code>\d{1,2}-[A-Z]\.[A-Z][a-z]*(?:\s+\d{1,2}-[A-Z]\.[A-Z][a-z]*)+
</code>```

Basically, it is <SINGLE_NAME_PATTERN>(?:\s+<SINGLE_NAME_PATTERN>)+, where (?:...) is a non-capturing group that is used to group subpatterns, \s+ (one or more whitespaces) and the name subpattern, and the whole group is matched 1 or more times (thanks to the + quantifier at the end).

See the regex demo. Perhaps, it is also a good idea to add word boundaries \b at the start and end of the regex pattern.

If you need to get them as separate entities, just split the match.

Title: VBA RegEx Continuous Matching

Body:
I am trying to get a RegEx to identify when multiple names appear in succession inside a string. The names all have the same pattern of [0-9]{1,2}-[A-Z]\.[A-Z][a-z]*. So, for example using the test string of: '22-A.Albert missing. Added 1-D.Barnes with 50FTE. 1-D.Barnes 99-W.Grogan is created new.' I want to match '1-D.Barnes 99-W.Grogan'... so here's what I tried:

Dim regEx As VBScript_RegExp_55.RegExp
Dim matches As VBScript_RegExp_55.MatchCollection
Set regEx = New VBScript_RegExp_55.RegExp
With regEx
    .Global = True
    .IgnoreCase = False
    .MultiLine = True
    .pattern = "\G[0-9]{1,2}-[A-Z]\.[A-Z][a-z]*"
End With
Set matches = regEx.Execute(exampleStr)

But the matches count always come back = 0... I tried multiple iterations of adding spaces before and after the name pattern string, I tried multiple iterations of various noncapturing groups... Nothing.

Then I decided to try Microsoft's own example on how to use the continuous matching anchor '\G'... on their own support website they say the pattern '\G(\d)' should match "(1)", "(3)", "(5)" in "(1)(3)(5)7"...
However when I set that example up as simply as possible:

Dim regEx As VBScript_RegExp_55.RegExp
Dim matches As VBScript_RegExp_55.MatchCollection
Set regEx = New VBScript_RegExp_55.RegExp
With regEx
    .Global = True
    .IgnoreCase = False
    .MultiLine = True
    .pattern = "\G\(\d\)"
End With
Set matches = regEx.Execute("(1)(3)(5)[7](9)")

I STILL GET NOTHING! I can't even get MSDN's own example to work for me.

Body:
You are usin VBScript_RegExp_55.RegExp, not the NET regex engine. It does not support \G anchor as VBA regex engine is ECMA-5 standard compliant.

To only match 2 or more names separated with whitespace, use

\d{1,2}-[A-Z]\.[A-Z][a-z]*(?:\s+\d{1,2}-[A-Z]\.[A-Z][a-z]*)+

Basically, it is <SINGLE_NAME_PATTERN>(?:\s+<SINGLE_NAME_PATTERN>)+, where (?:...) is a non-capturing group that is used to group subpatterns, \s+ (one or more whitespaces) and the name subpattern, and the whole group is matched 1 or more times (thanks to the + quantifier at the end).

See the regex demo. Perhaps, it is also a good idea to add word boundaries \b at the start and end of the regex pattern.

If you need to get them as separate entities, just split the match.


问:
How to use XmlNode.SelectSingleNode in different RSS format?
I am getting data from news website RSS. I got it from about 20 news websites. But, 1 website RSS  is diffrent. 20 RSS use same format but this website RSS is different. how can I search "entry" nodes in this diffrent RSS. I search this situation on the internet but I can not find the result I want. Can you help me ?

This is normal format of RSS

This is my code for normal format RSS

```<code>XmlDocument xdoc = new XmlDocument();

        xdoc.Load("http://www.milliyet.com.tr/rss/rssNew/gundemRss.xml");

        XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");

        if (el != null)
        {
            el.ParentNode.RemoveChild(el);
        }
        XmlNode Haberler = el.SelectSingleNode("channel");

        List<Milliyet> newMilliyet = new List<Milliyet>();

        foreach (XmlNode haber in Haberler.SelectNodes("item"))
        {
            var link = haber.SelectSingleNode("link").InnerText;

            if (MilliyetHaberList.ContainsKey(link))
                continue;
</code>```

This is diffrent format RSS

答:
Your error is wrong file format,this way not working because all RSS link not xml file,sometimes rss link return application/rss+xml content type.

for example:NTV

NTV rss link :http://www.ntv.com.tr/gundem.rss

if you use postman and get this link you will see content type:application/rss+xml

you should use HttpRequest like this

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.ntv.com.tr/gundem.rss");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        StreamReader stream = new StreamReader(response.GetResponseStream());

        string responseString = stream.ReadToEnd();

        string xmlString = responseString.Replace("xmlns=\"http://www.w3.org/2005/Atom\"", "");

        XmlDocument xdoc = new XmlDocument();

        xdoc.LoadXml(xmlString);

        var feedNode = xdoc.LastChild;

        XmlNodeList entries = feedNode.SelectNodes("entry");
        List<NTV> NTVNewsList = new List<NTV>();

        foreach (XmlNode entry in entries)
        {
            NTV NTVInstance = new NTV();
            foreach (XmlNode child in entry.ChildNodes)
            {
                string childName = child.Name;
                switch (childName)
                {
                    case "title":
                        NTVInstance.Title = child.InnerText;
                        break;
                    case "summary":
                        NTVInstance.Description = child.InnerText;
                        break;
                    case "published":
                        string dateStr = child.InnerText;
                        NTVInstance.PubDate = Convert.ToDateTime(dateStr);
                        break;
                    case "link":
                        NTVInstance.Link = child.Attributes["href"].Value;
                        NTVInstance.Tags = GetTags(NTVInstance.Link);

                        break;
                    default:
                        break;
                }

            }
</code>```

Body:
I am getting data from news website RSS. I got it from about 20 news websites. But, 1 website RSS  is diffrent. 20 RSS use same format but this website RSS is different. how can I search "entry" nodes in this diffrent RSS. I search this situation on the internet but I can not find the result I want. Can you help me ?

This is normal format of RSS

This is my code for normal format RSS

XmlDocument xdoc = new XmlDocument();

        xdoc.Load("http://www.milliyet.com.tr/rss/rssNew/gundemRss.xml");

        XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");

        if (el != null)
        {
            el.ParentNode.RemoveChild(el);
        }
        XmlNode Haberler = el.SelectSingleNode("channel");

        List<Milliyet> newMilliyet = new List<Milliyet>();

        foreach (XmlNode haber in Haberler.SelectNodes("item"))
        {
            var link = haber.SelectSingleNode("link").InnerText;

            if (MilliyetHaberList.ContainsKey(link))
                continue;

This is diffrent format RSS

Body:
Your error is wrong file format,this way not working because all RSS link not xml file,sometimes rss link return application/rss+xml content type.

for example:NTV

NTV rss link :http://www.ntv.com.tr/gundem.rss

if you use postman and get this link you will see content type:application/rss+xml

you should use HttpRequest like this

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.ntv.com.tr/gundem.rss");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        StreamReader stream = new StreamReader(response.GetResponseStream());

        string responseString = stream.ReadToEnd();

        string xmlString = responseString.Replace("xmlns=\"http://www.w3.org/2005/Atom\"", "");

        XmlDocument xdoc = new XmlDocument();

        xdoc.LoadXml(xmlString);

        var feedNode = xdoc.LastChild;

        XmlNodeList entries = feedNode.SelectNodes("entry");
        List<NTV> NTVNewsList = new List<NTV>();

        foreach (XmlNode entry in entries)
        {
            NTV NTVInstance = new NTV();
            foreach (XmlNode child in entry.ChildNodes)
            {
                string childName = child.Name;
                switch (childName)
                {
                    case "title":
                        NTVInstance.Title = child.InnerText;
                        break;
                    case "summary":
                        NTVInstance.Description = child.InnerText;
                        break;
                    case "published":
                        string dateStr = child.InnerText;
                        NTVInstance.PubDate = Convert.ToDateTime(dateStr);
                        break;
                    case "link":
                        NTVInstance.Link = child.Attributes["href"].Value;
                        NTVInstance.Tags = GetTags(NTVInstance.Link);

                        break;
                    default:
                        break;
                }

            }


问:
AppEngine: Step-by-Step Debugging
While working with AppEngine locally (i.e. using dev_appserver.py), is there anyway to do a step-by-step debugging? It is a too old fashion to use logging.info() or similar functions to show the values of all the variables in the code and decide where the error is.</p>

答:
If the local appengine process is a normal python process you have a couple of options:

In your code, place "code breakpoints": import pdb; pdb.set_trace(). Run dev_appserver.py as normal, and the python debugger will break when it reaches the line with the code.

Run dev_appserver.py in pdb. From the shell: $ python -m pdb dev_appserver.py. To set a breakpoint, use the command b filename.py:linenumber. Then use the c command to continue. See http://docs.python.org/library/pdb.html#debugger-commands

See the pdb module documentation.

Title: AppEngine: Step-by-Step Debugging


问:
How to plot vertical scatter using only matplotlib
I need to plot vertical scatters in matplotlib but I couldn't find anything in matplotlib.org/examples or StackOverflow.

I tried something of my own but I am missing Jitter. Jitter changes X component slightly for the points having same (or very similar) Y components so they won't overlap. Is there anything which I can use or will I have to change x components manually?

```<code>import numpy as np
from matplotlib import pyplot as plt

x = np.array([1,2,3])
l = ['A','B','C']
a = np.array([2,2,3])
b = np.array([3,3,4])
c = np.array([7,7,5])
d = (np.array(a) + np.array(b) + np.array(c)) / 3

plt.subplot(111)
plt.margins(0.2)
plt.xticks(x,l)
plt.plot(x, a, 'ro', label='a')
plt.plot(x, b, 'ro', label='b')
plt.plot(x, c, 'ro', label='c')
plt.plot(x, d, 'k_', markersize=15, label='avg')
plt.tight_layout()
plt.savefig('vertical_scatter')
plt.close()
</code>```

which gave me following

I found this on Seaborn.

which is what I want but only using matplotlib.

答:
Like I mentioned in my comment, you could shift the x-values according to the distance of neighboring y-points. Smaller distances should be mapped to a larger x-shift. This can be done with a logarithm or another function doing that.

```<code>import numpy as np
import matplotlib.pyplot as plt

n = 100
y = np.random.random(n)
x = np.ones(n)
x0 = x[0]

y = np.sort(y)
dist = np.diff(y)  # has one entry less than y
dist = np.hstack([dist, np.median(dist)])  # add random value to match shapes
x = np.log(dist)
x = (x - np.min(x)) / (np.max(x) - np.min(x))  # mapped to range from 0 to 1
x = x0 + 0.5*(x - 0.5)  # mapped to range from x0-1/4 to x0+1/4

plt.scatter(x,y)
plt.scatter(x+1,y)
plt.scatter(x+2,y)

plt.show()
</code>```

Body:
I need to plot vertical scatters in matplotlib but I couldn't find anything in matplotlib.org/examples or StackOverflow.

I tried something of my own but I am missing Jitter. Jitter changes X component slightly for the points having same (or very similar) Y components so they won't overlap. Is there anything which I can use or will I have to change x components manually?

import numpy as np
from matplotlib import pyplot as plt

x = np.array([1,2,3])
l = ['A','B','C']
a = np.array([2,2,3])
b = np.array([3,3,4])
c = np.array([7,7,5])
d = (np.array(a) + np.array(b) + np.array(c)) / 3

plt.subplot(111)
plt.margins(0.2)
plt.xticks(x,l)
plt.plot(x, a, 'ro', label='a')
plt.plot(x, b, 'ro', label='b')
plt.plot(x, c, 'ro', label='c')
plt.plot(x, d, 'k_', markersize=15, label='avg')
plt.tight_layout()
plt.savefig('vertical_scatter')
plt.close()

which gave me following

I found this on Seaborn.

which is what I want but only using matplotlib.

Body:
Like I mentioned in my comment, you could shift the x-values according to the distance of neighboring y-points. Smaller distances should be mapped to a larger x-shift. This can be done with a logarithm or another function doing that.

import numpy as np
import matplotlib.pyplot as plt

n = 100
y = np.random.random(n)
x = np.ones(n)
x0 = x[0]

y = np.sort(y)
dist = np.diff(y)  # has one entry less than y
dist = np.hstack([dist, np.median(dist)])  # add random value to match shapes
x = np.log(dist)
x = (x - np.min(x)) / (np.max(x) - np.min(x))  # mapped to range from 0 to 1
x = x0 + 0.5*(x - 0.5)  # mapped to range from x0-1/4 to x0+1/4

plt.scatter(x,y)
plt.scatter(x+1,y)
plt.scatter(x+2,y)

plt.show()