问:
Send file via socket - buffer size
TL;DR: How do I send (with a single connection) file, its size and its name. All examples in the internet send a file alone.

Server:

```<code>public class Server {
    private static int PORT = 6667;
    private ServerSocket serverSocket;

    public void run() throws IOException {
        System.out.println("Opening server");
        serverSocket = new ServerSocket(PORT);

        while(true) {
            try(Socket incomingSocket = serverSocket.accept()) {
                System.out.println("Accepted connection: " + incomingSocket);
                incomingSocket.setSoTimeout(2000); // Don't let scanner block the thread.

                InputStream inputStream = incomingSocket.getInputStream();
                Scanner scanner = new Scanner(inputStream);

                String command = "";
                if(scanner.hasNextLine())
                    command = scanner.nextLine();

                if(command.equals("update")) {
                    File file = new File("abc.txt");
                    sendFile(incomingSocket, file);
                }
                else {
                    // ...
                    System.out.println("Another command");
                }
            }
        }
    }

    private void sendFile(Socket socket, File file) throws IOException {
        byte[] bytes = new byte[(int)file.length()];
        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        bufferedInputStream.read(bytes, 0, bytes.length);
        OutputStream outputStream = socket.getOutputStream();

        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println(file.length());
        writer.println(file.getName());

        System.out.println("Sending " + file.getName() + "(" + bytes.length + " bytes) to " + socket);
        outputStream.write(bytes, 0, bytes.length);
        outputStream.flush();
        System.out.println("File sent");
    }

    public void stopRunning() {
        try {
            serverSocket.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Client:

```<code>public class Client {
    private static String HOST = "localhost";
    private static int PORT = 6667;

    public void run() throws IOException {
        Socket socket = new Socket(HOST, PORT);
        System.out.println("Connecting...");

        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println("update");      // Example command which will determine what server sends back

        receiveFile(socket);

        socket.close();
    }

    private void receiveFile(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();

        int size = 16384;
        String name = "example.txt";

        Scanner scanner = new Scanner(inputStream);
        size = Integer.parseInt(scanner.next());
        name = scanner.next();

        FileOutputStream fileOutputStream = new FileOutputStream(name);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        byte[] buffer = new byte[size];
        int bytesRead, totalRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
            totalRead += bytesRead;
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        bufferedOutputStream.flush();

        System.out.println("File " + name + " received. " + totalRead + " bytes read");

        bufferedOutputStream.close();
        fileOutputStream.close();
    }
</code>```

I want my server to send a file to the client. It should also include the file's name and its size. Name because it's quite important and the size because I don't want to make a hardcoded buffer with a huge size.

Tried it with the code above. The client's "scanner part"

```<code>Scanner scanner = new Scanner(inputStream);
size = Integer.parseInt(scanner.next());
name = scanner.next();
</code>```

works just okay, but the file is not received. inputStream.read(buffer, 0, buffer.length) never reads the remaining bytes from the stream.

If i comment out the scanner part, the bytes are read correctly(size and name information + file itself)

So, the question is, how do I send it with a single connection? Or should I make 2 separate connections, in the first one asking for size and file name and sending the file in the second one?

答:
Scanner is good for text-based work.

One way to do what you want is using DataInputStream and DataOutputStream. Only one connection is needed:

```<code>public void send(File file, OutputStream os) throws IOException {
    DataOutputStream dos = new DataOutputStream(os);

    // writing name
    dos.writeUTF(file.getName());
    // writing length
    dos.writeLong(file.length());

    // writing file content
    ... your write loop, write to dos

    dos.flush();
}

public void receive(InputStream is) throws IOException {
    DataInputStream dis = new DataInputStream(is);

    String fileName = dis.readUTF();
    long fileSize = dis.readLong();

    // reading file content
    ... your read loop, read from dis
}
</code>```

Title: Send file via socket - buffer size

Body:
TL;DR: How do I send (with a single connection) file, its size and its name. All examples in the internet send a file alone.

Server:

public class Server {
    private static int PORT = 6667;
    private ServerSocket serverSocket;

    public void run() throws IOException {
        System.out.println("Opening server");
        serverSocket = new ServerSocket(PORT);

        while(true) {
            try(Socket incomingSocket = serverSocket.accept()) {
                System.out.println("Accepted connection: " + incomingSocket);
                incomingSocket.setSoTimeout(2000); // Don't let scanner block the thread.

                InputStream inputStream = incomingSocket.getInputStream();
                Scanner scanner = new Scanner(inputStream);

                String command = "";
                if(scanner.hasNextLine())
                    command = scanner.nextLine();

                if(command.equals("update")) {
                    File file = new File("abc.txt");
                    sendFile(incomingSocket, file);
                }
                else {
                    // ...
                    System.out.println("Another command");
                }
            }
        }
    }

    private void sendFile(Socket socket, File file) throws IOException {
        byte[] bytes = new byte[(int)file.length()];
        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        bufferedInputStream.read(bytes, 0, bytes.length);
        OutputStream outputStream = socket.getOutputStream();

        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println(file.length());
        writer.println(file.getName());

        System.out.println("Sending " + file.getName() + "(" + bytes.length + " bytes) to " + socket);
        outputStream.write(bytes, 0, bytes.length);
        outputStream.flush();
        System.out.println("File sent");
    }

    public void stopRunning() {
        try {
            serverSocket.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

Client:

public class Client {
    private static String HOST = "localhost";
    private static int PORT = 6667;

    public void run() throws IOException {
        Socket socket = new Socket(HOST, PORT);
        System.out.println("Connecting...");

        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println("update");      // Example command which will determine what server sends back

        receiveFile(socket);

        socket.close();
    }

    private void receiveFile(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();

        int size = 16384;
        String name = "example.txt";

        Scanner scanner = new Scanner(inputStream);
        size = Integer.parseInt(scanner.next());
        name = scanner.next();

        FileOutputStream fileOutputStream = new FileOutputStream(name);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        byte[] buffer = new byte[size];
        int bytesRead, totalRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
            totalRead += bytesRead;
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        bufferedOutputStream.flush();

        System.out.println("File " + name + " received. " + totalRead + " bytes read");

        bufferedOutputStream.close();
        fileOutputStream.close();
    }

I want my server to send a file to the client. It should also include the file's name and its size. Name because it's quite important and the size because I don't want to make a hardcoded buffer with a huge size.

Tried it with the code above. The client's "scanner part"

Scanner scanner = new Scanner(inputStream);
size = Integer.parseInt(scanner.next());
name = scanner.next();

works just okay, but the file is not received. inputStream.read(buffer, 0, buffer.length) never reads the remaining bytes from the stream.

If i comment out the scanner part, the bytes are read correctly(size and name information + file itself)

So, the question is, how do I send it with a single connection? Or should I make 2 separate connections, in the first one asking for size and file name and sending the file in the second one?

Body:
Scanner is good for text-based work.

One way to do what you want is using DataInputStream and DataOutputStream. Only one connection is needed:

public void send(File file, OutputStream os) throws IOException {
    DataOutputStream dos = new DataOutputStream(os);

    // writing name
    dos.writeUTF(file.getName());
    // writing length
    dos.writeLong(file.length());

    // writing file content
    ... your write loop, write to dos

    dos.flush();
}

public void receive(InputStream is) throws IOException {
    DataInputStream dis = new DataInputStream(is);

    String fileName = dis.readUTF();
    long fileSize = dis.readLong();

    // reading file content
    ... your read loop, read from dis
}


来源: stackexchange

问:
jQuery Array problem
I am trying to create an array images to preload by getting each of the image link in the rel attributes.

I have on a page:

```<code><div id="gallery_thumbs">
  <a><img src="images/image-1-thumb.jpg" rel="images/image-1.jpg" /></a>
  <a><img src="images/image-2-thumb.jpg" rel="images/image-2.jpg" /></a>
  <a><img src="images/image-3-thumb.jpg" rel="images/image-3.jpg" /></a>
  <a><img src="images/image-4-thumb.jpg" rel="images/image-4.jpg" /></a>
</div>
</code>```

When the page loads I need to get all the rel attributes in the #gallery_thumbs a img and append these to an array like so:

```<code>preload([ 'images/image-1.jpg', 'images/image-2.jpg', 'images/image-3.jpg', 'images/image-4.jpg']);
</code>```

Can anyone help?

答:
You can use map function:</p>

```<code>$("img").map(function(i,e) { return $(e).attr('rel');})
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery Array problem

Body:
I am trying to create an array images to preload by getting each of the image link in the rel attributes.

I have on a page:

When the page loads I need to get all the rel attributes in the #gallery_thumbs a img and append these to an array like so:

preload([ 'images/image-1.jpg', 'images/image-2.jpg', 'images/image-3.jpg', 'images/image-4.jpg']);

Can anyone help?

Body:
You can use map function:

$("img").map(function(i,e) { return $(e).attr('rel');})


问:
Understanding CDN - do we actually connect to the origin server too?
TECHNICAL QUESTION --> When connecting to a CDN (eg. cloudflare), does a CDN actually connect to the original shared server when the visitor visits the website? Because if it doesn't connect then probably we don't need to focus that much on the origin server's speed? Or a CDN does rely on the origin's server's speed?

OPTIONS:

1)use CDN + use cheap shared server (eg. Hostgator)

2)upgrade to VPS or even dedicated server, but do NOT use CDN.

3) use CDN + upgrade to VPS / dedicated server

Which option is recommended when you are on budget? My understanding is that there is no need to upgrade the shared server to VPS, the CDN is enough as an upgrade. Or a CDN does rely on the origin's server's speed?

Thanks for any technical insights!

答:
CDN's connect to the origin server to grab static resources the first time. That's images, scripts, stylesheets, fonts, video, etc. They are then stored on the edge servers and future requests don't go to your server.

However html files are NOT cached on the CDN. Every page load hits your origin server through the CDN. You can set up CDN page rules to cache html pages, too, but that's of no use on dynamic sites.

If you have dynamic pages, option (2) is best if on a budget. Especially if you're using WordPress (slow). Money of no concern, (3) is best.

ContentLicense: CC BY-SA 3.0


问:
Intl formatting of huge floating point numbers
I'm trying to better understand why large numbers, with potentially large precisions are inconsistently handled, specifically in JavaScript and it's localization facilities (e.g. ECMA-402/Intl).  I'm assuming this has to do with the use of floating point numbers, but I'd like to understand where the limits are and/or how to avoid these pitfalls.

For example, using Intl.NumberFormat:

```<code>console.log(new Intl.NumberFormat('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3 }).format(9999999999990.001)); // logs 9,999,999,999,990.000

let test1 = 9999999999990.001
console.log(test1);  // logs 9999999999990.002
</code>```

How would I be able to figure out where these numbers start to get inconsistent?  Is there some kind of limit?  Does that limit change as I increase decimal precision, e.g. :

```<code>let test2 = 9999999999990.0004;
console.log(test2) // logs 9999999999990
</code>```

答:
Is there some kind of limit? Does that limit change as I increase decimal precision?

Yes, and yes. Floating-point numbers in JavaScript are themselves stored in 64 bits of space, which means they are limited in the precision they can represent. See this answer for more information.

How would I be able to figure out where these numbers start to get inconsistent?

Pass your "numeric literals" to a function in the form of strings, and check to see if that string, when coerced to a number and back, returns the correct literal:

function safeNumber (s) {
  if (String(+s) !== s)
    throw new Error('Unsafe number!')
  return +s
}

let safe = safeNumber('999999999999999')
console.log(safe)

let unsafe = safeNumber('9999999999990.001')
console.log(unsafe)```

Body:
I'm trying to better understand why large numbers, with potentially large precisions are inconsistently handled, specifically in JavaScript and it's localization facilities (e.g. ECMA-402/Intl).  I'm assuming this has to do with the use of floating point numbers, but I'd like to understand where the limits are and/or how to avoid these pitfalls.

For example, using Intl.NumberFormat:

console.log(new Intl.NumberFormat('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3 }).format(9999999999990.001)); // logs 9,999,999,999,990.000

let test1 = 9999999999990.001
console.log(test1);  // logs 9999999999990.002

How would I be able to figure out where these numbers start to get inconsistent?  Is there some kind of limit?  Does that limit change as I increase decimal precision, e.g. :

let test2 = 9999999999990.0004;
console.log(test2) // logs 9999999999990


问:
Generic async Retry with Timeout function in C#
I have hundreds of calls to various external API's that I want to wrap in a generic async function that is capable of doing retries and handling timeouts.

Basically, I think I need to implement something like this function call:

```<code>await Retry(()=>someFunctionAsync(doWorkParams, new CancellationToken()), retryCount, timeout);
</code>```

How do I define such Retry function?  Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

答:
How do I define such Retry function?

Install Polly.

Define a policy and use it.

Profit.

Something like this should work:

```<code>static async Task RetryAsync(Func<CancellationToken, Task> func, int retryCount, TimeSpan timeout)
{
  using (var cts = new CancellationTokenSource(timeout))
  {
    var policy = Policy.Handle<Exception>(ex => !(ex is OperationCanceledException))
        .RetryAsync(retryCount);
    await policy.ExecuteAsync(() => func(cts.Token)).ConfigureAwait(false);
  }
}
</code>```

Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

That's a totally different question. Blocking on asynchronous code always has pitfalls. There is no solution that works for any arbitrary Func<Task>. See my MSDN article for a variety of hacks you can try, if you must do this. It would be better, though, to keep asynchronous code asynchronous, and synchronous code synchronous.

Body:
I have hundreds of calls to various external API's that I want to wrap in a generic async function that is capable of doing retries and handling timeouts.

Basically, I think I need to implement something like this function call:

await Retry(()=>someFunctionAsync(doWorkParams, new CancellationToken()), retryCount, timeout);

How do I define such Retry function?  Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

Body:
How do I define such Retry function?

Install Polly.

Define a policy and use it.

Profit.

Something like this should work:

static async Task RetryAsync(Func<CancellationToken, Task> func, int retryCount, TimeSpan timeout)
{
  using (var cts = new CancellationTokenSource(timeout))
  {
    var policy = Policy.Handle<Exception>(ex => !(ex is OperationCanceledException))
        .RetryAsync(retryCount);
    await policy.ExecuteAsync(() => func(cts.Token)).ConfigureAwait(false);
  }
}

Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

That's a totally different question. Blocking on asynchronous code always has pitfalls. There is no solution that works for any arbitrary Func<Task>. See my MSDN article for a variety of hacks you can try, if you must do this. It would be better, though, to keep asynchronous code asynchronous, and synchronous code synchronous.


问:
Recursive entity detaching in entity framework
I've written a method to recursively detaching my objects in entity framework. Actually it works, but the problem is, after execute this method, the one to many properties (the Collections of the object) are removed. Below my Code:</p>

```<code>public void DetachRec(object objectToDetach)
{
  DetachRec(objectToDetach, new HashSet<object>());
}

// context is my ObjectContext
private void DetachRec(object objectToDetach, HashSet<object> visitedObjects)
{
  visitedObjects.Add(objectToDetach);

  if (objectToDetach == null)
  {
    return;
  }
  Type type = objectToDetach.GetType();
  PropertyInfo[] propertyInfos = type.GetProperties();
  foreach (PropertyInfo propertyInfo in propertyInfos)
  {
    // on to many
    if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
    {

      if (context.Entry(objectToDetach).Collection(propertyInfo.Name).IsLoaded)
      {

        var propValue = (IEnumerable) propertyInfo.GetValue(objectToDetach, null);

        if (propValue != null)
        {
          var subcontext = new List<object>();

          foreach (var subObject in propValue)
          {
            subcontext.Add(subObject);
          }
          foreach (var subObject in subcontext)
          {
            if (!visitedObjects.Contains(subObject))
            {
              context.DetachRecursive(subObject, visitedObjects);
            }
          }
        }
      }
    }
    // (many to one)
    else if (propertyInfo.PropertyType.Assembly == type.Assembly)
    {
        //the part to detach many-to-one objects
    }
  }

  context.Detach(objectToDetach);
}
</code>```

答:
Before detaching the collection elements, you could store the collection value and set the collection property to null. This way you'll prevent EF from removing the collection elements when the elements and/or the parent entity is detached. At the end of the process, you will simply restore those values back.

Start by adding the following using to the source code file:

```<code>using System.Data.Entity.Infrastructure;
</code>```

Change the public method implementation as follows:

```<code>public void DetachRec(object objectToDetach)
{
    var visitedObjects = new HashSet<object>();
    var collectionsToRestore = new List<Tuple<DbCollectionEntry, object>>();
    DetachRec(objectToDetach, visitedObjects, collectionsToRestore);
    foreach (var item in collectionsToRestore)
        item.Item1.CurrentValue = item.Item2;
}
</code>```

the private recursive method signature to:

```<code>private void DetachRec(object objectToDetach, HashSet<object> visitedObjects, List<DbCollectionEntry, object>> collectionsToRestore)
</code>```

and the one to many if block body to:

```<code>var collectionEntry = context.Entry(objectToDetach).Collection(propertyInfo.Name);
if (collectionEntry.IsLoaded)
{
    var collection = collectionEntry.CurrentValue;
    if (collection != null)
    {
        collectionsToRestore.Add(Tuple.Create(collectionEntry, collection));
        collectionEntry.CurrentValue = null;
        foreach (var item in (IEnumerable)collection)
        {
            if (!visitedObjects.Contains(item))
            {
                DetachRec(item, visitedObjects, collectionsToRestore);
            }
        }
    }
}
</code>```

and you are done.

Body:
I've written a method to recursively detaching my objects in entity framework. Actually it works, but the problem is, after execute this method, the one to many properties (the Collections of the object) are removed. Below my Code:

public void DetachRec(object objectToDetach)
{
  DetachRec(objectToDetach, new HashSet<object>());
}

// context is my ObjectContext
private void DetachRec(object objectToDetach, HashSet<object> visitedObjects)
{
  visitedObjects.Add(objectToDetach);

  if (objectToDetach == null)
  {
    return;
  }
  Type type = objectToDetach.GetType();
  PropertyInfo[] propertyInfos = type.GetProperties();
  foreach (PropertyInfo propertyInfo in propertyInfos)
  {
    // on to many
    if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
    {

      if (context.Entry(objectToDetach).Collection(propertyInfo.Name).IsLoaded)
      {

        var propValue = (IEnumerable) propertyInfo.GetValue(objectToDetach, null);

        if (propValue != null)
        {
          var subcontext = new List<object>();

          foreach (var subObject in propValue)
          {
            subcontext.Add(subObject);
          }
          foreach (var subObject in subcontext)
          {
            if (!visitedObjects.Contains(subObject))
            {
              context.DetachRecursive(subObject, visitedObjects);
            }
          }
        }
      }
    }
    // (many to one)
    else if (propertyInfo.PropertyType.Assembly == type.Assembly)
    {
        //the part to detach many-to-one objects
    }
  }

  context.Detach(objectToDetach);
}

Body:
Before detaching the collection elements, you could store the collection value and set the collection property to null. This way you'll prevent EF from removing the collection elements when the elements and/or the parent entity is detached. At the end of the process, you will simply restore those values back.

Start by adding the following using to the source code file:

using System.Data.Entity.Infrastructure;

Change the public method implementation as follows:

public void DetachRec(object objectToDetach)
{
    var visitedObjects = new HashSet<object>();
    var collectionsToRestore = new List<Tuple<DbCollectionEntry, object>>();
    DetachRec(objectToDetach, visitedObjects, collectionsToRestore);
    foreach (var item in collectionsToRestore)
        item.Item1.CurrentValue = item.Item2;
}

the private recursive method signature to:

private void DetachRec(object objectToDetach, HashSet<object> visitedObjects, List<DbCollectionEntry, object>> collectionsToRestore)

and the one to many if block body to:

var collectionEntry = context.Entry(objectToDetach).Collection(propertyInfo.Name);
if (collectionEntry.IsLoaded)
{
    var collection = collectionEntry.CurrentValue;
    if (collection != null)
    {
        collectionsToRestore.Add(Tuple.Create(collectionEntry, collection));
        collectionEntry.CurrentValue = null;
        foreach (var item in (IEnumerable)collection)
        {
            if (!visitedObjects.Contains(item))
            {
                DetachRec(item, visitedObjects, collectionsToRestore);
            }
        }
    }
}

and you are done.


问:
Where Buildroot exports configuration symbols
I want to know where in the code buildroot exports the configuration symbols so that they can be read in the .mk for each package:

Example:

In the package exim.mk there is a test on BR2_PACKAGE_OPENSSL value:

```<code>ifeq ($(BR2_PACKAGE_OPENSSL),y)
</code>```

The symbol is defined in the .config, but how exim.mk read it

答:
Buildroot is based on the make build system. make reads in the top-level Makefile, and parses the include directives in that file. One such directive is

```<code>-include $(BR2_CONFIG)
</code>```

The BR2_CONFIG variable expands to .config (either in the Buildroot directory, or in the output directory if O= is given). The .config file contains all the configuration options that you selected using the Kconfig infrastructure.

Next, the top-level Makefile has

```<code>include $(sort $(wildcard package/*/*.mk))
</code>```

This reads in all the .mk files in the package directory, including exim.mk. So when exim.mk is parsed, the BR2_PACKAGE_OPENSSL value set in .config will be evaluated. This can be either

```<code>BR2_PACKAGE_OPENSSL=y
</code>```

if the option was selected, or

```<code># BR2_PACKAGE_OPENSSL is not set
</code>```

if it was not selected. So the condition will be true in the first case and false in the second case.

Body:
I want to know where in the code buildroot exports the configuration symbols so that they can be read in the .mk for each package:

Example:

In the package exim.mk there is a test on BR2_PACKAGE_OPENSSL value:

ifeq ($(BR2_PACKAGE_OPENSSL),y)

The symbol is defined in the .config, but how exim.mk read it

Body:
Buildroot is based on the make build system. make reads in the top-level Makefile, and parses the include directives in that file. One such directive is

-include $(BR2_CONFIG)

The BR2_CONFIG variable expands to .config (either in the Buildroot directory, or in the output directory if O= is given). The .config file contains all the configuration options that you selected using the Kconfig infrastructure.

Next, the top-level Makefile has

include $(sort $(wildcard package/*/*.mk))

This reads in all the .mk files in the package directory, including exim.mk. So when exim.mk is parsed, the BR2_PACKAGE_OPENSSL value set in .config will be evaluated. This can be either

BR2_PACKAGE_OPENSSL=y

if the option was selected, or

# BR2_PACKAGE_OPENSSL is not set

if it was not selected. So the condition will be true in the first case and false in the second case.


问:
Merging a dataframe in a dict with another dataframe in Python
I have a dict that currently looks like this:

```<code>raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
import pandas as pd
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
dict = {}
dict = {'Check':df1}
print dict
</code>```

I am trying to append the appended df to the df element of this dict such as:

```<code>appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
import pandas as pd
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print appended

adfs = {k:df.merge(appended[appended.Desc==df.Desc],on=['Series_Date'],how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}
</code>```

However, on running this merge statement, I get the following error: ValueError: Can only compare identically-labeled Series objects

Tried reading on thie error but not sure how it's applicable here, any thoughts what could be done to get over this error or alternatively, another approach to do

答:
How about merging on both desc and Series_date

adfs = {k:df.merge(appended,on=['Desc' , 'Series_Date'], how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}

A statement like appended.Desc == df.Desc is problematic, as these series are of different shape. You can try isin, such as appended.Desc.isin(df.Desc).

Body:
I have a dict that currently looks like this:

raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
import pandas as pd
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
dict = {}
dict = {'Check':df1}
print dict

I am trying to append the appended df to the df element of this dict such as:

appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
import pandas as pd
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print appended

adfs = {k:df.merge(appended[appended.Desc==df.Desc],on=['Series_Date'],how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}

However, on running this merge statement, I get the following error: ValueError: Can only compare identically-labeled Series objects

Tried reading on thie error but not sure how it's applicable here, any thoughts what could be done to get over this error or alternatively, another approach to do


问:
Output string with leading spaces to log, keeping the spaces
How can I print leading spaces to the log?

When I do something like

```<code>data _null_;
  x = '  Hello, world!';
  put x;
run;
</code>```

The result is

```<code>2522  data _null_;
2523    x = '  Hello, world!';
2524    putlog x;
2525  run;

Hello, world!
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds
</code>```

I looked through the PUT documentation, but nothing stood out to me.  It seems like using a format, such as $CHARw., might work.  However, that would require knowing the length of the string ahead of time.

I would like the log output to look like this:

```<code>  Hello, world!  (<--edited by hand to display leading spaces)
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds
</code>```

答:
You can try using a non printable character - works with both put and putlog

```<code>data _null_;
  x = '09'x !! '       Hello, world!';
  putlog x;
run;
</code>```

Other ways of creating 'blanks' in your log include:

```<code>data _null_;
  x = '09'x !! '       Hello, world!';
  put // x // '09'x;
run;
</code>```

The / lets you add a blank line.

Also, you can class sections of your log as NOTE / WARNING / ERROR by adding a dash, as follows:

```<code>data _null_;
  put 'NOTE: ';
  put 'NOTE- Check';
  put 'NOTE- This';
  put 'NOTE- Out!';
  put 'NOTE- ';
run;
</code>```

Body:
How can I print leading spaces to the log?

When I do something like

data _null_;
  x = '  Hello, world!';
  put x;
run;

The result is

2522  data _null_;
2523    x = '  Hello, world!';
2524    putlog x;
2525  run;

Hello, world!
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

I looked through the PUT documentation, but nothing stood out to me.  It seems like using a format, such as $CHARw., might work.  However, that would require knowing the length of the string ahead of time.

I would like the log output to look like this:

  Hello, world!  (<--edited by hand to display leading spaces)
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

Body:
You can try using a non printable character - works with both put and putlog

data _null_;
  x = '09'x !! '       Hello, world!';
  putlog x;
run;

Other ways of creating 'blanks' in your log include:

data _null_;
  x = '09'x !! '       Hello, world!';
  put // x // '09'x;
run;

The / lets you add a blank line.

Also, you can class sections of your log as NOTE / WARNING / ERROR by adding a dash, as follows:

data _null_;
  put 'NOTE: ';
  put 'NOTE- Check';
  put 'NOTE- This';
  put 'NOTE- Out!';
  put 'NOTE- ';
run;


问:
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

答:
Why can't you do something such as</p>

```<code>SELECT *
FROM   TABLE
WHERE (TABLE.primary_key IN (
  SELECT   TABLE.primary_key
  FROM     TABLE
  ORDER BY TABLE.id ASC
  LIMIT    2
))
ORDER BY TABLE.id DESC
</code>```

Title: Mysql select first then limit

Body:
Why can't you do something such as

SELECT *
FROM   TABLE
WHERE (TABLE.primary_key IN (
  SELECT   TABLE.primary_key
  FROM     TABLE
  ORDER BY TABLE.id ASC
  LIMIT    2
))
ORDER BY TABLE.id DESC


问:
Peak to Trough in time series data
Looking to find every instance in which a time series of a stock index declines by 10% or greater.  I am struggling to program it so that it understands order matters (don't want appreciation by 10%).

Ideally the code would: Pick value, check if value after it is 10% below, if not, check next, keep checking next until one is found then record that.  Then, move to that "trough' or 'valley' as the beginning to continue the process of checking if values after it are 10% or more less than that value.

I have an Excel file with dates in the first column and the index value in the second

This is what it outputs which I don't think can be correct based on a graph

```<code># Import Libraries
import pandas as pd
import numpy as np
import peakutils
from peakutils.plot import plot as pplot
from matplotlib import pyplot
import matplotlib.pyplot as plt
from scipy import signal
import csv
import scipy
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

# from pandas import DataFrame

# Import Excel as array
index = pd.read_csv(r"\Users\Reed_2\Desktop\Indexonly.csv")
print("as Pandas")
print (index.values)
# convert to 2 NumPy arrays
dates = index['Date'].as_matrix()
values = index['Index'].as_matrix()
print("values as NumPy")
print(values)
print("Date values")
print(dates)

# Find peaks
peaks = peakutils.indexes(values, thres=0.1, min_dist=1)

print ("peaks")
print(peaks)

a = np.asarray(peaks)
np.savetxt(r"C:\Users\Reed_2\Desktop\export.csv", a, delimiter=",")
</code>```

Have access to Python, R Studio, and MatLab.  Prefer Python as I know it best.

Very grateful for any help on this.

答:
Consider the series of returns s

```<code>np.random.seed([3,1415])
s = pd.Series(
    np.random.lognormal(.005, .5, size=100),
    pd.date_range('2015-01-01', periods=100, freq='B')
).cumprod()

s.plot()
</code>```

Use a generator to slice the index

```<code>def gen_slice(s, thresh):
    sidx = s.index
    idx = s.index[0]
    v = s.get_value(idx)
    yield idx
    for idx in sidx[1:]:
        v0 = s.get_value(idx)
        if (v0 / v) < 1-thresh:
            v = v0
            yield idx

s.loc[list(gen_slice(s, .1))]

2015-01-01    0.346504
2015-01-02    0.184687
2015-01-05    0.069298
2015-01-06    0.022508
2015-01-07    0.018996
2015-01-26    0.014204
2015-02-03    0.012777
2015-05-01    0.008999
2015-05-04    0.006039
2015-05-06    0.004855
dtype: float64
</code>```

We can see that every percentage change is less than 10%

```<code>s.loc[list(gen_slice(s, .1))].pct_change()

2015-01-01         NaN
2015-01-02   -0.467000
2015-01-05   -0.624783
2015-01-06   -0.675194
2015-01-07   -0.156034
2015-01-26   -0.252278
2015-02-03   -0.100442
2015-05-01   -0.295665
2015-05-04   -0.328967
2015-05-06   -0.195990
dtype: float64
</code>```

We can plot where those events happened.

```<code>idx = list(gen_slice(s, .1))

ax = s.plot()
ax.vlines(idx, s.min(), s.max())
</code>```

See also below:

It may become necessary to traverse the elements of a series or the rows of a dataframe in a way that the next element or next row is dependent on the previously selected element or row.  This is called path dependency.

Consider the following time series s with irregular frequency.

```<code>#starting python community conventions
import numpy    as np
import pandas   as pd

# n is number of observations
n = 5000

day = pd.to_datetime(['2013-02-06'])
# irregular seconds spanning 28800 seconds (8 hours)
seconds = np.random.rand(n) * 28800 * pd.Timedelta(1, 's')
# start at 8 am
start = pd.offsets.Hour(8)
# irregular timeseries
tidx = day + start + seconds
tidx = tidx.sort_values()

s = pd.Series(np.random.randn(n), tidx, name='A').cumsum()
s.plot();
</code>```

Let's assume a path dependent condition.  Starting with the first member of the series, I want to grab each subsequent element such that the absolute difference between that element and the current element is greater than or equal to x.

We'll solve this problem using python generators.

Generator function

```<code>def mover(s, move_size=10):
    """Given a reference, find next value with
    an absolute difference >= move_size"""
    ref = None
    for i, v in s.iteritems():
        if ref is None or (abs(ref - v) >= move_size):
            yield i, v
            ref = v
</code>```

Then we can define a new series moves like so

```<code>moves = pd.Series({i:v for i, v in mover(s, move_size=10)},
                  name='_{}_'.format(s.name))
</code>```

Plotting them both

```<code>moves.plot(legend=True)
s.plot(legend=True)
</code>```

The analog for dataframes would be:

```<code>def mover_df(df, col, move_size=2):
    ref = None
    for i, row in df.iterrows():
        if ref is None or (abs(ref - row.loc[col]) >= move_size):
            yield row
            ref = row.loc[col]

df = s.to_frame()
moves_df = pd.concat(mover_df(df, 'A', 10), axis=1).T

moves_df.A.plot(label='_A_', legend=True)
df.A.plot(legend=True)
</code>```

Title: Peak to Trough in time series data

Body:
Looking to find every instance in which a time series of a stock index declines by 10% or greater.  I am struggling to program it so that it understands order matters (don't want appreciation by 10%).

Ideally the code would: Pick value, check if value after it is 10% below, if not, check next, keep checking next until one is found then record that.  Then, move to that "trough' or 'valley' as the beginning to continue the process of checking if values after it are 10% or more less than that value.

I have an Excel file with dates in the first column and the index value in the second

This is what it outputs which I don't think can be correct based on a graph

# Import Libraries
import pandas as pd
import numpy as np
import peakutils
from peakutils.plot import plot as pplot
from matplotlib import pyplot
import matplotlib.pyplot as plt
from scipy import signal
import csv
import scipy
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

# from pandas import DataFrame

# Import Excel as array
index = pd.read_csv(r"\Users\Reed_2\Desktop\Indexonly.csv")
print("as Pandas")
print (index.values)
# convert to 2 NumPy arrays
dates = index['Date'].as_matrix()
values = index['Index'].as_matrix()
print("values as NumPy")
print(values)
print("Date values")
print(dates)

# Find peaks
peaks = peakutils.indexes(values, thres=0.1, min_dist=1)

print ("peaks")
print(peaks)

a = np.asarray(peaks)
np.savetxt(r"C:\Users\Reed_2\Desktop\export.csv", a, delimiter=",")

Have access to Python, R Studio, and MatLab.  Prefer Python as I know it best.

Very grateful for any help on this.

Body:
Consider the series of returns s

np.random.seed([3,1415])
s = pd.Series(
    np.random.lognormal(.005, .5, size=100),
    pd.date_range('2015-01-01', periods=100, freq='B')
).cumprod()

s.plot()

Use a generator to slice the index

def gen_slice(s, thresh):
    sidx = s.index
    idx = s.index[0]
    v = s.get_value(idx)
    yield idx
    for idx in sidx[1:]:
        v0 = s.get_value(idx)
        if (v0 / v) < 1-thresh:
            v = v0
            yield idx

s.loc[list(gen_slice(s, .1))]

2015-01-01    0.346504
2015-01-02    0.184687
2015-01-05    0.069298
2015-01-06    0.022508
2015-01-07    0.018996
2015-01-26    0.014204
2015-02-03    0.012777
2015-05-01    0.008999
2015-05-04    0.006039
2015-05-06    0.004855
dtype: float64

We can see that every percentage change is less than 10%

s.loc[list(gen_slice(s, .1))].pct_change()

2015-01-01         NaN
2015-01-02   -0.467000
2015-01-05   -0.624783
2015-01-06   -0.675194
2015-01-07   -0.156034
2015-01-26   -0.252278
2015-02-03   -0.100442
2015-05-01   -0.295665
2015-05-04   -0.328967
2015-05-06   -0.195990
dtype: float64

We can plot where those events happened.

idx = list(gen_slice(s, .1))

ax = s.plot()
ax.vlines(idx, s.min(), s.max())

See also below:

It may become necessary to traverse the elements of a series or the rows of a dataframe in a way that the next element or next row is dependent on the previously selected element or row.  This is called path dependency.

Consider the following time series s with irregular frequency.

#starting python community conventions
import numpy    as np
import pandas   as pd

# n is number of observations
n = 5000

day = pd.to_datetime(['2013-02-06'])
# irregular seconds spanning 28800 seconds (8 hours)
seconds = np.random.rand(n) * 28800 * pd.Timedelta(1, 's')
# start at 8 am
start = pd.offsets.Hour(8)
# irregular timeseries
tidx = day + start + seconds
tidx = tidx.sort_values()

s = pd.Series(np.random.randn(n), tidx, name='A').cumsum()
s.plot();

Let's assume a path dependent condition.  Starting with the first member of the series, I want to grab each subsequent element such that the absolute difference between that element and the current element is greater than or equal to x.

We'll solve this problem using python generators.

Generator function

def mover(s, move_size=10):
    """Given a reference, find next value with
    an absolute difference >= move_size"""
    ref = None
    for i, v in s.iteritems():
        if ref is None or (abs(ref - v) >= move_size):
            yield i, v
            ref = v

Then we can define a new series moves like so

moves = pd.Series({i:v for i, v in mover(s, move_size=10)},
                  name='_{}_'.format(s.name))

Plotting them both

moves.plot(legend=True)
s.plot(legend=True)

The analog for dataframes would be:

def mover_df(df, col, move_size=2):
    ref = None
    for i, row in df.iterrows():
        if ref is None or (abs(ref - row.loc[col]) >= move_size):
            yield row
            ref = row.loc[col]

df = s.to_frame()
moves_df = pd.concat(mover_df(df, 'A', 10), axis=1).T

moves_df.A.plot(label='_A_', legend=True)
df.A.plot(legend=True)


问:
RxJava "serialize" method use cases
I want to know cases in which we need to "serialize" observable, its necessary. I mean cases in which "onNext" method will get called concurrently instead of one after another. </p>

答: Originally, serialize() was introduced to fix some badly behaving custom Observables from the consumer's end instead of making the author fix his create()-ion in 1.x. As the enforcing of the Observable protocol became more prominent, there was less need for the operator in practice. It still ended up in v2 just in case and for "nostalgic reasons". Note that its sibling, Subject.toSerialized() is completely legitimate and is there to serialize access to a Subject in case it is driven from multiple threads.

Title: RxJava "serialize" method use cases


问:
Python - Write for loop output to file
I have a function that outputs a list of IPs.

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))
</code>```

The output usually looks like
Below are the IPs for CSDP_LAB_STAGING

```<code>172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51
</code>```

Now I want to write this output to file.

What I have done is

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()
</code>```

But the above code only writes the very last IP to test.txt. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ?

P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.

答:
I went through everyones response above and tried each one out. But every solution led to only the last IP being printed to file. Reading the documentation brought me to the conclusion that I need to append to file rather than write to it.</p>

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    my_file=open("test.txt","a")
    for ips in ip:
        my_file.write(ips.get('ip')+'\n')
    my_file.close()
</code>```

Title: Python - Write for loop output to file

Body:
I have a function that outputs a list of IPs.

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))

The output usually looks like
Below are the IPs for CSDP_LAB_STAGING

172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51

Now I want to write this output to file.

What I have done is

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()

But the above code only writes the very last IP to test.txt. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ?

P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.

Body:
I went through everyones response above and tried each one out. But every solution led to only the last IP being printed to file. Reading the documentation brought me to the conclusion that I need to append to file rather than write to it.

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    my_file=open("test.txt","a")
    for ips in ip:
        my_file.write(ips.get('ip')+'\n')
    my_file.close()


问:
keystroke interrupt for PIC microcontroller
I am writing a code where the user can press a key corresponding to the information the user wants to know and print it on the LCD Display. So far I am able to write the code to print on LCD but I am not able to figure out how to ask MCU to wait for a keystroke and then print.
Can anyone suggest me what is the logic to do it?

Microcontroller: PIC18F4550; MPLAB X IDE, XC8 with PICkit3. I am using Windows 7.
Keypad: 3x4 matrix keypad - MCAK304NBWB

My code is:

```<code>#define C1_DAT LATBbits.LATB4 //Column 1 is set portB4 as output
#define C2_DAT LATBbits.LATB5 //Column 2 is set portB5 as output
#define C3_DAT LATBbits.LATB6 //Column 3 is set portB6 as output

#define C1_DIR TRISBbits.TRISB4 //Column 1 is set portB4 as output
#define C2_DIR TRISBbits.TRISB5 //Column 2 is set portB5 as output
#define C3_DIR TRISBbits.TRISB6 //Column 3 is set portB6 as output
.....

C1_DIR = 0; //drive column 1 low
        rows[0] = PORTB & 0x0f; //read all four rows1 buttons
        rows[1] = 0x0f;
        rows[2] = 0x0f;
        DelayXLCD();

        if ( (rows[0] & 0b0001) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 1 is pressed");
        DelayXLCD();
        //break;

        if ( (rows[0] & 0b0010) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 4 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[0] & 0b0100) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 7 is pressed");
        DelayXLCD();

        if ( (rows[0] & 0b1000) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key * is pressed");
        DelayXLCD();
        //break;
        if ( (rows[1] & 0b0001) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 2 is pressed");
        DelayXLCD();

        if ( (rows[1] & 0b0010) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 5 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[1] & 0b0100) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 8 is pressed");
        //break;
        if ( (rows[1] & 0b1000) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 0 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b0001) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 3 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b0010) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 6 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b0100) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 9 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b1000) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key # is pressed");
        DelayXLCD();
        Delay_s(20);
        //if ( (rows[0] & rows[1] & rows[2]) == 0x0F)    // will be 0x0F if all three values are 0x0F
            //putrsXLCD("no keys are pressed");
        //DelayXLCD();

    } while((rows[0] & rows[1] & rows[2]) != 0x0F); // wait for keys release
    {putrsXLCD("no keys are pressed");
        Delay_s(50);
        LCD_Clear();} //end of main loop
</code>```

答:
Using timers in this context (regular polling of the keyboard) does not really help because they also use interrupts. You might as well dive into it and teach yourself to use interrupts. Basically, an interrupt is a SHORT piece of code that is executed when some event occurs.

For your keyboard, use an interrupt-on-change. When the interrupt triggers, read the keyboard, and set a global semaphore (flag) that your main program can check at it leisure while performing other tasks (e.g. in an event loop in the main() routine.

Alternatively, if you don't have much else to do, but continuously poll the keyboard input lines to see if there is any activity.

Body:
I am writing a code where the user can press a key corresponding to the information the user wants to know and print it on the LCD Display. So far I am able to write the code to print on LCD but I am not able to figure out how to ask MCU to wait for a keystroke and then print.
Can anyone suggest me what is the logic to do it?

Microcontroller: PIC18F4550; MPLAB X IDE, XC8 with PICkit3. I am using Windows 7.
Keypad: 3x4 matrix keypad - MCAK304NBWB

My code is:

#define C1_DAT LATBbits.LATB4 //Column 1 is set portB4 as output
#define C2_DAT LATBbits.LATB5 //Column 2 is set portB5 as output
#define C3_DAT LATBbits.LATB6 //Column 3 is set portB6 as output

#define C1_DIR TRISBbits.TRISB4 //Column 1 is set portB4 as output
#define C2_DIR TRISBbits.TRISB5 //Column 2 is set portB5 as output
#define C3_DIR TRISBbits.TRISB6 //Column 3 is set portB6 as output
.....

C1_DIR = 0; //drive column 1 low
        rows[0] = PORTB & 0x0f; //read all four rows1 buttons
        rows[1] = 0x0f;
        rows[2] = 0x0f;
        DelayXLCD();

        if ( (rows[0] & 0b0001) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 1 is pressed");
        DelayXLCD();
        //break;

        if ( (rows[0] & 0b0010) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 4 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[0] & 0b0100) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 7 is pressed");
        DelayXLCD();

        if ( (rows[0] & 0b1000) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key * is pressed");
        DelayXLCD();
        //break;
        if ( (rows[1] & 0b0001) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 2 is pressed");
        DelayXLCD();

        if ( (rows[1] & 0b0010) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 5 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[1] & 0b0100) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 8 is pressed");
        //break;
        if ( (rows[1] & 0b1000) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 0 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b0001) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 3 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b0010) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 6 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b0100) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key 9 is pressed");
        DelayXLCD();
        //break;
        if ( (rows[2] & 0b1000) == 0)    // will be zero if the "0" button is currently pressed.
            putrsXLCD("key # is pressed");
        DelayXLCD();
        Delay_s(20);
        //if ( (rows[0] & rows[1] & rows[2]) == 0x0F)    // will be 0x0F if all three values are 0x0F
            //putrsXLCD("no keys are pressed");
        //DelayXLCD();

    } while((rows[0] & rows[1] & rows[2]) != 0x0F); // wait for keys release
    {putrsXLCD("no keys are pressed");
        Delay_s(50);
        LCD_Clear();} //end of main loop


问:
Get maximum video resolution with getUserMedia
I'm trying to get highest video resolution as possible through JS navigator.getUserMedia. I know about constraints, but don't know how to choose right in my case.

The problem is looks like there is no way to say "I want a video at maximum resolution". So instead I'm trying to say "I want video not less than very big resolution".

When I'm trying minWidth: 1600, Chrome returns me 1280×720 video (highest possible for my camera, I think). But what if user has camera with higher resolution? So I'm asking for minWidth: 2048 video, and Chrome returns only 640×480.

```<code>var constraints = {
  video: {
    optional: [
    {minWidth: 2048}
    ]
  }
};
</code>```

This is online example: http://jsbin.com/kibeza/1/watch?js,output

And there is actual problem: Chrome doesn't know math. It think what 1600 is greater than 2048. I can't ask for video "not less than 100500", because in this case I'll get standard low resolution. I cant ask video "not less than some reasonable small resolution", because there can be users with higher resolution and I want to get higher resolution.

答:
Still I haven't found any good API to get maximum video resolution with getUserMedia.

But here I am sharing my idea to get maximum supported video resolution of the connected device using Binary Search algorithm and it's working great.

Here are the steps to do this job,

Store some standard resolutions in an Array, maintaining ascending
order .

Set leftIndex = 0 and rightIndex = size of resolution array.

Check midIndex = (left+right)/2 resolution supported or not, and
modify left and right based on the result.

Here I am sharing my implementation:

```<code>var ResolutionsToCheck = [
                {width: 160, height:120},
                {width: 320, height:180},
                {width: 320, height:240},
                {width: 640, height:360},
                {width: 640, height:480},
                {width: 768, height:576},
                {width: 1024, height:576},
                {width: 1280, height:720},
                {width: 1280, height:768},
                {width: 1280, height:800},
                {width: 1280, height:900},
                {width: 1280, height:1000},
                {width: 1920, height:1080},
                {width: 1920, height:1200},
                {width: 2560, height:1440},
                {width: 3840, height:2160},
                {width: 4096, height:2160}
            ];

var left = 0;
var right = ResolutionsToCheck.length;
var selectedWidth;
var selectedHeight;
var mid;

function FindMaximum_WidthHeight_ForCamera()
{
    console.log("left:right = ", left, ":", right);
    if(left > right)
    {
        console.log("Selected Height:Width = ", selectedWidth, ":", selectedHeight);
        return;
    }

    mid = Math.floor((left + right) / 2);

    var temporaryConstraints = {
        "audio": true,
        "video": {
            "mandatory": {
            "minWidth": ResolutionsToCheck[mid].width,
            "minHeight": ResolutionsToCheck[mid].height,
            "maxWidth": ResolutionsToCheck[mid].width,
            "maxHeight": ResolutionsToCheck[mid].height
            },
        "optional": []
        }
    }

    navigator.mediaDevices.getUserMedia(temporaryConstraints).then(checkSuccess).catch(checkError);
}

function checkSuccess(stream)
{
    console.log("Success for --> " , mid , " ", ResolutionsToCheck[mid]);
    selectedWidth = ResolutionsToCheck[mid].width;
    selectedHeight = ResolutionsToCheck[mid].height;

    left = mid+1;

    for (let track of stream.getTracks())
    {
        track.stop()
    }

    FindMaximum_WidthHeight_ForCamera();
}
function checkError(error)
{
    console.log("Failed for --> " + mid , " ", ResolutionsToCheck[mid],  " ", error);
    right = mid-1;

    FindMaximum_WidthHeight_ForCamera();
}
</code>```

Just call function FindMaximum_WidthHeight_ForCamera(). When operation will be completed then maximum video resolution will be stored in selectedWidth and selectedHeight variables. Here I am also attaching console output for my device:

```<code>//Console Output
left:right =  0 : 17
Success for -->  8   Objectheight: 768width: 1280__proto__: Object
left:right =  9 : 17
Failed for --> 13   Objectheight: 1200width: 1920__proto__: Object   NavigatorUserMediaError
left:right =  9 : 12
Success for -->  10   Objectheight: 900width: 1280__proto__: Object
left:right =  11 : 12
Failed for --> 11   Objectheight: 1000width: 1280__proto__: Object   NavigatorUserMediaError
left:right =  11 : 10
Selected Height:Width =  1280 : 900
</code>```

I have tested this implementation using Chrome Version 57.0.2987.110 (64-bit) and Logitech, Inc. Webcam C270. But I think this solution should work in each scenario. Thank You.

Body:
I'm trying to get highest video resolution as possible through JS navigator.getUserMedia. I know about constraints, but don't know how to choose right in my case.

The problem is looks like there is no way to say "I want a video at maximum resolution". So instead I'm trying to say "I want video not less than very big resolution".

When I'm trying minWidth: 1600, Chrome returns me 1280×720 video (highest possible for my camera, I think). But what if user has camera with higher resolution? So I'm asking for minWidth: 2048 video, and Chrome returns only 640×480.

var constraints = {
  video: {
    optional: [
    {minWidth: 2048}
    ]
  }
};

This is online example: http://jsbin.com/kibeza/1/watch?js,output

And there is actual problem: Chrome doesn't know math. It think what 1600 is greater than 2048. I can't ask for video "not less than 100500", because in this case I'll get standard low resolution. I cant ask video "not less than some reasonable small resolution", because there can be users with higher resolution and I want to get higher resolution.

Body:
Still I haven't found any good API to get maximum video resolution with getUserMedia.

But here I am sharing my idea to get maximum supported video resolution of the connected device using Binary Search algorithm and it's working great.

Here are the steps to do this job,

Store some standard resolutions in an Array, maintaining ascending
order .

Set leftIndex = 0 and rightIndex = size of resolution array.

Check midIndex = (left+right)/2 resolution supported or not, and
modify left and right based on the result.

Here I am sharing my implementation:

var ResolutionsToCheck = [
                {width: 160, height:120},
                {width: 320, height:180},
                {width: 320, height:240},
                {width: 640, height:360},
                {width: 640, height:480},
                {width: 768, height:576},
                {width: 1024, height:576},
                {width: 1280, height:720},
                {width: 1280, height:768},
                {width: 1280, height:800},
                {width: 1280, height:900},
                {width: 1280, height:1000},
                {width: 1920, height:1080},
                {width: 1920, height:1200},
                {width: 2560, height:1440},
                {width: 3840, height:2160},
                {width: 4096, height:2160}
            ];

var left = 0;
var right = ResolutionsToCheck.length;
var selectedWidth;
var selectedHeight;
var mid;

function FindMaximum_WidthHeight_ForCamera()
{
    console.log("left:right = ", left, ":", right);
    if(left > right)
    {
        console.log("Selected Height:Width = ", selectedWidth, ":", selectedHeight);
        return;
    }

    mid = Math.floor((left + right) / 2);

    var temporaryConstraints = {
        "audio": true,
        "video": {
            "mandatory": {
            "minWidth": ResolutionsToCheck[mid].width,
            "minHeight": ResolutionsToCheck[mid].height,
            "maxWidth": ResolutionsToCheck[mid].width,
            "maxHeight": ResolutionsToCheck[mid].height
            },
        "optional": []
        }
    }

    navigator.mediaDevices.getUserMedia(temporaryConstraints).then(checkSuccess).catch(checkError);
}

function checkSuccess(stream)
{
    console.log("Success for --> " , mid , " ", ResolutionsToCheck[mid]);
    selectedWidth = ResolutionsToCheck[mid].width;
    selectedHeight = ResolutionsToCheck[mid].height;

    left = mid+1;

    for (let track of stream.getTracks())
    {
        track.stop()
    }

    FindMaximum_WidthHeight_ForCamera();
}
function checkError(error)
{
    console.log("Failed for --> " + mid , " ", ResolutionsToCheck[mid],  " ", error);
    right = mid-1;

    FindMaximum_WidthHeight_ForCamera();
}

Just call function FindMaximum_WidthHeight_ForCamera(). When operation will be completed then maximum video resolution will be stored in selectedWidth and selectedHeight variables. Here I am also attaching console output for my device:

//Console Output
left:right =  0 : 17
Success for -->  8   Objectheight: 768width: 1280__proto__: Object
left:right =  9 : 17
Failed for --> 13   Objectheight: 1200width: 1920__proto__: Object   NavigatorUserMediaError
left:right =  9 : 12
Success for -->  10   Objectheight: 900width: 1280__proto__: Object
left:right =  11 : 12
Failed for --> 11   Objectheight: 1000width: 1280__proto__: Object   NavigatorUserMediaError
left:right =  11 : 10
Selected Height:Width =  1280 : 900

I have tested this implementation using Chrome Version 57.0.2987.110 (64-bit) and Logitech, Inc. Webcam C270. But I think this solution should work in each scenario. Thank You.


问:
PHP array search
I'm trying to add some quick and simple search functionality to a site. The site has an XML file with all their stores, and I want to create a search box to search for the closest store to the user by town or postcode.

I have put all the data into an array, but as far as I can tell, there is no way to 'search' an array (NOT array_search) to retrieve results like using a MySQL LIKE query.

Surely there must be a way? Using MySQL isn't an option in this case.

答:
Three options:

As your source is XML, you could use QueryPath or phpQuery to filter the initial data set.

If MySQL is not an option, you could still use a SQLite in-memory database, if you really want to use LIKE.

Or time tested and most simple: just manually loop over your array and do manual comparisons.

Title: PHP array search


问:
Uploading files with PHP on a linux machine
I'm trying to make some sort of cloud application on a headless raspbian machine.
The testing happens on a wamp-server running on windows8.1. PHP version is 5.6

The code works fine on my testing windows, but I run into issues when running the same code on my linux server. I've narrowed down the issue to the fact that (the linux user behind) my PHP code doesn't have write permissions on the folder where it should store files.

I can think of two ways to solve the issue: either give that php-user permissions, or change the user behind the php code. The last one would be quite interesting if it was possible to change per-script.

So, for my concrete question:

1) Where can I find what user is being used by my PHP code?

2) Can I change what user my PHP code uses, preferably on a per-project basis?

EDIT:

My script was running as root, as is shown by echo get_current_user();. I changed ownership of all files to root:webhosting, which was previously ftpuser:ftpgroup. However, when setting permissions to 770 I get access denied

EDIT2:

When using var_dump(posix_geteuid()); instead of get_current_user();, i get UID 33, which matches user www-data.

SOLUTION:

By looking at the EUID with var_dump(posix_geteuid(); I was able to validate the actual user, which does NOT match the get_current_user();. Changing the directroy and all files in it with sudo chown -R www-data:www-data <root of site> I managed to set the correct permissions.

答:
I am not sure what the specifics are but normally when I have issues like that I change the ownership to www-data:www-data and if necessary for upload folders I change the folder permissions to 0755 and inside files permissions to 0644.

EDIT

I changed the permissions setting for security purposes.


问:
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>```

答:
*{
     text-align: center;
    }
    h1,nav{
     font-family: arial;
    }
    #headerNav{
     display: none;
    }
    #footerNav{
     position: fixed;
     bottom: 0px;
     width: 100%;
     background-color: white;
     padding: 0px;
    }
    nav ul{
     padding: 0px;
          margin: 0px
    }
    nav li{
     list-style-type: none;
     border: 1px solid black;
     margin: 0px;
    }

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

    nav a, nav a:visited {
     color: green;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
   <h1>Somalia</h1>
   <nav id="headerNav">
    <ul>
     <li>Home</li>
     <li>History And Politics</li>
     <li>Geography</li>
     <li>Economy</li>
     <li>Culture And Demographics</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>Home</li>
     <li>History And Politics</li>
     <li>Geography</li>
     <li>Economy</li>
     <li>Culture And Demographics</li>
    </ul>
   </nav>

  </footer</code>```

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:
*{
     text-align: center;
    }
    h1,nav{
     font-family: arial;
    }
    #headerNav{
     display: none;
    }
    #footerNav{
     position: fixed;
     bottom: 0px;
     width: 100%;
     background-color: white;
     padding: 0px;
    }
    nav ul{
     padding: 0px;
          margin: 0px
    }
    nav li{
     list-style-type: none;
     border: 1px solid black;
     margin: 0px;
    }

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

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

<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


问:
FactoryGirl with belongs_to / has_many association with minimum of 1 association
The issue I'm having is specific to a relationship with a belongs_to and has_many where the has_many relationship has a requirement of at least one association.  This requirement is causing my Factories to fail my model level validation and not be created.

My Group model

```<code>Group < ActiveRecord::Base
  has_many :organizations, dependent: nullify
  # commenting out the following line will make the tests pass
  validates :organizations, presence: true
  ...
end
</code>```

The Organization model

```<code>Organization < ActiveRecord::Base
  belongs_to :group
  ...
end
</code>```

Organization Factory

```<code>FactoryGirl.define do
  factory :organization
    name "test organization"
  end
end
</code>```

And finally the problem child:
Group Factory

```<code>FactoryGirl.define do
  factory :group do
    name "test group"
    after(:create) do |group|
      create(:organization, group: group)
    end
  end
end
</code>```

and in my test, I declare the factory instance:

```<code>describe "something happens with a Group" do
  let(:group) { FactoryGirl.create :group }

  it "should work" do
    ...
  end
end
</code>```

The errors my tests return are varied, but generally all point to FactoryGirl being unable to create an instance of the Group factory.  e.g.

```<code># when a test relies on creating an instance of 'Group'
ActiveRecord::RecordInvalid:
    Validation failed: Organizations can't be blank
</code>```

The method I'm using (callback) to create my Group factory is from this Thoughtbot post https://robots.thoughtbot.com/aint-no-calla-back-girl

There are many similar posts, but all of them that I've found as well as the Thoughtbot documentation don't mention this specific use case.  Thanks in advance.

答:
How about something like

```<code>FactoryGirl.define do
  factory :group do
    name 'test group'
    organizations { [association(:organization)] }
  end
end
</code>```

The main idea is to build the needed objects before saving them. You may also try build_list if you need more.

Body:
The issue I'm having is specific to a relationship with a belongs_to and has_many where the has_many relationship has a requirement of at least one association.  This requirement is causing my Factories to fail my model level validation and not be created.

My Group model

Group < ActiveRecord::Base
  has_many :organizations, dependent: nullify
  # commenting out the following line will make the tests pass
  validates :organizations, presence: true
  ...
end

The Organization model

Organization < ActiveRecord::Base
  belongs_to :group
  ...
end

Organization Factory

FactoryGirl.define do
  factory :organization
    name "test organization"
  end
end

And finally the problem child:
Group Factory

FactoryGirl.define do
  factory :group do
    name "test group"
    after(:create) do |group|
      create(:organization, group: group)
    end
  end
end

and in my test, I declare the factory instance:

describe "something happens with a Group" do
  let(:group) { FactoryGirl.create :group }

  it "should work" do
    ...
  end
end

The errors my tests return are varied, but generally all point to FactoryGirl being unable to create an instance of the Group factory.  e.g.

# when a test relies on creating an instance of 'Group'
ActiveRecord::RecordInvalid:
    Validation failed: Organizations can't be blank

The method I'm using (callback) to create my Group factory is from this Thoughtbot post https://robots.thoughtbot.com/aint-no-calla-back-girl

There are many similar posts, but all of them that I've found as well as the Thoughtbot documentation don't mention this specific use case.  Thanks in advance.

Body:
How about something like

FactoryGirl.define do
  factory :group do
    name 'test group'
    organizations { [association(:organization)] }
  end
end

The main idea is to build the needed objects before saving them. You may also try build_list if you need more.


问:
JAVA making time to decrease to zero by swing timer
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

```<code>        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();
</code>```

is it possible?

答:
The TIMER value is never decremented by the timer event.  Therefore the same time will always be displayed every 1000 milliseconds.

Edit: Assuming "timing" is a Swing component the call to repaint should be unnecessary.

Body:
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();

is it possible?