问:
requests.post with Authentication giving error 415 for jira rest api in python
```<code>url = "https://example.com/jira/rest/api/2/issue/issue_key/comment"
data = json.dumps({"body": 'some string'})
headers = {'content-type':'application/json'}
r = requests.post(url, data, auth=('username', 'password'))
</code>```

-->  r.status_code output is 415.

But in case of

```<code>r = requests.get(url, data, auth=('username', 'password'))
</code>```

-->  r.status_code output is 200. Please help me to identify issue.

答:
The server application probably doesn't process application/json so when you send it json data it returns 415 error

415 Unsupported Media Type

See here

The GET request seems to work but it may just be sending back a login prompt. POST the data in a format that the server application can process.

Body:
url = "https://example.com/jira/rest/api/2/issue/issue_key/comment"
data = json.dumps({"body": 'some string'})
headers = {'content-type':'application/json'}
r = requests.post(url, data, auth=('username', 'password'))

-->  r.status_code output is 415.

But in case of

r = requests.get(url, data, auth=('username', 'password'))

-->  r.status_code output is 200. Please help me to identify issue.


来源: stackexchange

问:
How Do I get a webpage to display inside a tabbed page?
Is there a way to display webpages as tabbed page? The tabbed page has 2 tabs. One for about and one for contact, Is it possible to put the content of the tabbed page as just a url like "www.example.com/about" or "www.example.com/contact"?
Currently I just have a button at the tabbed page that will open the browser. Code below:</p>

```<code>  public AboutPage()
    {
        InitializeComponent();
        this.Title = "About";

        StackLayout contact = new StackLayout
        {
            VerticalOptions = LayoutOptions.Center,
            Children = {
            new Label {
                HorizontalTextAlignment=TextAlignment.Center,
                Text = "contact here"
            }
            }
        };
        var browser = new WebView();
        var htmlSource = new HtmlWebViewSource();
        htmlSource.BaseUrl = "http://www.google.com";
        browser.Source = htmlSource;
        Button abtbutton = new Button
        {
            Text = "View about page"
        };
        abtbutton.Clicked += OnAboutBtnClicked;
        this.Children.Add(new ContentPage
        {
            Title = "About",
            Content = browser
        }
        );
        this.Children.Add(new ContentPage
        {
            Title = "Contact",
            Content = contact
        });
    }

    void OnAboutBtnClicked(object sender, EventArgs args)
    {
        Device.OpenUri(new Uri("http://www.google.com"));
    }
</code>```

答:
I think you need two webViews.

```<code>var browser = new WebView();
browser.Source = new UrlWebViewSource { Url = "https://developer.xamarin.com/" };
this.Children.Add(new ContentPage
{
    Title = "About",
    Content = browser
}
);

var browser2 = new WebView();
browser2.Source = new UrlWebViewSource { Url = "https://stackoverflow.com/" };
this.Children.Add(new ContentPage
{
    Title = "Contact",
    Content = browser2
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to display webpages as tabbed page? The tabbed page has 2 tabs. One for about and one for contact, Is it possible to put the content of the tabbed page as just a url like "www.example.com/about" or "www.example.com/contact"?
Currently I just have a button at the tabbed page that will open the browser. Code below:

  public AboutPage()
    {
        InitializeComponent();
        this.Title = "About";

        StackLayout contact = new StackLayout
        {
            VerticalOptions = LayoutOptions.Center,
            Children = {
            new Label {
                HorizontalTextAlignment=TextAlignment.Center,
                Text = "contact here"
            }
            }
        };
        var browser = new WebView();
        var htmlSource = new HtmlWebViewSource();
        htmlSource.BaseUrl = "http://www.google.com";
        browser.Source = htmlSource;
        Button abtbutton = new Button
        {
            Text = "View about page"
        };
        abtbutton.Clicked += OnAboutBtnClicked;
        this.Children.Add(new ContentPage
        {
            Title = "About",
            Content = browser
        }
        );
        this.Children.Add(new ContentPage
        {
            Title = "Contact",
            Content = contact
        });
    }

    void OnAboutBtnClicked(object sender, EventArgs args)
    {
        Device.OpenUri(new Uri("http://www.google.com"));
    }

Body:
I think you need two webViews.

var browser = new WebView();
browser.Source = new UrlWebViewSource { Url = "https://developer.xamarin.com/" };
this.Children.Add(new ContentPage
{
    Title = "About",
    Content = browser
}
);

var browser2 = new WebView();
browser2.Source = new UrlWebViewSource { Url = "https://stackoverflow.com/" };
this.Children.Add(new ContentPage
{
    Title = "Contact",
    Content = browser2
});


问:
Best way to get values from a dictionary in Python
Apologies for the potentially noobish question.

I have this dict:

```<code>info = {'a': [u'option1'], 'b': [u'option2', u'option3'], 'c': [], 'd': [], 'e': [], 'f': [u'option4', u'option5', u'option6', u'option7', u'option8', u'option9', u'option10', u'option11'], 'g': [], 'h': []}
</code>```

I need to make a query with each value.
In Python what is the best way to get the values?

I currently do this:

```<code>keys = info.keys ()
for i in keys:
    for j in info [i]:
        # Make query with j
</code>```

I think it can be done better.
Thank you very much!

答:
Do you want to iterate over the list elements in every value? If you don't use the key, you can use dict.values() directly:

```<code>>>> [option for v in info.values() for option in v]
['option1', 'option2', 'option3', 'option4', 'option5', 'option6', 'option7', 'option8', 'option9', 'option10', 'option11']
</code>```

Body:
Apologies for the potentially noobish question.

I have this dict:

info = {'a': [u'option1'], 'b': [u'option2', u'option3'], 'c': [], 'd': [], 'e': [], 'f': [u'option4', u'option5', u'option6', u'option7', u'option8', u'option9', u'option10', u'option11'], 'g': [], 'h': []}

I need to make a query with each value.
In Python what is the best way to get the values?

I currently do this:

keys = info.keys ()
for i in keys:
    for j in info [i]:
        # Make query with j

I think it can be done better.
Thank you very much!

Body:
Do you want to iterate over the list elements in every value? If you don't use the key, you can use dict.values() directly:

>>> [option for v in info.values() for option in v]
['option1', 'option2', 'option3', 'option4', 'option5', 'option6', 'option7', 'option8', 'option9', 'option10', 'option11']


问:
why Catch block is executing after return statement in C#
I am trying to use try catch in C# application but I am facing problem suppose first-time internet issue came and then again it tries to sync second-time internet came then after return statement it's going again in catch(CommunicationException comEx) block and return false.

why its happening

```<code>int SyncFailCount = 0;
private bool SyncCustomers(long TenantId, DataTable dtCusomers)
{
   bool IsSyncSuccess = false;
    try
    {
        SyncQBClient client = new SyncQBClient();
        client.SynvCustomer(TenantId, dtCusomers);
        SyncFailCount = 0;
        IsSyncSuccess = true;
    }
    catch (CommunicationException comEx) // Mohan: Exception due to Internet issue
    {
        SyncFailCount = SyncFailCount + 1;
        Thread.Sleep(300);
        if (SyncFailCount <= 5)
        {
            SyncCustomers(TenantId, dtCusomers);
        }
    }
    catch (TimeoutException TimeoutEx) // Mohan: Exception due to timeout from web service
    {
        SyncFailCount = SyncFailCount + 1;
        Thread.Sleep(300);
        if (SyncFailCount <= 5)
        {
            SyncCustomers(TenantId, dtCusomers);
        }
        SyncFailCount = 0;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "CashPundit", MessageBoxButtons.OK, MessageBoxIcon.Error);
        SyncFailCount = 0;
    }
    return IsSyncSuccess;
}
</code>```

答:
Trace what is happening when there is one CommunicationException or TimeoutException and the Thread.Sleep "fixes" this:

you are calling SyncCustomers from "outside" and setting the local variable IsSyncSuccess to false

you end up in a catch block and call SyncCustomers again.

this sets a new local variable IsSyncSuccess to false

the method succeeds and returns the true value

now you are back in the original version of your method, inside that catch block

you ignore the returned value, and the value of IsSyncSuccess local to this original invovation of your method is still false. This is the value that you are returning.

So a partial solution would be to not ignore the return value when you recursively call SyncCustomers from within a catch block:

```<code>IsSyncSuccess = SyncCustomers(...);
</code>```

But then you still have a possible infinite recursion that you need to deal with:

When there is a CommunicationException or TimeoutException, you are increasing SyncFailCount, and calling SyncCustomers again - which resets that SyncFailCount back to 0! You are never reaching that limit of 5

Body:
I am trying to use try catch in C# application but I am facing problem suppose first-time internet issue came and then again it tries to sync second-time internet came then after return statement it's going again in catch(CommunicationException comEx) block and return false.

why its happening

int SyncFailCount = 0;
private bool SyncCustomers(long TenantId, DataTable dtCusomers)
{
   bool IsSyncSuccess = false;
    try
    {
        SyncQBClient client = new SyncQBClient();
        client.SynvCustomer(TenantId, dtCusomers);
        SyncFailCount = 0;
        IsSyncSuccess = true;
    }
    catch (CommunicationException comEx) // Mohan: Exception due to Internet issue
    {
        SyncFailCount = SyncFailCount + 1;
        Thread.Sleep(300);
        if (SyncFailCount <= 5)
        {
            SyncCustomers(TenantId, dtCusomers);
        }
    }
    catch (TimeoutException TimeoutEx) // Mohan: Exception due to timeout from web service
    {
        SyncFailCount = SyncFailCount + 1;
        Thread.Sleep(300);
        if (SyncFailCount <= 5)
        {
            SyncCustomers(TenantId, dtCusomers);
        }
        SyncFailCount = 0;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "CashPundit", MessageBoxButtons.OK, MessageBoxIcon.Error);
        SyncFailCount = 0;
    }
    return IsSyncSuccess;
}

Body:
Trace what is happening when there is one CommunicationException or TimeoutException and the Thread.Sleep "fixes" this:

you are calling SyncCustomers from "outside" and setting the local variable IsSyncSuccess to false

you end up in a catch block and call SyncCustomers again.

this sets a new local variable IsSyncSuccess to false

the method succeeds and returns the true value

now you are back in the original version of your method, inside that catch block

you ignore the returned value, and the value of IsSyncSuccess local to this original invovation of your method is still false. This is the value that you are returning.

So a partial solution would be to not ignore the return value when you recursively call SyncCustomers from within a catch block:

IsSyncSuccess = SyncCustomers(...);

But then you still have a possible infinite recursion that you need to deal with:

When there is a CommunicationException or TimeoutException, you are increasing SyncFailCount, and calling SyncCustomers again - which resets that SyncFailCount back to 0! You are never reaching that limit of 5


问:
Why does Set.of() throw an IllegalArgumentException if the elements are duplicates?
In Java 9 new static factory methods were introduced on the Set interface, called of(), which accept multiple elements, or even an array of elements.

I wanted to turn a list into a set to remove any duplicate entries in the set, which can be done (prior to Java 9) using:

```<code>Set<String> set = new HashSet<>();
set.addAll(list);
</code>```

But I thought it would be cool to use this new Java 9 static factory method doing:

```<code>Set.of(list.toArray())
</code>```

where the list is a List of Strings, previously defined.

But alas, java threw an IllegalArgumentException when the elements were duplicates, also stated in the Javadoc of the method. Why is this?

Edit: this question is not a duplicate of another question about a conceptually equivalent topic, the Map.of() method, but distinctly different. Not all static factory of() methods behave the same. In other words, when I am asking something about the Set.of() method I would not click on a question dealing with the Map.of() method.

答:
You are expecting this to be a "last-wins", just like HashSet I guess, but this was a deliberate decision (as Stuart Marks - the creator of these explains). He even has an example like this:

```<code>Map.ofEntries(
   "!", "Eclamation"
   .... // lots of other entries
   ""
   "|", "VERTICAL_BAR"
);
</code>```

The choice is that since this could be error-prone, they should prohibit it.

Also notice that Set.of() returns an immutable Set, so you could wrap your Set into:

```<code>Collections.unmodifiableCollection(new HashSet<>(list))
</code>```

Body:
In Java 9 new static factory methods were introduced on the Set interface, called of(), which accept multiple elements, or even an array of elements.

I wanted to turn a list into a set to remove any duplicate entries in the set, which can be done (prior to Java 9) using:

Set<String> set = new HashSet<>();
set.addAll(list);

But I thought it would be cool to use this new Java 9 static factory method doing:

Set.of(list.toArray())

where the list is a List of Strings, previously defined.

But alas, java threw an IllegalArgumentException when the elements were duplicates, also stated in the Javadoc of the method. Why is this?

Edit: this question is not a duplicate of another question about a conceptually equivalent topic, the Map.of() method, but distinctly different. Not all static factory of() methods behave the same. In other words, when I am asking something about the Set.of() method I would not click on a question dealing with the Map.of() method.

Body:
You are expecting this to be a "last-wins", just like HashSet I guess, but this was a deliberate decision (as Stuart Marks - the creator of these explains). He even has an example like this:

Map.ofEntries(
   "!", "Eclamation"
   .... // lots of other entries
   ""
   "|", "VERTICAL_BAR"
);

The choice is that since this could be error-prone, they should prohibit it.

Also notice that Set.of() returns an immutable Set, so you could wrap your Set into:

Collections.unmodifiableCollection(new HashSet<>(list))


问:
manual renewal for android inapp subscriptions before expiry date
According to the billing subscriptions documentation, there is a possibility of triggering a manual renewal before the current subscriptions has expired.

For eg. If I invoke the same purchase flow on a particular monthly sub 2 times in a row, the second one will fail with the error 'You have already subscribed to xxx'. I am expecting it to succeed and add an additional month to the expiry date.

Is there a way of manually renewing IAP before the expiry date?

答: the manual renewal will happen with subscription recovery. </p>


问:
Login code returns to index page instead of moving forward
I want that when I select admin and enter username and password it should go to admin.html and if I enter details for student or teacher it goes to student.html and teacher.html respectively.

I am not able to find out the issue in the code. No error is logged but still it's not working. Database is already created in phpmyadmin with name ezgradingsystem that has a table named loginform with columns named ID, username, `password' and 'type' (that will differentiate between admin, teacher and student login).

Still it's not working. When I enter user name and password it takes me back to index.php page.

Here is the code

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Login Form </title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <link rel="stylesheet" type="text/css" href="styles1.css"
    </head>
    <body>

        <h1>

            <span>E</span>
            <span>Z</span>
            <span> </span>
             <span>G</span>
             <span>R</span>
             <span>A</span>
             <span>D</span>
             <span>I</span>
             <span>N</span>
             <span>G</span>
             <span> </span>
             <span>S</span>
             <span>Y</span>
             <span>S</span>
             <span>T</span>
             <span>E</span>
             <span>M</span>
              </h1>

        <div class="loginBox">
            <img src="user.png" alt="user" class="user"><br>
            <br>
            <br>
            <br>
                    <h2 >Log in Here</h2>
            <form  method="POST" >

                                <select name = "type">
                                <option value="-1">Login As
                                </option>
                                <option value="Admin">Admin</option>
                                <option value="Student">Student</option>
                                <option value="Teacher">Teacher</option>
                                </select></td>/

                <p>Username</p>
                <input type="text" name="username" placeholder="Enter your username here">
                <p>Password</p>
                <input type="password" name="password" placeholder="Enter password here">
                <input type="submit" name="" value="Sign In">

            </form>
                        <br><br><br>

                            </div>

    </body>
    </html>
<?php
$con =mysql_connect("localhost","root","");
if(!$con)
{
    echo "unable to establish connection".mysql_error();
}
$db=mysql_select_db("ezgradingsystem",$con);
if(!$db)
{
    echo "Database not found".mysql_error();
}

     if(isset($_POST['submit']))
     {

         $type=$_POST['type'];
         $username=$_POST['username'];
         $password=$_POST['pwd'];
         $query="select * from loginform where username='$username' and password ='$password'and type='$type'";
         $result=mysql_query($query);
         while($row=mysql_fetch_array($result))
         {
             if($row['username']==$username && $row['password']==$password && $row['type']=='admin')
             {

                 header("Location: admin.html");
             }
             elseif($row['username'] ==$username && $row['password']==$password && row['type']=='student')

                 {

                 header("Location: student.html");
             }
             elseif($row['username']==$username && $row['password']==$password && row['type']=='teacher')

                 {

                 header("Location: teacher.html");
             }
         }
     }

    ?>
</code>```

答:
Maybe you use your type as your condition on if , try use this
    `

```<code> if(isset($_POST['submit']))
 {

     $type=$_POST['type'];
     $username=$_POST['username'];
     $password=$_POST['password'];
     $query="select * from loginform where username='$username' and password ='$password'and type='$type'";
     $result=mysql_query($query);
     while($row=mysql_fetch_array($result))
     {
         if($type=='Admin')
         {

             header("Location: admin.html");
         }
         elseif($type=='Student')

             {

             header("Location: student.html");
         }
         elseif($type=='Teacher')

             {

             header("Location: teacher.html");
         }
     }
 }

?>`
</code>```

Body:
I want that when I select admin and enter username and password it should go to admin.html and if I enter details for student or teacher it goes to student.html and teacher.html respectively.

I am not able to find out the issue in the code. No error is logged but still it's not working. Database is already created in phpmyadmin with name ezgradingsystem that has a table named loginform with columns named ID, username, `password' and 'type' (that will differentiate between admin, teacher and student login).

Still it's not working. When I enter user name and password it takes me back to index.php page.

Here is the code

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Login Form </title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <link rel="stylesheet" type="text/css" href="styles1.css"

            E
            Z

             G
             R
             A
             D
             I
             N
             G

             S
             Y
             S
             T
             E
             M

Log in Here

            <form  method="POST" >

                                <select name = "type">
                                <option value="-1">Login As
                                </option>
                                <option value="Admin">Admin</option>
                                <option value="Student">Student</option>
                                <option value="Teacher">Teacher</option>
                                </select>	/

Username

                <input type="text" name="username" placeholder="Enter your username here">

Password

                <input type="password" name="password" placeholder="Enter password here">
                <input type="submit" name="" value="Sign In">

            </form>

<?php
$con =mysql_connect("localhost","root","");
if(!$con)
{
    echo "unable to establish connection".mysql_error();
}
$db=mysql_select_db("ezgradingsystem",$con);
if(!$db)
{
    echo "Database not found".mysql_error();
}

     if(isset($_POST['submit']))
     {

         $type=$_POST['type'];
         $username=$_POST['username'];
         $password=$_POST['pwd'];
         $query="select * from loginform where username='$username' and password ='$password'and type='$type'";
         $result=mysql_query($query);
         while($row=mysql_fetch_array($result))
         {
             if($row['username']==$username && $row['password']==$password && $row['type']=='admin')
             {

                 header("Location: admin.html");
             }
             elseif($row['username'] ==$username && $row['password']==$password && row['type']=='student')

                 {

                 header("Location: student.html");
             }
             elseif($row['username']==$username && $row['password']==$password && row['type']=='teacher')

                 {

                 header("Location: teacher.html");
             }
         }
     }

    ?>

Body:
Maybe you use your type as your condition on if , try use this
    `

 if(isset($_POST['submit']))
 {

     $type=$_POST['type'];
     $username=$_POST['username'];
     $password=$_POST['password'];
     $query="select * from loginform where username='$username' and password ='$password'and type='$type'";
     $result=mysql_query($query);
     while($row=mysql_fetch_array($result))
     {
         if($type=='Admin')
         {

             header("Location: admin.html");
         }
         elseif($type=='Student')

             {

             header("Location: student.html");
         }
         elseif($type=='Teacher')

             {

             header("Location: teacher.html");
         }
     }
 }

?>`


问:
PHP's curl on Apache only opens one connection per server per browser
I'm having a problem with curl in PHP that I can't figure out.  I have a web server (Apache) that talks to a web service over HTTPS on another Apache server.  We'll call them "server A" and "server B".

The problem I'm seeing is that server A only makes one connection at a time using curl to server B per browser that's connected to server A.  I'm not sure if this is a curl or apache problem.  I have seen references in several places to a max connection per server setting of one for a curl client but I can't verify that it exists.

Scenario:

I load up twenty different pages in three different browsers, each in its own tab/window within that browser. I tried Firefox, Chrome, and Konqueror all at the same time.  Firefox had all its per-server connection limits raised significantly through about:config

All of those pages are hosted on server A and loading was started close to simultaneously

Each instance of the page on server A talks to server B using curl

A single call of this type to server B normally takes ~10 seconds

Only one TCP connection from A->B is open at any one time per browser that is connected to server A (3 total from A->B)

I verified that multiple connections from the browsers are opened to server A

AFAICT the requests are all serialized.  I'm able to verify that multiple connections are open from browsers to server A, but only one https connection is open from A->B per browser connected to A.

Server B can handle many connections simultaneously but for some reason server A won't open multiple connections to server B.  I have tried sending "Connection: close" from both servers A and B to see if that would help.  It did not.

I have found lots of people talking about making multiple asynchronous connections per script but what I want to do is open multiple connections across different page instances to one external server.

Any ideas on what the problem is or how to fix it?

答:
Did you consider that server B allows only 1 secure connection ?

As i know this is a browser security issues that allows only 1 secure connection to same host at 1 time.

ContentLicense: CC BY-SA 2.5


问:
Twitter Bootstrap : Same height for grid
With Bootstrap 4, I want to same height for my sections. But I want to enlarge only content
 (Not the header and the footer)

section {
  background: #ccc;
  border: 1px solid #000
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
          <li>
            Item 3
          </li>
          <li>
            Item 4
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
</div></code>```

Can you help me?

答:
section {
  background: #ccc;
  border: 1px solid #000;
  height: 100%;
  display: flex !important;
  flex-direction: column;
  align-content: space-between;
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}

.content {
  flex: 1 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />

<div class="row">
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
          <li>
            Item 3
          </li>
          <li>
            Item 4
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
</div></code>```

Body:
With Bootstrap 4, I want to same height for my sections. But I want to enlarge only content
 (Not the header and the footer)

section {
  background: #ccc;
  border: 1px solid #000
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

        Title

            Item 1

        Footer

        Title

            Item 1

            Item 2

        Footer

        Title

            Item 1

            Item 2

            Item 3

            Item 4

        Footer

Can you help me?

Body:
section {
  background: #ccc;
  border: 1px solid #000;
  height: 100%;
  display: flex !important;
  flex-direction: column;
  align-content: space-between;
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}

.content {
  flex: 1 0 auto;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />

<div class="row">
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
          <li>
            Item 3
          </li>
          <li>
            Item 4
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
</div>


问:
C++ with Kafka - consumer just receives some producer messages
I'm using the following C++ code to produce messages to Kafka:

```<code>#include <thread>
#include <cppkafka/producer.h>

using namespace cppkafka;

int main()
{
    for(int i = 0 ; i < 100 ; i++)
    {
        std::cout << "sending msg number: " << i << std::endl;
        std::string str("{'msg number' : " + std::to_string(i) + "}");

        // Create a message builder for this topic
        MessageBuilder builder("test");

        // Construct the configuration
        Configuration config =
        {
            { "metadata.broker.list", "192.168.1.100:9092"}
        };

        // Create the producer
        Producer producer(config);

        builder.payload(str);

        producer.produce(builder); //Only a few messages are received!

        std::this_thread::sleep_for(std::chrono::milliseconds(50));//If I remove this, no message is received!
    }
}
</code>```

On my machine where I have running the Zookeeper and Kafka server, I'm running a consumer, to show the messages received, by using this:

```<code>bin/kafka-console-consumer.sh --bootstrap-server 192.168.1.100:9092 --topic test
</code>```

My C++ code produces the following:

```<code>sending msg number: 0
sending msg number: 1
sending msg number: 2
sending msg number: 3
(...) //from 0 to 99...all the messages are sent!
sending msg number: 98
sending msg number: 99
</code>```

I was expecting the consumer, to receive all these messages, but I see just a few:

```<code>{'msg number' : 40}
{'msg number' : 58}
{'msg number' : 70}
{'msg number' : 75}
{'msg number' : 91}
{'msg number' : 96}
</code>```

And no more received.

If I remove the line:

```<code>std::this_thread::sleep_for(std::chrono::milliseconds(50));
</code>```

I do not receive any message.
Why is my Kafka server not receiving all my messages?

答:
Original Comment:

It is probably sort of spam prevention, i.e. sending messages out too quickly and the server is just ditching them

There are lots of different anti-spam techniques developed by web server providers. This is to stop somebody spamming your server by sending tonnes of web traffic. I think this is likely what you are doing

https://en.wikipedia.org/wiki/Anti-spam_techniques

Body:
I'm using the following C++ code to produce messages to Kafka:

#include <thread>
#include <cppkafka/producer.h>

using namespace cppkafka;

int main()
{
    for(int i = 0 ; i < 100 ; i++)
    {
        std::cout << "sending msg number: " << i << std::endl;
        std::string str("{'msg number' : " + std::to_string(i) + "}");

        // Create a message builder for this topic
        MessageBuilder builder("test");

        // Construct the configuration
        Configuration config =
        {
            { "metadata.broker.list", "192.168.1.100:9092"}
        };

        // Create the producer
        Producer producer(config);

        builder.payload(str);

        producer.produce(builder); //Only a few messages are received!

        std::this_thread::sleep_for(std::chrono::milliseconds(50));//If I remove this, no message is received!
    }
}

On my machine where I have running the Zookeeper and Kafka server, I'm running a consumer, to show the messages received, by using this:

bin/kafka-console-consumer.sh --bootstrap-server 192.168.1.100:9092 --topic test

My C++ code produces the following:

sending msg number: 0
sending msg number: 1
sending msg number: 2
sending msg number: 3
(...) //from 0 to 99...all the messages are sent!
sending msg number: 98
sending msg number: 99

I was expecting the consumer, to receive all these messages, but I see just a few:

{'msg number' : 40}
{'msg number' : 58}
{'msg number' : 70}
{'msg number' : 75}
{'msg number' : 91}
{'msg number' : 96}

And no more received.

If I remove the line:

std::this_thread::sleep_for(std::chrono::milliseconds(50));

I do not receive any message.
Why is my Kafka server not receiving all my messages?

ContentLicense: CC BY-SA 4.0


问:
Pages not loading in Single Page Application Angular JS
I am trying to implement Single Page Application in AngularJs. However, when I select the link ({{item.Name}} in Tree.Html). Corresponding view is not displayed in ng-View.

Any help will be appreciated

Main.html

```<code><body ng-app="InfoModule" ng-controller="MainController" style="max-width:1000px; margin:auto">
<nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">Information</a>

        </div>
        <span class="pull-right navbar-text">{{UserName}}</span>
    </div>
</nav>

<div class="row">
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">

        Info Page
        <div ui-tree data-drag-enabled="false">
            <ol ui-tree-nodes ng-model="itemList" class="font-weight-normal">
                <li ng-repeat="item in itemList track by $index" ui-tree-node ng-include="'Tree.html'">

                </li>
            </ol>

        </div>
    </div>
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
        <div ng-include="Details"></div>
        <div data-ng-view>

        </div>

    </div>
</div>
<div class="panel-footer">
    (C) My Solutions
</div>
</code>```

Tree.html

```<code><div ui-tree-handle class="tree-node tree-node-content">
<a class="btn btn-success btn-xs" ng-if="item.nodes && item.nodes.length > 0" ng-click="toggle(this)">
    <span class="glyphicon" ng-class="{'glyphicon-chevron-right': collapsed,'glyphicon-chevron-down': !collapsed}"></span>
</a>
<a href="#Details" >
    {{item.Name}}
</a>
</code>```

Master.js

```<code>var app = angular.module('InfoModule', ['ui.tree', 'ngRoute', 'ngStorage']);
</code>```

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

```<code>$routeProvider
.when('/login', {
    templateURL: 'Login.html',
    controller: '/mYscriptS/LoginController.js'
})
.when('Details', {
    templateURL: 'pages/Details.html',
    controller: '../mYscriptS/DetailsController.js'
})

    .when('/Main', {
        templateURL: 'main.html',
        controller: '/mYscriptS/MainController.js'
    });
//.otherwise({
//    redirectTo: 'pages/Main.html'
//    //templateURL: '/Main.html',
//    //controller: '/mYscriptS/MainController.js'
//});

$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
});

$locationProvider.html5Mode(true);
</code>```

}]);

Details.html

```<code><div ng-controller="DetailsController" >
<div class="row">
    <div class="col-md-6">
        User Id
        {{UserName}}
    </div>
    <div class="col-md-6">
        <input type="text" name="txtUserId" />
    </div>
</div>
<div class="row">
    <div class="col-md-6">
        Password
    </div>
    <div class="col-md-6">
        <input type="text" name="txtPassword" />
    </div>
</div>
</code>```

答:
Once I had gotten a problem that was same as yours.

I've tried to figure it out, and many people recommended using 'ui.router' instead of 'ngRoute'.

Maybe there are more differences between them specifically.

But even just this explain, could help you deciding side.

ngRoute is a angular core module which is good for basic scenarios. I believe that they will add more powerful features in upcoming releases.

Ui-router is a contributed module which is overcome the problems of ngRoute. Mainly Nested/Complex views.

URL: https://github.com/angular-ui/ui-router

Body:
I am trying to implement Single Page Application in AngularJs. However, when I select the link ({{item.Name}} in Tree.Html). Corresponding view is not displayed in ng-View.

Any help will be appreciated

Main.html

            Information

        {{UserName}}

        Info Page

    (C) My Solutions

Tree.html

 0" ng-click="toggle(this)">

    {{item.Name}}

Master.js

var app = angular.module('InfoModule', ['ui.tree', 'ngRoute', 'ngStorage']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

$routeProvider
.when('/login', {
    templateURL: 'Login.html',
    controller: '/mYscriptS/LoginController.js'
})
.when('Details', {
    templateURL: 'pages/Details.html',
    controller: '../mYscriptS/DetailsController.js'
})

    .when('/Main', {
        templateURL: 'main.html',
        controller: '/mYscriptS/MainController.js'
    });
//.otherwise({
//    redirectTo: 'pages/Main.html'
//    //templateURL: '/Main.html',
//    //controller: '/mYscriptS/MainController.js'
//});

$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
});

$locationProvider.html5Mode(true);

}]);

Details.html

        User Id
        {{UserName}}

        <input type="text" name="txtUserId" />

        Password

        <input type="text" name="txtPassword" />


问:
Clear MySQL table data when Spring Boot loads
I'm using Spring Boot with Hibernate.  I'm trying to delete all the contents of a MySQL table when the server reloads.  I know it sounds dumb, but I can't really find a way to do it, probably because it sounds dumb.  Any ideas?</p>

答:
Since you want only a single table cleared and not all the schema you cannot use ddl-auto properties.

I suggest adding your deleteAll logic for that table to a ApplicationListener on the event ContextRefreshedEvent where you can use all spring beans (this is the difference to @PostConstructor where you can't) so you can annotate this class as spring service and use autowired in it

```<code>public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{

        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
             //Do your job
            }
    }
</code>```

or if you don't need anything specific just do your logic in a @PostConstruct block of any class, though you need all your context to be initialized in this specific case (@PostConstruct only guarantees that autowiring is finished in the annotated bean )

Here's a list of event http://www.logicbig.com/tutorials/spring-framework/spring-core/spring-events/

Body:
Since you want only a single table cleared and not all the schema you cannot use ddl-auto properties.

I suggest adding your deleteAll logic for that table to a ApplicationListener on the event ContextRefreshedEvent where you can use all spring beans (this is the difference to @PostConstructor where you can't) so you can annotate this class as spring service and use autowired in it

public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{

        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
             //Do your job
            }
    }

or if you don't need anything specific just do your logic in a @PostConstruct block of any class, though you need all your context to be initialized in this specific case (@PostConstruct only guarantees that autowiring is finished in the annotated bean )

Here's a list of event http://www.logicbig.com/tutorials/spring-framework/spring-core/spring-events/


答:
For Python 2.x

```<code>for key,values in info.iteritems():
    print keys,values
</code>```

Using dict.iteritems() you can iterate through the keys and values in dictionary and make queries or anything.

Dict: name of the dictionary*

Title: Best way to get values from a dictionary in Python

Body:
For Python 2.x

for key,values in info.iteritems():
    print keys,values

Using dict.iteritems() you can iterate through the keys and values in dictionary and make queries or anything.

Dict: name of the dictionary*


答:
You can do it this way:

```<code>for vals in info.values():
    for j in vals:
        # make queries with j
</code>```

You can get the list of all the values like this:

```<code>values = [x for vals in info.values() for x in vals]
</code>```

Then you can use

```<code>for j in values:
     # make queries with j
</code>```

Body:
You can do it this way:

for vals in info.values():
    for j in vals:
        # make queries with j

You can get the list of all the values like this:

values = [x for vals in info.values() for x in vals]

Then you can use

for j in values:
     # make queries with j


问:
How to use Typescript Definition files in Visual Studio 2017?
I have an ASP.NET Core 2.0 app that I'm trying to use TypeScript on, and it works, but when I try to use jQuery it doesn't give me any intellisense. Simple enough I thought, I just need to add the definition file and all will be well. Except, none of the ways I've tried seem to work.

Adding the DefinitellyTyped nuget package does nothing, and in-fact, I can't see where it's being placed, unlike in VS2013. Adding the NPM packages "jquery" and "jquery-ts" does nothing. The only thing that has worked was for me to manually add the definition file from another project, but that's just too much work to have to do whenever there's updates.

So, what is the proper way to get TS definition files to work for libraries I want to use in my project? Not sure if it matters, but I'm using Gulp in my project.

答:
I pull in all of my type definitions using NPM, in association with a package.json file.

The below will result in the jQuery types (and jQuery itself) being pulled into the node_modules folder when you npm install in your project folder. You can use a Gulp task to move files you need for real from node_modules into your public folder (i.e. if you want to get jQuery via NPM).

```<code>{
    "name": "your-project",
    "private": true,
    "devDependencies": {
      "@types/jquery": "^3.2.16"
    },
    "dependencies": {
      "jquery": "^3.2.1"
    }
}
</code>```

NPM is the de-facto way to grab types, and all the Definitely Typed ones are inside the `@types organisation.

Visual Studio plays nicely with NPM now.

Body:
I pull in all of my type definitions using NPM, in association with a package.json file.

The below will result in the jQuery types (and jQuery itself) being pulled into the node_modules folder when you npm install in your project folder. You can use a Gulp task to move files you need for real from node_modules into your public folder (i.e. if you want to get jQuery via NPM).

{
    "name": "your-project",
    "private": true,
    "devDependencies": {
      "@types/jquery": "^3.2.16"
    },
    "dependencies": {
      "jquery": "^3.2.1"
    }
}

NPM is the de-facto way to grab types, and all the Definitely Typed ones are inside the `@types organisation.

Visual Studio plays nicely with NPM now.


问:
How do I exclude a specific row in Laravel?
I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

```<code>$finalNews = News::find(DB::table('news')->max('id'));
</code>```

But than I have another variable which return all the rows from News table with the following code

```<code>$news = News::orderBy('id','desc')->get();
</code>```

I want to exclude the news row which is equal to $finalNews
at the end of controller I return view with following data

```<code>return view('news', ['news' => $news, 'finalNews' => $finalNews]);
</code>```

How can I exclude the last news? I am using Laravel and MySQL.

答:
Exclude the Id of latest news from the news list</p>

```<code>$finalNews = News::find(DB::table('news')->max('id'));

$latestId = $finalNews->id;

$news = News::where('id','!=',$latestId)
        ->orderBy('id','desc')
        ->get();
</code>```

Body:
I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

$finalNews = News::find(DB::table('news')->max('id'));

But than I have another variable which return all the rows from News table with the following code

$news = News::orderBy('id','desc')->get();

I want to exclude the news row which is equal to $finalNews
at the end of controller I return view with following data

return view('news', ['news' => $news, 'finalNews' => $finalNews]);

How can I exclude the last news? I am using Laravel and MySQL.

Body:
Exclude the Id of latest news from the news list

$finalNews = News::find(DB::table('news')->max('id'));

$latestId = $finalNews->id;

$news = News::where('id','!=',$latestId)
        ->orderBy('id','desc')
        ->get();


问:
JavaScript syncronicity: Combining onAuthRequired Listener and native massaging
I have this problem ... and I've been trying to get a username and password pair passed to background.js of my extension. The process goes as follows:

A Credentials Server (CS) is started up with encrypted credential tokens

Selenium opens the browser with custom extension

The extension is triggered onAuthRequired

The Native Messaging Host (NMH) starts then receives a 'ready' message

The NMH uses a simple protocol to request tokens from the CS

The NMH decrypts the tokens

The NMH passes the credentials to background.js

background.js returns the credentials to chrome

Authentication magic happens on the remote server

I have solved everything right up to 6 ... maybe 7. The issue is that I am not able to actually capture what the NMH is sending.
It seems to be that either the credentials are not formatted correctly, thus they're being rejected or there's a problem with how the JavaScript side is put together and so it's just a case of broken code.
It's also possible that what I intend is not at all possible ... though I doubt that is the case.

I will provide as much code as I can ... and while I appreciate any help, I am happy to get a generic example which can be modified in my own time.

Got a better approach? I'm all ears! Happy to create a new question to address other ideas.

EDIT 1.0:
I should add that, when run, the alert at line 9 does popup.
When modified to read:

window.alert(String(response));

I get [object Object]

EDIT 2.0:
I changed window.alert(String(response)); to window.alert(JSON.stringify(response)); and it produced the expected outcome: {"username":"\"some_user\"","password":"\"1Password\"}
I expect this would translate to '{username:"some_user",password:"1Password"}'

There appears to be a problem passing the value of response to creds since the NMH fails to run at all once I try to access the username/password property of creds outside the callback.
This is probably a scope issue ...

Edit 3.0:
I found the issue - it's a synchronicity problem.
I've found many, many questions on this - I'll answer this when I've come up with a work around myself. Feel free to answer with a solution, should you have one.

Current background.js (not working)

chrome.webRequest.onAuthRequired.addListener(() => {
 var hostName = "aardvark_nm_host";
 var creds = null;

 chrome.runtime.sendNativeMessage(
   hostName,
   { text: "Ready" },
   function(response){
     window.alert("response");
     console.log(response);
     creds = JSON.parse(response);
   }
 );
 return {authCredentials: creds};
},
 {urls: ["<all_urls>"]},
 ['blocking']
);```
</div>
</div>
</p>

<p>Current aardvark_nm_host.py (Probably working)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>#!/usr/bin/env python

from locksmith import decrypt_token, KEYFILE
import socket
import struct
import sys
import json

PORT = 9999
ADDR = 'localhost'

ERRMSG = {"username":"ERROR", "password":"password"}

def report_string(string):
  def transceive(signal):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server = (ADDR, PORT)
    sock.connect(server)

    try:
      sock.sendall(signal)
    except Exception as e:
      print >>sys.stderr, e
      sock.close()
    try:
      sock.sendall(string)
      sock.close()
    except Exception as e:
      print >>sys.stderr, e
      sock.close()

  transceive('S')

def get_tokens():
  def recv_burst(sock):
    total_data = []
    while True:
      data = sock.recv(1024)
      if not data:
        break
      total_data.append(data)
    return ''.join(total_data)

  def transceive(signal):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server = (ADDR, PORT)
    sock.connect(server)

    try:
      sock.sendall(signal)
      message = recv_burst(sock)

    except Exception as e:
      report_string(e)

    finally:
      sock.close()

    return message

  try:
    username = transceive('U')
    username = decrypt_token(username)
    report_string(username)
  except Exception as e:
    report_string(str(e))
    username = "TOKEN_ERROR"
  try:
    password = transceive('P')
    password = decrypt_token(password)
    report_string(password)
  except Exception as e:
    report_string(str(e))
    password = "TOKEN_ERROR"

  return {"username":username, "password":password}

def read_message():
  text_length = sys.stdin.read(4)
  if len(text_length) == 0:
    sys.exit(0)

  text_length = struct.unpack('@I', text_length)[0]
  text = sys.stdin.read(text_length)
  return json.loads(text)

def encode_message(message):
  encoded_content = json.dumps(message)
  encoded_length = struct.pack('@I', len(encoded_content))
  return {'length': encoded_length, 'content': encoded_content}

def send_message(encoded_message):
  sys.stdout.write(encoded_message['length'])
  sys.stdout.write(encoded_message['content'])
  sys.stdout.flush()

def interpretation(message):
  return message["text"] == "Ready"

while True:
  received_message = read_message()
  report_string(received_message)

  if interpretation(received_message):
    creds = get_tokens()
    send_message(encode_message(creds))
    creds = None
  else:
    send_message(encode_message(ERRMSG))</code>```

Current extension manifest.json

{
    "version": "1.0.0",
    "manifest_version": 2,
    "name": "authvark",
    "permissions": [
        "<all_urls>",
        "webRequest",
        "webRequestBlocking",
        "nativeMessaging"
    ],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }
}```
</div>
</div>
</p>

<p>native-messaging-hosts/manifest.json
<div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "aardvark_nm_host",
  "description": "Intermediary Credential Host",
  "path": "/path/to/aardvark_nm_host.py",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://.../"
  ]
}</code>```

答:
The solution to the problem was to use callbacks.

I thought I would have to deal with Promises, which I did a lot of work on ... only to find there was a much easier answer.

Much easier.

Body:
I have this problem ... and I've been trying to get a username and password pair passed to background.js of my extension. The process goes as follows:

A Credentials Server (CS) is started up with encrypted credential tokens

Selenium opens the browser with custom extension

The extension is triggered onAuthRequired

The Native Messaging Host (NMH) starts then receives a 'ready' message

The NMH uses a simple protocol to request tokens from the CS

The NMH decrypts the tokens

The NMH passes the credentials to background.js

background.js returns the credentials to chrome

Authentication magic happens on the remote server

I have solved everything right up to 6 ... maybe 7. The issue is that I am not able to actually capture what the NMH is sending.
It seems to be that either the credentials are not formatted correctly, thus they're being rejected or there's a problem with how the JavaScript side is put together and so it's just a case of broken code.
It's also possible that what I intend is not at all possible ... though I doubt that is the case.

I will provide as much code as I can ... and while I appreciate any help, I am happy to get a generic example which can be modified in my own time.

Got a better approach? I'm all ears! Happy to create a new question to address other ideas.

EDIT 1.0:
I should add that, when run, the alert at line 9 does popup.
When modified to read:

window.alert(String(response));

I get [object Object]

EDIT 2.0:
I changed window.alert(String(response)); to window.alert(JSON.stringify(response)); and it produced the expected outcome: {"username":"\"some_user\"","password":"\"1Password\"}
I expect this would translate to '{username:"some_user",password:"1Password"}'

There appears to be a problem passing the value of response to creds since the NMH fails to run at all once I try to access the username/password property of creds outside the callback.
This is probably a scope issue ...

Edit 3.0:
I found the issue - it's a synchronicity problem.
I've found many, many questions on this - I'll answer this when I've come up with a work around myself. Feel free to answer with a solution, should you have one.

Current background.js (not working)

chrome.webRequest.onAuthRequired.addListener(() => {
 var hostName = "aardvark_nm_host";
 var creds = null;

 chrome.runtime.sendNativeMessage(
   hostName,
   { text: "Ready" },
   function(response){
     window.alert("response");
     console.log(response);
     creds = JSON.parse(response);
   }
 );
 return {authCredentials: creds};
},
 {urls: ["<all_urls>"]},
 ['blocking']
);

Current aardvark_nm_host.py (Probably working)

#!/usr/bin/env python

from locksmith import decrypt_token, KEYFILE
import socket
import struct
import sys
import json

PORT = 9999
ADDR = 'localhost'

ERRMSG = {"username":"ERROR", "password":"password"}

def report_string(string):
  def transceive(signal):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server = (ADDR, PORT)
    sock.connect(server)

    try:
      sock.sendall(signal)
    except Exception as e:
      print >>sys.stderr, e
      sock.close()
    try:
      sock.sendall(string)
      sock.close()
    except Exception as e:
      print >>sys.stderr, e
      sock.close()

  transceive('S')

def get_tokens():
  def recv_burst(sock):
    total_data = []
    while True:
      data = sock.recv(1024)
      if not data:
        break
      total_data.append(data)
    return ''.join(total_data)

  def transceive(signal):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server = (ADDR, PORT)
    sock.connect(server)

    try:
      sock.sendall(signal)
      message = recv_burst(sock)

    except Exception as e:
      report_string(e)

    finally:
      sock.close()

    return message

  try:
    username = transceive('U')
    username = decrypt_token(username)
    report_string(username)
  except Exception as e:
    report_string(str(e))
    username = "TOKEN_ERROR"
  try:
    password = transceive('P')
    password = decrypt_token(password)
    report_string(password)
  except Exception as e:
    report_string(str(e))
    password = "TOKEN_ERROR"

  return {"username":username, "password":password}

def read_message():
  text_length = sys.stdin.read(4)
  if len(text_length) == 0:
    sys.exit(0)

  text_length = struct.unpack('@I', text_length)[0]
  text = sys.stdin.read(text_length)
  return json.loads(text)

def encode_message(message):
  encoded_content = json.dumps(message)
  encoded_length = struct.pack('@I', len(encoded_content))
  return {'length': encoded_length, 'content': encoded_content}

def send_message(encoded_message):
  sys.stdout.write(encoded_message['length'])
  sys.stdout.write(encoded_message['content'])
  sys.stdout.flush()

def interpretation(message):
  return message["text"] == "Ready"

while True:
  received_message = read_message()
  report_string(received_message)

  if interpretation(received_message):
    creds = get_tokens()
    send_message(encode_message(creds))
    creds = None
  else:
    send_message(encode_message(ERRMSG))

Current extension manifest.json

{
    "version": "1.0.0",
    "manifest_version": 2,
    "name": "authvark",
    "permissions": [
        "<all_urls>",
        "webRequest",
        "webRequestBlocking",
        "nativeMessaging"
    ],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }
}

native-messaging-hosts/manifest.json

{
  "name": "aardvark_nm_host",
  "description": "Intermediary Credential Host",
  "path": "/path/to/aardvark_nm_host.py",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://.../"
  ]
}


问:
React Native Push Notication - react-native-fcm - ios cannot build

Hello,

I'm trying to use push notification in  react native and for that, I am using react-native-fcm.

It is working on Android and it allows the receiving of notifications from firebase.

However, on IOS, I get build errors as shown in the attached photo.

I did react-native link, made sure the lib was in build phases for linked binaries and also modified the AppDelegate as mentioned in the installation steps.

Has anyone encountered the below error? I did a project clean, delete the build folder but to no avail.

答:
Install pods for FCM...

https://medium.com/google-cloud/push-notification-for-react-native-bef05ea4d1d0

Please check


问:
ssl_error_rx_record_too_long and Apache SSL
I've got a customer trying to access one of my sites, and they keep getting this error > ssl_error_rx_record_too_long

They're getting this error on all browsers, all platforms. I can't reproduce the problem at all.

My server and myself are located in the USA, the customer is located in India.

I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried the solution mentioned here, but the customer has stated it did not fix the issue.

Can anyone tell me how I can fix this, or how I can reproduce this???

THE SOLUTION

Turns out the customer had a misconfigured local proxy!

答:
The link mentioned by Subimage was right on the money for me.  It suggested changing the virtual host tag, ie, from <VirtualHost myserver.example.com:443> to <VirtualHost _default_:443>

Error code: ssl_error_rx_record_too_long

This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate.

Below are some things we recommend trying.

Ensure that port 443 is open and enabled on your server. This is the standard port for https communications.

If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443.

If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows

```<code>Listen 80
Listen 443 https
</code>```

Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP.

If using Apache2 check your vhost config. Some users have reported changing <VirtualHost> to _default_ resolved the error.

That fixed my problem.  It's rare that I google an error message and get the first hit with the right answer!  :-)

In addition to the above, these are some other solutions that other folks have found were causing the issue:

Make sure that your SSL certificate is not expired

Try to specify the Cipher:

SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3

OwnerDisplayName: Subimage

LastEditorDisplayName: Subimage

Body:
The link mentioned by Subimage was right on the money for me.  It suggested changing the virtual host tag, ie, from <VirtualHost myserver.example.com:443> to <VirtualHost _default_:443>

Error code: ssl_error_rx_record_too_long

This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate.

Below are some things we recommend trying.

Ensure that port 443 is open and enabled on your server. This is the standard port for https communications.

If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443.

If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows

Listen 80
Listen 443 https

Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP.

If using Apache2 check your vhost config. Some users have reported changing <VirtualHost> to _default_ resolved the error.

That fixed my problem.  It's rare that I google an error message and get the first hit with the right answer!  :-)

In addition to the above, these are some other solutions that other folks have found were causing the issue:

Make sure that your SSL certificate is not expired

Try to specify the Cipher:

SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3


问:
Last child not removing border bottom
HTML:

```<code><div class="offer-section">
    <div class="divider"></div>
</div>
<div class="offer-section">
    <div class="divider"></div>
</div>
<div class="offer-section">
    <div class="divider"></div>
</div>
<div class="offer-section">
    <div class="divider"></div>
</div>
</code>```

CSS:

```<code>.offer-section{
   .divider { border: solid 1px #bdbdc3; height: 2px; margin-top: 5%; }
}
.offer-section:last-child {
   .divider { }
}
</code>```

Trying to add a divider to the bottom of every offer-section div except the last one. However the code above does not seem to be able to do the job. Would appreciate any help :)

答:
You need to provide proper CSS properties as per the requirement, as given below. </p>

```<code>.offer-section{
  .divider { border: solid 1px #bdbdc3; height: 2px; margin-top: 5%; }
}
.offer-section:last-child {
  .divider { border: none; }
}
</code>```

Title: Last child not removing border bottom

Body:
HTML:

CSS:

.offer-section{
   .divider { border: solid 1px #bdbdc3; height: 2px; margin-top: 5%; }
}
.offer-section:last-child {
   .divider { }
}

Trying to add a divider to the bottom of every offer-section div except the last one. However the code above does not seem to be able to do the job. Would appreciate any help :)

Body:
You need to provide proper CSS properties as per the requirement, as given below.

.offer-section{
  .divider { border: solid 1px #bdbdc3; height: 2px; margin-top: 5%; }
}
.offer-section:last-child {
  .divider { border: none; }
}


问:
C# Automapper - map class with several properties from one Type in different ways
I have a class Validation period with 7 properties that are from same class:

```<code>public class ValidationPeriod
{
    string code;
    DateTime startingDate;
    DateTime endingDate;
    bool validForDaysWithNoTimeSet;
    DayValidation monday;
    DayValidation tuesday;
    DayValidation wednesday;
    DayValidation thursday;
    DayValidation friday;
    DayValidation saturday;
    DayValidation sunday;

    public string Code { get => code; set => code = value; }
    public DateTime StartingDate { get => startingDate; set => startingDate = value; }
    public DateTime EndingDate { get => endingDate; set => endingDate = value; }
    public bool ValidForDaysWithNoTimeSet { get => validForDaysWithNoTimeSet; set => validForDaysWithNoTimeSet = value; }
    public DayValidation Monday { get => monday; set => monday = value; }
    public DayValidation Tuesday { get => tuesday; set => tuesday = value; }
    public DayValidation Wednesday { get => wednesday; set => wednesday = value; }
    public DayValidation Thursday { get => thursday; set => thursday = value; }
    public DayValidation Friday { get => friday; set => friday = value; }
    public DayValidation Saturday { get => saturday; set => saturday = value; }
    public DayValidation Sunday { get => sunday; set => sunday = value; }

    public class DayValidation
    {
        DateTime startingTime;
        DateTime endingTime;
        bool valid;
        bool timeWithinBounds;
        bool endTimeAfterMidnight;

        public DateTime StartingTime { get => startingTime; set => startingTime = value; }
        public DateTime EndingTime { get => endingTime; set => endingTime = value; }
        public bool Valid { get => valid; set => valid = value; }
        public bool TimeWithinBounds { get => timeWithinBounds; set => timeWithinBounds = value; }
        public bool EndTimeAfterMidnight { get => endTimeAfterMidnight; set => endTimeAfterMidnight = value; }
    }

}
</code>```

I want to map it to another object ,where definition for the dates are with different properties for day. I can't change the second class and i don't want to create separate class for every day of week.

Automapper gives me error when i try something like this:

```<code> internal static void Map(IMapperConfigurationExpression c)
        {
            c.CreateMap<ODATAConnector.ISWIValidationPeriod, Core.ValidationPeriod>()
                .ForMember(dest => dest.Code, opt => opt.MapFrom(src => src.ID))
                .ForMember(dest => dest.StartingDate, opt => opt.MapFrom(src => src.StartingDateTime.Value))
                .ForMember(dest => dest.EndingDate, opt => opt.MapFrom(src => src.EndingDateTime))
                .ForMember(dest => dest.ValidForDaysWithNoTimeSet, opt => opt.MapFrom(src => src.ValidForDaysWithNoTimeSet))
                .ForMember(dest => dest.Monday.Valid, opt => opt.MapFrom(src => src.ValidOnMon))
                .ForMember(dest => dest.Monday.TimeWithinBounds, opt => opt.MapFrom(src => src.Mon_Time_within_Bounds))
                .ForMember(dest => dest.Monday.StartingTime, opt => opt.MapFrom(src => src.Monday_Starting_Time))
                .ForMember(dest => dest.Monday.EndingTime, opt => opt.MapFrom(src => src.Monday_Ending_Time))
                .ForMember(dest => dest.Monday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Mon_End_Time_After_Midnight))

                .ForMember(dest => dest.Tuesday.Valid, opt => opt.MapFrom(src => src.ValidOnTue))
                .ForMember(dest => dest.Tuesday.TimeWithinBounds, opt => opt.MapFrom(src => src.Tue_Time_within_Bounds))
                .ForMember(dest => dest.Tuesday.StartingTime, opt => opt.MapFrom(src => src.Tuesday_Starting_Time))
                .ForMember(dest => dest.Tuesday.EndingTime, opt => opt.MapFrom(src => src.Tuesday_Ending_Time))
                .ForMember(dest => dest.Tuesday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Tue_End_Time_After_Midnight))

                .ForMember(dest => dest.Wednesday.Valid, opt => opt.MapFrom(src => src.ValidOnWed))
                .ForMember(dest => dest.Wednesday.TimeWithinBounds, opt => opt.MapFrom(src => src.Wed_Time_within_Bounds))
                .ForMember(dest => dest.Wednesday.StartingTime, opt => opt.MapFrom(src => src.Wednesday_Starting_Time))
                .ForMember(dest => dest.Wednesday.EndingTime, opt => opt.MapFrom(src => src.Wednesday_Ending_Time))
                .ForMember(dest => dest.Wednesday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Wed_End_Time_After_Midnight))

                .ForMember(dest => dest.Thursday.Valid, opt => opt.MapFrom(src => src.ValidOnThu))
                .ForMember(dest => dest.Thursday.TimeWithinBounds, opt => opt.MapFrom(src => src.Thu_Time_within_Bounds))
                .ForMember(dest => dest.Thursday.StartingTime, opt => opt.MapFrom(src => src.Thursday_Starting_Time))
                .ForMember(dest => dest.Thursday.EndingTime, opt => opt.MapFrom(src => src.Thursday_Ending_Time))
                .ForMember(dest => dest.Thursday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Thu_End_Time_After_Midnight))

                .ForMember(dest => dest.Friday.Valid, opt => opt.MapFrom(src => src.ValidOnFri))
                .ForMember(dest => dest.Friday.TimeWithinBounds, opt => opt.MapFrom(src => src.Fri_Time_within_Bounds))
                .ForMember(dest => dest.Friday.StartingTime, opt => opt.MapFrom(src => src.Friday_Starting_Time))
                .ForMember(dest => dest.Friday.EndingTime, opt => opt.MapFrom(src => src.Friday_Ending_Time))
                .ForMember(dest => dest.Friday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Fri_End_Time_After_Midnight))

                .ForMember(dest => dest.Saturday.Valid, opt => opt.MapFrom(src => src.ValidOnSat))
                .ForMember(dest => dest.Saturday.TimeWithinBounds, opt => opt.MapFrom(src => src.Sat_Time_within_Bounds))
                .ForMember(dest => dest.Saturday.StartingTime, opt => opt.MapFrom(src => src.Saturday_Starting_Time))
                .ForMember(dest => dest.Saturday.EndingTime, opt => opt.MapFrom(src => src.Saturday_Ending_Time))
                .ForMember(dest => dest.Saturday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Sat_End_Time_After_Midnight))

                .ForMember(dest => dest.Sunday.Valid, opt => opt.MapFrom(src => src.ValidOnSun))
                .ForMember(dest => dest.Sunday.TimeWithinBounds, opt => opt.MapFrom(src => src.Sun_Time_within_Bounds))
                .ForMember(dest => dest.Sunday.StartingTime, opt => opt.MapFrom(src => src.Sunday_Starting_Time))
                .ForMember(dest => dest.Sunday.EndingTime, opt => opt.MapFrom(src => src.Sunday_Ending_Time))
                .ForMember(dest => dest.Sunday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Sun_End_Time_After_Midnight));

        }
</code>```

how can i achieve this. I want  ValidationPeriod.Monday.StartingTime to be mapped to src.Monday_Starting_Time and ValidationPeriod.Tuesday.StartingTime to be mapped to src.Tuesday_Starting_Time and etc.

答:
I solved it using ResolveUsing. This is my code. Thank you for the suggestion to initialize my object
!</p>

```<code> c.CreateMap<ODATAConnector.ISWIValidationPeriod, Core.ValidationPeriod>()

            .ForMember(dest => dest.Code, opt => opt.MapFrom(src => src.ID))
            .ForMember(dest => dest.StartingDate, opt => opt.MapFrom(src => src.StartingDateTime.Value))
            .ForMember(dest => dest.EndingDate, opt => opt.MapFrom(src => src.EndingDateTime))
            .ForMember(dest => dest.ValidForDaysWithNoTimeSet, opt => opt.MapFrom(src => src.ValidForDaysWithNoTimeSet))
            .ForMember(dest => dest.Monday, opt => opt.ResolveUsing(model => new Core.ValidationPeriod.DayValidation()
            {
                Valid = model.ValidOnMon.Value,
                StartingTime = Convert.ToDateTime(model.Monday_Starting_Time),
                EndingTime = Convert.ToDateTime(model.Monday_Ending_Time),
                TimeWithinBounds = model.Mon_Time_within_Bounds.Value,
                EndTimeAfterMidnight = model.Mon_End_Time_After_Midnight.Value
            }))
            .ForMember(dest => dest.Tuesday, opt => opt.ResolveUsing(model => new Core.ValidationPeriod.DayValidation()
            {
                Valid = model.ValidOnTue.Value,
                StartingTime = Convert.ToDateTime(model.Tuesday_Starting_Time),
                EndingTime = Convert.ToDateTime(model.Tuesday_Ending_Time),
                TimeWithinBounds = model.Tue_Time_within_Bounds.Value,
                EndTimeAfterMidnight = model.Tue_End_Time_After_Midnight.Value
            }))
</code>```

Body:
I have a class Validation period with 7 properties that are from same class:

public class ValidationPeriod
{
    string code;
    DateTime startingDate;
    DateTime endingDate;
    bool validForDaysWithNoTimeSet;
    DayValidation monday;
    DayValidation tuesday;
    DayValidation wednesday;
    DayValidation thursday;
    DayValidation friday;
    DayValidation saturday;
    DayValidation sunday;

    public string Code { get => code; set => code = value; }
    public DateTime StartingDate { get => startingDate; set => startingDate = value; }
    public DateTime EndingDate { get => endingDate; set => endingDate = value; }
    public bool ValidForDaysWithNoTimeSet { get => validForDaysWithNoTimeSet; set => validForDaysWithNoTimeSet = value; }
    public DayValidation Monday { get => monday; set => monday = value; }
    public DayValidation Tuesday { get => tuesday; set => tuesday = value; }
    public DayValidation Wednesday { get => wednesday; set => wednesday = value; }
    public DayValidation Thursday { get => thursday; set => thursday = value; }
    public DayValidation Friday { get => friday; set => friday = value; }
    public DayValidation Saturday { get => saturday; set => saturday = value; }
    public DayValidation Sunday { get => sunday; set => sunday = value; }

    public class DayValidation
    {
        DateTime startingTime;
        DateTime endingTime;
        bool valid;
        bool timeWithinBounds;
        bool endTimeAfterMidnight;

        public DateTime StartingTime { get => startingTime; set => startingTime = value; }
        public DateTime EndingTime { get => endingTime; set => endingTime = value; }
        public bool Valid { get => valid; set => valid = value; }
        public bool TimeWithinBounds { get => timeWithinBounds; set => timeWithinBounds = value; }
        public bool EndTimeAfterMidnight { get => endTimeAfterMidnight; set => endTimeAfterMidnight = value; }
    }

}

I want to map it to another object ,where definition for the dates are with different properties for day. I can't change the second class and i don't want to create separate class for every day of week.

Automapper gives me error when i try something like this:

 internal static void Map(IMapperConfigurationExpression c)
        {
            c.CreateMap<ODATAConnector.ISWIValidationPeriod, Core.ValidationPeriod>()
                .ForMember(dest => dest.Code, opt => opt.MapFrom(src => src.ID))
                .ForMember(dest => dest.StartingDate, opt => opt.MapFrom(src => src.StartingDateTime.Value))
                .ForMember(dest => dest.EndingDate, opt => opt.MapFrom(src => src.EndingDateTime))
                .ForMember(dest => dest.ValidForDaysWithNoTimeSet, opt => opt.MapFrom(src => src.ValidForDaysWithNoTimeSet))
                .ForMember(dest => dest.Monday.Valid, opt => opt.MapFrom(src => src.ValidOnMon))
                .ForMember(dest => dest.Monday.TimeWithinBounds, opt => opt.MapFrom(src => src.Mon_Time_within_Bounds))
                .ForMember(dest => dest.Monday.StartingTime, opt => opt.MapFrom(src => src.Monday_Starting_Time))
                .ForMember(dest => dest.Monday.EndingTime, opt => opt.MapFrom(src => src.Monday_Ending_Time))
                .ForMember(dest => dest.Monday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Mon_End_Time_After_Midnight))

                .ForMember(dest => dest.Tuesday.Valid, opt => opt.MapFrom(src => src.ValidOnTue))
                .ForMember(dest => dest.Tuesday.TimeWithinBounds, opt => opt.MapFrom(src => src.Tue_Time_within_Bounds))
                .ForMember(dest => dest.Tuesday.StartingTime, opt => opt.MapFrom(src => src.Tuesday_Starting_Time))
                .ForMember(dest => dest.Tuesday.EndingTime, opt => opt.MapFrom(src => src.Tuesday_Ending_Time))
                .ForMember(dest => dest.Tuesday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Tue_End_Time_After_Midnight))

                .ForMember(dest => dest.Wednesday.Valid, opt => opt.MapFrom(src => src.ValidOnWed))
                .ForMember(dest => dest.Wednesday.TimeWithinBounds, opt => opt.MapFrom(src => src.Wed_Time_within_Bounds))
                .ForMember(dest => dest.Wednesday.StartingTime, opt => opt.MapFrom(src => src.Wednesday_Starting_Time))
                .ForMember(dest => dest.Wednesday.EndingTime, opt => opt.MapFrom(src => src.Wednesday_Ending_Time))
                .ForMember(dest => dest.Wednesday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Wed_End_Time_After_Midnight))

                .ForMember(dest => dest.Thursday.Valid, opt => opt.MapFrom(src => src.ValidOnThu))
                .ForMember(dest => dest.Thursday.TimeWithinBounds, opt => opt.MapFrom(src => src.Thu_Time_within_Bounds))
                .ForMember(dest => dest.Thursday.StartingTime, opt => opt.MapFrom(src => src.Thursday_Starting_Time))
                .ForMember(dest => dest.Thursday.EndingTime, opt => opt.MapFrom(src => src.Thursday_Ending_Time))
                .ForMember(dest => dest.Thursday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Thu_End_Time_After_Midnight))

                .ForMember(dest => dest.Friday.Valid, opt => opt.MapFrom(src => src.ValidOnFri))
                .ForMember(dest => dest.Friday.TimeWithinBounds, opt => opt.MapFrom(src => src.Fri_Time_within_Bounds))
                .ForMember(dest => dest.Friday.StartingTime, opt => opt.MapFrom(src => src.Friday_Starting_Time))
                .ForMember(dest => dest.Friday.EndingTime, opt => opt.MapFrom(src => src.Friday_Ending_Time))
                .ForMember(dest => dest.Friday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Fri_End_Time_After_Midnight))

                .ForMember(dest => dest.Saturday.Valid, opt => opt.MapFrom(src => src.ValidOnSat))
                .ForMember(dest => dest.Saturday.TimeWithinBounds, opt => opt.MapFrom(src => src.Sat_Time_within_Bounds))
                .ForMember(dest => dest.Saturday.StartingTime, opt => opt.MapFrom(src => src.Saturday_Starting_Time))
                .ForMember(dest => dest.Saturday.EndingTime, opt => opt.MapFrom(src => src.Saturday_Ending_Time))
                .ForMember(dest => dest.Saturday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Sat_End_Time_After_Midnight))

                .ForMember(dest => dest.Sunday.Valid, opt => opt.MapFrom(src => src.ValidOnSun))
                .ForMember(dest => dest.Sunday.TimeWithinBounds, opt => opt.MapFrom(src => src.Sun_Time_within_Bounds))
                .ForMember(dest => dest.Sunday.StartingTime, opt => opt.MapFrom(src => src.Sunday_Starting_Time))
                .ForMember(dest => dest.Sunday.EndingTime, opt => opt.MapFrom(src => src.Sunday_Ending_Time))
                .ForMember(dest => dest.Sunday.EndTimeAfterMidnight, opt => opt.MapFrom(src => src.Sun_End_Time_After_Midnight));

        }

how can i achieve this. I want  ValidationPeriod.Monday.StartingTime to be mapped to src.Monday_Starting_Time and ValidationPeriod.Tuesday.StartingTime to be mapped to src.Tuesday_Starting_Time and etc.

Body:
I solved it using ResolveUsing. This is my code. Thank you for the suggestion to initialize my object
!

 c.CreateMap<ODATAConnector.ISWIValidationPeriod, Core.ValidationPeriod>()

            .ForMember(dest => dest.Code, opt => opt.MapFrom(src => src.ID))
            .ForMember(dest => dest.StartingDate, opt => opt.MapFrom(src => src.StartingDateTime.Value))
            .ForMember(dest => dest.EndingDate, opt => opt.MapFrom(src => src.EndingDateTime))
            .ForMember(dest => dest.ValidForDaysWithNoTimeSet, opt => opt.MapFrom(src => src.ValidForDaysWithNoTimeSet))
            .ForMember(dest => dest.Monday, opt => opt.ResolveUsing(model => new Core.ValidationPeriod.DayValidation()
            {
                Valid = model.ValidOnMon.Value,
                StartingTime = Convert.ToDateTime(model.Monday_Starting_Time),
                EndingTime = Convert.ToDateTime(model.Monday_Ending_Time),
                TimeWithinBounds = model.Mon_Time_within_Bounds.Value,
                EndTimeAfterMidnight = model.Mon_End_Time_After_Midnight.Value
            }))
            .ForMember(dest => dest.Tuesday, opt => opt.ResolveUsing(model => new Core.ValidationPeriod.DayValidation()
            {
                Valid = model.ValidOnTue.Value,
                StartingTime = Convert.ToDateTime(model.Tuesday_Starting_Time),
                EndingTime = Convert.ToDateTime(model.Tuesday_Ending_Time),
                TimeWithinBounds = model.Tue_Time_within_Bounds.Value,
                EndTimeAfterMidnight = model.Tue_End_Time_After_Midnight.Value
            }))


答:
The Set.of() factory methods produce immutable Sets for a given number of elements.

In the variants that support a fixed number of arguments (static <E> Set<E> of(), static <E> Set<E> of(E e1), static <E> Set<E> of(E e1,E e2), etc...) the requirement of not having duplicates are easier to understand - when you call the method Set.of(a,b,c), you are stating you wish to create an immutable Set of exactly 3 elements, so if the arguments contain duplicates, it makes sense to reject your input instead of producing a smaller Set.

While the Set<E> of(E... elements) variant is different (if allows creating a Set of an arbitrary number of elements), it follows the same logic of the other variants. If you pass n elements to that method, you are stating you wish to create an immutable Set of exactly n elements, so duplicates are not allowed.

You can still create a Set from a List (having potential duplicates) in a one-liner using:

```<code>Set<String> set = new HashSet<>(list);
</code>```

which was already available before Java 9.

Title: Why does Set.of() throw an IllegalArgumentException if the elements are duplicates?

Body:
In Java 9 new static factory methods were introduced on the Set interface, called of(), which accept multiple elements, or even an array of elements.

I wanted to turn a list into a set to remove any duplicate entries in the set, which can be done (prior to Java 9) using:

Set<String> set = new HashSet<>();
set.addAll(list);

But I thought it would be cool to use this new Java 9 static factory method doing:

Set.of(list.toArray())

where the list is a List of Strings, previously defined.

But alas, java threw an IllegalArgumentException when the elements were duplicates, also stated in the Javadoc of the method. Why is this?

Edit: this question is not a duplicate of another question about a conceptually equivalent topic, the Map.of() method, but distinctly different. Not all static factory of() methods behave the same. In other words, when I am asking something about the Set.of() method I would not click on a question dealing with the Map.of() method.

Body:
The Set.of() factory methods produce immutable Sets for a given number of elements.

In the variants that support a fixed number of arguments (static <E> Set<E> of(), static <E> Set<E> of(E e1), static <E> Set<E> of(E e1,E e2), etc...) the requirement of not having duplicates are easier to understand - when you call the method Set.of(a,b,c), you are stating you wish to create an immutable Set of exactly 3 elements, so if the arguments contain duplicates, it makes sense to reject your input instead of producing a smaller Set.

While the Set<E> of(E... elements) variant is different (if allows creating a Set of an arbitrary number of elements), it follows the same logic of the other variants. If you pass n elements to that method, you are stating you wish to create an immutable Set of exactly n elements, so duplicates are not allowed.

You can still create a Set from a List (having potential duplicates) in a one-liner using:

Set<String> set = new HashSet<>(list);

which was already available before Java 9.


问:
Triggering Branch Indexing on Multibranch Pipelines (Jenkins/Git)
I'm trying to automatically trigger 'Branch Indexing' on a Multibranch Pipelines job in Jenkins.

At the moment, only one method seems to actually work, which is polling, but I am unable to do that and polling is a bad solution anyway.

The plug-in doesn't support 'Trigger builds remotely (e.g., from scripts)' (options are not saved), so I cannot trigger it via a web hook on push etc.

I tried creating a 'trigger' freestyle build on the repo but the 'Post-build Actions - Build other projects' claims the Multibranch Pipeline project is not a buildable project.

If polling is the only way I can do this, then I need to disable automatic SCM triggering (otherwise we get duplicate builds when we re-index) because I'll need to enable web hook triggering on the branch projects.

But that doesn't work, because I'm setting up the web hook via a pipeline script in the branch project, and you need to have built it at least once to have that property registered.

I've been going around in circles for a while, so hopefully I've just missed something obvious, but any help would be appreciated.

I imagined being able to do one of the following

Somehow trigger the multi-branch project as a downstream project

Poll the multibranch project, and only build branch projects which have not been built before

Cheers

答:
Based on @jjc's answer, I've created a version using the build step also for triggering the scan:

String downStreamProject = 'my-folder/my-multibranch-project'
String downStreamJob = "${downStreamProject}/${env.BRANCH_NAME}"
if (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
    // we would need "wait: true", which is not possible as of now
    // https://github.com/jenkinsci/pipeline-build-step-plugin/blob/3ff14391fe27c8ee9ccea9ba1977131fe3b26dbe/src/main/java/org/jenkinsci/plugins/workflow/support/steps/build/BuildTriggerStepExecution.java#L66
    build job: downStreamProject, wait: false
    // continue only once the expected job appears
    while (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
        sleep(1)
    }
}
build downStreamJob
```

This requires the following signatures to be approved:

method jenkins.model.Jenkins getItemByFullName java.lang.String

staticMethod jenkins.model.Jenkins getInstance

Body:
Based on @jjc's answer, I've created a version using the build step also for triggering the scan:

String downStreamProject = 'my-folder/my-multibranch-project'
String downStreamJob = "${downStreamProject}/${env.BRANCH_NAME}"
if (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
    // we would need "wait: true", which is not possible as of now
    // https://github.com/jenkinsci/pipeline-build-step-plugin/blob/3ff14391fe27c8ee9ccea9ba1977131fe3b26dbe/src/main/java/org/jenkinsci/plugins/workflow/support/steps/build/BuildTriggerStepExecution.java#L66
    build job: downStreamProject, wait: false
    // continue only once the expected job appears
    while (Jenkins.instance.getItemByFullName(downStreamJob) == null) {
        sleep(1)
    }
}
build downStreamJob

This requires the following signatures to be approved:

method jenkins.model.Jenkins getItemByFullName java.lang.String

staticMethod jenkins.model.Jenkins getInstance


问:
Laravel Join 2 tables , one data from first table and multiple row from second table

FirstTable

id   |   name   |

1   | student1 |

2   | student2 |

3   | student3 |

4   | student4 |

==============================

SecondTable

Id | stud_id | subject | mark

1  |  1     | maths   | 50

2  |  1     | english   | 45

3  |  2     | maths   | 20

4  |  3     | maths   | 40

How would i query  in laravel with the above table structure..
i need outpus as

```<code>{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}
</code>```

答:
I have done it in Laravel Query Builder.
Please see  below.</p>

```<code>$stud = DB::table('FirstTable')
               ->join('SecondTable','FirstTable.id','=','SecondTable.stud_id')
               ->where('FirstTable.id','=','1')
               ->get();
dd($stud);
</code>```

Body:
FirstTable

id   |   name   |

1   | student1 |

2   | student2 |

3   | student3 |

4   | student4 |

==============================

SecondTable

Id | stud_id | subject | mark

1  |  1     | maths   | 50

2  |  1     | english   | 45

3  |  2     | maths   | 20

4  |  3     | maths   | 40

How would i query  in laravel with the above table structure..
i need outpus as

{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}

Body:
I have done it in Laravel Query Builder.
Please see  below.

$stud = DB::table('FirstTable')
               ->join('SecondTable','FirstTable.id','=','SecondTable.stud_id')
               ->where('FirstTable.id','=','1')
               ->get();
dd($stud);


问:
How do I replace all the spaces with %20 in C#?
I want to make a string into a URL using C#. There must be something in the .NET framework that should help, right?</p>

答:
As commented on the approved story, the HttpServerUtility.UrlEncode method replaces spaces with + instead of %20.
Use one of these two methods instead: Uri.EscapeUriString() or Uri.EscapeDataString()

Sample code:

```<code>HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"

//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"
</code>```

Body:
As commented on the approved story, the HttpServerUtility.UrlEncode method replaces spaces with + instead of %20.
Use one of these two methods instead: Uri.EscapeUriString() or Uri.EscapeDataString()

Sample code:

HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"

//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"


问:
Set Location in PowerShell that contains a ampersand (&)
How do i set my directory using PowerShell to the below location ?

```<code>W:\B&M\Store Segmentation\Pete\Python
</code>```

I tried using:

```<code>PS > Set-Location -Path W:\B"&"M\Store Segmentation\Pete\Python
</code>```

答:
While using " or ' is totally a better idea, but should be informed of PowerShell escape character:

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

Using this caracher, you can scape special characters, for example:

```<code>Set-Location C:\A`&B
</code>```

You need it for example in cases that the folder name contains []:

```<code>Set-Location 'C:\A&B[1]'     # Will Fail
Set-Location 'C:\A&B`[1`]'   # Correct
</code>```

Body:
How do i set my directory using PowerShell to the below location ?

W:\B&M\Store Segmentation\Pete\Python

I tried using:

PS > Set-Location -Path W:\B"&"M\Store Segmentation\Pete\Python

Body:
While using " or ' is totally a better idea, but should be informed of PowerShell escape character:

`

Using this caracher, you can scape special characters, for example:

Set-Location C:\A`&B

You need it for example in cases that the folder name contains []:

Set-Location 'C:\A&B[1]'     # Will Fail
Set-Location 'C:\A&B`[1`]'   # Correct


问:
Call StrFormatByteSize64 function from within C#
how can I call the StrFormatByteSize64 function from the Win API from within C#? I'm trying the following code, but without success:

```<code>[DllImport("shlwapi.dll")]
static extern void StrFormatByteSize64(ulong qdw, char[] pszBuf, uint cchBuf);

char[] temp = new char[128];
ulong size = 2000;
StrFormatByteSize64(size, temp, 128);
Console.WriteLine(temp);
</code>```

The function's documentation can be found here: http://msdn.microsoft.com/en-us/library/bb759971%28VS.85%29.aspx

Thank you!

答:
Try adding [Out] before char[].

Edit:

I can't believe I didn't notice this sooner, but another problem is that your function is not void! It returns a pointer. You might want to fix that if you want it to work. :)

```<code>[DllImport("shlwapi.dll")]
static extern IntPtr StrFormatByteSize64(long qdw, [In] StringBuilder pszBuf,
                                         uint cchBuf);

//...
ulong num = 10000000;
var sb = new StringBuilder(1024);
if (StrFormatByteSize64(num, sb, (uint)sb.Capacity) != IntPtr.Zero)
{
    //Conversion successful... do stuff
}
</code>```

Body:
how can I call the StrFormatByteSize64 function from the Win API from within C#? I'm trying the following code, but without success:

[DllImport("shlwapi.dll")]
static extern void StrFormatByteSize64(ulong qdw, char[] pszBuf, uint cchBuf);

char[] temp = new char[128];
ulong size = 2000;
StrFormatByteSize64(size, temp, 128);
Console.WriteLine(temp);

The function's documentation can be found here: http://msdn.microsoft.com/en-us/library/bb759971%28VS.85%29.aspx

Thank you!

Body:
Try adding [Out] before char[].

Edit:

I can't believe I didn't notice this sooner, but another problem is that your function is not void! It returns a pointer. You might want to fix that if you want it to work. :)

[DllImport("shlwapi.dll")]
static extern IntPtr StrFormatByteSize64(long qdw, [In] StringBuilder pszBuf,
                                         uint cchBuf);

//...
ulong num = 10000000;
var sb = new StringBuilder(1024);
if (StrFormatByteSize64(num, sb, (uint)sb.Capacity) != IntPtr.Zero)
{
    //Conversion successful... do stuff
}