问:
i am Trying more Flags to prevent the Activity to be opened more than one time at the Same time
i tried Flags  like </p>

```<code> intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
</code>```

<p>i Login to my application and open the home page > when i receive a notification and preessed on it to see details at home page it opened well But the previous </p>

答:
You can achieve this with the help of launch mode

go to manifest where your activity is declared.
And add following attribute to your activity declaration.

android:launchMode="singleTask"

And in your activity class ovveride following method

```<code>public void onNewIntent(Intent intent) {
   setIntent(intent);
   //do other stuff with new intent
}
</code>```

I will also suggest you to read more about activity launch mode https://developer.android.com/guide/topics/manifest/activity-element.html

Body:
i tried Flags  like

 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);

i Login to my application and open the home page > when i receive a notification and preessed on it to see details at home page it opened well But the previous

Body:
You can achieve this with the help of launch mode

go to manifest where your activity is declared.
And add following attribute to your activity declaration.

android:launchMode="singleTask"

And in your activity class ovveride following method

public void onNewIntent(Intent intent) {
   setIntent(intent);
   //do other stuff with new intent
}

I will also suggest you to read more about activity launch mode https://developer.android.com/guide/topics/manifest/activity-element.html


来源: stackexchange

答:
Your class file is bad.  Copy the source (since you have it) into the IDE of your choice and rebuild it (usually in a menu called Build, Run, or Project).

I took your source code, added the missing brace at the end, compiled it, and ran it using java fibo and it worked just fine.  As a side note, Java classes should start with capital letters.

ContentLicense: CC BY-SA 3.0

Title: I have a class file which does not output the result due to code segment being the wrong length

Body:
Below is the hexdump of the class file in question. I have no idea about why this code doesn't run and it gives a java.lang.ClassFormatError: Code segment has wrong length in class file fibo when running in terminal using java fibo. Does anybody with a expertise in this understand why the code length is incorrect?

     //source code as requested
            public class fibo{

            public static void main(String args[]){
                System.out.println(fibonacci(10));
            }

         public static int fibonacci(int n)  {
                if(n == 0)
                    return 0;
                else if(n == 1)
                  return 1;
               else
                  return fibonacci(n - 1) + fibonacci(n - 2);
            }

ca fe ba be 00 00 00 34  00 1f 0c 00 19 00 1e 01
00 16 28 5b 4c 6a 61 76  61 2f 6c 61 6e 67 2f 53
74 72 69 6e 67 3b 29 56  01 00 10 6a 61 76 61 2f
6c 61 6e 67 2f 4f 62 6a  65 63 74 01 00 06 3c 69
6e 69 74 3e 07 00 03 0c  00 04 00 0a 07 00 13 0a
00 07 00 1c 01 00 09 66  69 62 6f 2e 6a 61 76 61
01 00 03 28 29 56 07 00  16 01 00 04 43 6f 64 65
01 00 04 66 69 62 6f 01  00 04 6d 61 69 6e 01 00
0d 53 74 61 63 6b 4d 61  70 54 61 62 6c 65 09 00
0b 00 01 01 00 0a 53 6f  75 72 63 65 46 69 6c 65
01 00 04 28 49 29 56 01  00 13 6a 61 76 61 2f 69
6f 2f 50 72 69 6e 74 53  74 72 65 61 6d 01 00 07
70 72 69 6e 74 6c 6e 0a  00 05 00 06 01 00 10 6a
61 76 61 2f 6c 61 6e 67  2f 53 79 73 74 65 6d 01
00 04 28 49 29 49 0c 00  1b 00 17 01 00 03 6f 75
74 07 00 0d 01 00 09 66  69 62 6f 6e 61 63 63 69
0c 00 14 00 12 0a 00 1a  00 18 01 00 15 4c 6a 61
76 61 2f 69 6f 2f 50 72  69 6e 74 53 74 72 65 61
6d 3b 00 21 00 1a 00 05  00 00 00 00 00 03 00 01
00 04 00 0a 00 01 00 0c  00 00 00 11 00 01 00 01
00 00 00 05 2a b7 00 15  b1 00 00 00 00 00 09 00
0e 00 02 00 01 00 0c 00  00 00 18 00 02 00 01 00
00 00 0c b2 00 10 10 0a  b8 00 1d b6 00 08 b1 00
00 00 00 00 09 00 1b 00  17 00 01 00 0c 00 00 00
37 00 03 00 01 00 00 00  1b 1a 9a 00 05 03 ac 1a
04 a0 00 05 04 ac 1a 04  64 b8 00 1d 1a 05 64 b8
00 1d 60 ac 00 00 00 01  00 0f 00 00 00 04 00 02
06 06 00 01 00 11 00 00  00 02 00 09


问:
create new array of objects from existing array
I have an existing array that I would like to reformat in JS. Here is the existing array where each item is an object:

```<code>[
 {
  end_time:"7.14",
  pk:45065,
  start_time:"4.51",
  text:"Lorem Ipsum"
 },
 {
  end_time:"9.00",
  pk:45066,
  start_time:"7.14",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"13.09",
  pk:450667 ,
  start_time:"9.00",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"17.01",
  pk:45068,
  start_time:"13.09",
  text:"Lorem Ipsum"
 },
 {
  end_time:"25.10",
  pk:45069,
  start_time:"17.01",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"28.06",
  pk:450670 ,
  start_time:"25.10",
  text:"Lorem Ipsum Something"
 },
]
</code>```

I would like to create a new array of objects where for every three objects in old array becomes one object in the new array like so:

```<code> [
  segment: {
    phrase: {
      end_time:"7.14",
      pk:45065,
      start_time:"4.51",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"9.00",
      pk:45066,
      start_time:"7.14",
      text:"Lorem Ipsum Something"
     },
     phrase: {
      end_time:"13.09",
      pk:450667 ,
      start_time:"9.00",
      text:"Lorem Ipsum Something"
     }
  },
  segment {
    phrase: {
      end_time:"17.01",
      pk:45068,
      start_time:"13.09",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"25.10",
      pk:45069,
      start_time:"17.01",
      text:"Lorem Ipsum Something"
    },
    phrase: {
      end_time:"28.06",
      pk:450670 ,
      start_time:"25.10",
      text:"Lorem Ipsum Something"
    },
  }
]
</code>```

What I am struggling with most is how to pull out every three items and push to the new segment object inside a map or loop I guess. I am not sure the most efficient way to go about this. Any help is much appreciated.

答:
Reduce function drops every object from the json array inside a new object, where the key is phrase and its value is that specified object. Then, just assign the result to a newly created object as the value of the segment key.

var json = [{end_time:"7.14",pk:45065,start_time:"4.51",text:"Lorem Ipsum"},{end_time:"9.00",pk:45066,start_time:"7.14",text:"Lorem Ipsum Something"},{end_time:"13.09",pk:450667,start_time:"9.00",text:"Lorem Ipsum Something"},{end_time:"17.01",pk:45068,start_time:"13.09",text:"Lorem Ipsum"},{end_time:"25.10",pk:45069,start_time:"17.01",text:"Lorem Ipsum Something"},{end_time:"28.06",pk:450670,start_time:"25.10",text:"Lorem Ipsum Something"}],
  res = json.reduce(function(s,a){
    obj = {};
    obj.phrase = a;
    s.push(obj);
    return s;
  }, []);

  var object = {};
  object.segment = res;
  var result = [object];

  console.log(result);```

Body:
I have an existing array that I would like to reformat in JS. Here is the existing array where each item is an object:

[
 {
  end_time:"7.14",
  pk:45065,
  start_time:"4.51",
  text:"Lorem Ipsum"
 },
 {
  end_time:"9.00",
  pk:45066,
  start_time:"7.14",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"13.09",
  pk:450667 ,
  start_time:"9.00",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"17.01",
  pk:45068,
  start_time:"13.09",
  text:"Lorem Ipsum"
 },
 {
  end_time:"25.10",
  pk:45069,
  start_time:"17.01",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"28.06",
  pk:450670 ,
  start_time:"25.10",
  text:"Lorem Ipsum Something"
 },
]

I would like to create a new array of objects where for every three objects in old array becomes one object in the new array like so:

 [
  segment: {
    phrase: {
      end_time:"7.14",
      pk:45065,
      start_time:"4.51",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"9.00",
      pk:45066,
      start_time:"7.14",
      text:"Lorem Ipsum Something"
     },
     phrase: {
      end_time:"13.09",
      pk:450667 ,
      start_time:"9.00",
      text:"Lorem Ipsum Something"
     }
  },
  segment {
    phrase: {
      end_time:"17.01",
      pk:45068,
      start_time:"13.09",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"25.10",
      pk:45069,
      start_time:"17.01",
      text:"Lorem Ipsum Something"
    },
    phrase: {
      end_time:"28.06",
      pk:450670 ,
      start_time:"25.10",
      text:"Lorem Ipsum Something"
    },
  }
]

What I am struggling with most is how to pull out every three items and push to the new segment object inside a map or loop I guess. I am not sure the most efficient way to go about this. Any help is much appreciated.


问:
How to use multiple functions, File-Out and del, in single Powershell command?
I am using Powershell v4.0 to remove some duplicate files off of our drive and generate some reports. Our hope is no one will care that we're removing duplicate files - but if they do then I can just restore the files to their location.

I create a report showing all duplicates. I create a report of all the files I'll keep. I create a report of all the files I'll erase. And finally I actually make the deletion.

The first command is to get a report of all the duplicate files that I have:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select } | Out-File "c:\users\me\desktop\duplicatelist.txt"
</code>```

The second command is to get a report of all the files I'll keep:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group[0] | select } | Out-File "c:\users\me\desktop\keep.txt"
</code>```

The third command is to get a report of all the files I'll erase:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | Out-File "c:\users\me\desktop\delete.txt"
</code>```

The fourth command is to delete all of the duplicate files:

```<code>ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | del
</code>```

Can I combine multiple commands? It takes eight hours and thirty minutes per iteration of the command, so running it four times doesn't seem like a great solution.

In the least to be able to print out what I'm deleting, and to delete the files at the same step would be a good step forward.

答:
Rather than hashing 4 times, save the hashes to a variable to reuse:</p>

```<code>$groupedhashes = ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 }

$groupedhashes | % { $_.group | select } | Out-File "c:\users\me\desktop\duplicatelist.txt"
$groupedhashes | % { $_.group[0] | select } | Out-File "c:\users\me\desktop\keep.txt"
$groupedhashes | % { $_.group | select -skip 1} | Out-File "c:\users\me\desktop\delete.txt"
$groupedhashes | % { $_.group | select -skip 1} | del
</code>```

Body:
I am using Powershell v4.0 to remove some duplicate files off of our drive and generate some reports. Our hope is no one will care that we're removing duplicate files - but if they do then I can just restore the files to their location.

I create a report showing all duplicates. I create a report of all the files I'll keep. I create a report of all the files I'll erase. And finally I actually make the deletion.

The first command is to get a report of all the duplicate files that I have:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select } | Out-File "c:\users\me\desktop\duplicatelist.txt"

The second command is to get a report of all the files I'll keep:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group[0] | select } | Out-File "c:\users\me\desktop\keep.txt"

The third command is to get a report of all the files I'll erase:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | Out-File "c:\users\me\desktop\delete.txt"

The fourth command is to delete all of the duplicate files:

ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1} | del

Can I combine multiple commands? It takes eight hours and thirty minutes per iteration of the command, so running it four times doesn't seem like a great solution.

In the least to be able to print out what I'm deleting, and to delete the files at the same step would be a good step forward.

Body:
Rather than hashing 4 times, save the hashes to a variable to reuse:

$groupedhashes = ls *.*| Get-FileHash | group -Property hash | where { $_.count -gt 1 }

$groupedhashes | % { $_.group | select } | Out-File "c:\users\me\desktop\duplicatelist.txt"
$groupedhashes | % { $_.group[0] | select } | Out-File "c:\users\me\desktop\keep.txt"
$groupedhashes | % { $_.group | select -skip 1} | Out-File "c:\users\me\desktop\delete.txt"
$groupedhashes | % { $_.group | select -skip 1} | del


问:
Why am I getting a TransactionRequiredException in @PostConstruct method in JTA EJB?
I have Java EE project where I want to use an injected JTA EntityManager in the @PostConstruct method. EntityManager.persist fails due to javax.persistence.TransactionRequiredException. It succeeds when called through an EJB instance injected into a  JSF managed bean. Manually starting a transaction with @Resource UserTransaction and UserTransaction.begin/commit or EntityManager.getTransaction.begin/commit because it's a JTA EntityManager.

The EJB interface

```<code>@Local
public interface UserService extends Serializable {

    public void saveUser(AUser user);
}

@Entity
public class AUser implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    private String username;

    public AUser() {
    }

    public AUser(String username) {
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
</code>```

The EJB implementation:

```<code>@Stateless
public class DefaultUserService implements UserService {
    private static final long serialVersionUID = 1L;
    @PersistenceContext
    private EntityManager entityManager;

    public DefaultUserService() {
    }

    @PostConstruct
    private void init() {
        AUser user = new AUser("initUser");
        saveUser(user);
    }

    @Override
    public void saveUser(AUser user) {
        entityManager.persist(user);
    }
}
</code>```

persistence.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="richtercloud_javaee-persist-in-postconstruct-jar_jar_1.0-SNAPSHOTPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/example1</jta-data-source>
    <class>richtercloud.javaee.persist.in.postconstruct.jar.entities.AUser</class>
    <properties>
      <property name="eclipselink.target-database" value="Derby"/>
      <!-- necessary in order to avoid syntax errors -->
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
      <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
      <property name="eclipselink.target-server" value="Glassfish"/>
      <!-- avoid non-severe NullPointerException being logged in GlasFish
            <ref>https://java.net/jira/browse/GLASSFISH-21468f</ref>-->
    </properties>
  </persistence-unit>
</persistence>
</code>```

I didn't know how to provide the jdbc/example1 data source (it's GlassFish 4.1 JDBC resource based on a JDBC connection pool referring to a Derby database with network driver). Everything else it available at https://github.com/krichter722/javaee-persist-in-postconstruct.

I read Persisting in @PostConstruct: javax.persistence.TransactionRequiredException which exceeds the example of a simple EntityManager.persist call in @PostConstruct and http://www.tikalk.com/java/doing-transactional-work-spring-service-using-postconstruct-method/ which refers to Spring which I'm not using. I found no statement that @PersistenceContext EntityManager behaves differently in @PostConstruct.

答: it doesn't guarantee that @PostConstruct and @PreDestroy are a part of transaction. so no DB operations should be done in PostConstruct method as well as PreDestroy method. </p>

Body:
I have Java EE project where I want to use an injected JTA EntityManager in the @PostConstruct method. EntityManager.persist fails due to javax.persistence.TransactionRequiredException. It succeeds when called through an EJB instance injected into a  JSF managed bean. Manually starting a transaction with @Resource UserTransaction and UserTransaction.begin/commit or EntityManager.getTransaction.begin/commit because it's a JTA EntityManager.

The EJB interface

@Local
public interface UserService extends Serializable {

    public void saveUser(AUser user);
}

@Entity
public class AUser implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    private String username;

    public AUser() {
    }

    public AUser(String username) {
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

The EJB implementation:

@Stateless
public class DefaultUserService implements UserService {
    private static final long serialVersionUID = 1L;
    @PersistenceContext
    private EntityManager entityManager;

    public DefaultUserService() {
    }

    @PostConstruct
    private void init() {
        AUser user = new AUser("initUser");
        saveUser(user);
    }

    @Override
    public void saveUser(AUser user) {
        entityManager.persist(user);
    }
}

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="richtercloud_javaee-persist-in-postconstruct-jar_jar_1.0-SNAPSHOTPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/example1</jta-data-source>
    <class>richtercloud.javaee.persist.in.postconstruct.jar.entities.AUser</class>
    <properties>
      <property name="eclipselink.target-database" value="Derby"/>

      <property name="javax.persistence.schema-generation.database.action" value="create"/>
      <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
      <property name="eclipselink.target-server" value="Glassfish"/>

    </properties>
  </persistence-unit>
</persistence>

I didn't know how to provide the jdbc/example1 data source (it's GlassFish 4.1 JDBC resource based on a JDBC connection pool referring to a Derby database with network driver). Everything else it available at https://github.com/krichter722/javaee-persist-in-postconstruct.

I read Persisting in @PostConstruct: javax.persistence.TransactionRequiredException which exceeds the example of a simple EntityManager.persist call in @PostConstruct and http://www.tikalk.com/java/doing-transactional-work-spring-service-using-postconstruct-method/ which refers to Spring which I'm not using. I found no statement that @PersistenceContext EntityManager behaves differently in @PostConstruct.


问:
Bootstrap Button Group Show/Hide Div
I've got a Bootstrap button group that has 2 buttons (JSON and XML) with JSON being active when the page is loaded.  Pressing the XML button will automatically change focus to it.

Now, I'd like to attach some behavior to these buttons so that clicking the XML button hides the error-json pre element and shows the error-xml pre element.

Is there a Bootstrap-native way to accomplish this?

```<code><div class="btn-group">
    <button class="btn btn-default" autofocus="true">JSON</button>
    <button class="btn btn-default">XML</button>
</div>

<pre id="error-json" class="hidden"><code class="language-json">{
  "ErrorCode": STATUS_CODE,
  "Description": ERROR_MSG
}</code>```

<error>
  <ErrorCode>STATUS_CODE</ErrorCode>
  <Description>ERROR_MSG</Description>
</error>
```
</code>```

答:
$("#error-xml").hide();
$(".btn").click(function () {
 var id = $(this).attr("id");
  if(id == "json"){
  $(this).attr("autofocus",true).siblings().attr("autofocus",false);
   $("#error-xml").hide();
   $("#error-json").show();
  }else{
  $(this).attr("autofocus",true).siblings().attr("autofocus",false);
   $("#error-json").hide();
   $("#error-xml").show();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:focus{
  outline: 1px solid blue;
}</code>```

    <button class="btn btn-default" id="json" autofocus="autofocus">JSON</button>
    <button class="btn btn-default" id="xml">XML</button>

{
  "ErrorCode": STATUS_CODE,
  "Description": ERROR_MSG
}```

<pre id="error-xml"><code class="language-xml"><error>
  <ErrorCode>STATUS_CODE</ErrorCode>
  <Description>ERROR_MSG</Description>
</error>
</code>``````

Title: Bootstrap Button Group Show/Hide Div

Body:
I've got a Bootstrap button group that has 2 buttons (JSON and XML) with JSON being active when the page is loaded.  Pressing the XML button will automatically change focus to it.

Now, I'd like to attach some behavior to these buttons so that clicking the XML button hides the error-json pre element and shows the error-xml pre element.

Is there a Bootstrap-native way to accomplish this?

    <button class="btn btn-default" autofocus="true">JSON</button>
    <button class="btn btn-default">XML</button>

{
  "ErrorCode": STATUS_CODE,
  "Description": ERROR_MSG
}

<error>
  <ErrorCode>STATUS_CODE</ErrorCode>
  <Description>ERROR_MSG</Description>
</error>

Body:
$("#error-xml").hide();
$(".btn").click(function () {
 var id = $(this).attr("id");
  if(id == "json"){
  $(this).attr("autofocus",true).siblings().attr("autofocus",false);
   $("#error-xml").hide();
   $("#error-json").show();
  }else{
  $(this).attr("autofocus",true).siblings().attr("autofocus",false);
   $("#error-json").hide();
   $("#error-xml").show();
  }
});

:focus{
  outline: 1px solid blue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="btn-group">
    <button class="btn btn-default" id="json" autofocus="autofocus">JSON</button>
    <button class="btn btn-default" id="xml">XML</button>
</div>

<pre id="error-json" class="hidden"><code class="language-json">{
  "ErrorCode": STATUS_CODE,
  "Description": ERROR_MSG
}</code></pre>

<pre id="error-xml"><code class="language-xml">&lt;error&gt;
  &lt;ErrorCode&gt;STATUS_CODE&lt;/ErrorCode&gt;
  &lt;Description&gt;ERROR_MSG&lt;/Description&gt;
&lt;/error&gt;
</code></pre>


问:
Why do I have white spacing around my positioned nav?
This my be a noob quesston but, Why do I have white spacing around my positioned nav?I created a nav that appears at the bottom for moblie devices and I have what looks like top and bottom padding in my nav element, but when I pull up the dev tools there is no padding or anything I would think would cause this, What is it and how can I remove it?

https://jsfiddle.net/7am3d06L/

```<code><html>
    <head>
        <title>Somalia</title>
        <meta charset="utf-8">
        <meta name="keywords" content="css, html, test">
        <meta name="description" content="This is an html and css review">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            *{
                text-align: center;
            }
            h1,nav{
                font-family: arial;
            }
            #headerNav{
                display: none;
            }
            #footerNav{
                position: fixed;
                bottom: 0px;
                width: 100%;
                background-color: white;
                padding: 0;
            }
            nav ul{
                padding: 0;
            }
            nav li{
                list-style-type: none;
                border: 1px solid black;
                margin: 0;
            }

            nav a{
                text-decoration: none;
                font-weight: 700;
            }

            nav a, nav a:visited {
                color: green;
            }

        </style>
    </head>
    <body>
        <header>
            <h1>Somalia</h1>
            <nav id="headerNav">
                <ul>
                    <li><a href="index.html">Home</a></li>
                    <li><a href="historyAndPolitics.html">History And Politics</a></li>
                    <li><a href="Geography">Geography</a></li>
                    <li><a href="economy.html">Economy</a></li>
                    <li><a href="cultureAndDemographics.html">Culture And Demographics</a></li>
                </ul>
            </nav>
        </header>
        <article>
        <p>
        Somalia (/səˈmɑːliə, soʊ-, -ljə/ so-mah-lee-ə; Somali: Soomaaliya; Arabic: الصومال aṣ-Ṣūmāl),
        officially the Federal Republic of Somalia[1] (Somali: Jamhuuriyadda Federaalka Soomaaliya, Arabic:
        <bdi>جمهورية الصومال الفيدرالية</bdi> Jumhūrīyat aṣ-Ṣūmāl al-Fidirālīyah), is a country located in the
        Horn of Africa. It is bordered by Ethiopia to the west, Djibouti to the northwest, the Gulf of Aden to the
        north, the Indian Ocean to the east, and Kenya to the southwest. Somalia has the longest coastline on
        Africa's mainland, and its terrain consists mainly of plateaus, plains and highlands. Climatically, hot
        conditions prevail year-round, with periodic monsoon winds and irregular rainfall.
        </p>
        <p>Somalia has an estimated population of around 12.3 million. Around 85% of its residents are ethnic
        Somalis,[3] who have historically inhabited the northern part of the country. Ethnic minorities are largely
        concentrated in the southern regions. The official languages of Somalia are Somali and Arabic, both of
        which belong to the Afroasiatic family. Most people in the country are Muslim, with the majority being Sunni.
        </p>

        <p>In antiquity, Somalia was an important commercial centre. It is among the most probable locations of the
        fabled ancient Land of Punt. During the Middle Ages, several powerful Somali empires dominated the regional
        trade, including the Ajuran Empire, the Adal Sultanate, the Warsangali Sultanate, and the Geledi Sultanate.
        In the late 19th century, through a succession of treaties with these kingdoms, the British and Italian
        empires gained control of parts of the coast and established the colonies of British Somaliland and Italian
        Somaliland.[19][20] In the interior, Mohammed Abdullah Hassan's Dervish State repelled the British Empire
        four times and forced it to retreat to the coastal region, before succumbing to defeat in 1920 by British
        airpower.[22] The toponym Somalia was coined by the Italian explorer Luigi Robecchi Bricchetti (1855–1926).
        Italy acquired full control of the northeastern, central and southern parts of the area after successfully
        waging the so-called Campaign of the Sultanates against the ruling Majeerteen Sultanate and Sultanate of
        Hobyo.[20] Italian occupation lasted until 1941, yielding to British military administration. British
        Somaliland would remain a protectorate, while Italian Somaliland in 1949 became a United Nations
        Trusteeship under Italian administration, the Trust Territory of Somaliland. In 1960, the two regions
        united to form the independent Somali Republic under a civilian government.</p>

        <p>The Supreme Revolutionary Council seized power in 1969 and established the Somali Democratic Republic.
        Led by Mohamed Siad Barre, this government later collapsed in 1991 as the Somali Civil War broke out.
        Various armed factions began competing for influence in the power vacuum, particularly in the south.
        During this period, due to the absence of a central government, Somalia was a "failed state", and residents
        returned to customary and religious law in most regions. A few autonomous regions, including the
        Somaliland and Puntland administrations emerged in the north. The early 2000s saw the creation of fledgling
        interim federal administrations. The Transitional National Government (TNG) was established in 2000,
        followed by the formation of the Transitional Federal Government (TFG) in 2004, which reestablished
        national institutions such as the military. In 2006, the TFG, assisted by Ethiopian troops,
        assumed control of most of the nation's southern conflict zones from the newly formed Islamic Courts Union
        (ICU). The ICU subsequently splintered into more radical groups such as Al-Shabaab, which battled the TFG
        and its AMISOM allies for control of the region.</p>

        <p>By mid-2012, the insurgents had lost most of the territory that they had seized. In 2011–2012, a
        political process providing benchmarks for the establishment of permanent democratic institutions was
        launched. Within this administrative framework a new provisional constitution was passed in August 2012,
        which reformed Somalia as a federation.[29] Following the end of the TFG's interim mandate the same month,
        the Federal Government of Somalia, the first permanent central government in the country since the start
        of the civil war, was formed[30] and a period of reconstruction began in Mogadishu. Somalia has maintained
        an informal economy, mainly based on livestock, remittances from Somalis working abroad, and
        telecommunications</p>
        </article>
        <footer>
            <nav id="footerNav">
                <ul>
                    <li><a href="index.html">Home</a></li>
                    <li><a href="historyAndPolitics.html">History And Politics</a></li>
                    <li><a href="Geography">Geography</a></li>
                    <li><a href="economy.html">Economy</a></li>
                    <li><a href="cultureAndDemographics.html">Culture And Demographics</a></li>
                </ul>
            </nav>

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

答:
You reset the padding but you need to reset the margin also:

```<code>nav ul{
    padding: 0;
    margin: 0;
}
</code>```

See example

Body:
This my be a noob quesston but, Why do I have white spacing around my positioned nav?I created a nav that appears at the bottom for moblie devices and I have what looks like top and bottom padding in my nav element, but when I pull up the dev tools there is no padding or anything I would think would cause this, What is it and how can I remove it?

https://jsfiddle.net/7am3d06L/

        <title>Somalia</title>
        <meta charset="utf-8">
        <meta name="keywords" content="css, html, test">
        <meta name="description" content="This is an html and css review">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Somalia

Home

History And Politics

Geography

Economy

Culture And Demographics

        Somalia (/səˈmɑːliə, soʊ-, -ljə/ so-mah-lee-ə; Somali: Soomaaliya; Arabic: الصومال aṣ-Ṣūmāl),
        officially the Federal Republic of Somalia[1] (Somali: Jamhuuriyadda Federaalka Soomaaliya, Arabic:
        <bdi>جمهورية الصومال الفيدرالية</bdi> Jumhūrīyat aṣ-Ṣūmāl al-Fidirālīyah), is a country located in the
        Horn of Africa. It is bordered by Ethiopia to the west, Djibouti to the northwest, the Gulf of Aden to the
        north, the Indian Ocean to the east, and Kenya to the southwest. Somalia has the longest coastline on
        Africa's mainland, and its terrain consists mainly of plateaus, plains and highlands. Climatically, hot
        conditions prevail year-round, with periodic monsoon winds and irregular rainfall.

Somalia has an estimated population of around 12.3 million. Around 85% of its residents are ethnic
        Somalis,[3] who have historically inhabited the northern part of the country. Ethnic minorities are largely
        concentrated in the southern regions. The official languages of Somalia are Somali and Arabic, both of
        which belong to the Afroasiatic family. Most people in the country are Muslim, with the majority being Sunni.

In antiquity, Somalia was an important commercial centre. It is among the most probable locations of the
        fabled ancient Land of Punt. During the Middle Ages, several powerful Somali empires dominated the regional
        trade, including the Ajuran Empire, the Adal Sultanate, the Warsangali Sultanate, and the Geledi Sultanate.
        In the late 19th century, through a succession of treaties with these kingdoms, the British and Italian
        empires gained control of parts of the coast and established the colonies of British Somaliland and Italian
        Somaliland.[19][20] In the interior, Mohammed Abdullah Hassan's Dervish State repelled the British Empire
        four times and forced it to retreat to the coastal region, before succumbing to defeat in 1920 by British
        airpower.[22] The toponym Somalia was coined by the Italian explorer Luigi Robecchi Bricchetti (1855–1926).
        Italy acquired full control of the northeastern, central and southern parts of the area after successfully
        waging the so-called Campaign of the Sultanates against the ruling Majeerteen Sultanate and Sultanate of
        Hobyo.[20] Italian occupation lasted until 1941, yielding to British military administration. British
        Somaliland would remain a protectorate, while Italian Somaliland in 1949 became a United Nations
        Trusteeship under Italian administration, the Trust Territory of Somaliland. In 1960, the two regions
        united to form the independent Somali Republic under a civilian government.

The Supreme Revolutionary Council seized power in 1969 and established the Somali Democratic Republic.
        Led by Mohamed Siad Barre, this government later collapsed in 1991 as the Somali Civil War broke out.
        Various armed factions began competing for influence in the power vacuum, particularly in the south.
        During this period, due to the absence of a central government, Somalia was a "failed state", and residents
        returned to customary and religious law in most regions. A few autonomous regions, including the
        Somaliland and Puntland administrations emerged in the north. The early 2000s saw the creation of fledgling
        interim federal administrations. The Transitional National Government (TNG) was established in 2000,
        followed by the formation of the Transitional Federal Government (TFG) in 2004, which reestablished
        national institutions such as the military. In 2006, the TFG, assisted by Ethiopian troops,
        assumed control of most of the nation's southern conflict zones from the newly formed Islamic Courts Union
        (ICU). The ICU subsequently splintered into more radical groups such as Al-Shabaab, which battled the TFG
        and its AMISOM allies for control of the region.

By mid-2012, the insurgents had lost most of the territory that they had seized. In 2011–2012, a
        political process providing benchmarks for the establishment of permanent democratic institutions was
        launched. Within this administrative framework a new provisional constitution was passed in August 2012,
        which reformed Somalia as a federation.[29] Following the end of the TFG's interim mandate the same month,
        the Federal Government of Somalia, the first permanent central government in the country since the start
        of the civil war, was formed[30] and a period of reconstruction began in Mogadishu. Somalia has maintained
        an informal economy, mainly based on livestock, remittances from Somalis working abroad, and
        telecommunications

Home

History And Politics

Geography

Economy

Culture And Demographics

Body:
You reset the padding but you need to reset the margin also:

nav ul{
    padding: 0;
    margin: 0;
}

See example


问:
How to update Android emulator without Android Studio?
I don't have Android Studio, just the Android SDK. When I launch one of my Android emulators using the Android Virtual Devices (AVD) Manager, I get the following message:

Your emulator is out of date, please update by launching Android Studio.

According to the steps, it seems that one could update the emulator even without Android Studio just by using the Android SDK Manager. But there is no SDK Tools tab.

Is the SDK Manager which is launched as a standalone application different from the SDK Manager available in the Android Studio?

Also, as you can see, everything is up-to-date and the version of Android SDK Tools is even newer than the one that is offered for downloading on the Android website (25.2.3 at the time of writing this question).

So how do I update the emulator? I don't need/want Android Studio.

答:
The standalone GUI SDK Manager is deprecated as of SDK Tools v25.2.3.

The instructions you see in the "Starting Android Emulator" run window are specific to updating via Android Studio.  The SDK Manager inside of Android Studio is different than the standalone tool. We added new SDK packages that the old SDK Manager does not understand how to process nor update, including the new Emulator.

You have two ways going forward to update the emulator:

Use the new command line SDK Manager: $ ./sdkmanager --update Read more here

Use the new SDK Manager in Android Studio

Based on the window output, it also looks like your AVDs might be old, so you may want to create new AVDs or update for the latest features and better emulator performance & stability.

SDK Tools Release Notes saying it has been deprecated:

ContentLicense: CC BY-SA 4.0


问:
Is it possible to have a custom webpart listen to default SharePoint search box?
SharePoint has a search box by default at the top of the Portal.  I want my WebPart to be able to intercept that search and provide search results.  Is this possible, and if so any tips or links on how to do this?  </p>

答: You could use jQuery in your webpart and handle the onkeypress event of that textbox.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Tom Anderson


问:
Mysql select first then limit
How can i select the newest 5 rows from mysql (newest by id for example) then order them asc or desc ??

the problem is i have 1,2,3,4,5,6,7 , i want to select the newest 2 for example (6,7) then order them asc or desc (6,7 or 7,6) , but if i use the orderby then the limit it would be (1,2) or (7,6) , is there anyway to do it from ONE sql statement ?

thank you

答:
You may use something like</p>

```<code>SELECT * FROM TABLE WHERE ID IN (SELECT ID FROM TABLE WHERE X ORDER BY ID LIMIT 2) ORDER BY ID DESC
</code>```

Title: Mysql select first then limit

Body:
You may use something like

SELECT * FROM TABLE WHERE ID IN (SELECT ID FROM TABLE WHERE X ORDER BY ID LIMIT 2) ORDER BY ID DESC


问:
Correlate ETW file object with DiskIO events
I am trying to understand how to make ETW tracing work reliably.  The problem I am having is that I do not consistently receive the FileIo rundown or name events that I need in order to correlate file names with DiskIo events at the driver level.  I am using realtime event tracing.  I have studied the statistics coming back from ETW at the end of a session and I do not appear to be dropping events (EventsLost and RealTimeBuffersLost are always zero).  In some cases, I receive the FileName/FileRundown events and in others I do not.

I have found some useful information in this thread: How to determine the file name involved in an IO operation using windows etw tracing?.  There I found some links to the source code for ProcessHacker (http://processhacker.sourceforge.net/doc/etwmon_8c_source.html).  Studying the ProcessHacker code, I see a couple of differences with how I am setting up event tracing.  I wonder if these differences are leading to my issues?

First, ProcessHacker sets up two trace sessions.  One receives the bulk of the desired ETW events (FileIo, DiskIo, NetworkIo).  The other only looks for FileRundown events.  In my application, I use one trace session to catch everything.  An interesting thing I notice about the EVENT_TRACE_PROPERTIES used for the rundown session is that it does not specify any EnableFlags.  The "main" session uses the flags that I would expect (DISK_IO, FILE_IO, NETWORK_TCPIP).

Second, ProcessHacker uses the newer "EventRecord" callback instead of the old "EventTrace" callbacks.  My app is using the "old" EventTrace callback.  This selection is made by specifying PROCESS_TRACE_MODE_EVENT_RECORD in the EVENT_TRACE_LOGFILE structure.

Would either of these differences lead to the behavior I am seeing?

答:
I answered my own question.  The key was the first difference I pointed out.  I split the event handling tasks between two threads instead of trying to handle everything in a single thread.  So, now I direct FileIo, DiskIo and Image events to one thread and FileCreate, FileRundown and FileName events to another.  This solved the issue.

This suggests that I was dropping ETW events somewhere along the chain.  Yet the ETW session statistics do not report this fact (EventsLost RealTimeEventsLost and BuffersLost are all zero).

I guess it should be obvious, but performance is critical when trying to process large volumes (millions) of ETW events.  In my case, I am listening to the events at the Driver level (DriverCall, DriverComplete, etc.).  This ramps up the volume of events and seems to exacerbate the issue I was seeing.

I ran some simple experiments before resolving this.  In the experiment, I disabled the Driver level events.  In this case, a single threaded event processor was able to keep up with the DiskIo events and the FileName events.  As soon as I turn the Driver events back on I get back to the state where I do not reliably receive FileName events.


问:
How to assign a method to an existing struct object
I was wondering if doing something like this in Go is even possible.

```<code>type MyStruct struct {
    id int
}

func (ms *MyStruct) PrintHello() {
    fmt.Printf("Hello from original method %v", ms.id)
}

func main() {
    fmt.Println("Hello, playground")
    m := MyStruct{}
    m.PrintHello()

    m.PrintHello = func() {fmt.Printf("Hello from newer method 2")}
}

Error: cannot assign to m.PrintHello
</code>```

https://play.golang.org/p/2oJQFFH4O5

Sorry if this doesn't make sense for Go programmers, I am new to Go and wondering if some of the things that can be done in dynamically typed languages can be done in Go.

答:
Given that Go is a statically typed language, you cannot do this specific piece of code. However, functions are variables, so you CAN do something like this. Just remember that this is technically NOT the same as assigning a new method, as JimB states in the comments.

https://play.golang.org/p/rfuCzXD8fP

```<code>package main

import (
    "fmt"
)

type MyStruct struct {
    id         int
    PrintHello func(ms * MyStruct)
}

func (ms *MyStruct) init() {
    ms.PrintHello = func(ms *MyStruct) { fmt.Printf("Hello from original method %v\n", ms.id) }
}

func main() {
    m := &MyStruct{id: 42}
    m.init()
    m.PrintHello(m)

    m.PrintHello = func(ms *MyStruct) { fmt.Printf("Hello from newer method 2 %d\n", ms.id) }
    m.PrintHello(m)
}
</code>```

Because this function is not really a method, you can only access the internal struct values by passing it as an argument. This means that if this ever has to cross package boundaries, unexported values will not be available.

It is also important to note that the function type needs to be the same. So if you defined the function as PrintHello func(ms * MyStruct) error in the struct, you would need to assign a function that returns an error.

Body:
I was wondering if doing something like this in Go is even possible.

type MyStruct struct {
    id int
}

func (ms *MyStruct) PrintHello() {
    fmt.Printf("Hello from original method %v", ms.id)
}

func main() {
    fmt.Println("Hello, playground")
    m := MyStruct{}
    m.PrintHello()

    m.PrintHello = func() {fmt.Printf("Hello from newer method 2")}
}

Error: cannot assign to m.PrintHello

https://play.golang.org/p/2oJQFFH4O5

Sorry if this doesn't make sense for Go programmers, I am new to Go and wondering if some of the things that can be done in dynamically typed languages can be done in Go.

Body:
Given that Go is a statically typed language, you cannot do this specific piece of code. However, functions are variables, so you CAN do something like this. Just remember that this is technically NOT the same as assigning a new method, as JimB states in the comments.

https://play.golang.org/p/rfuCzXD8fP

package main

import (
    "fmt"
)

type MyStruct struct {
    id         int
    PrintHello func(ms * MyStruct)
}

func (ms *MyStruct) init() {
    ms.PrintHello = func(ms *MyStruct) { fmt.Printf("Hello from original method %v\n", ms.id) }
}

func main() {
    m := &MyStruct{id: 42}
    m.init()
    m.PrintHello(m)

    m.PrintHello = func(ms *MyStruct) { fmt.Printf("Hello from newer method 2 %d\n", ms.id) }
    m.PrintHello(m)
}

Because this function is not really a method, you can only access the internal struct values by passing it as an argument. This means that if this ever has to cross package boundaries, unexported values will not be available.

It is also important to note that the function type needs to be the same. So if you defined the function as PrintHello func(ms * MyStruct) error in the struct, you would need to assign a function that returns an error.


问:
Rename method in class body
Is it possible to rename method in Python?
Something like this

```<code>class Validation(unittest.TestCase):

    def __init__(self, methodName='runTest'):
        super(Validation, self).__init__(methodName)
        #Doesn't work
        setattr(self,'do_folders_equal','test_do_folders_equal')
</code>```

Rename method 'do_folders_equal' to 'test_do_folders_equal'..
 Usage above , obviously, is incorrect...How to do this hack?

答:
You wouldn't rename it, you'd just assign it to another variable:

class Validation(unittest.TestCase):

```<code>def __init__(self, methodName='runTest'):
    super(Validation, self).__init__(methodName)
    self.test_do_folders_equal = self.do_folders_equal
</code>```

However there can sometimes be some weird interplay with inherited methods etc, so it sort of depends what you are trying to do.  Not sure how this behaves on old-style classes either...

EDIT: Or using a name read at runtime:

class Validation(unittest.TestCase):

```<code>def __init__(self, methodName='runTest'):
    super(Validation, self).__init__(methodName)
    setattr(self, 'test_do_folders_equal', getattr(self, 'do_folders_equal'))
</code>```

Title: Rename method in class body

Body:
Is it possible to rename method in Python?
Something like this

class Validation(unittest.TestCase):

    def __init__(self, methodName='runTest'):
        super(Validation, self).__init__(methodName)
        #Doesn't work
        setattr(self,'do_folders_equal','test_do_folders_equal')

Rename method 'do_folders_equal' to 'test_do_folders_equal'..
 Usage above , obviously, is incorrect...How to do this hack?

Body:
You wouldn't rename it, you'd just assign it to another variable:

class Validation(unittest.TestCase):

def __init__(self, methodName='runTest'):
    super(Validation, self).__init__(methodName)
    self.test_do_folders_equal = self.do_folders_equal

However there can sometimes be some weird interplay with inherited methods etc, so it sort of depends what you are trying to do.  Not sure how this behaves on old-style classes either...

EDIT: Or using a name read at runtime:

class Validation(unittest.TestCase):

def __init__(self, methodName='runTest'):
    super(Validation, self).__init__(methodName)
    setattr(self, 'test_do_folders_equal', getattr(self, 'do_folders_equal'))


问:
Define a pointer with an arbitrary span
If I have a large array where the data streams are interleaved in some complex fashion, can I define a pointer p such that p + 1 is some arbitrary offset b bytes.

For example lets say I have 1,000,000 ints, 4 bytes each.

```<code>int* p_int = my_int_array;
</code>```

This gives me *(p_int+1) == my_int_array[1] (moves 4 bytes)

I am looking for something like

```<code>something_here(b)* big_span_p_int = my_int_array;
</code>```

which would make *(big_span_p_int + 1) == my_int_array[b] (moves 4*b or b bytes, whichever is possible or easier)

Is this possible? easy?

Thanks for the help.

EDIT:

b is compile time variable.

答:
If b is a constant expression (a compile-time constant), then pointer declared as

```<code>int (*big_span_p_int)[b]
</code>```

will move by b * sizeof(int) bytes every time you increment it.

In C you can use a run-time value in place of b, but since your question is tagged [C++], this is not applicable.

Title: Define a pointer with an arbitrary span

Body:
If I have a large array where the data streams are interleaved in some complex fashion, can I define a pointer p such that p + 1 is some arbitrary offset b bytes.

For example lets say I have 1,000,000 ints, 4 bytes each.

int* p_int = my_int_array;

This gives me *(p_int+1) == my_int_array[1] (moves 4 bytes)

I am looking for something like

something_here(b)* big_span_p_int = my_int_array;

which would make *(big_span_p_int + 1) == my_int_array[b] (moves 4*b or b bytes, whichever is possible or easier)

Is this possible? easy?

Thanks for the help.

EDIT:

b is compile time variable.

Body:
If b is a constant expression (a compile-time constant), then pointer declared as

int (*big_span_p_int)[b]

will move by b * sizeof(int) bytes every time you increment it.

In C you can use a run-time value in place of b, but since your question is tagged [C++], this is not applicable.


问:
Deadlock issue in neo4j while updating the relationship by multiple thread
I have two nodes called Member and Content and both are related in n:n way with relationship HAS_RECOMMENDED (Member -[:HAS_RECOMMENDED] -> Content). One member can have multiple recommended contents and one content can be recommended by multiple members.

When I am creating the graph and relationship from java using multiple threads, I am getting below error:

org.springframework.dao.ConcurrencyFailureException: Error executing
  Cypher "Neo.TransientError.Transaction.DeadlockDetected"; Code:
  Neo.TransientError.Transaction.DeadlockDetected; Description:
  LockClient[1604184] can't wait on resource RWLock[NODE(63575),
  hash=2083848996] since => LockClient[1604184] <-[:HELD_BY]-
  RWLock[NODE(63663), hash=1735956338] <-[:WAITING_FOR]-
  LockClient[1604182] <-[:HELD_BY]- RWLock[NODE(63575),
  hash=2083848996]; nested exception is
  org.neo4j.ogm.exception.CypherException: Error executing Cypher
  "Neo.TransientError.Transaction.DeadlockDetected"; Code:
  Neo.TransientError.Transaction.DeadlockDetected; Description:
  LockClient[1604184] can't wait on resource RWLock[NODE(63575),
  hash=2083848996] since => LockClient[1604184] <-[:HELD_BY]-
  RWLock[NODE(63663), hash=1735956338] <-[:WAITING_FOR]-
  LockClient[1604182] <-[:HELD_BY]- RWLock[NODE(63575), hash=2083848996]

答:
When a relationship is created, its endpoint nodes are write-locked. If multiple threads attempt to create relationships involving the same set of endpoint nodes, deadlocks can occur, as you are experiencing.

If you can have each thread work on its own set of endpoint nodes (not shared by any other thread), then you should be able to avoid these kind of deadlocks.


问:
Database choice for crawled page semantics
I'm not sure whether this question has already been asked in the past.
I'm writing a webcrawler, intended to extract information from multiple websites for promotions,prices and product descriptions.

Which database choice would be ideal to do an in memory comparison on the data of promotions and prices, based on identification of the same product from multiple websites.

I know the design is going to be complex for the Scraper, HTMLDataProcessor and Storage for wrangling. But, I'm looking for a solve for the data layer choice.

Appreciate the help on this.

答:
I'd suggest first you create your object model or Entity relationship diagram for all the entities.(a.k.a ER diagram)

For instance you can see the tutorial here: http://creately.com/blog/diagrams/er-diagrams-tutorial/

Once you have the diagram and relationships between your entity then you can make a choice of whether you need relational database or not.

You need to answer question like:

Do you care about FK (foreign key) constraints?

What is the most common query and do you care about it's performance?

Is an in-memory database sufficient or do you need data to be persisted?

Think along those lines.


问:
C-Lomuto Quicksort Exe does not work
```<code>#include <stdio.h>
#define ARRAY_SIZE 10

void lomuto (int A[], int l, int r, int smallerAtLeft)
{
    if (smallerAtLeft == 1) //move elements smaller than pivot to the left and the greater ones to the right
    {
        int tmp, tmp2,pivot,i,j;
        pivot = A[r];
        i = l-1;
        for (j =0; j<r-1; j++)
        {
            if (A[j] <= pivot)
            {
                i++;
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }
        tmp2 = A[i+1];
        A[i+1] = A[r];
        A[r] = tmp2;
     }

     if (smallerAtLeft == 0) //move elements smaller than pivot to the right and the greater ones to the left
     {
        int tmp3, tmp4,pivot,i,j;
        pivot = A[r];
        i = l-1;
        for (j=0; j<r-1; j++)
        {
            if (A[j]>= pivot)
            {
                i++;
                tmp3 = A[i];
                A[i] = A[j];
                A[j] = tmp3;
            }
        }
        tmp4 = A[i+1];
        A[i+1] = A[r];
        A[r] = tmp4;
    }

}
void quicksort (int A[], int l, int r, int ascending)
{
    lomuto (A,l,r,ascending);
}

int main()
{
    int testarray;
    int testArray[ARRAY_SIZE] = {4, 2, 5, 3, 6, 7, 8, 1, 0};
    quicksort (testarray,0,8,1);
    return testarray;
}
</code>```

Good evening.
Usually I search almost every forum and deepest threads for dubiety in my codes.
But this time I did not found an answer that could help me. I would be so thankful if anyone could tell my why the code-exe stops working but during compiling there is no error showing onscreen.
We have to implement the quicksort algorithm with the lomuto-partitioning. If the variable "smallerAtLeft" ist equal to 1, the array should be ordered by an increasing property and if its equal to 0 decreasingly.

Furthermore we have to implement to void functions like you see in the code. The "lomuto-fct" and the "quicksort-fct" that contains the lomuto one.

Maybe this Reverse-Lomuto-Thread will help some other people too in the future..

答:
I don't think you understand what the return value from main is and what it's used for. It is usually an indicator of success and failure, with the typical values 0 for success and a small positive value for failure. There are even macros defined for this purpose in the <stdlib.h> header file: EXIT_SUCCESS and EXIT_FAILURE.

If you want to see the sorted array you need to print it:

```<code>printf("Sorted array = {");
for (unsigned i = 0; i < ARRAY_SIZE; ++i)
{
    printf(" %d", testArray[i]);
}
printf(" }\n");
</code>```

That of course requires you to pass the actual array to your sorting function.

Title: C-Lomuto Quicksort Exe does not work

Body:
#include <stdio.h>
#define ARRAY_SIZE 10

void lomuto (int A[], int l, int r, int smallerAtLeft)
{
    if (smallerAtLeft == 1) //move elements smaller than pivot to the left and the greater ones to the right
    {
        int tmp, tmp2,pivot,i,j;
        pivot = A[r];
        i = l-1;
        for (j =0; j<r-1; j++)
        {
            if (A[j] <= pivot)
            {
                i++;
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }
        tmp2 = A[i+1];
        A[i+1] = A[r];
        A[r] = tmp2;
     }

     if (smallerAtLeft == 0) //move elements smaller than pivot to the right and the greater ones to the left
     {
        int tmp3, tmp4,pivot,i,j;
        pivot = A[r];
        i = l-1;
        for (j=0; j<r-1; j++)
        {
            if (A[j]>= pivot)
            {
                i++;
                tmp3 = A[i];
                A[i] = A[j];
                A[j] = tmp3;
            }
        }
        tmp4 = A[i+1];
        A[i+1] = A[r];
        A[r] = tmp4;
    }

}
void quicksort (int A[], int l, int r, int ascending)
{
    lomuto (A,l,r,ascending);
}

int main()
{
    int testarray;
    int testArray[ARRAY_SIZE] = {4, 2, 5, 3, 6, 7, 8, 1, 0};
    quicksort (testarray,0,8,1);
    return testarray;
}

Good evening.
Usually I search almost every forum and deepest threads for dubiety in my codes.
But this time I did not found an answer that could help me. I would be so thankful if anyone could tell my why the code-exe stops working but during compiling there is no error showing onscreen.
We have to implement the quicksort algorithm with the lomuto-partitioning. If the variable "smallerAtLeft" ist equal to 1, the array should be ordered by an increasing property and if its equal to 0 decreasingly.

Furthermore we have to implement to void functions like you see in the code. The "lomuto-fct" and the "quicksort-fct" that contains the lomuto one.

Maybe this Reverse-Lomuto-Thread will help some other people too in the future..

Body:
I don't think you understand what the return value from main is and what it's used for. It is usually an indicator of success and failure, with the typical values 0 for success and a small positive value for failure. There are even macros defined for this purpose in the <stdlib.h> header file: EXIT_SUCCESS and EXIT_FAILURE.

If you want to see the sorted array you need to print it:

printf("Sorted array = {");
for (unsigned i = 0; i < ARRAY_SIZE; ++i)
{
    printf(" %d", testArray[i]);
}
printf(" }\n");

That of course requires you to pass the actual array to your sorting function.


问:
Obtaining the Build ID in a Java Application
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime? </p>

<p>Building from within Eclipse, all I need is the ID, I can then pass it up to the title.  </p>

答:
If you want to use a timestamp for the build, you can obtain that from the jar or class modifation dates or the MANIFEST file.

Maven populates a MANIFEST file with the module version number in the jar. You can read this to obtain the version of all the maven modules you are using.

Making the timestamp part of the "unique id" ensures every build has a different id.

Body:
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime?

Building from within Eclipse, all I need is the ID, I can then pass it up to the title.


问:
Creating a new file using a variable in python
The code that I am currently using is this:

```<code>date = time.strftime("%d/%m/%y")
filename = ('attendence{}' + str(date) +'.txt')
f = open(filename, 'w+')
</code>```

However, the error I receive is this:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'attendence{}31/03/17.txt'
</code>```

The error is not with other parts of my code as this will work.

```<code>f = open('attendence{}.txt', 'w+')
</code>```

my end goal is to create a new file that contains the current date.

答:
The problem is with the date format :

```<code>date = time.strftime("%d/%m/%y")
</code>```

You could try :

```<code>date = time.strftime("%d_%m_%y")
</code>```

'attendence{}31/03/17.txt' isn't just a filename, it's a relative path with :

1 folder : 'attendence{}31'

1 subfolder : '03'

1 filename '17.txt'.

Python is complaining that the folder 'attendence{}31/03' doesn't exist.

Note that {} might confuse the system, some programs or some users. If there's no information inside the curly brackets, you might as well remove them.

Body:
The code that I am currently using is this:

date = time.strftime("%d/%m/%y")
filename = ('attendence{}' + str(date) +'.txt')
f = open(filename, 'w+')

However, the error I receive is this:

FileNotFoundError: [Errno 2] No such file or directory: 'attendence{}31/03/17.txt'

The error is not with other parts of my code as this will work.

f = open('attendence{}.txt', 'w+')

my end goal is to create a new file that contains the current date.

Body:
The problem is with the date format :

date = time.strftime("%d/%m/%y")

You could try :

date = time.strftime("%d_%m_%y")

'attendence{}31/03/17.txt' isn't just a filename, it's a relative path with :

1 folder : 'attendence{}31'

1 subfolder : '03'

1 filename '17.txt'.

Python is complaining that the folder 'attendence{}31/03' doesn't exist.

Note that {} might confuse the system, some programs or some users. If there's no information inside the curly brackets, you might as well remove them.


问:
find number of repeating substrings in a string
I am looking for an algorithm that will find the number of repeating substrings in a single string.

For this, I was looking for some dynamic programming algorithms but didn't find any that would help me. I just want some tutorial on how to do this.

Let's say I have a string ABCDABCDABCD. The expected output for this would be 3, because there is ABCD 3 times.

For input AAAA, output would be 4, since A is repeated 4 times.

For input ASDF, output would be 1, since every individual character is repeated 1 time only.

I hope that someone can point me in the right direction. Thank you.

答:
How do you want to specify the "repeating string"?  Is it simply the first group of characters up until either a) the first character is found again, b) the pattern begins to repeat, or c) some other criteria?

So, if your string is "ABBAABBA", is that a 2 because "ABBA" repeats twice or is it 1 because you have "ABB" followed by "AAB"?  What about "ABCDABCE" -- does "ABC" count (despite the "D" in between repetitions?)  In "ABCDABCABCDABC", is the repeating string "ABCD" (1) or "ABCDABC" (2)?

What about "AAABBAAABB" -- is that 3 ("AAA") or 2 ("AAABB")?

If the end of the repeating string is another instance of the first letter, it's pretty simple:

Work your way through the string character by character, putting each character into another variable as you go, until the next character matches the first one.  Then, given the length of the substring in your second variable, check the next bit of your string to see if it matches.  Continue until it doesn't match or you hit the end of the string.

If you just want to find any length pattern that repeats regardless of whether the first character is repeated within the pattern, it gets more complicated (but, fortunately, it's the sort of thing computers are good at).

You'll need to go character by character building a pattern in another variable as above, but you'll also have to watch for the first character to reappear and start building a second substring as you go, to see if it matches the first.  This should probably go in an array as you might encounter a third (or more) instance of the first character which would trigger the need to track yet another possible match.

It's not difficult but there is a lot to keep track of and it's a rather annoying problem.  Is there a particular reason you're doing this?


问:
How am I supposed to register a package to PyPI?
In the documentation for packaging and distributing Python packages, it says to use twine with repository = https://upload.pypi.org/legacy/ in .pypirc. Now this URL is both – from the last bit of it – a legacy way to do things, and a non-existing one at that:

```<code>$ twine register dist/scriptdoctest-0.1-py2.py3-none-any.whl
Registering package to https://upload.pypi.org/legacy/
Enter your username: MyUserName
Enter your password:
Registering scriptdoctest-0.1-py2.py3-none-any.whl
HTTPError: 410 Client Error: This API is no longer supported, instead simply upload the file. for url: https://upload.pypi.org/legacy/
</code>```

Is using scriptdoctest.egg-info/PKG-INFO now the preferred and only way to register a package, or is there some other way to do this with twine or some other CLI tool?

答:
Use this repository URL, and it will work repository = https://upload.pypi.org/legacy/.

I guess documentation is a bit out of date since a lot has been happening with packaging including the move to warehouse: https://pypi.org/

Body:
In the documentation for packaging and distributing Python packages, it says to use twine with repository = https://upload.pypi.org/legacy/ in .pypirc. Now this URL is both – from the last bit of it – a legacy way to do things, and a non-existing one at that:

$ twine register dist/scriptdoctest-0.1-py2.py3-none-any.whl
Registering package to https://upload.pypi.org/legacy/
Enter your username: MyUserName
Enter your password:
Registering scriptdoctest-0.1-py2.py3-none-any.whl
HTTPError: 410 Client Error: This API is no longer supported, instead simply upload the file. for url: https://upload.pypi.org/legacy/

Is using scriptdoctest.egg-info/PKG-INFO now the preferred and only way to register a package, or is there some other way to do this with twine or some other CLI tool?


问:
Why can't a server be controlled without a client?
Ok, in all the years servers have existed, you're telling me the best you can do is give me a crappy cron job if I want to make a script run every n seconds on my server? There MUST be a way built into a programming language or something that lets me run a function or script or something at intervals without a client having to send a request to the server. Is there any language that lets you do this? node js? How do big companies do server maintenance then? Why can php listen for requests constantly and webhooks but can't control the very thing it was designed to control without someone else sending a request?</p>

答:
Why can't a server be controlled without a client?

It can. A server may respond to the requests sent by the client but it can also do other things.

Ok, in all the years servers have existed, you're telling me the best you can do is give me a crappy cron job if I want to make a script run every n seconds on my server?

I don't know who said you that but that is simply not true. Even a shell script can do that.

There MUST be a way built into a programming language or something that lets me run a function or script or something at intervals without a client having to send a request to the server.

There must be and there is. See below for examples.

Is there any language that lets you do this?

Yes, there are many such languages. For example JavaScript had setTimeout() and setInterval() since something like 1995.

node js?

Yes, Node.js can do that and many other things. Since you asked specifically about Node.js - here are soem of the modules that you can use  for that:

https://www.npmjs.com/package/pm2

https://www.npmjs.com/package/node-schedule

https://www.npmjs.com/package/cron

https://www.npmjs.com/package/node-cron

https://www.npmjs.com/package/node-cron-job

https://www.npmjs.com/package/node-crontab

https://www.npmjs.com/package/periodic-task

https://www.npmjs.com/package/async-polling

https://www.npmjs.com/package/timeplan

https://www.npmjs.com/package/later

https://www.npmjs.com/package/agenda

In fact there are many more modules that handle scheduled tasks.

How do big companies do server maintenance then?

There are many ways to do that, including the ones mentioned above. Sometimes they use cron, sometimes they use webhooks and other RPC to orchestrate large numbers of servers and initiate various tasks, sometimes the servers are doing it themselves. You can use stream, queue or pub/sub services in some cases to manage more complex scenarios.

Why can php listen for requests constantly and webhooks but can't control the very thing it was designed to control without someone else sending a request?

Because PHP is not a standalone server. You can think of what you write in PHP as a kind of request handlers. And you need requests for the request handlers to, well, handle the requests.

In contrast, programs written in Node are standalone programs that keep running and can do what they want and when they want, and they just happen to respond to requests from the client. PHP scripts, on the other hand, are not standalone long-running programs but they are invoked by a server like Apache or nginx on every request to a specific route that is handled by a specific PHP script, and then the script runs, does its job of serving this single request and finishes, only to be invoked later for another request if it happens.

Now, if you want to have a periodically running PHP script then you can do something like this: put the script on the server, it can respond only to localhost if you want, and test it if it runs every time that you do e.g. a POST request to http://localhost:1234/script.php and if it does you can do few things to make it run every n seconds as you wanted:

(1) You can put curl -X POST http://localhost:1234/script.php in crontab

(2) You can make a shell script like this:

```<code>#!/bin/sh
while true; do
  curl -X POST http://localhost:1234/script.php
  sleep 10
done
</code>```

(3) You can make a Node program like this:

```<code>#!/usr/bin/env node
const request = require('request');
setInterval(() => request.post('http://localhost:1234/script.php'), 10000);
</code>```

(4) You can use any other language that lets you run standalone programs.

This is one way to have a PHP script that you want to be run periodically.

Body:
Why can't a server be controlled without a client?

It can. A server may respond to the requests sent by the client but it can also do other things.

Ok, in all the years servers have existed, you're telling me the best you can do is give me a crappy cron job if I want to make a script run every n seconds on my server?

I don't know who said you that but that is simply not true. Even a shell script can do that.

There MUST be a way built into a programming language or something that lets me run a function or script or something at intervals without a client having to send a request to the server.

There must be and there is. See below for examples.

Is there any language that lets you do this?

Yes, there are many such languages. For example JavaScript had setTimeout() and setInterval() since something like 1995.

node js?

Yes, Node.js can do that and many other things. Since you asked specifically about Node.js - here are soem of the modules that you can use  for that:

https://www.npmjs.com/package/pm2

https://www.npmjs.com/package/node-schedule

https://www.npmjs.com/package/cron

https://www.npmjs.com/package/node-cron

https://www.npmjs.com/package/node-cron-job

https://www.npmjs.com/package/node-crontab

https://www.npmjs.com/package/periodic-task

https://www.npmjs.com/package/async-polling

https://www.npmjs.com/package/timeplan

https://www.npmjs.com/package/later

https://www.npmjs.com/package/agenda

In fact there are many more modules that handle scheduled tasks.

How do big companies do server maintenance then?

There are many ways to do that, including the ones mentioned above. Sometimes they use cron, sometimes they use webhooks and other RPC to orchestrate large numbers of servers and initiate various tasks, sometimes the servers are doing it themselves. You can use stream, queue or pub/sub services in some cases to manage more complex scenarios.

Why can php listen for requests constantly and webhooks but can't control the very thing it was designed to control without someone else sending a request?

Because PHP is not a standalone server. You can think of what you write in PHP as a kind of request handlers. And you need requests for the request handlers to, well, handle the requests.

In contrast, programs written in Node are standalone programs that keep running and can do what they want and when they want, and they just happen to respond to requests from the client. PHP scripts, on the other hand, are not standalone long-running programs but they are invoked by a server like Apache or nginx on every request to a specific route that is handled by a specific PHP script, and then the script runs, does its job of serving this single request and finishes, only to be invoked later for another request if it happens.

Now, if you want to have a periodically running PHP script then you can do something like this: put the script on the server, it can respond only to localhost if you want, and test it if it runs every time that you do e.g. a POST request to http://localhost:1234/script.php and if it does you can do few things to make it run every n seconds as you wanted:

(1) You can put curl -X POST http://localhost:1234/script.php in crontab

(2) You can make a shell script like this:

#!/bin/sh
while true; do
  curl -X POST http://localhost:1234/script.php
  sleep 10
done

(3) You can make a Node program like this:

#!/usr/bin/env node
const request = require('request');
setInterval(() => request.post('http://localhost:1234/script.php'), 10000);

(4) You can use any other language that lets you run standalone programs.

This is one way to have a PHP script that you want to be run periodically.


问:
Django Admin linking to related objects
My app has users who create pages. In the Page screen of the admin, I'd like to list the User who created the page, and in that list, I'd like the username to have a link that goes to the user page in admin (not the Page).

```<code>class PageAdmin(admin.ModelAdmin):
    list_display = ('name', 'user', )
    list_display_links = ('name','user',)
admin.site.register(Page, PageAdmin)
</code>```

I was hoping that by making it a link in the list_display it would default to link to the actual user object, but it still goes to Page.

I'm sure I'm missing something simple here.

答:
I needed this for a lot of my admin pages, so I created a mixin for it that handles different use cases:

pip install django-admin-relation-links
```
<p>Then:</p>
<pre class="lang-py prettyprint-override"><code>from django.contrib import admin
from django_admin_relation_links import AdminChangeLinksMixin

@admin.register(Group)
class MyModelAdmin(AdminChangeLinksMixin, admin.ModelAdmin):

    # ...

    change_links = ['field_name']
</code>```

See the GitHub page for more info. Try it out and let me know how it works out!

https://github.com/gitaarik/django-admin-relation-links

Title: Django Admin linking to related objects

Body:
My app has users who create pages. In the Page screen of the admin, I'd like to list the User who created the page, and in that list, I'd like the username to have a link that goes to the user page in admin (not the Page).

class PageAdmin(admin.ModelAdmin):
    list_display = ('name', 'user', )
    list_display_links = ('name','user',)
admin.site.register(Page, PageAdmin)

I was hoping that by making it a link in the list_display it would default to link to the actual user object, but it still goes to Page.

I'm sure I'm missing something simple here.

Body:
I needed this for a lot of my admin pages, so I created a mixin for it that handles different use cases:

pip install django-admin-relation-links

Then:

from django.contrib import admin
from django_admin_relation_links import AdminChangeLinksMixin

@admin.register(Group)
class MyModelAdmin(AdminChangeLinksMixin, admin.ModelAdmin):

    # ...

    change_links = ['field_name']

See the GitHub page for more info. Try it out and let me know how it works out!

https://github.com/gitaarik/django-admin-relation-links


问:
Build Application to Answer Phone Call and Delegate To iPhone's Phone Application
We want to build an application that the user can interact with while taking a phone call.  The idea is that the user can do voice communication using the phone application of the iPhone and at the same time use our application to type and send additional data that is relevant to the call such as an e-mail address.  This is the scenario:

User get's a call on the iPhone

The user clicks a button on our app to answer the call and let the phone application on the iPhone handle the phone call in the background.

Our application continues to run in the foreground so that the user can interact with our application to type and send data such as an e-mail address that is relevant to the call.

Is there a way for our application to answer an incoming phone call and let the phone application of the iPhone handle the call in the background while our application continues to run in the foreground?

Thanks,
Prasanna

答:
This is not possible with the iPhone SDK.

You could possibly do this if you created your own calling (for example, like Skype does) but I'd say you're barking up the wrong iTree here. It is however possible on jail-broken devices using the custom toolchain but I wouldn't want to recommend that path for development!


问:
How to get only specified item of list?
I extract the following data from database with the following MySql Query:

```<code>SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value
FROM vista_struttura AS vs
LEFT JOIN vista_struttura_attributi AS vsa
    ON vs.id_vista_struttura = vsa.id_vista_struttura
LEFT JOIN vista_struttura_attributi_raccordi AS vsar
    ON vsa.input_type = vsar.input_type
ORDER BY vs.sort;
</code>```

Data extracted are

I have to save this data in a model built from myself with the following code:

```<code>var model = new List<Header>();
using (var connection = new MySqlConnection(connectionString))
{
    connection.Open();
    var sql =   "SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value " +
                "FROM vista_struttura AS vs " +
                "LEFT JOIN vista_struttura_attributi AS vsa " +
                    "ON vs.id_vista_struttura = vsa.id_vista_struttura " +
                "LEFT JOIN vista_struttura_attributi_raccordi AS vsar " +
                    "ON vsa.input_type = vsar.input_type " +
                "ORDER BY vs.sort";
    var cmd = new MySqlCommand(sql, connection);
    var rdr = cmd.ExecuteReader();

    var rows = new List<ViewProperties>();

    while (rdr.Read())
    {
        var value = rdr[0].ToString();
        var isHeader = Convert.ToBoolean(rdr[1]);
        var isRequired = (rdr[2] == DBNull.Value) ? (bool?) null : Convert.ToBoolean(rdr[2]);
        var name = rdr[3].ToString();
        var inputType = rdr[4].ToString();

        var properties = new ViewProperties()
        {
            Value = value,
            IsHeader = isHeader,
            IsRequired = isRequired,
            Name = name,
            InputType = inputType
        };

        rows.Add(properties);

        var header = new Header()
        {
            HeaderValue = (properties.IsHeader == true) ? properties.Value : null,
            Rows = rows
        };
        if (header.HeaderValue != null)
        {
            model.Add(header);
        }

    }
}
</code>```

Models

Header

```<code>public class Header
{
    public string HeaderValue { get; set; }
    public IList<ViewProperties> Rows { get; set; }
}
</code>```

ViewProperties

```<code>public class ViewProperties
{
    public string Value { get; set; }
    public bool IsHeader { get; set; }
    public bool? IsRequired { get; set; }
    public string Name { get; set; }
    public string InputType { get; set; }
}
</code>```

Debugging the app I get a wrong model, not such as I want...

I want to get first 4 rows for first header and the other last 3 rows for the second header.

How can i do?

What's better to do: before get this model and then handle it with linq, or get already correct model?

Thanks

答:
You need the following code for the desired result, make the necessary modifications:</p>

```<code>var rows = new List<ViewProperties>();  // ViewProperties List

// Segregate null value, GroupBy to aggregate using Value
var viewPropertiesGrouping = rows.Where(x => x.IsHeader)
                                 .GroupBy(x => x.Value);

// Traverse through IEnumerable<IGrouping<string,ViewProperties>>, created above and fill the Header object and add to the Model

foreach (var prop in viewPropertiesGrouping)
{
    Header header  = new Header();
    header.HeaderValue = prop.Key;
    header.Rows = prop.Select(y => y).ToList();
    model.Add(header);
}
</code>```

Title: How to get only specified item of list?

Body:
I extract the following data from database with the following MySql Query:

SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value
FROM vista_struttura AS vs
LEFT JOIN vista_struttura_attributi AS vsa
    ON vs.id_vista_struttura = vsa.id_vista_struttura
LEFT JOIN vista_struttura_attributi_raccordi AS vsar
    ON vsa.input_type = vsar.input_type
ORDER BY vs.sort;

Data extracted are

I have to save this data in a model built from myself with the following code:

var model = new List();
using (var connection = new MySqlConnection(connectionString))
{
    connection.Open();
    var sql =   "SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value " +
                "FROM vista_struttura AS vs " +
                "LEFT JOIN vista_struttura_attributi AS vsa " +
                    "ON vs.id_vista_struttura = vsa.id_vista_struttura " +
                "LEFT JOIN vista_struttura_attributi_raccordi AS vsar " +
                    "ON vsa.input_type = vsar.input_type " +
                "ORDER BY vs.sort";
    var cmd = new MySqlCommand(sql, connection);
    var rdr = cmd.ExecuteReader();

    var rows = new List<ViewProperties>();

    while (rdr.Read())
    {
        var value = rdr[0].ToString();
        var isHeader = Convert.ToBoolean(rdr[1]);
        var isRequired = (rdr[2] == DBNull.Value) ? (bool?) null : Convert.ToBoolean(rdr[2]);
        var name = rdr[3].ToString();
        var inputType = rdr[4].ToString();

        var properties = new ViewProperties()
        {
            Value = value,
            IsHeader = isHeader,
            IsRequired = isRequired,
            Name = name,
            InputType = inputType
        };

        rows.Add(properties);

        var header = new Header()
        {
            HeaderValue = (properties.IsHeader == true) ? properties.Value : null,
            Rows = rows
        };
        if (header.HeaderValue != null)
        {
            model.Add(header);
        }

    }
}

Models

Header

public class Header
{
    public string HeaderValue { get; set; }
    public IList<ViewProperties> Rows { get; set; }
}

ViewProperties

public class ViewProperties
{
    public string Value { get; set; }
    public bool IsHeader { get; set; }
    public bool? IsRequired { get; set; }
    public string Name { get; set; }
    public string InputType { get; set; }
}

Debugging the app I get a wrong model, not such as I want...

I want to get first 4 rows for first header and the other last 3 rows for the second header.

How can i do?

What's better to do: before get this model and then handle it with linq, or get already correct model?

Thanks

Body:
You need the following code for the desired result, make the necessary modifications:

var rows = new List<ViewProperties>();  // ViewProperties List

// Segregate null value, GroupBy to aggregate using Value
var viewPropertiesGrouping = rows.Where(x => x.IsHeader)
                                 .GroupBy(x => x.Value);

// Traverse through IEnumerable<IGrouping<string,ViewProperties>>, created above and fill the Header object and add to the Model

foreach (var prop in viewPropertiesGrouping)
{
    Header header  = new Header();
    header.HeaderValue = prop.Key;
    header.Rows = prop.Select(y => y).ToList();
    model.Add(header);
}


问:
What are the necessary special member functions that should to be declared?
I am currently learning about C++. I learnt about some special member functions which are generated by the compiler.

• Default constructor. • Copy constructor • Move Constructor • Copy assignment operator • Move assignment operator • Destructor

I know about the functionalities of each member function. But I wanna know which of these member function are necessary and should be declared (instead of being generated by the compiler), as a part of good coding practices, keeping memory and efficiency in mind.

答:
But I wanna which of these member function are necessary and should be declared (instead of being generated by the compiler)

If the implicitly generated special member functions do what you intend, then none of them should be declared explicitly.

If some of the otherwise generated special member functions do not do what you intend, then you must declare them explicitly, and provide the implementation that you need.

If you have an explicit non-trivial definition for any of [destructor, copy/move constructor/assignment], then as a rule of thumb, you probably need a definition for each of them.


问:
Create a one-sided distance map
I create with this code a black square of zeros with a white vertical line of ones at the middle and I want to create a distance map with respect to this line but only at the left side of the vertical line. How can I do this? </p>

<p>The following code yields a distance map on both sides of the line. </p>

```<code>c=zeros(500,500);
c(:,250)=1;
figure, imshow(c)

[D, idx]= bwdist(c,'euclidean')
</code>```

答:
Actually, this question could have been asked in a different and challenging way. What if I had a different input shape (not a single column line) and what if I wanted to find the distance map in a specific angle interval(not just the left side). Here is my solution. Find the (x,y) coordinates of the input shape and then for each of the pixel find a mask in a specific direction + direction interval. Here is the function.

```<code>function mask = directional_mask(im, mainDirection, dirInterval)

% im: BW input image
% mainDirection : mask direction (in degrees)
% dirInterval:  mask direction interval (from dirMask-dirInterval to dirMask+dirInterval)

[Ys, Xs] = find(im);

[sizeX, sizeY] = size(im);

[X, Y] = meshgrid(1:sizeX,1:sizeY);

mask = im * 0;

for i = 1 : numel(Xs)

    refX = Xs(i);
    refY = Ys(i);

    [theta, ~] = cart2pol(X-refX, Y-refY);

    % adding pi/2 so that north angle is 0 degree
    dirmat = wrapTo2Pi(theta + pi/2);
    dirmat = rad2deg(dirmat);

    % upper and lower direction intervals
    thetaUp = mainDirection + dirInterval;
    thetaDown = mainDirection - dirInterval;

    dirmat2 = dirmat(:);

    % finding indices of the angle intervals
    thetas = [thetaUp, thetaDown];
    if thetaUp >= 360
        thetaUp = thetas(1) - 360;
        thetaDown = thetas(2);
        dirmat2((dirmat2>thetaUp) & (dirmat2<thetaDown)) = nan;
    elseif thetaDown < 0
        thetaUp = thetas(1);
        thetaDown = thetas(2) + 360;
        dirmat2((dirmat2>thetaUp) & (dirmat2<thetaDown)) = nan;
    else
        dirmat2((dirmat2>thetaUp) | (dirmat2<thetaDown)) = nan;
    end

    % final mask
    tmp = im*0;
    tmp(~isnan(dirmat2)) = 1;

    mask = mask | tmp;

end

mask = double(mask);
</code>```

Then let's say I have an input image like the one below and I want to calculate the distance map towards 45 degrees.

```<code>im=zeros(100);
for i=35:65; im(i,i)=1; end
im2=imrotate(im,60); im=imresize(im2,size(im)); im=im~=0;

mainDirection = 45;
dirInterval = 5;
[mask] = directional_mask(im, mainDirection, dirInterval);

% original distance map
d = bwdist(im);

% directional distance map
d2 = mask.*d;

figure;
subplot(131); imagesc(mask+2*im), axis image; colorbar; title('Mask + Orig. Input')
subplot(132); imagesc(d), axis image;  colorbar; title('Initial Distance Map')
subplot(133); imagesc(d2), axis image;  colorbar; title('Directional Distance Map')
set(findall(gcf,'-property','FontSize'),'FontSize',16)
</code>```

Let's say I wanted the distance map towards 180 degrees. Just change the "mainDirection"

```<code>mainDirection = 180;
</code>```

Let's try it on different shapes.

```<code>im=zeros(100);
im(40:60,40:60)=1; im2=imrotate(im,30);im=imresize(im2,size(im)); im=im~=0;

mainDirection = 180;
dirInterval = 5;
</code>```

If you want a mask in a specific direction interval (theta+-interval), just change the "dirInterval". Here is an example

```<code>mainDirection = 180;
dirInterval = 30;
</code>```

In the original question, @Mac wanted to mask the distance map towards the left side. Then:

```<code>im=zeros(100); im(:,50)=1;

mainDirection = 270;
dirInterval = 90;
</code>```

Title: Create a one-sided distance map

Body:
I create with this code a black square of zeros with a white vertical line of ones at the middle and I want to create a distance map with respect to this line but only at the left side of the vertical line. How can I do this?

The following code yields a distance map on both sides of the line.

c=zeros(500,500);
c(:,250)=1;
figure, imshow(c)

[D, idx]= bwdist(c,'euclidean')

Body:
Actually, this question could have been asked in a different and challenging way. What if I had a different input shape (not a single column line) and what if I wanted to find the distance map in a specific angle interval(not just the left side). Here is my solution. Find the (x,y) coordinates of the input shape and then for each of the pixel find a mask in a specific direction + direction interval. Here is the function.

function mask = directional_mask(im, mainDirection, dirInterval)

% im: BW input image
% mainDirection : mask direction (in degrees)
% dirInterval:  mask direction interval (from dirMask-dirInterval to dirMask+dirInterval)

[Ys, Xs] = find(im);

[sizeX, sizeY] = size(im);

[X, Y] = meshgrid(1:sizeX,1:sizeY);

mask = im * 0;

for i = 1 : numel(Xs)

    refX = Xs(i);
    refY = Ys(i);

    [theta, ~] = cart2pol(X-refX, Y-refY);

    % adding pi/2 so that north angle is 0 degree
    dirmat = wrapTo2Pi(theta + pi/2);
    dirmat = rad2deg(dirmat);

    % upper and lower direction intervals
    thetaUp = mainDirection + dirInterval;
    thetaDown = mainDirection - dirInterval;

    dirmat2 = dirmat(:);

    % finding indices of the angle intervals
    thetas = [thetaUp, thetaDown];
    if thetaUp >= 360
        thetaUp = thetas(1) - 360;
        thetaDown = thetas(2);
        dirmat2((dirmat2>thetaUp) & (dirmat2<thetaDown)) = nan;
    elseif thetaDown < 0
        thetaUp = thetas(1);
        thetaDown = thetas(2) + 360;
        dirmat2((dirmat2>thetaUp) & (dirmat2<thetaDown)) = nan;
    else
        dirmat2((dirmat2>thetaUp) | (dirmat2<thetaDown)) = nan;
    end

    % final mask
    tmp = im*0;
    tmp(~isnan(dirmat2)) = 1;

    mask = mask | tmp;

end

mask = double(mask);

Then let's say I have an input image like the one below and I want to calculate the distance map towards 45 degrees.

im=zeros(100);
for i=35:65; im(i,i)=1; end
im2=imrotate(im,60); im=imresize(im2,size(im)); im=im~=0;

mainDirection = 45;
dirInterval = 5;
[mask] = directional_mask(im, mainDirection, dirInterval);

% original distance map
d = bwdist(im);

% directional distance map
d2 = mask.*d;

figure;
subplot(131); imagesc(mask+2*im), axis image; colorbar; title('Mask + Orig. Input')
subplot(132); imagesc(d), axis image;  colorbar; title('Initial Distance Map')
subplot(133); imagesc(d2), axis image;  colorbar; title('Directional Distance Map')
set(findall(gcf,'-property','FontSize'),'FontSize',16)

Let's say I wanted the distance map towards 180 degrees. Just change the "mainDirection"

mainDirection = 180;

Let's try it on different shapes.

im=zeros(100);
im(40:60,40:60)=1; im2=imrotate(im,30);im=imresize(im2,size(im)); im=im~=0;

mainDirection = 180;
dirInterval = 5;

If you want a mask in a specific direction interval (theta+-interval), just change the "dirInterval". Here is an example

mainDirection = 180;
dirInterval = 30;

In the original question, @Mac wanted to mask the distance map towards the left side. Then:

im=zeros(100); im(:,50)=1;

mainDirection = 270;
dirInterval = 90;


问:
Are there any ajax for PHP like zk or vaadin for java
Are there any frameworks for php that follow the style of vaadin?
In vaadin you can define web forms using java with touching javascript or any client scripting in swing style.</p>

答:
I have been searching for something similar to Vaadin. The only framework I have found is zk, which works with Java.

Anyway, you can develop in ZK using any languages supported by the JVM.


问:
Field validation for URL or IP address
Currently, I found a regex here which seems to do what want, and passes some tests on regex101. However that same expression does not work in angular ng-pattern:

This is the expression:

```<code>/^(http(s?):\/\/)?(((www\.)?+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)$/?
.
</code>```

which produces this error:

```<code>Invalid regular expression: /^(http(s?)://)?(((www.)?+[a-zA-Z0-9.-_]+(.[a-zA-Z]{2,3})+)|((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0…){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))(/[a-zA-Z0-9_-s./?%#&=]*)?$/: Nothing to repeat
.
</code>```

Maybe I'm getting too far ahead and dont need a regex for this. Is there something which accommodates for accepting URLs as well as IP addresses?

Title: Field validation for URL or IP address

Body:
Currently, I found a regex here which seems to do what want, and passes some tests on regex101. However that same expression does not work in angular ng-pattern:

This is the expression:

/^(http(s?):\/\/)?(((www\.)?+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)$/?
.

which produces this error:

Invalid regular expression: /^(http(s?)://)?(((www.)?+[a-zA-Z0-9.-_]+(.[a-zA-Z]{2,3})+)|((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0…){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))(/[a-zA-Z0-9_-s./?%#&=]*)?$/: Nothing to repeat
.

Maybe I'm getting too far ahead and dont need a regex for this. Is there something which accommodates for accepting URLs as well as IP addresses?

Body:
Looks like \ disappears, try to use double backslashes like this

^(http(s?):\\/\\/)?(((www\\.)?+[a-zA-Z0-9\\.\\-\\_]+(\\.[a-zA-Z]{2,3})+)|(\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b))(\\/[a-zA-Z0-9\\_\\-\\s\\.\\/\\?\\%\\#\\&\\=]*)?$

It happens due to backslash being interpreted in string as escape character.


问:
Mail() function in Laragon v.2.2.2 - Wrong encoding after sent
I am using Laragon v. 2.2.2 - Development environment

I tried to send mail with polish characters "śćńółęśąśżćźó",
also I added correct headers "Content-type: text/html; charset=UTF-8" and file encoding to mail,
but in sendmail output logs and on gmail, the message looks like:
"L>A?L"AlL,ATL>A.L>LLA?LsAl".

Sendmail output logs:

```<code>17.03.31 16:02:58 ** --- MESSAGE BEGIN ---
17.03.31 16:02:58 ** To: ***@gmail.com
17.03.31 16:02:58 ** Subject: test
17.03.31 16:02:58 ** X-PHP-Originating-Script: 0:index.php
17.03.31 16:02:58 ** Content-type: text/html; charset=UTF-8
17.03.31 16:02:58 **
17.03.31 16:02:58 ** śćńółęśąśżćźó
17.03.31 16:02:58 ** --- MESSAGE END ---

17.03.31 16:02:59 >> Date: Fri, 31 Mar 2017 16:02:59 <EOL>
17.03.31 16:02:59 >> To: ***@gmail.com<EOL>
17.03.31 16:02:59 >> Subject: test<EOL>
17.03.31 16:02:59 >> X-PHP-Originating-Script: 0:index.php<EOL>
17.03.31 16:02:59 >> Content-type: text/html; charset=UTF-8<EOL>
17.03.31 16:02:59 >> <EOL>
17.03.31 16:02:59 >> L>A?L"AlL,ATL>A.L>LLA?LsAl<EOL>
17.03.31 16:02:59 >> .<EOL>
</code>```

PHP Code:

```<code><?php
    mail('***@gmail.com', 'test', 'śćńółęśąśżćźó', "Content-type: text/html; charset=UTF-8");
?>
</code>```

Mails are sent through Laragon email configuration (I am using Gmail)

How to fix that?

答:
Declare all MIME headers including declaration of 8bit encoding.  It should allow your sendmail (SMTP) server conduct conversions required by receiving SMTP server.

Non ASCII characters in email headers require another special encoding (RFC2047).

Due to very ancient tradition emails are expected to contain only 7bit characters by default.

```<code>MIME-Version: 1.0
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 8bit
</code>```

Body:
I am using Laragon v. 2.2.2 - Development environment

I tried to send mail with polish characters "śćńółęśąśżćźó",
also I added correct headers "Content-type: text/html; charset=UTF-8" and file encoding to mail,
but in sendmail output logs and on gmail, the message looks like:
"L>A?L"AlL,ATL>A.L>LLA?LsAl".

Sendmail output logs:

17.03.31 16:02:58 ** --- MESSAGE BEGIN ---
17.03.31 16:02:58 ** To: ***@gmail.com
17.03.31 16:02:58 ** Subject: test
17.03.31 16:02:58 ** X-PHP-Originating-Script: 0:index.php
17.03.31 16:02:58 ** Content-type: text/html; charset=UTF-8
17.03.31 16:02:58 **
17.03.31 16:02:58 ** śćńółęśąśżćźó
17.03.31 16:02:58 ** --- MESSAGE END ---

17.03.31 16:02:59 >> Date: Fri, 31 Mar 2017 16:02:59 <EOL>
17.03.31 16:02:59 >> To: ***@gmail.com<EOL>
17.03.31 16:02:59 >> Subject: test<EOL>
17.03.31 16:02:59 >> X-PHP-Originating-Script: 0:index.php<EOL>
17.03.31 16:02:59 >> Content-type: text/html; charset=UTF-8<EOL>
17.03.31 16:02:59 >> <EOL>
17.03.31 16:02:59 >> L>A?L"AlL,ATL>A.L>LLA?LsAl<EOL>
17.03.31 16:02:59 >> .<EOL>

PHP Code:

<?php
    mail('***@gmail.com', 'test', 'śćńółęśąśżćźó', "Content-type: text/html; charset=UTF-8");
?>

Mails are sent through Laragon email configuration (I am using Gmail)

How to fix that?

Body:
Declare all MIME headers including declaration of 8bit encoding.  It should allow your sendmail (SMTP) server conduct conversions required by receiving SMTP server.

Non ASCII characters in email headers require another special encoding (RFC2047).

Due to very ancient tradition emails are expected to contain only 7bit characters by default.

MIME-Version: 1.0
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 8bit