问:
There are two circular statement, how can l write it in opencl kernel?
There are two circular statement, for example:

```<code>for(int i=0;i<1000;i++)
 for (int j=0;j<1000;j++)
{
  for(int k=i*5;k<i*5+5;k++)
   for(int l=j*5;l<j*5+5;j++)
  {
   marrytemp=A[i]+B[j]+marry;
  }
 marry[i,j]=marrytemp;
}
</code>```

how can l write it in opencl kernel?

答:
Write the kernel to handle the inner two loops (k,l), then enqueue it as a 2D kernels with global size of i,j.

Edit to add outline of kernel:

The kernel would be something along the lines of:

```<code>__kernel void innerLoop(__global float* A, __global float* B, __global float* marry)
{
    int i = get_global_id(1);
    int j = get_global_id(0);
    int marraytemp = 0;
    for(int k=i*5;k<i*5+5;k++)
    {
        for(int l=j*5;l<j*5+5;j++)
        {
            marrytemp=A[i]+B[j]+marrytemp;
        }
    }
    marry[i,j]=marrytemp;
}
</code>```

And then it would be called something like:

```<code>clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&A);
clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&B);
clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&marray);

size_t global_item_size[] = {100, 100};
clEnqueueNDRangeKernel(command_queue, kernel, 2, NULL, &global_item_size, NULL, 0, NULL, NULL);
</code>```

Both of these need additional support code (such as creating command_queue and kernel) and have not been compiled. They are just to give you the idea of how to split your four nested loops into an OpenCL kernel.

Body:
There are two circular statement, for example:

for(int i=0;i<1000;i++)
 for (int j=0;j<1000;j++)
{
  for(int k=i*5;k<i*5+5;k++)
   for(int l=j*5;l<j*5+5;j++)
  {
   marrytemp=A[i]+B[j]+marry;
  }
 marry[i,j]=marrytemp;
}

how can l write it in opencl kernel?

Body:
Write the kernel to handle the inner two loops (k,l), then enqueue it as a 2D kernels with global size of i,j.

Edit to add outline of kernel:

The kernel would be something along the lines of:

__kernel void innerLoop(__global float* A, __global float* B, __global float* marry)
{
    int i = get_global_id(1);
    int j = get_global_id(0);
    int marraytemp = 0;
    for(int k=i*5;k<i*5+5;k++)
    {
        for(int l=j*5;l<j*5+5;j++)
        {
            marrytemp=A[i]+B[j]+marrytemp;
        }
    }
    marry[i,j]=marrytemp;
}

And then it would be called something like:

clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&A);
clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&B);
clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&marray);

size_t global_item_size[] = {100, 100};
clEnqueueNDRangeKernel(command_queue, kernel, 2, NULL, &global_item_size, NULL, 0, NULL, NULL);

Both of these need additional support code (such as creating command_queue and kernel) and have not been compiled. They are just to give you the idea of how to split your four nested loops into an OpenCL kernel.


来源: stackexchange

问:
Simple regex - ignoring certain characters
I'm trying to use the match method with an argument of a regex to select a valid phone number, by definition, any string with nine digits.

For example:

9347584987 is valid,

(456)322-3456 is valid,

(324)5688890 is valid.

But

(340)HelloWorld is NOT valid and

456748 is NOT valid.

So far, I'm able to use \d{9} to select the example string of 9 digit characters in a row, but I'm not sure how to specifically ignore any character, such as '-' or '(' or ')' in the middle of the sequence.

What kind of Regex could I use here?

ContentLicense: CC BY-SA 3.0

Body:
Given:

nums=['9347584987','(456)322-3456','(324)5688890','(340)HelloWorld', '456748 is NOT valid']

You can split on a NON digit and rejoin to remove non digits:

> nums.map {|s| s.split(/\D/).join}
["9347584987", "4563223456", "3245688890", "340", "456748"]

Then filter on the length:

> nums.map {|s| s.split(/\D/).join}.select {|s| s.length==10}
["9347584987", "4563223456", "3245688890"]

Or, you can grab a group of numbers that look 'phony numbery' by using a regex to grab digits and common delimiters:

> nums.map {|s| s[/[\d\-()]+/]}
["9347584987", "(456)322-3456", "(324)5688890", "(340)", "456748"]

And then process that list as above.

That would delineate:

> '123 is NOT a valid area code for 456-7890'[/[\d\-()]+/]
=> "123"                               # no match

vs

> '123 is NOT a valid area code for 456-7890'.split(/\D/).join
=> "1234567890"                        # match


问:
How to determine if page is within iFrame and redirect to different pages
I currently have below logic to redirect to login page if session is expired:

```<code>if IsEmpty(Session("Something")) then response.redirect "login.asp"
</code>```

I need to add to this condition to redirect to a separate page if our site is within an external iFrame. So I implemented the following logic:

```<code><script type="text/javascript">
function isSiteFramed() {
    if (window.top !== window.self) {
        return true;
    }
    else {
        return false;
    }
}
</code>```

I am unable to call this javascript function in my vbscript. I was advised not to do the redirection within the javascript function itself as if cross site scripting in URL is put, then the javascript function would not be executed and therefore, the login page would not be redirected.

Any help would be great.

答:
There is no option in VBScript to redirect another frame in the browser.

See this MSDN article Manipulating Frames with VBScript and ASP

While ASP is great at building the individual pages for a web application dynamically, its features are rather limited when it comes to handling the frameset pages that are so common to today's sites. Using the Redirect method of the Response object we can redirect to a single page, but we can't target it to a specific frame—only the browser can do that.

I would also think that Server Side JScript would not be able to detect frames either.

Body:
I currently have below logic to redirect to login page if session is expired:

if IsEmpty(Session("Something")) then response.redirect "login.asp"

I need to add to this condition to redirect to a separate page if our site is within an external iFrame. So I implemented the following logic:


问:
Python not recognizing all elements of a list
I am trying to make a molar mass calculator using python 2.7. My current program works by asking for user input of a chemical formula, such as "C 6 H 12 O 6."

Then, the program turns the input into a list, and then separates the numbers from the characters. To do that, the user list is compared to the element list.

If a character matches up with an element, the program appends that element to a separate list. However, for some reason, 24 (originally 49) elements are not recognized as being in the list of elements, and therefore are not appended onto the new list.

For example, the program doesn't append "Mg" or "Al" to the new list. I have decreased the list of unrecognized elements from 49 to 24 by converting my lists and the input to uppercase with upper().

However, the 24 elements still do not get recognized. Below is the code that I believe is the problem.

```<code>reflistchar = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne','Na', 'Mg']
#A separate loop converts each element to uppercase. Shortened for simplicity.

s1 = raw_input('Formula: ')
s = s1.upper()
slist = s.split(' ')

x = len(slist)
y = 0
for i in range(x):
if any(i in reflistchar for i in slist[y]):
  slchar.append(slist[y])
y += 1
</code>```

For example:

Input:

```<code>element1 element2 element3 element4 element5
</code>```

Expected Output:

```<code>[element1, element2, element3, element4, element5]
</code>```

Current Output:

```<code>[element2, element3, element5]
</code>```

As I tried to show above, the user inputs 5 elements but only some of them are added to the list. The elements that are not added are consistently not added no matter what order they are inputted in.

I think this may be because these elements denote some sort of python function or variable. I greatly appreciate any advice on how to get the program to recognize them.

答:
A couple of pointers...

First, s.split() would be a better alternative to s.split(' ') since it handles multiple spaces better.

Next, you are iterating over a loop,... but not using i anywhere. That's not the main problem though.

Thirdly, the main problem, is this:

```<code>any(i in reflistchar for i in slist[y])
</code>```

slist[y] is a string. For example, if slist[y] holds 'Al', then you first check for 'A' in reflistchar, and then check for 'l' in reflistchar... Because you can iterate over strings too! This is why you're not getting what you want. You should instead use the in operator to check for existence.

Here's a fixed version of your code:

```<code>reflistchar = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne','Na', 'Mg']
string_list = raw_input('Formula: ').upper().split()

reflistchar = set(reflistchar)

elements = []
for e in string_list:
    if e in reflistchar:
        elements.append(e)
</code>```

Bonus! I converted reflistchar to a set for fast, constant O(1) lookup.

Body:
I am trying to make a molar mass calculator using python 2.7. My current program works by asking for user input of a chemical formula, such as "C 6 H 12 O 6."

Then, the program turns the input into a list, and then separates the numbers from the characters. To do that, the user list is compared to the element list.

If a character matches up with an element, the program appends that element to a separate list. However, for some reason, 24 (originally 49) elements are not recognized as being in the list of elements, and therefore are not appended onto the new list.

For example, the program doesn't append "Mg" or "Al" to the new list. I have decreased the list of unrecognized elements from 49 to 24 by converting my lists and the input to uppercase with upper().

However, the 24 elements still do not get recognized. Below is the code that I believe is the problem.

reflistchar = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne','Na', 'Mg']
#A separate loop converts each element to uppercase. Shortened for simplicity.

s1 = raw_input('Formula: ')
s = s1.upper()
slist = s.split(' ')

x = len(slist)
y = 0
for i in range(x):
if any(i in reflistchar for i in slist[y]):
  slchar.append(slist[y])
y += 1

For example:

Input:

element1 element2 element3 element4 element5

Expected Output:

[element1, element2, element3, element4, element5]

Current Output:

[element2, element3, element5]

As I tried to show above, the user inputs 5 elements but only some of them are added to the list. The elements that are not added are consistently not added no matter what order they are inputted in.

I think this may be because these elements denote some sort of python function or variable. I greatly appreciate any advice on how to get the program to recognize them.

Body:
A couple of pointers...

First, s.split() would be a better alternative to s.split(' ') since it handles multiple spaces better.

Next, you are iterating over a loop,... but not using i anywhere. That's not the main problem though.

Thirdly, the main problem, is this:

any(i in reflistchar for i in slist[y])

slist[y] is a string. For example, if slist[y] holds 'Al', then you first check for 'A' in reflistchar, and then check for 'l' in reflistchar... Because you can iterate over strings too! This is why you're not getting what you want. You should instead use the in operator to check for existence.

Here's a fixed version of your code:

reflistchar = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne','Na', 'Mg']
string_list = raw_input('Formula: ').upper().split()

reflistchar = set(reflistchar)

elements = []
for e in string_list:
    if e in reflistchar:
        elements.append(e)

Bonus! I converted reflistchar to a set for fast, constant O(1) lookup.


问:
Code snippets for Delphi?
Is there a good code snippets application for Delphi or general purpose with IDE integration? I would like to store Code, queries, notes, etc..

Thanks

答:
Dittos to Ozmosys above.

Also check CodeSnip Database Viewer from the delphidabbler:
http://www.delphidabbler.com/software/codesnip

OwnerDisplayName: Jlouro

ContentLicense: CC BY-SA 2.5

Title: Code snippets for Delphi?

LastEditorDisplayName: Out Into Space

OwnerDisplayName: Bob S


问:
How can an array value be SIX chars long and echoing nothing (string(6) " ")?
This is really weird. Look what is on my screen right now :

```<code>$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}
</code>```

This is just the output of :

```<code>var_dump($albumGenre);
</code>```

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?

答:
Because that value is a HTML entities &nbsp, like

```<code>var_dump(' ');
</code>```

Make sure you view source, and copy the output from var_dump...

Body:
This is really weird. Look what is on my screen right now :

$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}

This is just the output of :

var_dump($albumGenre);

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?

Body:
Because that value is a HTML entities &nbsp, like

var_dump('&nbsp;');

Make sure you view source, and copy the output from var_dump...


问:
What is httpinterceptor equivalent in angular2?
In angularjs, we have http interceptor

```<code>$httpProvider.interceptors.push('myHttpInterceptor');
</code>```

with which we can hook into all http calls, and show or hide loading bars, do logging, etc..

What is the equivalent in angular2?

答:
As @squadwuschel pointed out, work is underway to get this functionality into @angular/http.  This will be in the form of a new HttpClient API.

See https://github.com/angular/angular/pull/17143 for more details and current status.

Body:
In angularjs, we have http interceptor

$httpProvider.interceptors.push('myHttpInterceptor');

with which we can hook into all http calls, and show or hide loading bars, do logging, etc..

What is the equivalent in angular2?


问:
Combinations from different groups in a specific order
I have a list of parameters that each accept a specific range of inputs. I am working on creating a test that creates every possible valid input. Furthermore, each group is optional (can be skipped entirely), so the combination lengths don't necessarily have to be the same length of the list.

Input

```<code>List<string[]> temp = new List<string[]>
{
    // The order of these groups is important
    new string[] { "a", "b", "c" },
    new string[] { "d", "e" },
    new string[] { "f", "g", "h" }
};
</code>```

Constraints

0 or 1 item per group (a string[] above)

Order of the List<T> must be preserved

Valid Combinations

a, e, f

a, d, g

c, e, f

b, g

c, f

Invalid Combinations

a, b, f (a and b are from the same group - not allowed)

a, f, d (wrong order - d must come before f)

So far, I have gone back to my library where I have a Combinations LINQ method.

```<code>public static class IEnumerableExtensions
{
    // Can be used to get all permutations at a certain level
    // Source: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n#1898744
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}
</code>```

In the past I have only used this on single sequence to do things like generate every permutation of URL segments. But I am struggling with its usage on a nested list with the constraints of one per group and in a specific order.

I know I can solve this particular puzzle by doing 3 nested loops and using lists to track which items were already used, but I don't know in advance how many items will be in the List<T>, so that won't work in the general case.

How can I get all of the valid combinations of the above input?

I would prefer LINQ, but will accept any solution that solves this problem.

答:
Try following :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static List<string[]> temp = new List<string[]>
        {
            // The order of these groups is important
            new string[] { "a", "b", "c" },
            new string[] { "d", "e" },
            new string[] { "f", "g", "h" }
        };
        static void Main(string[] args)
        {
            Recursive(0, new List<string>());
            Console.ReadLine();
        }
        public static void Recursive(int level, List<string> output)
        {
            if (level < temp.Count)
            {
                foreach (string value in temp[level])
                {
                    List<string> newList = new List<string>();
                    newList.AddRange(output);
                    newList.Add(value);
                    Console.WriteLine(string.Join(",", newList));
                    Recursive(level + 1, newList);
                }
            }
        }
    }
}
</code>```

To get additional combinations starting with 2nd and 3rd level change main()

```<code>        static void Main(string[] args)
        {
            for (int i = 0; i < temp.Count; i++)
            {
                Recursive(i, new List<string>());
            }
            Console.ReadLine();
        }
</code>```

Body:
I have a list of parameters that each accept a specific range of inputs. I am working on creating a test that creates every possible valid input. Furthermore, each group is optional (can be skipped entirely), so the combination lengths don't necessarily have to be the same length of the list.

Input

List<string[]> temp = new List<string[]>
{
    // The order of these groups is important
    new string[] { "a", "b", "c" },
    new string[] { "d", "e" },
    new string[] { "f", "g", "h" }
};

Constraints

0 or 1 item per group (a string[] above)

Order of the List<T> must be preserved

Valid Combinations

a, e, f

a, d, g

c, e, f

b, g

c, f

Invalid Combinations

a, b, f (a and b are from the same group - not allowed)

a, f, d (wrong order - d must come before f)

So far, I have gone back to my library where I have a Combinations LINQ method.

public static class IEnumerableExtensions
{
    // Can be used to get all permutations at a certain level
    // Source: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n#1898744
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}

In the past I have only used this on single sequence to do things like generate every permutation of URL segments. But I am struggling with its usage on a nested list with the constraints of one per group and in a specific order.

I know I can solve this particular puzzle by doing 3 nested loops and using lists to track which items were already used, but I don't know in advance how many items will be in the List<T>, so that won't work in the general case.

How can I get all of the valid combinations of the above input?

I would prefer LINQ, but will accept any solution that solves this problem.

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static List<string[]> temp = new List<string[]>
        {
            // The order of these groups is important
            new string[] { "a", "b", "c" },
            new string[] { "d", "e" },
            new string[] { "f", "g", "h" }
        };
        static void Main(string[] args)
        {
            Recursive(0, new List<string>());
            Console.ReadLine();
        }
        public static void Recursive(int level, List<string> output)
        {
            if (level < temp.Count)
            {
                foreach (string value in temp[level])
                {
                    List<string> newList = new List<string>();
                    newList.AddRange(output);
                    newList.Add(value);
                    Console.WriteLine(string.Join(",", newList));
                    Recursive(level + 1, newList);
                }
            }
        }
    }
}

To get additional combinations starting with 2nd and 3rd level change main()

        static void Main(string[] args)
        {
            for (int i = 0; i < temp.Count; i++)
            {
                Recursive(i, new List<string>());
            }
            Console.ReadLine();
        }


问:
How to handle Task.Run Exception
I had a problem with catching the exception from Task.Run which was resolved by changing the code as follows. I'd like to know the difference between handling exceptions in these two ways :

In the Outside method I can't catch the exception, but in the Inside method I can.

```<code>void Outside()
{
    try
    {
        Task.Run(() =>
        {
            int z = 0;
            int x = 1 / z;
        });
    }
    catch (Exception exception)
    {
        MessageBox.Show("Outside : " + exception.Message);
    }
}

void Inside()
{
    Task.Run(() =>
    {
        try
        {
            int z = 0;
            int x = 1 / z;
        }
        catch (Exception exception)
        {
            MessageBox.Show("Inside : "+exception.Message);
        }
    });
}
</code>```

答:
For me I wanted my Task.Run to continue on after an error, letting the UI deal with the error as it has time.

My (weird?) solution is to also have a Form.Timer running.  My Task.Run has it's queue (for long-running non-UI stuff), and my Form.Timer has its queue (for UI stuff).

Since this method was already working for me, it was trivial to add error handling:  If the task.Run gets an error, it adds the error info to the Form.Timer queue, which displays the error dialog.

ContentLicense: CC BY-SA 4.0

Title: How to handle Task.Run Exception

Body:
I had a problem with catching the exception from Task.Run which was resolved by changing the code as follows. I'd like to know the difference between handling exceptions in these two ways :

In the Outside method I can't catch the exception, but in the Inside method I can.

void Outside()
{
    try
    {
        Task.Run(() =>
        {
            int z = 0;
            int x = 1 / z;
        });
    }
    catch (Exception exception)
    {
        MessageBox.Show("Outside : " + exception.Message);
    }
}

void Inside()
{
    Task.Run(() =>
    {
        try
        {
            int z = 0;
            int x = 1 / z;
        }
        catch (Exception exception)
        {
            MessageBox.Show("Inside : "+exception.Message);
        }
    });
}


问:
mailchimp popup form not showing up
I have created a popup form in my mailchimp account and I cannot get it to show up on my site. The code generated is

```<code><script type="text/javascript" src="s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script><script type="text/javascript">require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"xxxx-xxxxx.com","uuid":"xxxxxxxxxxx","lid":"xxxxxxxx"}) })</script>
</code>```

I tried adding it to header.php, footer.php in wordpress but it doesn't work.

答:
it could be conflict with existing jquery.

the embed.js will auto search for jquery.js at the web root directory.
just place the file there and it should works.

if you do not want to mess up your web root by creating another duplicate jquery js file, you can use htaccess to map it to your existing path.

RewriteEngine on
Options +FollowSymLinks
RewriteRule ^/?jquery.js$  /themes/inspinia/vendors/jquery/jquery-2.1.1.js [L]

or, visit this page for more detail:
https://www.organicweb.com.au/19561/wordpress/mailchimp-popup-instructions/

Title: mailchimp popup form not showing up

Body:
I have created a popup form in my mailchimp account and I cannot get it to show up on my site. The code generated is

I tried adding it to header.php, footer.php in wordpress but it doesn't work.


问:
Logging without loss of time
Greetz fellows!

I'm looking for a way to log actions of a CLI script without losing time. I did some benchmarks and I figured out that by echoing someting after each action, the script will be nearly 2x slower and by appending actions to a log file it'll be 17x times slower.

So, anyone has a solution?

答:
Logging to a file should be a lot faster than echoing to the screen (it's the process of displaying the text that's most likely the limit).

As such, you could simply write the debug to a file and (if so required) "tail -f" the file to see the live debug. (I'm presuming you're running under Linux/Unix, etc.)

As a suggestion:

```<code>function logDebugToFile($string) {

    // Set defaults...
    $filename = 'INSERT REQUIRED PATH/FILENAME HERE.log';

    $ourFP = fopen($filename, 'a+');
    if (is_resource($ourFP)) {
        fwrite($ourFP, $string."\n");
        fclose($ourFP);
        return true;
    }

    return false;
}
</code>```

Title: Logging without loss of time

Body:
Logging to a file should be a lot faster than echoing to the screen (it's the process of displaying the text that's most likely the limit).

As such, you could simply write the debug to a file and (if so required) "tail -f" the file to see the live debug. (I'm presuming you're running under Linux/Unix, etc.)

As a suggestion:

function logDebugToFile($string) {

    // Set defaults...
    $filename = 'INSERT REQUIRED PATH/FILENAME HERE.log';

    $ourFP = fopen($filename, 'a+');
    if (is_resource($ourFP)) {
        fwrite($ourFP, $string."\n");
        fclose($ourFP);
        return true;
    }

    return false;
}


问:
Pure CSS, div hover can affect more than one element
I can change the size of a div element when is hover another div element, like this example.
https://jsfiddle.net/9510a6kj/

```<code> .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>
</code>```

But it's possible to change the size of two different div elements when is hover the first element.

For example on mouse hover div "a", change size of div "b" and div "c".

Thank you.

答:
Yes, you can do it with the sibling selector. While the adjacent sibling selector you used in your fiddle will style the element immediately following it in the DOM, the sibling selector will style all the sibling elements as long as they follow .a.

HTML

```<code><div class="parent">
   <div class="a"></div>
   <div class="b"></div>
   <div class="c"></div>
</div>
</code>```

CSS

```<code>.a:hover ~ div{
 //style .b and .c here
}
</code>```

Note well though, the sibling selector only works for siblings that follow...it wont work for siblings before your reference element. CSS cannot go back up the DOM tree as yet.

Body:
I can change the size of a div element when is hover another div element, like this example.
https://jsfiddle.net/9510a6kj/

 .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>

But it's possible to change the size of two different div elements when is hover the first element.

For example on mouse hover div "a", change size of div "b" and div "c".

Thank you.

Body:
Yes, you can do it with the sibling selector. While the adjacent sibling selector you used in your fiddle will style the element immediately following it in the DOM, the sibling selector will style all the sibling elements as long as they follow .a.

HTML

<div class="parent">
   <div class="a"></div>
   <div class="b"></div>
   <div class="c"></div>
</div>

CSS

.a:hover ~ div{
 //style .b and .c here
}

Note well though, the sibling selector only works for siblings that follow...it wont work for siblings before your reference element. CSS cannot go back up the DOM tree as yet.


问:
Nested form for has many :through join model, where join model has additional attribute
I have two models connected through a join model. The join model stores an additional attribute value, which is a boolean A Role has many Permissions through RolePermission, and RolePermission stores whether that Role can perform the action indicated by that Permission.

Every Role should have a RolePermission record for every Permission (of which there are ~10).

I'm having trouble creating my form, however. I want there to be a checkbox for each Permission, which is used to indicate the boolean value of the value attribute for RolePermission.

models

```<code>class Role < ApplicationRecord
    has_many :role_permissions, dependent: :destroy
    has_many :permissions, through: :role_permissions

    accepts_nested_attributes_for :role_permissions
end

class RolePermission < ApplicationRecord
    belongs_to :role
    belongs_to :permission
end

class Permission < ApplicationRecord
    has_many :role_permissions
    has_many :roles, through: :role_permissions
end
</code>```

table columns

```<code>Roles
    name: string
    description: string

Permissions
    name: string
    description: string

RolePermissions
    role: references
    permission: references
    value: boolean
</code>```

views/roles/_form.html.erb

```<code><%= form_for [@chronicle, @role], url: url do |f| %>

    ...

    <%= f.fields_for :role_permissions, Permission.all do |ff| %>
      ???
      <%= ff.label :name %>
      <%= ff.check_box :value %>
      ???
    <% end %>

    <%= f.submit text, class: 'btn btn-primary btn-block' %>
<% end %>
</code>```

controllers/roles_controller.rb

```<code>class RolesController < ApplicationController
    ...

    def create
      @chronicle = Chronicle.find(params[:chronicle_id])
      @role = @chronicle.roles.build(role_params)
      ???
      @role_permissions = @role.role_permissions.build
      ???

      if @chronicle.save
        flash[:success] = 'Role successfully created.'
        redirect_to chronicle_role_url(@chronicle, @role)
      else
        render 'new'
      end
    end

    private
        def role_params
          params.require(:role).permit(:name, :description, role_permission_attributes: [] )
        end
    end
end
</code>```

答:
I still believe in the concept without the Role_permission model in the middle. Each role should have their own permissions (has_many), but the permission name and description are being reused when each role has their permission created.

Here is what i did.

I created a hash with the values for name and description in the private section of the role-controller

```<code># roles_controller.rb
def permission_values
  {
    "Can edit" => "This is not good if you want to party",
    "Can show" => "Yes, yes, yes. Go ahead",
    "Can hike" => "Oh my! A hike-role?",
    "And so on" => "What do we have here?"
  }
end
</code>```

Then when i create the Role and the permissions i use .build with the permission_values.

Couldn't do it with seeds.rb because the Role has to be created before assigning permissions

```<code>#roles_controller.rb
def new
@role = Role.new
  permission_values.each do |titel, desc|
    @role.permissions.build(name: titel, description: desc)
  end
end
</code>```

And in the form i use .object and .hidden_field to show and create the values.

```<code># _form.html.erb
...
<%= f.fields_for :permissions do |ff|%>
<h4><%= ff.object.name %></h4>
<%= ff.hidden_field :name %>
<p><%= ff.object.description %></p>
<%= ff.hidden_field :description %>
<%= ff.check_box :permitted %>
<% end %>
</code>```

And there you have it!

Now each user will have the same permissions displayed, but they can check permitted if they want and save it with their Role.
In the show, something like:

```<code># show.html.erb
# I would make a helper-method
# And some index-symbol-power!
<%= "Hey! I'm permitted to do this!" if @role.permissions.find_by_name("Can
edit").permitted? %>
</code>```

Note:

Remember the :id in the permission_attributes in the role_params, so the permissions doesn't duplicate on edit.

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

Body:
I have two models connected through a join model. The join model stores an additional attribute value, which is a boolean A Role has many Permissions through RolePermission, and RolePermission stores whether that Role can perform the action indicated by that Permission.

Every Role should have a RolePermission record for every Permission (of which there are ~10).

I'm having trouble creating my form, however. I want there to be a checkbox for each Permission, which is used to indicate the boolean value of the value attribute for RolePermission.

models

class Role < ApplicationRecord
    has_many :role_permissions, dependent: :destroy
    has_many :permissions, through: :role_permissions

    accepts_nested_attributes_for :role_permissions
end

class RolePermission < ApplicationRecord
    belongs_to :role
    belongs_to :permission
end

class Permission < ApplicationRecord
    has_many :role_permissions
    has_many :roles, through: :role_permissions
end

table columns

Roles
    name: string
    description: string

Permissions
    name: string
    description: string

RolePermissions
    role: references
    permission: references
    value: boolean

views/roles/_form.html.erb

<%= form_for [@chronicle, @role], url: url do |f| %>

    ...

    <%= f.fields_for :role_permissions, Permission.all do |ff| %>
      ???
      <%= ff.label :name %>
      <%= ff.check_box :value %>
      ???
    <% end %>

    <%= f.submit text, class: 'btn btn-primary btn-block' %>
<% end %>

controllers/roles_controller.rb

class RolesController < ApplicationController
    ...

    def create
      @chronicle = Chronicle.find(params[:chronicle_id])
      @role = @chronicle.roles.build(role_params)
      ???
      @role_permissions = @role.role_permissions.build
      ???

      if @chronicle.save
        flash[:success] = 'Role successfully created.'
        redirect_to chronicle_role_url(@chronicle, @role)
      else
        render 'new'
      end
    end

    private
        def role_params
          params.require(:role).permit(:name, :description, role_permission_attributes: [] )
        end
    end
end

Body:
I still believe in the concept without the Role_permission model in the middle. Each role should have their own permissions (has_many), but the permission name and description are being reused when each role has their permission created.

Here is what i did.

I created a hash with the values for name and description in the private section of the role-controller

# roles_controller.rb
def permission_values
  {
    "Can edit" => "This is not good if you want to party",
    "Can show" => "Yes, yes, yes. Go ahead",
    "Can hike" => "Oh my! A hike-role?",
    "And so on" => "What do we have here?"
  }
end

Then when i create the Role and the permissions i use .build with the permission_values.

Couldn't do it with seeds.rb because the Role has to be created before assigning permissions

#roles_controller.rb
def new
@role = Role.new
  permission_values.each do |titel, desc|
    @role.permissions.build(name: titel, description: desc)
  end
end

And in the form i use .object and .hidden_field to show and create the values.

# _form.html.erb
...
<%= f.fields_for :permissions do |ff|%>
<h4><%= ff.object.name %></h4>
<%= ff.hidden_field :name %>
<p><%= ff.object.description %></p>
<%= ff.hidden_field :description %>
<%= ff.check_box :permitted %>
<% end %>

And there you have it!

Now each user will have the same permissions displayed, but they can check permitted if they want and save it with their Role.
In the show, something like:

# show.html.erb
# I would make a helper-method
# And some index-symbol-power!
<%= "Hey! I'm permitted to do this!" if @role.permissions.find_by_name("Can
edit").permitted? %>

Note:

Remember the :id in the permission_attributes in the role_params, so the permissions doesn't duplicate on edit.

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


问:
How to clone Bitbucket repo using OAuth so that it works more than an hour
For GitHub repository I'm able to call e.g.

```<code>$ git clone https://49d2a764bad9037cbb4a98bb27b3eba4f68d7264@github.com/owner/repo.git
</code>```

And then I have:

```<code>$ git remote -vv
origin        https://49d2a764bad9037cbb4a98bb27b3eba4f68d7264@github.com/owner/repo.git (fetch)
origin        https://49d2a764bad9037cbb4a98bb27b3eba4f68d7264@github.com/owner/repo.git (push)
</code>```

Then I can contribute to the repository without credentials indefinitely.

Now for Bitbucket OAuth tokens expire after one hour.
Is it possible to achieve the same "functionality" for Bitbucket repo?

Can App Password be used for this?

Can refresh_token be used for this better than having to issue a curl to actually refresh the token manually like described here https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html?

答:
You can use an app-specific password for this, as long as you grant sufficient permissions for whatever it is you're trying to do. Set up the app password in your Bitbucket settings under "App password"; once you make your selections, Bitbucket will generate the password for you, and show it to you once.

To use your new app password with Git, you can set the URL on the remote to something like the following (assuming your username on Bitbucket is "user" and the randomly-generated app password is "pass"):

[remote "origin"]
url = https://user:pass@bitbucket.org/owner/repo.git

To use an app password with Mercurial, you can set things in the [auth] section of the repo's hgrc:

[auth]
bb.prefix = https://bitbucket.org/owner/repo
bb.username = user
bb.password = pass

Body:
For GitHub repository I'm able to call e.g.

$ git clone https://49d2a764bad9037cbb4a98bb27b3eba4f68d7264@github.com/owner/repo.git

And then I have:

$ git remote -vv
origin        https://49d2a764bad9037cbb4a98bb27b3eba4f68d7264@github.com/owner/repo.git (fetch)
origin        https://49d2a764bad9037cbb4a98bb27b3eba4f68d7264@github.com/owner/repo.git (push)

Then I can contribute to the repository without credentials indefinitely.

Now for Bitbucket OAuth tokens expire after one hour.
Is it possible to achieve the same "functionality" for Bitbucket repo?

Can App Password be used for this?

Can refresh_token be used for this better than having to issue a curl to actually refresh the token manually like described here https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html?


问:
FrameLayout Interference with AppBarLayout
My Problem with FrameLayout

FrameLayout style Interference with AppBarLayout

I want to be under the AppBarLayout

problem screenshot

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        android:layoutDirection="rtl"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Create FrameLayout like this:</p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
            <android.support.design.widget.CoordinatorLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="56dp"
                    android:background="?attr/colorPrimary"
                    app:layout_scrollFlags="scroll|enterAlways"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                <android.support.design.widget.TabLayout
                    android:id="@+id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabMode="fixed"
                    android:layoutDirection="rtl"
                    app:tabGravity="fill"/>
            </android.support.design.widget.AppBarLayout>

            <FrameLayout
                android:id="@+id/frame_container"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
            </android.support.design.widget.CoordinatorLayout>
</code>```

Body:
My Problem with FrameLayout

FrameLayout style Interference with AppBarLayout

I want to be under the AppBarLayout

problem screenshot

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        android:layoutDirection="rtl"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>

Body:
Create FrameLayout like this:

    <?xml version="1.0" encoding="utf-8"?>
            <android.support.design.widget.CoordinatorLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="56dp"
                    android:background="?attr/colorPrimary"
                    app:layout_scrollFlags="scroll|enterAlways"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                <android.support.design.widget.TabLayout
                    android:id="@+id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabMode="fixed"
                    android:layoutDirection="rtl"
                    app:tabGravity="fill"/>
            </android.support.design.widget.AppBarLayout>

            <FrameLayout
                android:id="@+id/frame_container"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
            </android.support.design.widget.CoordinatorLayout>


问:
Pandas - remove row similar to other row
I need to remove all rows from a pandas.DataFrame, which satisfy an unusual condition.

In case there is an exactly the same row, except for it has Nan value in column "C", I want to remove this row.

Given a table:

```<code>A    B    C      D
1    2    NaN    3
1    2    50     3
10   20   NaN    30
5    6    7      8
</code>```

I need to remove the first row, since it has Nan in column C, but there is absolutely same row (second) with real value in column C.

However, 3rd row must stay, because there're no rows with same A, B and D values as it has.

How do you perform this using pandas? Thank you!

答:
This feels right to me</p>

```<code>notdups = ~df.duplicated(df.columns.difference(['C']), keep=False)
notnans = df.C.notnull()

df[notdups | notnans]

    A   B     C   D
1   1   2  50.0   3
2  10  20   NaN  30
3   5   6   7.0   8
</code>```

Body:
I need to remove all rows from a pandas.DataFrame, which satisfy an unusual condition.

In case there is an exactly the same row, except for it has Nan value in column "C", I want to remove this row.

Given a table:

A    B    C      D
1    2    NaN    3
1    2    50     3
10   20   NaN    30
5    6    7      8

I need to remove the first row, since it has Nan in column C, but there is absolutely same row (second) with real value in column C.

However, 3rd row must stay, because there're no rows with same A, B and D values as it has.

How do you perform this using pandas? Thank you!

Body:
This feels right to me

notdups = ~df.duplicated(df.columns.difference(['C']), keep=False)
notnans = df.C.notnull()

df[notdups | notnans]

    A   B     C   D
1   1   2  50.0   3
2  10  20   NaN  30
3   5   6   7.0   8


问:
Show values from a MySQL database table inside a HTML table on a webpage
I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:

```<code><table border="1">
  <tr>
    <th>Submission ID</th>
    <th>Form ID</th>
    <th>IP</th>
    <th>Name</th>
    <th>E-mail</th>
    <th>Message</th>
  </tr>
  <tr>
    <td>123456789</td>
    <td>12345</td>
    <td>123.555.789</td>
    <td>John Johnny</td>
    <td>johnny@example.com</td>
    <td>This is the message John sent you</td>
  </tr>
</table>
</code>```

And then all the other values below 'john'.

答:
Learn more about PHP and the MySQLi Library at PHP.net.

First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:

```<code><?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
</code>```

Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a
 tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use 	 for each value, and also to open and close each row with echo"
" and echo"
. Finally we close the table, and the connection as well with mysqli::close().

```<code><?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
    echo "<tr>";
    for($i = 0; $i < $queryResult->field_count; $i++){
        echo "<td>$queryRow[$i]</td>";
    }
    echo "</tr>";
}
echo "</table>";
$conn->close();
?>
</code>```

Body:
I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:

    Submission ID
    Form ID
    IP
    Name
    E-mail
    Message

    123456789
    12345
    123.555.789
    John Johnny
    johnny@example.com
    This is the message John sent you

And then all the other values below 'john'.

Body:
Learn more about PHP and the MySQLi Library at PHP.net.

First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:

<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>

Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().

<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
    echo "<tr>";
    for($i = 0; $i < $queryResult->field_count; $i++){
        echo "<td>$queryRow[$i]</td>";
    }
    echo "</tr>";
}
echo "</table>";
$conn->close();
?>


问:
what is the need to create .babelrc in preact application
I am starting with Preact application. the documentation says

Instead of declaring the @jsx pragma in your code, it's best to configure it globally in a .babelrc:

For Babel 5 and prior:

```<code>{ "jsxPragma": "h" }
</code>```

For Babel 6:

```<code>{
  "plugins": [
    ["transform-react-jsx", { "pragma":"h" }]
  ]
}
</code>```

I am new to Preact world and wants to understand why do we need to create this file & what is jsx pragma ?

答:
The pragma is a comment (/** @jsx h */ here) placed on the top of a file containing some JSX, telling the JSX transformer which function you want to call to create each element of you virtual dom. Preact uses hyperscript, that's why you need to use the h pragma. Preact suggest to create this file so babel take care of the pragma itself, without you needing to add it to every file. This way you can't forget to put it on a file.

You suggest you to read WTF is JSX, which is a fundamental post if you want to know everything about JSX.

Body:
I am starting with Preact application. the documentation says

Instead of declaring the @jsx pragma in your code, it's best to configure it globally in a .babelrc:

For Babel 5 and prior:

{ "jsxPragma": "h" }

For Babel 6:

{
  "plugins": [
    ["transform-react-jsx", { "pragma":"h" }]
  ]
}

I am new to Preact world and wants to understand why do we need to create this file & what is jsx pragma ?


问:
json key value javascript : display value
I have an array 'images':

```<code>images":[{"url":"/uploads/posts/images/1/image.jpg"}]
</code>```

I then did the following to get the path of the first image:

```<code>var image = JSON.stringify(gon.posts[i].images[0]);
</code>```

However this makes var image:

```<code>{"url":"/uploads/posts/images/1/image.jpg"}
</code>```

How do I get just the path ie:

```<code>/uploads/posts/images/1/image.jpg ?
</code>```

I tried image.url but it didn't work.

答:
try this:</p>

```<code>var obj = {"images":[{"url":"/uploads/posts/images/1/image.jpg"}]};
alert(obj.images[0].url);
</code>```

Body:
I have an array 'images':

images":[{"url":"/uploads/posts/images/1/image.jpg"}]

I then did the following to get the path of the first image:

var image = JSON.stringify(gon.posts[i].images[0]);

However this makes var image:

{"url":"/uploads/posts/images/1/image.jpg"}

How do I get just the path ie:

/uploads/posts/images/1/image.jpg ?

I tried image.url but it didn't work.

Body:
try this:

var obj = {"images":[{"url":"/uploads/posts/images/1/image.jpg"}]};
alert(obj.images[0].url);


问:
Meteor 1.5 : Dynamic Import for Blaze
I am having two questions:

1) I want to use Meteor 1.5 Dynamic Import for Blaze but all the examples and tutorials are given for React. So I am confused how exactly it can be used . Can anyone give examples of it.

2) I am using packages from atmospherejs.com like amcharts which I only need at Admin Dashboard side. How to dynamically import them?

Thanks in Advance!

UPDATE(Solution):

Below is homepage.html (parent template)

```<code><template name="homepage">
  Homepage Content
 {{> Template.dynamic template=content}}
</template>
</code>```

login.html (child template)

```<code><template name="login">
  You're logged in!
</template>
</code>```

login.js

```<code>import '../homepage/homepage.js';
import './login.html';
API = function () {
  BlazeLayout.render("homepage",{content: 'login'});
}

export { API }
</code>```

main.js

```<code>LoadLogin = function () {
  import('/imports/modules/common/login/login.js').then(function (api) {
    api.API();
  })
}
</code>```

/lib/route.js

```<code>import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
FlowRouter.route('/', {
  name: 'homepage',
  action() {
    LoadLogin();
  }
});
</code>```

答:
The basic technique for dynamically importing modules in Meteor 1.5 using Blaze is as follows:

```<code>Template.theTemplate.events({
  'click button'(event, instance) {
    import("foo").then(Foo => {
      console.log(Foo);
    });
  }
});
</code>```

Make sure you take a close look at how your module is then imported, because apparently some refactoring may be needed when calling it in your code. For example, using "zxcvbn":

WAS

```<code>const result = zxcvbn(pwd);
</code>```

IS

```<code>const result = zxcvbn.default(pwd);
</code>```

Title: Meteor 1.5 : Dynamic Import for Blaze

Body:
I am having two questions:

1) I want to use Meteor 1.5 Dynamic Import for Blaze but all the examples and tutorials are given for React. So I am confused how exactly it can be used . Can anyone give examples of it.

2) I am using packages from atmospherejs.com like amcharts which I only need at Admin Dashboard side. How to dynamically import them?

Thanks in Advance!

UPDATE(Solution):

Below is homepage.html (parent template)

<template name="homepage">
  Homepage Content
 {{> Template.dynamic template=content}}
</template>

login.html (child template)

<template name="login">
  You're logged in!
</template>

login.js

import '../homepage/homepage.js';
import './login.html';
API = function () {
  BlazeLayout.render("homepage",{content: 'login'});
}

export { API }

main.js

LoadLogin = function () {
  import('/imports/modules/common/login/login.js').then(function (api) {
    api.API();
  })
}

/lib/route.js

import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
FlowRouter.route('/', {
  name: 'homepage',
  action() {
    LoadLogin();
  }
});

Body:
The basic technique for dynamically importing modules in Meteor 1.5 using Blaze is as follows:

Template.theTemplate.events({
  'click button'(event, instance) {
    import("foo").then(Foo => {
      console.log(Foo);
    });
  }
});

Make sure you take a close look at how your module is then imported, because apparently some refactoring may be needed when calling it in your code. For example, using "zxcvbn":

WAS

const result = zxcvbn(pwd);

IS

const result = zxcvbn.default(pwd);


问:
Select records based on what a field begins with?
I have a database with a table that has identifiers c1, c2, c3..etc..

Instead of writing a query that has a bunch of ORs in it, how can I modify the below query with something that will catch all the records that begin with a certain letter?

```<code>SELECT
    Person.spineinjuryAdmit,
    tblComorbidity.comorbidityexplanation,
    Count(tblComorbidity.comorbidityexplanation) AS CountOfcomorbidityexplanation

FROM tblKentuckyCounties
INNER JOIN (tblComorbidity
            INNER JOIN (Person
                        INNER JOIN tblComorbidityPerson
                            ON Person.PersonID = tblComorbidityPerson.personID)
                ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK)
    ON tblKentuckyCounties.ID = Person.County
GROUP BY    Person.spineinjuryAdmit,
            tblComorbidity.comorbidityexplanation
HAVING (((Person.spineinjuryAdmit)="c1" Or
         (Person.spineinjuryAdmit)="c2" Or
         (Person.spineinjuryAdmit)="c3"));
</code>```

答:
You can use regexp to query all rows that starts with several characters.

```<code>SELECT * FROM table WHERE column REGEXP '^[ c1, c2, c3]';
</code>```

This query will return all rows where column starts with 'c1' or 'c2' or 'c3'.

Body:
I have a database with a table that has identifiers c1, c2, c3..etc..

Instead of writing a query that has a bunch of ORs in it, how can I modify the below query with something that will catch all the records that begin with a certain letter?

SELECT
    Person.spineinjuryAdmit,
    tblComorbidity.comorbidityexplanation,
    Count(tblComorbidity.comorbidityexplanation) AS CountOfcomorbidityexplanation

FROM tblKentuckyCounties
INNER JOIN (tblComorbidity
            INNER JOIN (Person
                        INNER JOIN tblComorbidityPerson
                            ON Person.PersonID = tblComorbidityPerson.personID)
                ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK)
    ON tblKentuckyCounties.ID = Person.County
GROUP BY    Person.spineinjuryAdmit,
            tblComorbidity.comorbidityexplanation
HAVING (((Person.spineinjuryAdmit)="c1" Or
         (Person.spineinjuryAdmit)="c2" Or
         (Person.spineinjuryAdmit)="c3"));

Body:
You can use regexp to query all rows that starts with several characters.

SELECT * FROM table WHERE column REGEXP '^[ c1, c2, c3]';

This query will return all rows where column starts with 'c1' or 'c2' or 'c3'.


问:
Forum email address display issue
I created a web forum with the script below. I am able to receive inquiries from my site; however, the visitor's email address is not showing in the email sent from the webmaster. I would like to have some guidance here to fix the problem.

Here is my PHP script:

```<code><?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "abc@gmail.com";
$subject = "Contact Form";
mail($recipient, $subject, $formcontent) or die("Error!");
echo "Thank You!";
?>
</code>```

Here is what I got from the webmaster:
From: xx
Message: xx

No email address listed in the email sent by the webmaster.

I found some similar scripts on the web with two additional rows:

```<code>$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
</code>```

This actually gives me an Error output.

How can I fix the issue?

Thanks!

答:
You could add headers to the mail function.

```<code>$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "abc@gmail.com";
$subject = "Contact Form";

$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: <$email>" . "\r\n";

mail($recipient, $subject, $formcontent, $headers);
</code>```

FYI - I would santize and validate all POST values before using them in this manner

Title: Forum email address display issue

Body:
I created a web forum with the script below. I am able to receive inquiries from my site; however, the visitor's email address is not showing in the email sent from the webmaster. I would like to have some guidance here to fix the problem.

Here is my PHP script:

<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "abc@gmail.com";
$subject = "Contact Form";
mail($recipient, $subject, $formcontent) or die("Error!");
echo "Thank You!";
?>

Here is what I got from the webmaster:
From: xx
Message: xx

No email address listed in the email sent by the webmaster.

I found some similar scripts on the web with two additional rows:

$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");

This actually gives me an Error output.

How can I fix the issue?

Thanks!

Body:
You could add headers to the mail function.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "abc@gmail.com";
$subject = "Contact Form";

$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: <$email>" . "\r\n";

mail($recipient, $subject, $formcontent, $headers);

FYI - I would santize and validate all POST values before using them in this manner


问:
Remove all Key Shortcuts from Visual Studio
Is it possible to remove all Key-Shortcuts from Visual Studio, so I can assign them from scratch? I don't mean to reset them to their default value, but to nothing.</p>

答:
I wanted to do the same with my installation of Visual Studio - to remove all shortcuts and assign my own, from scratch. I managed to achieve this with a hacky AutoHotKey script.

If you select a command that is bound to a shortcut, within the 'Keyboard' section of the Visual Studio Options dialog, the 'Remove' button should activate. Notice that the 'R' is underlined (which, if isn't, hold the Alt key down).

On Windows, this generally means that the button can be activated by pressing Alt, and the underlined character.

Removing all shortcuts is then a matter of repeatedly un-binding the selected command with Alt + R and selecting the next command (↓), which I automated using the following script:

```<code>#z::              ; Binds to Win + Z.
Loop, 3500        ; Loops 3500 times.
{
    Send, {Down}  ; Sends the down keystroke.
    Send, !r      ; Sends the Alt + R keystroke.
    Sleep, 30     ; Delays for 30ms.
}
Return
</code>```

Adjust the number of repetitions (3500), and the hotkey to invoke the script (#z which means Win + Z) as necessary. Run the script, select the first command in the list, press (in this case) Win + Z, and wait for it to complete.

Note that commands don't always have a single key-binding, and therefore you might have to run the script a couple of times, or better yet, send the Alt + R keystroke multiple times a single repetition.

The script will attempt to remove un-assigned shortcuts too, upon which Windows will play a 'beeping' sound and therefore make sure to mute Windows before running the script.

Body:
I wanted to do the same with my installation of Visual Studio - to remove all shortcuts and assign my own, from scratch. I managed to achieve this with a hacky AutoHotKey script.

If you select a command that is bound to a shortcut, within the 'Keyboard' section of the Visual Studio Options dialog, the 'Remove' button should activate. Notice that the 'R' is underlined (which, if isn't, hold the Alt key down).

On Windows, this generally means that the button can be activated by pressing Alt, and the underlined character.

Removing all shortcuts is then a matter of repeatedly un-binding the selected command with Alt + R and selecting the next command (↓), which I automated using the following script:

#z::              ; Binds to Win + Z.
Loop, 3500        ; Loops 3500 times.
{
    Send, {Down}  ; Sends the down keystroke.
    Send, !r      ; Sends the Alt + R keystroke.
    Sleep, 30     ; Delays for 30ms.
}
Return

Adjust the number of repetitions (3500), and the hotkey to invoke the script (#z which means Win + Z) as necessary. Run the script, select the first command in the list, press (in this case) Win + Z, and wait for it to complete.

Note that commands don't always have a single key-binding, and therefore you might have to run the script a couple of times, or better yet, send the Alt + R keystroke multiple times a single repetition.

The script will attempt to remove un-assigned shortcuts too, upon which Windows will play a 'beeping' sound and therefore make sure to mute Windows before running the script.


问:
Adding Number Represented by Linked List
I'm stuck on this problem:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8

The problem is that  my result is 8 8 while the result should be 8 0 8.
I printed out the sum and it is 8 10 8 so it should work.
Any ideas?

Here is my code:

```<code>public Node addNumbers(Node number1, Node number2) {

        if(number1 == null && number2 == null)
            return null;

        Node sumOf = null;
        int sum = 0;
        int carry = 0;

        while(number1 != null && number2 != null) {
            sum = number1.data + number2.data + carry;
            System.out.println(sum);
            // update carry for next operation
            if(sum > 9)
                carry = 1;
            else
                carry = 0;

            if(sum > 9) {
                if(sumOf == null) {
                    sumOf = new Node(sum % 10);
                } else {
                    sumOf.next = new Node(sum % 10);
                }

            } else {
                if(sumOf == null) {
                    sumOf = new Node(sum);
                } else {
                    sumOf.next = new Node(sum);
                }

            }

            number1 = number1.next;
            number2 = number2.next;
        }

        return sumOf;
    }

    public void toString(Node node) {
        System.out.println();
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }

    public static void main(String[] args) {

        AddTwoNumbers add = new AddTwoNumbers();

        number1 = new Node(3);
        number1.next = new Node(1);
        number1.next.next = new Node(5);

        number2  = new Node(5);
        number2.next = new Node(9);
        number2.next.next = new Node(2);

        System.out.println("numbers: ");
        add.toString(number1);
        add.toString(number2);

        System.out.println();
        System.out.println("after adding: ");
        add.toString(add.addNumbers(number1, number2));
    }
}
</code>```

答:
Here is the solution, do note that i carry forward when the sum of two integers is greater than 9 else i continue with the sum of next integers from both the list.

```<code>class Node {
    private Object data;
    private Node next;
    public Object getData() { return data; }
    public void setData(Object data) {  this.data = data; }
    public Node getNext() { return next; }
    public void setNext(Node next) { this.next = next; }
    public Node(final Object data, final Node next) {
        this.data = data;
        this.next = next;
    }
    @Override
    public String toString() { return "Node:[Data=" + data + "]"; }
}

class SinglyLinkedList {
    Node start;
    public SinglyLinkedList() { start = null; }

    public void addFront(final Object data) {
        // create a reference to the start node with new data
        Node node = new Node(data, start);

        // assign our start to a new node
        start = node;
    }

    public void addRear(final Object data) {
        Node node = new Node(data, null);
        Node current = start;

        if (current != null) {
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(node);
        } else {
            addFront(data);
        }
    }

    public void deleteNode(final Object data) {
        Node previous = start;

        if (previous == null) {
            return;
        }

        Node current = previous.getNext();

        if (previous != null && previous.getData().equals(data)) {
            start = previous.getNext();
            previous = current;
            current = previous.getNext();
            return;
        }

        while (current != null) {
            if (current.getData().equals(data)) {
                previous.setNext(current.getNext());
                current = previous.getNext();
            } else {
                previous = previous.getNext();
                current = previous.getNext();
            }
        }
    }

    public Object getFront() {
        if (start != null) {
            return start.getData();
        } else {
            return null;
        }
    }

    public void print() {
        Node current = start;

        if (current == null) {
            System.out.println("SingleLinkedList is Empty");
        }

        while (current != null) {
            System.out.print(current);
            current = current.getNext();
            if (current != null) {
                System.out.print(", ");
            }
        }
    }

    public int size() {
        int size = 0;

        Node current = start;

        while (current != null) {
            current = current.getNext();
            size++;
        }
        return size;
    }

    public Node getStart() {
        return this.start;
    }

    public Node getRear() {
        Node current = start;
        Node previous = current;
        while (current != null) {
            previous = current;
            current = current.getNext();
        }
        return previous;
    }
}

public class AddNumbersInSinglyLinkedList {
    public static void main(String[] args) {
        SinglyLinkedList listOne = new SinglyLinkedList();
        SinglyLinkedList listTwo = new SinglyLinkedList();
        listOne.addFront(5);
        listOne.addFront(1);
        listOne.addFront(3);
        listOne.print();
        System.out.println();
        listTwo.addFront(2);
        listTwo.addFront(9);
        listTwo.addFront(5);
        listTwo.print();
        SinglyLinkedList listThree = add(listOne, listTwo);
        System.out.println();
        listThree.print();
    }

    private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
        SinglyLinkedList result = new SinglyLinkedList();
        Node startOne = listOne.getStart();
        Node startTwo = listTwo.getStart();
        int carry = 0;
        while (startOne != null || startTwo != null) {
            int one = 0;
            int two = 0;
            if (startOne != null) {
                one = (Integer) startOne.getData();
                startOne = startOne.getNext();
            }
            if (startTwo != null) {
                two = (Integer) startTwo.getData();
                startTwo = startTwo.getNext();
            }
            int sum = carry + one + two;
            carry = 0;
            if (sum > 9) {
                carry = sum / 10;
                result.addRear(sum % 10);
            } else {
                result.addRear(sum);
            }
        }
        return result;
    }
}
</code>```

Sample Run

```<code>Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]
</code>```

Body:
I'm stuck on this problem:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8

The problem is that  my result is 8 8 while the result should be 8 0 8.
I printed out the sum and it is 8 10 8 so it should work.
Any ideas?

Here is my code:

public Node addNumbers(Node number1, Node number2) {

        if(number1 == null && number2 == null)
            return null;

        Node sumOf = null;
        int sum = 0;
        int carry = 0;

        while(number1 != null && number2 != null) {
            sum = number1.data + number2.data + carry;
            System.out.println(sum);
            // update carry for next operation
            if(sum > 9)
                carry = 1;
            else
                carry = 0;

            if(sum > 9) {
                if(sumOf == null) {
                    sumOf = new Node(sum % 10);
                } else {
                    sumOf.next = new Node(sum % 10);
                }

            } else {
                if(sumOf == null) {
                    sumOf = new Node(sum);
                } else {
                    sumOf.next = new Node(sum);
                }

            }

            number1 = number1.next;
            number2 = number2.next;
        }

        return sumOf;
    }

    public void toString(Node node) {
        System.out.println();
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }

    public static void main(String[] args) {

        AddTwoNumbers add = new AddTwoNumbers();

        number1 = new Node(3);
        number1.next = new Node(1);
        number1.next.next = new Node(5);

        number2  = new Node(5);
        number2.next = new Node(9);
        number2.next.next = new Node(2);

        System.out.println("numbers: ");
        add.toString(number1);
        add.toString(number2);

        System.out.println();
        System.out.println("after adding: ");
        add.toString(add.addNumbers(number1, number2));
    }
}

Body:
Here is the solution, do note that i carry forward when the sum of two integers is greater than 9 else i continue with the sum of next integers from both the list.

class Node {
    private Object data;
    private Node next;
    public Object getData() { return data; }
    public void setData(Object data) {  this.data = data; }
    public Node getNext() { return next; }
    public void setNext(Node next) { this.next = next; }
    public Node(final Object data, final Node next) {
        this.data = data;
        this.next = next;
    }
    @Override
    public String toString() { return "Node:[Data=" + data + "]"; }
}

class SinglyLinkedList {
    Node start;
    public SinglyLinkedList() { start = null; }

    public void addFront(final Object data) {
        // create a reference to the start node with new data
        Node node = new Node(data, start);

        // assign our start to a new node
        start = node;
    }

    public void addRear(final Object data) {
        Node node = new Node(data, null);
        Node current = start;

        if (current != null) {
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(node);
        } else {
            addFront(data);
        }
    }

    public void deleteNode(final Object data) {
        Node previous = start;

        if (previous == null) {
            return;
        }

        Node current = previous.getNext();

        if (previous != null && previous.getData().equals(data)) {
            start = previous.getNext();
            previous = current;
            current = previous.getNext();
            return;
        }

        while (current != null) {
            if (current.getData().equals(data)) {
                previous.setNext(current.getNext());
                current = previous.getNext();
            } else {
                previous = previous.getNext();
                current = previous.getNext();
            }
        }
    }

    public Object getFront() {
        if (start != null) {
            return start.getData();
        } else {
            return null;
        }
    }

    public void print() {
        Node current = start;

        if (current == null) {
            System.out.println("SingleLinkedList is Empty");
        }

        while (current != null) {
            System.out.print(current);
            current = current.getNext();
            if (current != null) {
                System.out.print(", ");
            }
        }
    }

    public int size() {
        int size = 0;

        Node current = start;

        while (current != null) {
            current = current.getNext();
            size++;
        }
        return size;
    }

    public Node getStart() {
        return this.start;
    }

    public Node getRear() {
        Node current = start;
        Node previous = current;
        while (current != null) {
            previous = current;
            current = current.getNext();
        }
        return previous;
    }
}

public class AddNumbersInSinglyLinkedList {
    public static void main(String[] args) {
        SinglyLinkedList listOne = new SinglyLinkedList();
        SinglyLinkedList listTwo = new SinglyLinkedList();
        listOne.addFront(5);
        listOne.addFront(1);
        listOne.addFront(3);
        listOne.print();
        System.out.println();
        listTwo.addFront(2);
        listTwo.addFront(9);
        listTwo.addFront(5);
        listTwo.print();
        SinglyLinkedList listThree = add(listOne, listTwo);
        System.out.println();
        listThree.print();
    }

    private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
        SinglyLinkedList result = new SinglyLinkedList();
        Node startOne = listOne.getStart();
        Node startTwo = listTwo.getStart();
        int carry = 0;
        while (startOne != null || startTwo != null) {
            int one = 0;
            int two = 0;
            if (startOne != null) {
                one = (Integer) startOne.getData();
                startOne = startOne.getNext();
            }
            if (startTwo != null) {
                two = (Integer) startTwo.getData();
                startTwo = startTwo.getNext();
            }
            int sum = carry + one + two;
            carry = 0;
            if (sum > 9) {
                carry = sum / 10;
                result.addRear(sum % 10);
            } else {
                result.addRear(sum);
            }
        }
        return result;
    }
}

Sample Run

Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]


问:
OpenFile always open with PDF
Hi boys and girls(of course)

I have this method to open a file

```<code>public static void openFile(String filePath, Activity activity) {
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("file://"+filePath));
        activity.startActivityForResult(intent, 10);
    }catch (Exception e){
        e.printStackTrace();
        Toast.makeText(context, "Error abriendo."+filePath+" Abrir manualmente", Toast.LENGTH_LONG).show();
    }
}
</code>```

but when I sets the file path to a image.jpg saved in my sdcard it's always try to open with PDF-Drive and it's makes an error try open this kind of file.
but when I open the file directly from a filemanager it's opens with a default imageViewer.
 What I'm doing wrong?
Regards

答:
I tried to compile in java (NetBeans) a lib.jar but when I imported it to the android project it said that I could not find the Path class and the other that gave me error

I solved by creating my own getMimeType

At https://www.sitepoint.com/web-foundations/mime-types-complete-list/ I found a fairly complete list
I made a

```<code>HashMap<String, String> ~ <ext,mime>
</code>```

And to get the mime to the hash that contains all I ask me of the value of the extension

```<code>map.get(".bmp");
</code>```

Title: OpenFile always open with PDF

Body:
Hi boys and girls(of course)

I have this method to open a file

public static void openFile(String filePath, Activity activity) {
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("file://"+filePath));
        activity.startActivityForResult(intent, 10);
    }catch (Exception e){
        e.printStackTrace();
        Toast.makeText(context, "Error abriendo."+filePath+" Abrir manualmente", Toast.LENGTH_LONG).show();
    }
}

but when I sets the file path to a image.jpg saved in my sdcard it's always try to open with PDF-Drive and it's makes an error try open this kind of file.
but when I open the file directly from a filemanager it's opens with a default imageViewer.
 What I'm doing wrong?
Regards

Body:
I tried to compile in java (NetBeans) a lib.jar but when I imported it to the android project it said that I could not find the Path class and the other that gave me error

I solved by creating my own getMimeType

At https://www.sitepoint.com/web-foundations/mime-types-complete-list/ I found a fairly complete list
I made a

HashMap<String, String> ~ <ext,mime>

And to get the mime to the hash that contains all I ask me of the value of the extension

map.get(".bmp");


问:
Using a variable from another python file
I have the below code where I am interested in using the fqdm_or_ip variable in another python file.

This file is menu.py

```<code>def CONN_PARAMS():
    print("1. FQDN")
    print("2. IP ADDRESS")
    fqdn_or_ip = input("Are you going to use an IP or FQDN for the controller")
    if fqdn_or_ip == 1:
        controller = input("Enter FQDN or IP address"  )
        print("Are you sure this is correct?   " + controller)

    elseif (fqdn_or_ip) == 2):
        controller = input("Enter FQDN or IP address"):
</code>```

I am using the below code but I am unsure how to move the variable between files...once the menu.py collects answers to my questions the other python file will begin using that information.

This file is the one I am trying to pull the variable into....I think I am supposed to pass the variable into the () of menu.CONN_PARAMS but I was unsure how.

```<code>#!/usr/bin/python3

# import requests module for REST API calls
import requests

# import json module
import json

# menu.py
import menu

menu.CONN_PARAMS()
</code>```

Best,

Dan

答:
You could return the value you're interested in from the function you're calling.

If you're interested in multiple values you could also return a tuple / list / dict / ... instead of a single value.

menu.py

```<code>def CONN_PARAMS():
    print("1. FQDN")
    print("2. IP ADDRESS")
    fqdn_or_ip = input("Are you going to use an IP or FQDN for the controller")
    # ... whatever you need to do
    return fqdn_or_ip
</code>```

other_file.py

```<code># menu.py
import menu

fqdn_or_ip = menu.CONN_PARAMS()
</code>```

Body:
I have the below code where I am interested in using the fqdm_or_ip variable in another python file.

This file is menu.py

def CONN_PARAMS():
    print("1. FQDN")
    print("2. IP ADDRESS")
    fqdn_or_ip = input("Are you going to use an IP or FQDN for the controller")
    if fqdn_or_ip == 1:
        controller = input("Enter FQDN or IP address"  )
        print("Are you sure this is correct?   " + controller)

    elseif (fqdn_or_ip) == 2):
        controller = input("Enter FQDN or IP address"):

I am using the below code but I am unsure how to move the variable between files...once the menu.py collects answers to my questions the other python file will begin using that information.

This file is the one I am trying to pull the variable into....I think I am supposed to pass the variable into the () of menu.CONN_PARAMS but I was unsure how.

#!/usr/bin/python3

# import requests module for REST API calls
import requests

# import json module
import json

# menu.py
import menu

menu.CONN_PARAMS()

Best,

Dan

Body:
You could return the value you're interested in from the function you're calling.

If you're interested in multiple values you could also return a tuple / list / dict / ... instead of a single value.

menu.py

def CONN_PARAMS():
    print("1. FQDN")
    print("2. IP ADDRESS")
    fqdn_or_ip = input("Are you going to use an IP or FQDN for the controller")
    # ... whatever you need to do
    return fqdn_or_ip

other_file.py

# menu.py
import menu

fqdn_or_ip = menu.CONN_PARAMS()


问:
How can I set cookie in node js using express framework?
In my application, I need to set a cookie using the express framework. I have tried the following code but it's not setting the cookie.</p>
```<code>var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.static(__dirname + '/public'));

      app.use(function (req, res) {
           var randomNumber=Math.random().toString();
           randomNumber=randomNumber.substring(2,randomNumber.length);
           res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })

           console.log('cookie have created successfully');
      });

});

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);
</code>```

答:
Set a cookie:

```<code>res.cookie('cookie', 'monster')
</code>```

https://expressjs.com/en/4x/api.html#res.cookie

Read a cookie:

(using cookie-parser middleware)

```<code>req.cookies['cookie']
</code>```

https://expressjs.com/en/4x/api.html#req.cookies

Body:
In my application, I need to set a cookie using the express framework. I have tried the following code but it's not setting the cookie.

var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.static(__dirname + '/public'));

      app.use(function (req, res) {
           var randomNumber=Math.random().toString();
           randomNumber=randomNumber.substring(2,randomNumber.length);
           res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })

           console.log('cookie have created successfully');
      });

});

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);

Body:
Set a cookie:

res.cookie('cookie', 'monster')

https://expressjs.com/en/4x/api.html#res.cookie

Read a cookie:

(using cookie-parser middleware)

req.cookies['cookie']

https://expressjs.com/en/4x/api.html#req.cookies


问:
EaselJs animation issue
This is my first time learning EaselJs. I am having issues making my sprite animate with the five animations I listed in the data structure. Would anyone have an idea what I'm doing wrong?

link : my code

```<code>      function CreateTile(x,y, stage){
    var rect = new createjs.Shape();
    rect.graphics.beginFill("green").drawRect(0,0,50,50);
    rect.x = x;
    rect.y = y;

    var rect2 = new createjs.Shape();
    rect2.graphics.beginFill("lightgreen").drawRect(0,0,46,46);
    rect2.x = x + 2;
    rect2.y = y + 2;

    stage.addChild(rect);
    stage.addChild(rect2);
  }

  function GenerateField(height, width, stage)
  {
     var h_lim = height / 50;
     var w_lim = width / 50;

     for(var h = 0; h < h_lim; h++){
       for(var w = 0; w < w_lim; w++){
         CreateTile(w * 50,h * 50,stage);
       }
     }
     stage.update();
  }
  function init() {
    var stage = new createjs.Stage("demoCanvas");
    GenerateField(800,600, stage);
    var img = new Image();
    img.crossOrigin="Anonymous";
    img.src = "https://s13.postimg.org/n1dqnac93/spritesheet.png";
        var data = {
      images : [img],
      frames: {width:64, height:64},
        animations: {
            stand:0,
            forwardwalk:[0,1,2, "forwardwalk"],
            leftwalk:[7,8, "leftwalk"],
            rightwalk:[3,4, "rightwalk"],
            backwalk:[9,10,11, "backwalk"]
        }
    };

    var spritesheet = new createjs.SpriteSheet(data);
    var person   = new createjs.Sprite(spritesheet);
    person.x = 400;
    person.y = 400;
    person.gotoAndPlay("forwardwalk");
    stage.addChild(person);

    window.addEventListener('keydown', function(e){
        var code = e.keyCode;
        switch(code){
          case 37:
          person.x -= 64;
          stage.update();
          break; //Left key
          case 38:
          person.y -= 64;
          stage.update();
          break; //Up key
          case 39:
          person.x += 64;
          stage.update();
          break; //Right key
          case 40:
          person.y += 64;
          stage.update();
          break; //Down key
          default:
          break; // ignore
        }
    }, false);

    createjs.Ticker.useRAF = true;
    createjs.Ticker.setFPS(5);
    createjs.Ticker.on("tick", stage);
  }
</code>```

答:
This issue you have is that you have improperly defined your spritesheet. Spritesheets support a few formats:

Simple: Just a single name + frame (how you defined "stand"

Consecutive frames: name + start/end frame, as well as a "next" and "speed". This is how most of your "left" and "right" walk animations are defined.

Complex: If you have frames out of order, this is the best approach, since you specify the exact frame list, and then the other parameters specifically.

You can read all the format info here.

I believe you have confused the consecutive approach with the complex, and put 3 frames into the "forwardwalk" and "backwardwalk" animations. The animation find "2" as the next animation, and "forwardwalk" as the speed.

Instead of [0,1,2,"forwardwalk"], use [0,2,"forwardwalk"]. Same for "backwardwalk".

That should do it! Your sample works fine with that change.

Title: EaselJs animation issue

Body:
This is my first time learning EaselJs. I am having issues making my sprite animate with the five animations I listed in the data structure. Would anyone have an idea what I'm doing wrong?

link : my code

      function CreateTile(x,y, stage){
    var rect = new createjs.Shape();
    rect.graphics.beginFill("green").drawRect(0,0,50,50);
    rect.x = x;
    rect.y = y;

    var rect2 = new createjs.Shape();
    rect2.graphics.beginFill("lightgreen").drawRect(0,0,46,46);
    rect2.x = x + 2;
    rect2.y = y + 2;

    stage.addChild(rect);
    stage.addChild(rect2);
  }

  function GenerateField(height, width, stage)
  {
     var h_lim = height / 50;
     var w_lim = width / 50;

     for(var h = 0; h < h_lim; h++){
       for(var w = 0; w < w_lim; w++){
         CreateTile(w * 50,h * 50,stage);
       }
     }
     stage.update();
  }
  function init() {
    var stage = new createjs.Stage("demoCanvas");
    GenerateField(800,600, stage);
    var img = new Image();
    img.crossOrigin="Anonymous";
    img.src = "https://s13.postimg.org/n1dqnac93/spritesheet.png";
        var data = {
      images : [img],
      frames: {width:64, height:64},
        animations: {
            stand:0,
            forwardwalk:[0,1,2, "forwardwalk"],
            leftwalk:[7,8, "leftwalk"],
            rightwalk:[3,4, "rightwalk"],
            backwalk:[9,10,11, "backwalk"]
        }
    };

    var spritesheet = new createjs.SpriteSheet(data);
    var person   = new createjs.Sprite(spritesheet);
    person.x = 400;
    person.y = 400;
    person.gotoAndPlay("forwardwalk");
    stage.addChild(person);

    window.addEventListener('keydown', function(e){
        var code = e.keyCode;
        switch(code){
          case 37:
          person.x -= 64;
          stage.update();
          break; //Left key
          case 38:
          person.y -= 64;
          stage.update();
          break; //Up key
          case 39:
          person.x += 64;
          stage.update();
          break; //Right key
          case 40:
          person.y += 64;
          stage.update();
          break; //Down key
          default:
          break; // ignore
        }
    }, false);

    createjs.Ticker.useRAF = true;
    createjs.Ticker.setFPS(5);
    createjs.Ticker.on("tick", stage);
  }


答:
The third parameter of mail() is just the actual body of the message, which you have saved as $message. The fourth variable is where you define the headers, and is where you define who the message is From. Note that you don't actually need to pass the message as a header, and as such, your variable $formcontent, shouldn't contain your From: header. However, you do need to provide carriage returns in the form of "\r\n" after the provided email address.

The modified code would look like this:

```<code><?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name" . "\r\n";
$recipient = "abc@gmail.com";
$subject = "Contact Form";
mail($recipient, $subject, $message, $formcontent) or die("Error!");
echo "Thank You!";
?>
</code>```

Hope this helps! :)

Title: Forum email address display issue

Body:
The third parameter of mail() is just the actual body of the message, which you have saved as $message. The fourth variable is where you define the headers, and is where you define who the message is From. Note that you don't actually need to pass the message as a header, and as such, your variable $formcontent, shouldn't contain your From: header. However, you do need to provide carriage returns in the form of "\r\n" after the provided email address.

The modified code would look like this:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name" . "\r\n";
$recipient = "abc@gmail.com";
$subject = "Contact Form";
mail($recipient, $subject, $message, $formcontent) or die("Error!");
echo "Thank You!";
?>

Hope this helps! :)