问:
Declaration and use of function in c
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

答:
There were quite a few errors in your original code, but a solution that compiles can be like this:

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, count=0;
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year(day, month, year);
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year){
    int i = 0, count = 0; // declaration was missing
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};

    if (year%4==0) a[2]++;

    count = day;
    for (i=0;i<month;i++)
        count+=a[i];

    return count;
}
</code>```

First of all you declare your day_of_year function at the beginning of your code, but when you implement it you use additional arguments which is forbidden.

You should declare countand i inside the body of the function so I moved them from the function's argument list.

Second, when you call day_of_year in main you pass nothing, although you have them read from console.

Other than that the logic to determine whether the input year is a leap year is not an ideal solution but I leave that up to you to correct.

Hope it helps.

Title: Declaration and use of function in c

Body:
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}

Body:
There were quite a few errors in your original code, but a solution that compiles can be like this:

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, count=0;
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year(day, month, year);
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year){
    int i = 0, count = 0; // declaration was missing
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};

    if (year%4==0) a[2]++;

    count = day;
    for (i=0;i<month;i++)
        count+=a[i];

    return count;
}

First of all you declare your day_of_year function at the beginning of your code, but when you implement it you use additional arguments which is forbidden.

You should declare countand i inside the body of the function so I moved them from the function's argument list.

Second, when you call day_of_year in main you pass nothing, although you have them read from console.

Other than that the logic to determine whether the input year is a leap year is not an ideal solution but I leave that up to you to correct.

Hope it helps.


来源: stackexchange

问:
asp.net Panel get elements with Javascript
i m trying to get all elements of a asp panel with a js.
i tried with

```<code>function t1()
{

    var v = document.getElementById('<%=pnlFiltri.ClientID %>').elements;
    alert(v.length)
}

 <asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
    <asp:TextBox runat="server" type="text" id="tb_Descr" name="Editbox1" value=""/>
 </asp:Panel>

 <asp:Button ID="Upload" runat="server" Text="Upload" OnClientClick="t1();return false;" OnClick="b1_Click"/>
</code>```

but not working...

答:
you have to get children count of the panel. Please see the following code </p>

```<code>function t1() {

        var v = document.getElementById('<%=pnlFiltri.ClientID %>');
        alert(v.children.length)
    }
 <asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
            <asp:TextBox runat="server" type="text" ID="tb_Descr" name="Editbox1" value="" />
            <asp:TextBox runat="server" type="text" ID="TextBox1" name="Editbox1" value="" />
        </asp:Panel>

        <asp:Button ID="Upload" runat="server" Text="Upload" OnClientClick="t1();return false;" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i m trying to get all elements of a asp panel with a js.
i tried with

function t1()
{

    var v = document.getElementById('<%=pnlFiltri.ClientID %>').elements;
    alert(v.length)
}

 <asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
    <asp:TextBox runat="server" type="text" id="tb_Descr" name="Editbox1" value=""/>
 </asp:Panel>

 <asp:Button ID="Upload" runat="server" Text="Upload" OnClientClick="t1();return false;" OnClick="b1_Click"/>

but not working...

Body:
you have to get children count of the panel. Please see the following code

function t1() {

        var v = document.getElementById('<%=pnlFiltri.ClientID %>');
        alert(v.children.length)
    }
 <asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
            <asp:TextBox runat="server" type="text" ID="tb_Descr" name="Editbox1" value="" />
            <asp:TextBox runat="server" type="text" ID="TextBox1" name="Editbox1" value="" />
        </asp:Panel>

        <asp:Button ID="Upload" runat="server" Text="Upload" OnClientClick="t1();return false;" />


问:
Save an entity and all its related entities in a single save in spring boot jpa
I'm using Spring Boot,REST and JPA to build my application.
In app, there are 4 entities with one to many relationship.

Is it possible to save multiple entities in one save operation?

Please help!

Parent.java

```<code>@Entity
@Data
@NoArgsConstructor
public class Parent implements Serializable {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;
    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildA> childA = new ArrayList<>();

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildB> childB = new ArrayList<>();

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildC> childC = new ArrayList<>();

    ... getter and setter ...

}
</code>```

ChildA.java

```<code>@Entity
@Data
@NoArgsConstructor
public class ChildA{
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "parentId")
    private Parent parent;

    private String name;

    public void setParent(Parent parent){
        this.parent = parent;
    }

    ... getter and setter ...
}
</code>```

ChildB.java and ChildC.java are similar to ChildA.java

Repository.java

```<code>@Repository
public interface repository extends JpaRepository<Parent, Long> {

}
</code>```

I want save this json.

```<code>{
  "name": "parent-name",
  "childA": [
    {
      "name": "parent-childA"
    }
  ],
  "childB": [
    {
      "name": "parent-childB"
    }
  ],
  "childC": [
    {
      "name": "parent-childC"
    }
  ]
}
</code>```

DB

```<code>Parent
id   |   name
5        parent-name

ChildA
id   |   parent-id  |  name
 1   |       5      |  parent-childA

ChildB
id   |   parent-id  |  name
 1   |       5      |  parent-childA

ChildC
id   |   parent-id  |  name
 1   |       5      |  parent-childA
</code>```

答:
I found the answer.
Thanks for the reply.

```<code>@RestController
public class ParentController {
    @Autowired
    private ParentRepository parentRepository;

    @PutMapping("")
    public void save(@RequestBody @Valid Parent parent) {
        parentRepository.save(parent);

    }
</code>```

Parent.java add @JsonManagedReference

```<code>@JsonManagedReference
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<ChildA> childA = new ArrayList<>();
</code>```

And Child class
ChildA.java, ChildB.java, ChildC.java add @JsonBackReference

```<code>@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "parentId")
private Parent parent;
</code>```

Body:
I'm using Spring Boot,REST and JPA to build my application.
In app, there are 4 entities with one to many relationship.

Is it possible to save multiple entities in one save operation?

Please help!

Parent.java

@Entity
@Data
@NoArgsConstructor
public class Parent implements Serializable {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;
    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildA> childA = new ArrayList<>();

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildB> childB = new ArrayList<>();

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildC> childC = new ArrayList<>();

    ... getter and setter ...

}

ChildA.java

@Entity
@Data
@NoArgsConstructor
public class ChildA{
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "parentId")
    private Parent parent;

    private String name;

    public void setParent(Parent parent){
        this.parent = parent;
    }

    ... getter and setter ...
}

ChildB.java and ChildC.java are similar to ChildA.java

Repository.java

@Repository
public interface repository extends JpaRepository<Parent, Long> {

}

I want save this json.

{
  "name": "parent-name",
  "childA": [
    {
      "name": "parent-childA"
    }
  ],
  "childB": [
    {
      "name": "parent-childB"
    }
  ],
  "childC": [
    {
      "name": "parent-childC"
    }
  ]
}

DB

Parent
id   |   name
5        parent-name

ChildA
id   |   parent-id  |  name
 1   |       5      |  parent-childA

ChildB
id   |   parent-id  |  name
 1   |       5      |  parent-childA

ChildC
id   |   parent-id  |  name
 1   |       5      |  parent-childA

Body:
I found the answer.
Thanks for the reply.

@RestController
public class ParentController {
    @Autowired
    private ParentRepository parentRepository;

    @PutMapping("")
    public void save(@RequestBody @Valid Parent parent) {
        parentRepository.save(parent);

    }

Parent.java add @JsonManagedReference

@JsonManagedReference
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<ChildA> childA = new ArrayList<>();

And Child class
ChildA.java, ChildB.java, ChildC.java add @JsonBackReference

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "parentId")
private Parent parent;


问:
TransactionScope causes TransactionManagerCommunicationException when used for DB unit tests
I'd like to run some tests of stored procedures in my database without actually affecting the data (or, to put it more exactly, without a lasting impact after the test has run).

After some research I came up with the approach of using TransactionScope within my Visual Studio 2010 test project such as

```<code>using( new TransactionScope())
{
    using( SqlConnection connection = new SqlConnection("someConnectionString"))
    {
        connection.Open();
        using( SqlCommand command = new SqlCommand( "some sql", connection ))
        {
            // Do some database stuff...
        }
     }
}
</code>```

Now this works fine as long as I put all of this within a single test method, i.e. all my changes to the database are automatically rolled back when the using block for TransactionScope is finished.

My problem is now that I'd like to do some database stuff in ClassInitialize so I only have to do it once per test class and not for every test method. When I create a public TransactionScope property and assign it an instance of TransactionScope in the ClassInitialize method, this works okay. As soon as I do any database related stuff in one of my test methods, I run into a TransactionManagerCommunicationException within that method.

I don't quite understand why that is the case, and I'd also like to know whether there is a mistake in my approach or how I can get it to work without having to set up the TransactionScope including all set up stuff for the tests within each test method again.

EDIT

Code excerpt below, I hope this gives enough information:

```<code>public TransactionScope Scope { get; set; }

[ClassInitialize]
public static void ClassInitialize( TestContext testContext )
{
    Scope = new TransactionScope();
    // Do some db set up stuff, e.g. create records used for tests etc.
}

[ClassCleanup]
public static void ClassCleanup()
{
    Scope.Dispose();
}

[TestMethod]
public void MyTestMethod()
{
    using( SqlConnection connection = new SqlConnection( "someConnectionString" ) )
    {
        DataTable result = new DataTable();
        using( SqlCommand command = new SqlCommand( "spName", connection ) )
        {
            command.CommandType = CommandType.StoredProcedure;
            using( SqlDataAdapter adapter = new SqlDataAdapter() )
            {
                adapter.SelecteCommand = command;
                // The next line causes the exception to be thrown
                adapter.Fill( result );
            }
        }

        // Assertions against DataTable result
    }
}
</code>```

The exception is

TransactionManagerCommunicationException was unhandled by user code
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I understand that I could try and change the settings, but I do not understand why I get the exception to begin with - what is different compared to having the code above in a single (test) method?

Thanks in advance and

best regards

G.

答:
One approach I have used with success is creating a base class that implements setup and teardown. Within the setup method you create a new transaction scope and store it in a private class variable. Within the teardown method you rollback the transaction scope.

I'm using NUNit, but the principle should be the same for MSTest. The clue here is that SetUp and TearDown executes once before and after each unit test to ensure isolation among unit tests.

Also, as @blech mentions, the Microsoft Distributed Transaction Coordinator (MSDTC) service must be running for this solution to work.

ContentLicense: CC BY-SA 2.5

Body:
I'd like to run some tests of stored procedures in my database without actually affecting the data (or, to put it more exactly, without a lasting impact after the test has run).

After some research I came up with the approach of using TransactionScope within my Visual Studio 2010 test project such as

using( new TransactionScope())
{
    using( SqlConnection connection = new SqlConnection("someConnectionString"))
    {
        connection.Open();
        using( SqlCommand command = new SqlCommand( "some sql", connection ))
        {
            // Do some database stuff...
        }
     }
}

Now this works fine as long as I put all of this within a single test method, i.e. all my changes to the database are automatically rolled back when the using block for TransactionScope is finished.

My problem is now that I'd like to do some database stuff in ClassInitialize so I only have to do it once per test class and not for every test method. When I create a public TransactionScope property and assign it an instance of TransactionScope in the ClassInitialize method, this works okay. As soon as I do any database related stuff in one of my test methods, I run into a TransactionManagerCommunicationException within that method.

I don't quite understand why that is the case, and I'd also like to know whether there is a mistake in my approach or how I can get it to work without having to set up the TransactionScope including all set up stuff for the tests within each test method again.

EDIT

Code excerpt below, I hope this gives enough information:

public TransactionScope Scope { get; set; }

[ClassInitialize]
public static void ClassInitialize( TestContext testContext )
{
    Scope = new TransactionScope();
    // Do some db set up stuff, e.g. create records used for tests etc.
}

[ClassCleanup]
public static void ClassCleanup()
{
    Scope.Dispose();
}

[TestMethod]
public void MyTestMethod()
{
    using( SqlConnection connection = new SqlConnection( "someConnectionString" ) )
    {
        DataTable result = new DataTable();
        using( SqlCommand command = new SqlCommand( "spName", connection ) )
        {
            command.CommandType = CommandType.StoredProcedure;
            using( SqlDataAdapter adapter = new SqlDataAdapter() )
            {
                adapter.SelecteCommand = command;
                // The next line causes the exception to be thrown
                adapter.Fill( result );
            }
        }

        // Assertions against DataTable result
    }
}

The exception is

TransactionManagerCommunicationException was unhandled by user code
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I understand that I could try and change the settings, but I do not understand why I get the exception to begin with - what is different compared to having the code above in a single (test) method?

Thanks in advance and

best regards

G.


问:
Sending credentials with cross-domain posts?
According to Requests with credentials, Firefox will only send credentials along with cross-domain posts if

invocation.withCredentials = "true";

is set… But it doesn't seem like jQuery's Ajax API provides any mechanism for this.

Is there something I've missed? Is there some other way I can do it?

答:
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

```<code>$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );
</code>```

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was
  unable to negotiate an acceptable set of security parameters.Error
  code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

Body:
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was
  unable to negotiate an acceptable set of security parameters.Error
  code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT


问:
Batch file to delete folder if it contains specific file
I'm trying to create batch file that will do the following:

It will scan through all subfolders in specific directory for
specific file.

If it finds file within subfolder, all contents of
this subfolder and subfolder itself will be deleted.

For example the file I'm looking for is "test.txt" and main folder is "C:\Test" with following structure:

```<code>\A
\B with test.txt
\C
\C\C0
\C\C1
\C\C2 with test.txt
\D
\D\D0
\D\D1 with test.txt
\D\D1\D10
\D\D1\D11
</code>```

Each folder has some other random files in it.

In this example script should delete following folders and all their contents:

```<code>C:\Test\B
C:\Test\C\C2
C:\Test\D\D1
</code>```

I tried several different scripts, but with no success. Batch file is placed directly in "C:\Test\"

First script I checked is:

```<code>for /R %%f in (test.txt) do @IF EXIST %%f @echo "%%f"
</code>```

It properly listed only path to folders with text.txt inside. Because it worked, I tried following one to delete only files for test:

```<code>for /R %%f in (test.txt) do @IF EXIST %%f del /q /s /f "*.*"
</code>```

It deleted all files in main folder and all subfolders where batch file is, along with batch file itself.

I tried to edit then several other scripts to match my conditions, but results were obvious. Last thing I was able to create is:

```<code>for /R %%p in (test.txt) do @IF EXIST %%p (rd "%%p" /s || del "*.*" /s/f)
</code>```

I ommited here "/q" parameter to be able to see what it wants to delete. It finds properly first "text.txt" file. If "y" is chosen to delete this file, script returns error that this is not proper folder. Then it starts to delete files from main folder and all subfolders with batch file being first victim (it asks each time if I want to delete files in specific subfolder). Subfolders are not deleted, only their contents.

I'm out of ideas.

答:
Maybe you're overthiking this a bit. If you are reading from a file, it is very simple to just do rmdir which will automatically delete the files and subfolders in the directory. your del *.* is does not have a path set and will delete from the working dir.

Keep in mind your test folder should not have quotes if you use quotes in the script. so should be:

c:\Whatever the folder\folder

c:\Whatever the folder\folder 2

This should work just fine.

```<code>for /F "eol=; tokens=*" %%p in (test.txt) do @if exist %%p (echo rd /S "%%p")
</code>```

remove the echo once you are happy that it will only delete what you want. using the /Q option will also help you to delete without confirming each time.

```<code>for /F "eol=; tokens=*" %%p in (test.txt) do @if exist %%p (rd /S /Q "%%p")
</code>```

Body:
I'm trying to create batch file that will do the following:

It will scan through all subfolders in specific directory for
specific file.

If it finds file within subfolder, all contents of
this subfolder and subfolder itself will be deleted.

For example the file I'm looking for is "test.txt" and main folder is "C:\Test" with following structure:

\A
\B with test.txt
\C
\C\C0
\C\C1
\C\C2 with test.txt
\D
\D\D0
\D\D1 with test.txt
\D\D1\D10
\D\D1\D11

Each folder has some other random files in it.

In this example script should delete following folders and all their contents:

C:\Test\B
C:\Test\C\C2
C:\Test\D\D1

I tried several different scripts, but with no success. Batch file is placed directly in "C:\Test\"

First script I checked is:

for /R %%f in (test.txt) do @IF EXIST %%f @echo "%%f"

It properly listed only path to folders with text.txt inside. Because it worked, I tried following one to delete only files for test:

for /R %%f in (test.txt) do @IF EXIST %%f del /q /s /f "*.*"

It deleted all files in main folder and all subfolders where batch file is, along with batch file itself.

I tried to edit then several other scripts to match my conditions, but results were obvious. Last thing I was able to create is:

for /R %%p in (test.txt) do @IF EXIST %%p (rd "%%p" /s || del "*.*" /s/f)

I ommited here "/q" parameter to be able to see what it wants to delete. It finds properly first "text.txt" file. If "y" is chosen to delete this file, script returns error that this is not proper folder. Then it starts to delete files from main folder and all subfolders with batch file being first victim (it asks each time if I want to delete files in specific subfolder). Subfolders are not deleted, only their contents.

I'm out of ideas.

Body:
Maybe you're overthiking this a bit. If you are reading from a file, it is very simple to just do rmdir which will automatically delete the files and subfolders in the directory. your del *.* is does not have a path set and will delete from the working dir.

Keep in mind your test folder should not have quotes if you use quotes in the script. so should be:

c:\Whatever the folder\folder

c:\Whatever the folder\folder 2

This should work just fine.

for /F "eol=; tokens=*" %%p in (test.txt) do @if exist %%p (echo rd /S "%%p")

remove the echo once you are happy that it will only delete what you want. using the /Q option will also help you to delete without confirming each time.

for /F "eol=; tokens=*" %%p in (test.txt) do @if exist %%p (rd /S /Q "%%p")


问:
Parsing CSV file on Java to extract String
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"```
</div>
</div>
</p>

<p>I can open the file on Java with this line.</p>

```String file = "C:\\file.csv";
```

<p>To verify if file exists I use this line.</p>

```if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}
```

<p>Now I want to parse the file to extract <b>AD1</b> and display true if exist or false if not exists. Ive declared <b>Scanner</b> for this, but i dont know how to setup for this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }

} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}</code>```

Here the search_field is a JTextField.

答:
You are not reading your file line by line. What you are actually supposed to do is get a line, split it, remove the double quotes and compare to your string. Or you can wrap your input string in a double quote and just compare with the string after splitting. For this try the following code:</p>

```<code>Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));

  String s1 = null;
  String id= null;
  String[] tempArr = null;
  String searchStr = "\""+search_field.getText()+"\"";
  System.out.print("searchStr = " + searchStr );

  while(scanner.hasNext()) { // While there are more lines in file
    s1= scanner.nextLine();
    tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
    id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
    System.out.print("ID = " + id);

    if(id != null && id.equals(searchStr)) {
      System.out.print("OKOK");
      break; // quit the loop searchStr is found
    } else {
    System.out.println("NOK");
    }
  }
} catch (FileNotFoundException fe) {
 fe.printStackTrace();
} finally {
  scanner.close();
}
</code>```

Body:
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"

I can open the file on Java with this line.

String file = "C:\\file.csv";

To verify if file exists I use this line.

if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}

Now I want to parse the file to extract AD1 and display true if exist or false if not exists. Ive declared Scanner for this, but i dont know how to setup for this.

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }

} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}

Here the search_field is a JTextField.

Body:
You are not reading your file line by line. What you are actually supposed to do is get a line, split it, remove the double quotes and compare to your string. Or you can wrap your input string in a double quote and just compare with the string after splitting. For this try the following code:

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));

  String s1 = null;
  String id= null;
  String[] tempArr = null;
  String searchStr = "\""+search_field.getText()+"\"";
  System.out.print("searchStr = " + searchStr );

  while(scanner.hasNext()) { // While there are more lines in file
    s1= scanner.nextLine();
    tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
    id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
    System.out.print("ID = " + id);

    if(id != null && id.equals(searchStr)) {
      System.out.print("OKOK");
      break; // quit the loop searchStr is found
    } else {
    System.out.println("NOK");
    }
  }
} catch (FileNotFoundException fe) {
 fe.printStackTrace();
} finally {
  scanner.close();
}


问:
How and Why AWS bill comes after i suspended the account
Could you please help me about the Billing system of AWS.

I suspended my aws account last month that time my account bill is $900 but today I got the message that your aws account bill is $1200 . How it is possible.

答:
Amazon does not have a "suspend" account. You can close an account. If you are using resources in AWS you will be charged for them.

If you feel that your bill is in error, contact Amazon Billing department. Go to this page and select "I'm an AWS customer and I'm looking for billing or account support". In my experience they are very easy to work with.

AWS Billing Support

[EDIT - credit to @James Thorpe's comment]

Why did I receive a bill after I closed my AWS account?


问:
Comparing keys in HashMap and Values
I have a HashMap as follows-

```<code>HashMap<String, Integer> BC = new HashMap<String, Integer>();
</code>```

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

```<code>"the/at" 153
"that/cs" 45
"Ann/np" 3
</code>```

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

```<code>"the/at" 153
"the/det" 80
</code>```

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

```<code>private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }
</code>```

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

答:
```<code>import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Point {

    public static void main(String[] args) {
        HashMap<String, Integer> BC = new HashMap<>();
        //some random values
        BC.put("the/at",5);
        BC.put("Ann/npe",6);
        BC.put("the/atx",7);
        BC.put("that/cs",8);
        BC.put("the/aty",9);
        BC.put("Ann/np",1);
        BC.put("Ann/npq",2);
        BC.put("the/atz",3);
        BC.put("Ann/npz",4);
        BC.put("the/atq",0);
        BC.put("the/atw",12);
        BC.put("that/cs",14);
        BC.put("that/cs1",16);
        BC.put("the/at1",18);
        BC.put("the/at2",100);
        BC.put("the/at3",123);
        BC.put("that/det",153);
        BC.put("xyx",123);
        BC.put("xyx/w",2);
        System.out.println("\nUnsorted Map......");
        printMap(BC);

        System.out.println("\nSorted Map......By Key");
        //sort original map using TreeMap, it will sort the Map by keys automatically.
        Map<String, Integer> sortedBC = new TreeMap<>(BC);
        printMap(sortedBC);
        //  find all distinct prefixes by spliting the keys at "/"
        List<String> uniquePrefixes = sortedBC.keySet().stream().map(i->i.split("/")[0]).distinct().collect(Collectors.toList());
        System.out.println("\nuniquePrefixes: "+uniquePrefixes);

        TreeMap<String,Integer> mapOfMaxValues = new TreeMap<>();
        // for each prefix from the list above filter the entries from the sorted map
        // having keys starting with this prefix
        //and sort them by value in descending order and get the first which will have the highst value
        uniquePrefixes.stream().forEach(i->{
                Entry <String,Integer> e =
                sortedBC.entrySet().stream().filter(j->j.getKey().startsWith(i))
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).findFirst().get();

                mapOfMaxValues.put(e.getKey(), e.getValue());
            });

        System.out.println("\nmapOfMaxValues...\n");
        printMap(mapOfMaxValues);
    }
    //pretty print a map
    public static <K, V> void printMap(Map<K, V> map) {
        map.entrySet().stream().forEach((entry) -> {
            System.out.println("Key : " + entry.getKey()
                    + " Value : " + entry.getValue());
        });
    }
}

// note: only tested with random values provided in the code
// behavior for large maps untested
</code>```

Title: Comparing keys in HashMap and Values

Body:
I have a HashMap as follows-

HashMap<String, Integer> BC = new HashMap<String, Integer>();

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

"the/at" 153
"that/cs" 45
"Ann/np" 3

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

"the/at" 153
"the/det" 80

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!


问:
How to test PayPal free trial subscriptions with IPN?
We are trying to implement Free trials with PayPal subscriptions.

Currently we don't offer any trials, so PayPal sends a transaction notification every month for a particular subscription and we renew the license (basically add 30 more days to it and wait for the next transaction info after 30 days).

Now we are trying to offer 7-day free trials. So my question is, will it work like monthly, without-trial, subscriptions? Will PayPal notify our IPN on the 8th for a monthly payment. If it does, then we add 30 days. Currently we just add 7 days and wait for the monthly payment notification (to keep it in sync with our current logic). We don't handle cancellation notifications, just to make it clear. If the the user cancels on, say, 18th day, he can enjoy the subscription till 30th days. But it won't renew since we won't receive a payment notification to add 30 more days.

I saw a similar question IPN Question, but that doesn't answer our specific problem.

答:
You can actually done that in Recurring Payment with Express Checkout where it describe and explained here.

First you can call SetExpressCheckout and setup as below parameter;

```<code>VERSION = 204.0
METHOD = SetExpressCheckout
RETURNURL = http://testingPP.com/index.php?action=ECreturn
CANCELURL = http://testingPP.com/index.php?action=ECcancel
AMT = 0.01
L_BILLINGTYPE0=RecurringPayments
L_BILLINGAGREEMENTDESCRIPTION0=FitnessMembership
</code>```

Secondly, after the buyer has agree and accept the term, you can then call CreateRecurringProfile API

```<code>VERSION = 204.0
METHOD = CreateRecurringPaymentsProfile
TOKEN = EC-4AE27806US9336331
SUBSCRIBERNAME = Global Test Tool
PROFILESTARTDATE = 2018-11-17T00:00:00Z
PROFILEREFERENCE = FitnessMembership
DESC = FitnessMembership
BILLINGPERIOD = Month
BILLINGFREQUENCY = 12
AMT = 10.01
TRIALBILLINGPERIOD = Week
TRIALBILLINGFREQUENCY = 1
TRIALTOTALBILLINGCYCLES = 1
TRIALAMT = 0.00
</code>```

As you can see, I set the TRIALBILLINGPERIOD to Week which is only happen once but the regular profile will be charged Monthly for every 12 months for 10.01.

Body:
You can actually done that in Recurring Payment with Express Checkout where it describe and explained here.

First you can call SetExpressCheckout and setup as below parameter;

VERSION = 204.0
METHOD = SetExpressCheckout
RETURNURL = http://testingPP.com/index.php?action=ECreturn
CANCELURL = http://testingPP.com/index.php?action=ECcancel
AMT = 0.01
L_BILLINGTYPE0=RecurringPayments
L_BILLINGAGREEMENTDESCRIPTION0=FitnessMembership

Secondly, after the buyer has agree and accept the term, you can then call CreateRecurringProfile API

VERSION = 204.0
METHOD = CreateRecurringPaymentsProfile
TOKEN = EC-4AE27806US9336331
SUBSCRIBERNAME = Global Test Tool
PROFILESTARTDATE = 2018-11-17T00:00:00Z
PROFILEREFERENCE = FitnessMembership
DESC = FitnessMembership
BILLINGPERIOD = Month
BILLINGFREQUENCY = 12
AMT = 10.01
TRIALBILLINGPERIOD = Week
TRIALBILLINGFREQUENCY = 1
TRIALTOTALBILLINGCYCLES = 1
TRIALAMT = 0.00

As you can see, I set the TRIALBILLINGPERIOD to Week which is only happen once but the regular profile will be charged Monthly for every 12 months for 10.01.


问:
Automatically pause a playing sound only on certain slides in a PowerPoint slide show
I have a PowerPoint 2013 slide show with automatically advancing slides and background music. Some of the slides are videos and I would like the music to pause at such slides and automatically resume after. I could only find out how to make the music stop after a certain number of slides, but could not find out anything about pause/resume. Is this possible to do through the menus, or only with VBA?

Thanks a lot.
Iliya

答:
You can view this Link for more answers to your question.

You should be able to do this without code. Power Point > Transitions Tab > Sounds: [Stop Previous Sound].


问:
Error while installing geckodriver in Protractor - npm install --save geckodriver
I have listed the current npm version installed in my system and the error which occurs when i try to install geckodriver.I read [npm module version] - [geckodriver version]
1.10.x - geckodriver 0.19.1 in geckodriver npm site.It looks i have the 1.10.1 version only installed.Still i face error while installation.Also ran webdriver-manager update which unzipps the v0.19.1.zip

Note: I have admin access to the drive.
C:\Users\crk>npm version

{ npm: '5.5.1',

ares: '1.10.1-DEV',

http_parser: '2.7.0',

icu: '57.1',

modules: '48',

node: '6.9.2',

openssl: '1.0.2j',

uv: '1.9.1',

v8: '5.1.281.88',

zlib: '1.2.8' }

W:\Wgn\JS_UIAutomation>npm install --save geckodriver

geckodriver@1.10.0 postinstall W:\Wgn\JS_UIAutomation\node_modules\geckodriver
  node index.js

Downloading geckodriver...
events.js:160
      throw er; // Unhandled 'error' event
      ^

RequestError: connect ETIMEDOUT 192.30.253.113:443
    at ClientRequest. (W:\Wgn\JS_UIAutomation\node_modules\got\index.js:69:21)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at emitErrorNT (net.js:1278:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
npm WARN Error: EPERM: operation not permitted, scandir 'W:\Wgn\JS_UIAutomation\node_modules\geckodriver\node_modules'
npm WARN     at Error (native)
npm WARN  { Error: EPERM: operation not permitted, scandir 'W:\Wgn\JS_UIAutomation\node_modules\geckodriver\node_modules'
npm WARN     at Error (native)
npm WARN   stack: 'Error: EPERM: operation not permitted, scandir

\'W:\Wgn\JS_UIAutomation\node_modules\geckodriver\node_modules\'\n    at Error (native)',
npm WARN   errno: -4048,
npm WARN   code: 'EPERM',
npm WARN   syscall: 'scandir',
npm WARN   path: 'W:\Wgn\JS_UIAutomation\node_modules\geckodriver\node_modules' }
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! geckodriver@1.10.0 postinstall: node index.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the geckodriver@1.10.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

答:
You don't have some permissions needed to do this on W: drive.

Try to run the terminal as Administrator and then rerun your command npm install --save geckodriver


问:
API/Library to replace signtool.exe
The Windows SDK ships with a tool called signtool.exe that lets you sign a file with a certificate. I need to do the same thing but in a background service so I'm on the lookout for a library (preferably managed code, but COM will do) to do the same thing. Any ideas?

Found the answer. Here's how to use an X.509 certificate to sign a file in .NET:

```<code>CmsSigner signer = new CmsSigner();
signer.Certificate = new X509Certificate2(certificate);

SignedCms content = new SignedCms(new ContentInfo(File.ReadAllBytes(fileToSign)));
content.ComputeSignature(signer, true);
byte[] signedFile = content.Encode();

string signedFileName = fileToSign + ".signed";
File.WriteAllBytes(signedFileName, signedFile);

Console.WriteLine("Signed file: " + signedFileName);
</code>```

Here, certificate is the path to the .pfx file containing the certificate and fileToSign is the file to sign.

答:
For the google-Travelers arriving here:

This MSDN forum thread says there is a CryptUIWizDigitalSign API in windows. It also points to a blog article by Alejandro Campos Magencio that shows a sample implementation in VB.NET.

Since a C# version seems to be missing I converted Alejandro's code to C#. Note that the following code only works with files (yet).

```<code>using System;
using System.Security.Cryptography.X509Certificates;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    /// <summary>
    /// Provides code signing functionality via Windows COM Cryptui.dll.
    /// </summary>
    class Signer
    {

        public const Int32 CRYPTUI_WIZ_NO_UI = 1;
        public const Int32 CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE = 1;
        public const Int32 CRYPTUI_WIZ_DIGITAL_SIGN_CERT = 1;

        public struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO
        {
            public Int32 dwSize;
            public Int32 dwSubjectChoice;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pwszFileName;
            public Int32 dwSigningCertChoice;
            public IntPtr pSigningCertContext;
            public string pwszTimestampURL;
            public Int32 dwAdditionalCertChoice;
            public IntPtr pSignExtInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT
        {
            public Int32 dwSize;
            public Int32 cbBlob;
            public IntPtr pbBlob;
        }

        [DllImport("Cryptui.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CryptUIWizDigitalSign(Int32 dwFlags, IntPtr hwndParent, string pwszWizardTitle, ref CRYPTUI_WIZ_DIGITAL_SIGN_INFO pDigitalSignInfo, ref IntPtr ppSignContext);

        [DllImport("Cryptui.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool CryptUIWizFreeDigitalSignContext(IntPtr pSignContext);

        /// <summary>
        /// Signs the executable at the given path with the given code signing certificate.
        /// </summary>
        /// <example>
        ///    string certPath = @"C:\certs\CodeSigningTestCert.pfx";
        ///    string exePath = @"C:\temp\ConsoleApp2ToBeSigned.exe";
        ///    string certPwd = "myGreatSecurePassword";
        ///
        ///    try
        ///    {
        ///        string resultingSignature = Signer.SignExecutable(certPath, exePath, certPwd);
        ///    }
        ///    catch (Win32Exception ex)
        ///    {
        ///        Console.WriteLine(ex.Message + ", Native error code: " + ex.NativeErrorCode.ToString());
        ///    }
        ///    catch (Exception ex)
        ///    {
        ///        // Any unexpected errors?
        ///        Console.WriteLine(ex.Message);
        ///    }
        ///
        /// </example>
        /// <param name="certPath">The absolute path to the PFX file to be used for signing the exe file.</param>
        /// <param name="exePath">The absolute path to the executable to be signed.</param>
        /// <param name="certPwd">The password for the PFX file.</param>
        public static string SignExecutable(string certPath, string exePath, string certPwd)
        {
            X509Certificate2 cert = default(X509Certificate2);

            CRYPTUI_WIZ_DIGITAL_SIGN_INFO digitalSignInfo = default(CRYPTUI_WIZ_DIGITAL_SIGN_INFO);
            CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT signContext = default(CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT);

            IntPtr pSignContext = default(IntPtr);
            IntPtr pSigningCertContext = default(IntPtr);

            // Get certificate context
            cert = new X509Certificate2(certPath, certPwd);
            pSigningCertContext = cert.Handle;

            // Prepare signing info: exe and cert
            digitalSignInfo = new CRYPTUI_WIZ_DIGITAL_SIGN_INFO();
            digitalSignInfo.dwSize = Marshal.SizeOf(digitalSignInfo);
            digitalSignInfo.dwSubjectChoice = CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE;
            digitalSignInfo.pwszFileName = exePath;
            digitalSignInfo.dwSigningCertChoice = CRYPTUI_WIZ_DIGITAL_SIGN_CERT;
            digitalSignInfo.pSigningCertContext = pSigningCertContext;
            digitalSignInfo.pwszTimestampURL = null;
            digitalSignInfo.dwAdditionalCertChoice = 0;
            digitalSignInfo.pSignExtInfo = IntPtr.Zero;

            // Sign exe
            if ((!CryptUIWizDigitalSign(CRYPTUI_WIZ_NO_UI, IntPtr.Zero, null, ref digitalSignInfo, ref pSignContext)))
                throw new Win32Exception(Marshal.GetLastWin32Error(), "CryptUIWizDigitalSign");

            // Get the blob with the signature
            signContext = (CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT)Marshal.PtrToStructure(pSignContext, typeof(CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT));
            byte[] blob = new byte[signContext.cbBlob + 1];
            Marshal.Copy(signContext.pbBlob, blob, 0, signContext.cbBlob);

            // Free blob memory
            if ((!CryptUIWizFreeDigitalSignContext(pSignContext)))
                throw new Win32Exception(Marshal.GetLastWin32Error(), "CryptUIWizFreeDigitalSignContext");

            return System.Text.Encoding.Default.GetString(blob);
        }
    }
}
</code>```

Hope it helps!

OwnerDisplayName: Arun

Title: API/Library to replace signtool.exe

Body:
The Windows SDK ships with a tool called signtool.exe that lets you sign a file with a certificate. I need to do the same thing but in a background service so I'm on the lookout for a library (preferably managed code, but COM will do) to do the same thing. Any ideas?

Found the answer. Here's how to use an X.509 certificate to sign a file in .NET:

CmsSigner signer = new CmsSigner();
signer.Certificate = new X509Certificate2(certificate);

SignedCms content = new SignedCms(new ContentInfo(File.ReadAllBytes(fileToSign)));
content.ComputeSignature(signer, true);
byte[] signedFile = content.Encode();

string signedFileName = fileToSign + ".signed";
File.WriteAllBytes(signedFileName, signedFile);

Console.WriteLine("Signed file: " + signedFileName);

Here, certificate is the path to the .pfx file containing the certificate and fileToSign is the file to sign.

LastEditorDisplayName: Arun

Body:
For the google-Travelers arriving here:

This MSDN forum thread says there is a CryptUIWizDigitalSign API in windows. It also points to a blog article by Alejandro Campos Magencio that shows a sample implementation in VB.NET.

Since a C# version seems to be missing I converted Alejandro's code to C#. Note that the following code only works with files (yet).

using System;
using System.Security.Cryptography.X509Certificates;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    /// <summary>
    /// Provides code signing functionality via Windows COM Cryptui.dll.
    /// </summary>
    class Signer
    {

        public const Int32 CRYPTUI_WIZ_NO_UI = 1;
        public const Int32 CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE = 1;
        public const Int32 CRYPTUI_WIZ_DIGITAL_SIGN_CERT = 1;

        public struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO
        {
            public Int32 dwSize;
            public Int32 dwSubjectChoice;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pwszFileName;
            public Int32 dwSigningCertChoice;
            public IntPtr pSigningCertContext;
            public string pwszTimestampURL;
            public Int32 dwAdditionalCertChoice;
            public IntPtr pSignExtInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT
        {
            public Int32 dwSize;
            public Int32 cbBlob;
            public IntPtr pbBlob;
        }

        [DllImport("Cryptui.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CryptUIWizDigitalSign(Int32 dwFlags, IntPtr hwndParent, string pwszWizardTitle, ref CRYPTUI_WIZ_DIGITAL_SIGN_INFO pDigitalSignInfo, ref IntPtr ppSignContext);

        [DllImport("Cryptui.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool CryptUIWizFreeDigitalSignContext(IntPtr pSignContext);

        /// <summary>
        /// Signs the executable at the given path with the given code signing certificate.
        /// </summary>
        /// <example>
        ///    string certPath = @"C:\certs\CodeSigningTestCert.pfx";
        ///    string exePath = @"C:\temp\ConsoleApp2ToBeSigned.exe";
        ///    string certPwd = "myGreatSecurePassword";
        ///
        ///    try
        ///    {
        ///        string resultingSignature = Signer.SignExecutable(certPath, exePath, certPwd);
        ///    }
        ///    catch (Win32Exception ex)
        ///    {
        ///        Console.WriteLine(ex.Message + ", Native error code: " + ex.NativeErrorCode.ToString());
        ///    }
        ///    catch (Exception ex)
        ///    {
        ///        // Any unexpected errors?
        ///        Console.WriteLine(ex.Message);
        ///    }
        ///
        /// </example>
        /// <param name="certPath">The absolute path to the PFX file to be used for signing the exe file.</param>
        /// <param name="exePath">The absolute path to the executable to be signed.</param>
        /// <param name="certPwd">The password for the PFX file.</param>
        public static string SignExecutable(string certPath, string exePath, string certPwd)
        {
            X509Certificate2 cert = default(X509Certificate2);

            CRYPTUI_WIZ_DIGITAL_SIGN_INFO digitalSignInfo = default(CRYPTUI_WIZ_DIGITAL_SIGN_INFO);
            CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT signContext = default(CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT);

            IntPtr pSignContext = default(IntPtr);
            IntPtr pSigningCertContext = default(IntPtr);

            // Get certificate context
            cert = new X509Certificate2(certPath, certPwd);
            pSigningCertContext = cert.Handle;

            // Prepare signing info: exe and cert
            digitalSignInfo = new CRYPTUI_WIZ_DIGITAL_SIGN_INFO();
            digitalSignInfo.dwSize = Marshal.SizeOf(digitalSignInfo);
            digitalSignInfo.dwSubjectChoice = CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE;
            digitalSignInfo.pwszFileName = exePath;
            digitalSignInfo.dwSigningCertChoice = CRYPTUI_WIZ_DIGITAL_SIGN_CERT;
            digitalSignInfo.pSigningCertContext = pSigningCertContext;
            digitalSignInfo.pwszTimestampURL = null;
            digitalSignInfo.dwAdditionalCertChoice = 0;
            digitalSignInfo.pSignExtInfo = IntPtr.Zero;

            // Sign exe
            if ((!CryptUIWizDigitalSign(CRYPTUI_WIZ_NO_UI, IntPtr.Zero, null, ref digitalSignInfo, ref pSignContext)))
                throw new Win32Exception(Marshal.GetLastWin32Error(), "CryptUIWizDigitalSign");

            // Get the blob with the signature
            signContext = (CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT)Marshal.PtrToStructure(pSignContext, typeof(CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT));
            byte[] blob = new byte[signContext.cbBlob + 1];
            Marshal.Copy(signContext.pbBlob, blob, 0, signContext.cbBlob);

            // Free blob memory
            if ((!CryptUIWizFreeDigitalSignContext(pSignContext)))
                throw new Win32Exception(Marshal.GetLastWin32Error(), "CryptUIWizFreeDigitalSignContext");

            return System.Text.Encoding.Default.GetString(blob);
        }
    }
}

Hope it helps!


问:
PrimeNG confirm dialog ignoring some properties like closeable or closeOnEscape
So here I have simple confirm dialog

```<code>                            <p-confirmDialog header="Confirmation" icon="fa fa-question-circle" width="425" closeable="false" closeOnEscape="false" #cd>
                                <p-footer>
                                    <button type="button" pButton icon="fa-close" label="No" (click)="cd.reject()"></button>
                                    <button type="button" pButton icon="fa-check" label="Yes" (click)="cd.accept()"></button>
                                </p-footer>
                            </p-confirmDialog>
</code>```

however, for unknown to me reasons, dialog renders close button and closes on pressing esc key. Why closeable and closeOnEscape properties ignored? Only width and hight properties works for me.

答: Replace closeable="false" closeOnEscape="false" with [closeable]="false" [closeOnEscape]="false"

Body:
So here I have simple confirm dialog

                                    <button type="button" pButton icon="fa-close" label="No" (click)="cd.reject()"></button>
                                    <button type="button" pButton icon="fa-check" label="Yes" (click)="cd.accept()"></button>

however, for unknown to me reasons, dialog renders close button and closes on pressing esc key. Why closeable and closeOnEscape properties ignored? Only width and hight properties works for me.

ContentLicense: CC BY-SA 4.0


问:
Recursive binary tree search isn't returning True when the node has been found
myTree is a list of lists in python that represents a binary tree. For each list within the list, element 0 represents the pointer to the left child, element 1 represents the value of the node, and element 2 represents the pointer to the right child.

```<code>myTree = [[1,50,2],[3,27,4],[9,62,10],[5,12,6],[7,35,8],[-1,9,-1],[-1,14,-1],[-1,28,-1],[-1,41,-1],[11,59,12],[13,71,-1],[-1,52,-1],[-1,60,-1],[-1,68,-1]]

def findNode(item,comparingNode):
    #print (comparingNode)
    comparingNode = myTree[comparingNode]
    if item == comparingNode[1]:
        print(comparingNode[1])
        return True #This is where it is supposed to return True

    elif item > comparingNode[1]:
        if comparingNode[2] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp1")
            return findNode(item,comparingNode[2])
        else:
            return False

    else:
        if comparingNode[0] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
            findNode(item,comparingNode[0])
        else:
            return False

    #print(comparingNode[1])

if findNode(9,0) == True:
    print("found")
</code>```

When run, It doesn't produce an error message, and the program completes. The search has clearly found node 9 because, when run, it prints out 9 at the end. However, The function doesn't return True even though the debugger says it's visited the source line (line 9).

答:
You forgot a return in the else path. This works:</p>

```<code>def findNode(item,comparingNode):
    #print (comparingNode)
    comparingNode = myTree[comparingNode]
    if item == comparingNode[1]:
        print(comparingNode[1])
        return True #This is where it is supposed to return True

    elif item > comparingNode[1]:
        if comparingNode[2] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp1")
            return findNode(item,comparingNode[2])
        else:
            return False

    else:
        if comparingNode[0] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
            return findNode(item,comparingNode[0])
        else:
            return False
</code>```

Body:
myTree is a list of lists in python that represents a binary tree. For each list within the list, element 0 represents the pointer to the left child, element 1 represents the value of the node, and element 2 represents the pointer to the right child.

myTree = [[1,50,2],[3,27,4],[9,62,10],[5,12,6],[7,35,8],[-1,9,-1],[-1,14,-1],[-1,28,-1],[-1,41,-1],[11,59,12],[13,71,-1],[-1,52,-1],[-1,60,-1],[-1,68,-1]]

def findNode(item,comparingNode):
    #print (comparingNode)
    comparingNode = myTree[comparingNode]
    if item == comparingNode[1]:
        print(comparingNode[1])
        return True #This is where it is supposed to return True

    elif item > comparingNode[1]:
        if comparingNode[2] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp1")
            return findNode(item,comparingNode[2])
        else:
            return False

    else:
        if comparingNode[0] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
            findNode(item,comparingNode[0])
        else:
            return False

    #print(comparingNode[1])

if findNode(9,0) == True:
    print("found")

When run, It doesn't produce an error message, and the program completes. The search has clearly found node 9 because, when run, it prints out 9 at the end. However, The function doesn't return True even though the debugger says it's visited the source line (line 9).

Body:
You forgot a return in the else path. This works:

def findNode(item,comparingNode):
    #print (comparingNode)
    comparingNode = myTree[comparingNode]
    if item == comparingNode[1]:
        print(comparingNode[1])
        return True #This is where it is supposed to return True

    elif item > comparingNode[1]:
        if comparingNode[2] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp1")
            return findNode(item,comparingNode[2])
        else:
            return False

    else:
        if comparingNode[0] != -1:
            print(comparingNode[0],comparingNode[1],comparingNode[2],"comp2")
            return findNode(item,comparingNode[0])
        else:
            return False


问:
What is the best practice : to publish data to azure iothub or directly to azure tablestorage
I have an web app.  The current structure\flow is as below.

This has a webservice which is used by the Device module to place the device-specific-data into my Table STorage.

At the UI end SignalR is employed to display on Dashboard(view-cshtml) the latest value posted to the cloud as and when the data from the device gets into the TableStorage.

Data from different devices are expected to get into TableStorage and at the UI end, as per the device selected, the related data are diplayed.

My Query

Instead of directly publishing to  TableStorage, Will there be any benefit to have the Azure resource, IOTHub, to which the devices can be publishing its data?  If so please let me know on it.

-->  a. In this case where should the data that's placed on IoTHub be taken to, for storing all received data for future reference?

--->  b. I have earlier used an option of using StreamAnalytics , used a query to insert data receiving at IoTHub end to TableStorage.
Is is the only\good option available?

---> c. Or do we have any other options to hold the data published to IoTHub?

Is the current flow of inserting the data directly to TableStorage from the device OK(best practice?)? If not please suggest the best way of approaching the solution.

答:
The messages of device-to-cloud are routed to the built-in service-facing endpoint (messages/events) that is compatible with Event Hubs.This messages are retained by IoT Hub. The default is one day, but it can be increased to seven days.You can modify the retention time, either programmatically through the IoT Hub resource provider REST APIs, or by using the Azure portal.So you need not to publish the data to Table Storage directly, IoT Hub can store the data as cache.

Azure Storage consists of three data services: Blob storage, File storage, and Queue storage. Blob storage supports both standard and premium storage, with premium storage using only SSDs for the fastest performance possible. Another feature is cool storage, allowing you to store large amounts of rarely accessed data for a lower cost.


问:
Run docker run command in python script
I need to run following command inside python script to remove all exisiting docker services

```<code>import subprocess
bashCommand = "docker service rm $(docker service ls)"
process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE,  shell=True)
</code>```

This is not giving desired results. Services still exists after running this file.
I am using centos

答:
Have you tried you use subprocess.call instead?

For example,

```<code>import subprocess
subprocess.call("docker rmi $(docker ps -a -q)", shell=True)
</code>```

it works for rmi command.

Title: Run docker run command in python script

Body:
I need to run following command inside python script to remove all exisiting docker services

import subprocess
bashCommand = "docker service rm $(docker service ls)"
process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE,  shell=True)

This is not giving desired results. Services still exists after running this file.
I am using centos

Body:
Have you tried you use subprocess.call instead?

For example,

import subprocess
subprocess.call("docker rmi $(docker ps -a -q)", shell=True)

it works for rmi command.


问:
CSS Computed width different from specified
As shown in this bin the width specified for the preview button is 120 px while the rendered width is always 132 px (on different screens).

.btn-grey{
    cursor: pointer;
    background: #f1f3f6;
    border: 1px solid #d7d9e1;
    box-shadow: 1px 1px 1px #fff inset;
    border-radius: 3px;
    color: #838AAB;
    display: inline-block;
    height: 30px;
    padding: 0 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
            <div style="display: flex; width: 60%; justify-content: center;">
                <input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
                <input name="load" class="btn-grey" type="submit" value="Load " style="width: 120px; height: 35px;max-width: 120px; max-height: 35px;margin : 5px 5px 5px 5px "/>
            </div>

</body>
</html></code>```

答:
Just add box-sizing: border-box; in your button style

This will make sure that width and height properties (and min/max properties) includes content, padding and border, but not the margin.

For more information about box-sizing check the following link
https://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Body:
As shown in this bin the width specified for the preview button is 120 px while the rendered width is always 132 px (on different screens).

.btn-grey{
    cursor: pointer;
    background: #f1f3f6;
    border: 1px solid #d7d9e1;
    box-shadow: 1px 1px 1px #fff inset;
    border-radius: 3px;
    color: #838AAB;
    display: inline-block;
    height: 30px;
    padding: 0 5px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

                <input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
                <input name="load" class="btn-grey" type="submit" value="Load " style="width: 120px; height: 35px;max-width: 120px; max-height: 35px;margin : 5px 5px 5px 5px "/>


问:
Cumulocity Maven repository error loading dependencies
I’m currently trying to develop new drivers for some Tinkerforge sensors which aren’t supported yet by Cumulocity. I’ve cloned the project https://bitbucket.org/m2m/cumulocity-examples and added a new Driver to the tinkerforge-driver project https://bitbucket.org/m2m/cumulocity-examples/src/c2b5da5b234510085804dcc947f682941ccbed20/java-agent/tinkerforge-driver/?at=default. When I try to build the project to create the jar I’m running into issues related to Maven dependencies:

```<code>[ERROR] Failed to execute goal on project tinkerforge-driver: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
</code>```

When running the build with the parameter –X, I see the following exceptions in the log:

```<code>[ERROR] Failed to execute goal on project tinkerforge-driver: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project tinkerforge-driver: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:221)
       at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies(LifecycleDependencyResolver.java:127)
       at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved(MojoExecutor.java:245)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:199)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
       at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
       at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
       at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
       at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
       at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
       at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
       at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
       at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
       at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
       at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
       at java.lang.reflect.Method.invoke(Unknown Source)
       at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
       at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
       at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
       at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:211)
       at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:195)
       ... 23 more
Caused by: org.eclipse.aether.resolution.DependencyResolutionException: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:384)
       at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:205)
       ... 24 more
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:444)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
       at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:367)
       ... 25 more
Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at io.takari.aether.connector.AetherRepositoryConnector$2.wrap(AetherRepositoryConnector.java:893)
       at io.takari.aether.connector.AetherRepositoryConnector$2.wrap(AetherRepositoryConnector.java:1)
       at io.takari.aether.connector.AetherRepositoryConnector$GetTask.flush(AetherRepositoryConnector.java:673)
       at io.takari.aether.connector.AetherRepositoryConnector.get(AetherRepositoryConnector.java:310)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
       ... 27 more
</code>```

When I try to access the repository directly via http://resources.cumulocity.com/maven/repository/ I get a 403 Forbidden error.

I’ve update the maven settings.xml as specified here: https://bitbucket.org/m2m/cumulocity-examples

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <localRepository>C:/dev/.m2</localRepository>
    <activeProfiles>
    <activeProfile>cumulocity</activeProfile>
  </activeProfiles>
    <profiles>
      <profile>
        <id>cumulocity</id>
      <repositories>
        <repository>
          <id>cumulocity-maven-repo</id>
          <url>http://resources.cumulocity.com/maven/repository</url>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>cumulocity-plugins-repo</id>
          <url>http://resources.cumulocity.com/maven/repository</url>
        </pluginRepository>
      </pluginRepositories>
    </profile>
    </profiles>

</settings>
</code>```

Do I need to provide credentials for the Cumulocity Maven repo?

答:
for the repository issue: this is not a "browsable" webpage. Cumulocity has a guide how to configure the URL in Maven settings.xml or pom.xml file.

E.g see: http://cumulocity.com/guides/java/hello-world-basic/.

Hope that helps.

Best Regards
Michael

Body:
I’m currently trying to develop new drivers for some Tinkerforge sensors which aren’t supported yet by Cumulocity. I’ve cloned the project https://bitbucket.org/m2m/cumulocity-examples and added a new Driver to the tinkerforge-driver project https://bitbucket.org/m2m/cumulocity-examples/src/c2b5da5b234510085804dcc947f682941ccbed20/java-agent/tinkerforge-driver/?at=default. When I try to build the project to create the jar I’m running into issues related to Maven dependencies:

[ERROR] Failed to execute goal on project tinkerforge-driver: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

When running the build with the parameter –X, I see the following exceptions in the log:

[ERROR] Failed to execute goal on project tinkerforge-driver: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project tinkerforge-driver: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:221)
       at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies(LifecycleDependencyResolver.java:127)
       at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved(MojoExecutor.java:245)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:199)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
       at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
       at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
       at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
       at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
       at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
       at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
       at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
       at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
       at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
       at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
       at java.lang.reflect.Method.invoke(Unknown Source)
       at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
       at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
       at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
       at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project c8y.example:tinkerforge-driver:jar:8.14.0: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:211)
       at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:195)
       ... 23 more
Caused by: org.eclipse.aether.resolution.DependencyResolutionException: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:384)
       at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:205)
       ... 24 more
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: The following artifacts could not be resolved: c8y.example:jv-driver:jar:8.14.0, c8y.example:jv-agent-assembly:tar.gz:tar:8.14.0: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:444)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
       at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:367)
       ... 25 more
Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact c8y.example:jv-driver:jar:8.14.0 in cumulocity-maven-repo (http://resources.cumulocity.com/maven/repository)
       at io.takari.aether.connector.AetherRepositoryConnector$2.wrap(AetherRepositoryConnector.java:893)
       at io.takari.aether.connector.AetherRepositoryConnector$2.wrap(AetherRepositoryConnector.java:1)
       at io.takari.aether.connector.AetherRepositoryConnector$GetTask.flush(AetherRepositoryConnector.java:673)
       at io.takari.aether.connector.AetherRepositoryConnector.get(AetherRepositoryConnector.java:310)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)
       at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
       ... 27 more

When I try to access the repository directly via http://resources.cumulocity.com/maven/repository/ I get a 403 Forbidden error.

I’ve update the maven settings.xml as specified here: https://bitbucket.org/m2m/cumulocity-examples

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <localRepository>C:/dev/.m2</localRepository>
    <activeProfiles>
    <activeProfile>cumulocity</activeProfile>
  </activeProfiles>
    <profiles>
      <profile>
        <id>cumulocity</id>
      <repositories>
        <repository>
          <id>cumulocity-maven-repo</id>
          <url>http://resources.cumulocity.com/maven/repository</url>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>cumulocity-plugins-repo</id>
          <url>http://resources.cumulocity.com/maven/repository</url>
        </pluginRepository>
      </pluginRepositories>
    </profile>
    </profiles>

</settings>

Do I need to provide credentials for the Cumulocity Maven repo?


问:
Declaration and use of function in c
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

答:
I put some comments.    </p>

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    // you don't need to declare 'i' here, or a[]
    int day, month, year,count;

    printf ("\nEnter the day: ");
    scanf ("%d", &day);
    printf ("\nEnter the month: ");
    scanf ("%d", &month);
    printf ("\nEnter the year: ");
    scanf ("%d", &year);

    // you need to pass the parameters to the function
    count=day_of_year(day,month,year);

    printf ("\nCount: %d", count);
    return 0;
}
// here you put in the function signature two more variables.
//they are not used and also they differ from the initial definition.
int day_of_year (int day, int month, int year){
    int count=0,i=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};

    if (year%4==0) a[1]++;
    count = day;

    for (i=0;i<month;i++)
        count+=a[i];

    return count;
}
</code>```

Title: Declaration and use of function in c

Body:
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}

Body:
I put some comments.

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    // you don't need to declare 'i' here, or a[]
    int day, month, year,count;

    printf ("\nEnter the day: ");
    scanf ("%d", &day);
    printf ("\nEnter the month: ");
    scanf ("%d", &month);
    printf ("\nEnter the year: ");
    scanf ("%d", &year);

    // you need to pass the parameters to the function
    count=day_of_year(day,month,year);

    printf ("\nCount: %d", count);
    return 0;
}
// here you put in the function signature two more variables.
//they are not used and also they differ from the initial definition.
int day_of_year (int day, int month, int year){
    int count=0,i=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};

    if (year%4==0) a[1]++;
    count = day;

    for (i=0;i<month;i++)
        count+=a[i];

    return count;
}


问:
How to change local time for testing purposes?
I'm writing a script, that is based on the current time and it works fine, but I don't want to wait, so I can see, if the script works tomorrow, in 2, 3, 4 days, or a year.

Is there a way to trick the apache server (using php preferred) into thinking that it's a different time? :-)

And if so, is it easy to fix back withnout any perpament consequences?

答:
I presume at some level inside your script you're using the time function to get the current time? (If you're not, you most likely should be.)

If so, simply replace the call to time with a call to mktime, set to the appropriate date/time in the future.

Worse case scenario (if you're not using a PHP script), could just simply change the current system date/time using the system "date" command ("man date" for the details) if you're on Unix/Linux use or the appropriate control panel/system setting, etc. if you're on Windows/Mac OS X, etc. However, I'd really not recommend doing this unless you're using a private test server.

Additionally, as I said in my comment, having to change the system clock is a poor solution - you really need to abstract the current time in whatever script you're using.


问:
jQuery callback syntax
I am learning jQuery, and am trying to understand how the callback works. I know what it does (calls some function after finishing with the first one), but it's the syntax that thrown me off a bit. I have this code:

```<code>showMenuElement( 0 ); // call to initiate the menu

function showMenuElement( x ) {
    x += 1; // cycling through elements
    if (x < 4) {
        var el = "#menu-" + x;
        $( el ).fadeIn( 1000, showMenuElement(x) ); // show one element, then show next in line
    }
}
</code>```

...and it doesn't work like I want it to, as it shows all the menu items at once!
(here's the working fiddle: fiddle 1)

However, if I add the function() {...} part, like this:

```<code>showMenuElement( 0 ); // call to initiate the menu

function showMenuElement( x ) {
    x += 1; // cycling through elements
    if (x < 4) {
        var el = "#menu-" + x;
        $( el ).fadeIn( 1000, function() { showMenuElement(x) } ); // show one element, then show next in line
    }
}
</code>```

then it works like a charm, showing one item after another (as per fiddle 2).

I am looking for the explanation for why it does behave this way?
I though, that since it's a callback, it will look for a name of a function to implement, so what does the writing function() {...} explicitly changes?

答:
In your first code snippet, in the fadeIn method you call your function showMenuElement, instead of doing this fadeIn need a callback reference, not a call of a callback, it's because your second snippet work, you give it a reference without calling it.

(pardon my bad english)

Title: jQuery callback syntax

Body:
I am learning jQuery, and am trying to understand how the callback works. I know what it does (calls some function after finishing with the first one), but it's the syntax that thrown me off a bit. I have this code:

showMenuElement( 0 ); // call to initiate the menu

function showMenuElement( x ) {
    x += 1; // cycling through elements
    if (x < 4) {
        var el = "#menu-" + x;
        $( el ).fadeIn( 1000, showMenuElement(x) ); // show one element, then show next in line
    }
}

...and it doesn't work like I want it to, as it shows all the menu items at once!
(here's the working fiddle: fiddle 1)

However, if I add the function() {...} part, like this:

showMenuElement( 0 ); // call to initiate the menu

function showMenuElement( x ) {
    x += 1; // cycling through elements
    if (x < 4) {
        var el = "#menu-" + x;
        $( el ).fadeIn( 1000, function() { showMenuElement(x) } ); // show one element, then show next in line
    }
}

then it works like a charm, showing one item after another (as per fiddle 2).

I am looking for the explanation for why it does behave this way?
I though, that since it's a callback, it will look for a name of a function to implement, so what does the writing function() {...} explicitly changes?


答:
As Willem suggested in a comment above, the line:

```<code>findNode(item,comparingNode[0])
</code>```

Should be modified to:

```<code>return findNode(item,comparingNode[0])
</code>```

The the output will be:

```<code>1 50 2 comp2
3 27 4 comp2
5 12 6 comp2
9
found
</code>```

Title: Recursive binary tree search isn't returning True when the node has been found

Body:
As Willem suggested in a comment above, the line:

findNode(item,comparingNode[0])

Should be modified to:

return findNode(item,comparingNode[0])

The the output will be:

1 50 2 comp2
3 27 4 comp2
5 12 6 comp2
9
found


问:
Convert xPath to JSoup query
Does anyone know of an xPath to JSoup convertor?  I get the following xPath from Chrome:

```<code> //*[@id="docs"]/div[1]/h4/a
</code>```

and would like to change it into a Jsoup query.  The path contains an href I'm trying to reference.

答:
You don't necessarily need to convert Xpath to JSoup specific selectors.

Instead you can use XSoup which is based on JSoup and supports Xpath.

https://github.com/code4craft/xsoup

Here is an example using XSoup from the docs.

```<code>@Test
public void testSelect() {

    String html = "<html><div><a href='https://github.com'>github.com</a></div>" +
            "<table><tr><td>a</td><td>b</td></tr></table></html>";

    Document document = Jsoup.parse(html);

    String result = Xsoup.compile("//a/@href").evaluate(document).get();
    Assert.assertEquals("https://github.com", result);

    List<String> list = Xsoup.compile("//tr/td/text()").evaluate(document).list();
    Assert.assertEquals("a", list.get(0));
    Assert.assertEquals("b", list.get(1));
}
</code>```

Title: Convert xPath to JSoup query

Body:
Does anyone know of an xPath to JSoup convertor?  I get the following xPath from Chrome:

 //*[@id="docs"]/div[1]/h4/a

and would like to change it into a Jsoup query.  The path contains an href I'm trying to reference.

Body:
You don't necessarily need to convert Xpath to JSoup specific selectors.

Instead you can use XSoup which is based on JSoup and supports Xpath.

https://github.com/code4craft/xsoup

Here is an example using XSoup from the docs.

@Test
public void testSelect() {

    String html = "<html><div><a href='https://github.com'>github.com</a></div>" +
            "<table><tr><td>a</td><td>b</td></tr></table></html>";

    Document document = Jsoup.parse(html);

    String result = Xsoup.compile("//a/@href").evaluate(document).get();
    Assert.assertEquals("https://github.com", result);

    List<String> list = Xsoup.compile("//tr/td/text()").evaluate(document).list();
    Assert.assertEquals("a", list.get(0));
    Assert.assertEquals("b", list.get(1));
}