问:
C++ array pointer
I came across a C++ program like this

```<code>#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}
</code>```

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

答:
Int-array a is explicitly initialized to contain 10 elements. The internal representation of the variable a is a pointer to the first element. Writing a[3] is "give me the contents of a with an offset of 3".

The variable b is then created as an array of pointers (length 5) to int (it is not "point" but "pointer", btw). b is initialized with the contents of a, but since a is of a different type, it has to be typecast to the correct type (that is, b's type). Type cast basically means "pretend that the memory of variable a was of a different type". This is here done with a c-style cast

```<code>(int(*)[5]) a
</code>```

All in all, I wouldn't strive to replicate this coding style.

Also, the following code only works if a pointer to int is twice the size of an int, e.g. 64 bit pointer, 32 bit int. Dirty, dirty code.

Title: C++ array pointer

Body:
I came across a C++ program like this

#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

Body:
Int-array a is explicitly initialized to contain 10 elements. The internal representation of the variable a is a pointer to the first element. Writing a[3] is "give me the contents of a with an offset of 3".

The variable b is then created as an array of pointers (length 5) to int (it is not "point" but "pointer", btw). b is initialized with the contents of a, but since a is of a different type, it has to be typecast to the correct type (that is, b's type). Type cast basically means "pretend that the memory of variable a was of a different type". This is here done with a c-style cast

(int(*)[5]) a

All in all, I wouldn't strive to replicate this coding style.

Also, the following code only works if a pointer to int is twice the size of an int, e.g. 64 bit pointer, 32 bit int. Dirty, dirty code.


来源: stackexchange

问:
Electron builder icon is not showing on MAC
I am using electron-builder to build a dmg for mac version. Current version I use is 7.14.2 . I add build/icon.icns file which is 1024x1024 size, but after the build I see default EBP icon. I also set dmg icon which is showing on the top window panel when I have to move my app to Applications folder, but not on Application icon itself.

What I am doing wrong, the icon size? Or should I load icon through my BrowserWindow?

Thanks,
Tadas

答:
The best solution I found was to update to the latest electron-builder, as this issue was apparently fixed in version 8.4.1.

There was a fix for this exact issue. The issue show how some attempts were made to fix it but I found updating worked a treat
https://github.com/electron-userland/electron-builder/issues/840

ContentLicense: CC BY-SA 3.0


问:
Auto Rotates Movie View Screen in Swift3

When I click Play button, mediaPlayer view show the following picture.
How to auto rotates when I play mediaPlayer? Please! help me.

答:
Add this line in your ViewController.m file

```<code>  override func supportedInterfaceOrientations() -> Int {
  return Int(UIInterfaceOrientationMask.Landscape.rawValue)
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
  return UIInterfaceOrientation.LandscapeLeft
}

override func shouldAutorotate() -> Bool {
  return false
}
</code>```

And viewcontoller should be presented.

Body:
Add this line in your ViewController.m file

  override func supportedInterfaceOrientations() -> Int {
  return Int(UIInterfaceOrientationMask.Landscape.rawValue)
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
  return UIInterfaceOrientation.LandscapeLeft
}

override func shouldAutorotate() -> Bool {
  return false
}

And viewcontoller should be presented.


问:
File Locking (Read/Write) in ASP.NET Application
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

```<code>public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}
</code>```

And here's my code for the Reader :

```<code>private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}
</code>```

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

答:
Doing this in a web based environment, you are going to have a lot of issues with file locks, can you change this up to use a database instead?

Most hosting solutions are allowing up to 250mb SQL databases.

Not only will a database help with the locking issues, it will also allow you to purge older data more easily, after a wile, that log read is going to get really slow.

ContentLicense: CC BY-SA 2.5

Body:
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}

And here's my code for the Reader :

private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

OwnerDisplayName: Tom Anderson


问:
Is XHTML really Xtensible?
Is there any way (server- or client-side) that I can actually extend HTML to include new tags?  For example, it would be cool if I could write something like a schema fragment that defined a blogpost, which contains a postname, a postauthor, a posttime, and a postcontent, and thereafter refer to blogpost in my HTML rather than resorting to the basic HTML div and p tags.

答:
While the browser won't readily understand extensions based on the XML-derived extensibility, that doesn't mean people aren't working on this problem.

HTML5 additions like
 aside, the best solution for what you're trying to do is probably microformats. In the case of your blog example, hAtom.

Then you get something that browsers understand, but can be progressively enhanced as more systems support hAtom and you can style entries using class references like .hentry, .entry-title, and .author.

Title: Is XHTML really Xtensible?

Body:
While the browser won't readily understand extensions based on the XML-derived extensibility, that doesn't mean people aren't working on this problem.

HTML5 additions like <section> aside, the best solution for what you're trying to do is probably microformats. In the case of your blog example, hAtom.

Then you get something that browsers understand, but can be progressively enhanced as more systems support hAtom and you can style entries using class references like .hentry, .entry-title, and .author.


问:
I want to build a custom angularjs Unique Value Directive
I want to build a directive that checks for duplicate username. So I have created an index.html file and an uniqueId directive. Now in the directive I am not able to do ngModel.setValidity(). It is getting undefined.

Also I am fetching data from a local json file username.json.

When I console log console.log(ngModel.$setValidity('unique', unique)) I get undefined.

I have created a plunk for the code::

https://embed.plnkr.co/XTPf9PjiMn9if5Y0DaHt/

答:
please check plnkr link

If you type nitesh@gmail.com, it will display email already in use.
If you type nitesh@gmail.com1, it won't show error message.
I have changed condition.


问:
Which Java Collections are synchronized(thread safe), which are not?
Which Java Collections are synchronized, which are not?

Example:   HashSet is not synchronized

答:
synchronize makes performance lower. of course, Java collection is not synchronized. but Java provides a Synchronization Wrappers to synchronize Java Collection see link</p>

```<code>for example:

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;

    public class SynchronizedListExample {

        public static void main(String[] args) {

            List<String> syncList = Collections.synchronizedList(new ArrayList<String>());

            syncList.add("one");//no need to synchronize here
            syncList.add("two");
            syncList.add("three");
            String st = syncList.get(0); //it is ok here => no need to synchronize

            // when iterating over a synchronized list, we need to synchronize access to the synchronized list
           //because if you don't synchronize here, synchList maybe be changed during iterating over it
            synchronized (syncList) {
                Iterator<String> iterator = syncList.iterator();
                while (iterator.hasNext()) {
                    System.out.println("item: " + iterator.next());
                }
            }

        }

    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
synchronize makes performance lower. of course, Java collection is not synchronized. but Java provides a Synchronization Wrappers to synchronize Java Collection see link

for example:

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;

    public class SynchronizedListExample {

        public static void main(String[] args) {

            List<String> syncList = Collections.synchronizedList(new ArrayList<String>());

            syncList.add("one");//no need to synchronize here
            syncList.add("two");
            syncList.add("three");
            String st = syncList.get(0); //it is ok here => no need to synchronize

            // when iterating over a synchronized list, we need to synchronize access to the synchronized list
           //because if you don't synchronize here, synchList maybe be changed during iterating over it
            synchronized (syncList) {
                Iterator<String> iterator = syncList.iterator();
                while (iterator.hasNext()) {
                    System.out.println("item: " + iterator.next());
                }
            }

        }

    }


问:
Calculating the current member balance based on transactional data
I have a MySQL table of financial transactions.

The table is like so:

```<code>+----+-----------+--------+--------+---------+---------+
| id | member_id | status | amount | opening | closing |
+----+-----------+--------+--------+---------+---------+
| 1  | 2         | 1      | 1000   | 0       | 1000    |
| 2  | 2         | 2      | 100    | 1000    | 1000    |
| 3  | 2         | 1      | -20    | 1000    | 980     |
| 4  | 2         | 1      | 10     | 980     | 990     |
+----+-----------+--------+--------+---------+---------+
</code>```

Currently the opening and closing fields are empty. Status 1 is committed, and 2 is uncommitted.

Can some one please tell me how I would write a query to scan the entire table and update all the opening and closing balances?

There is almost 1,000,000 records in this table so it would be nice if the query was quite optimized. Also this is not going to be needed for real time mission critical data. It would only be the current estimation of the members balance.

答: Why not a materialized view created from stored procedures? It would separate the logic between data and calculated values. It would also give the fastest possible queries.</p>

Body:
I have a MySQL table of financial transactions.

The table is like so:

+----+-----------+--------+--------+---------+---------+
| id | member_id | status | amount | opening | closing |
+----+-----------+--------+--------+---------+---------+
| 1  | 2         | 1      | 1000   | 0       | 1000    |
| 2  | 2         | 2      | 100    | 1000    | 1000    |
| 3  | 2         | 1      | -20    | 1000    | 980     |
| 4  | 2         | 1      | 10     | 980     | 990     |
+----+-----------+--------+--------+---------+---------+

Currently the opening and closing fields are empty. Status 1 is committed, and 2 is uncommitted.

Can some one please tell me how I would write a query to scan the entire table and update all the opening and closing balances?

There is almost 1,000,000 records in this table so it would be nice if the query was quite optimized. Also this is not going to be needed for real time mission critical data. It would only be the current estimation of the members balance.


问:
what function can help me to know user input first character in textfield and how to make a blank line when I press keyboard return?
I have two problems.I am a beginner of swift

First,I want to hide the send button until user input frist character.I use textfield delegate functions that they don't implement this idea.

And then, I want to creat a blank line when user input in textfield.I know to use "textFieldShouldReturn" function ,but I use "\n" that it doesn't work for me.How to do this?

this is my code:

```<code>func textFieldDidBeginEditing(_ textField: UITextField) {

if textField.text?.isEmpty == false {

        aButton.isHidden = true
        sendButton.isHidden = false
    }
}
</code>```

update code:

```<code>func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    self.textField.text = "\n"

    return true
}
</code>```

I also want the textfield change it height.let user can input their message. Does it can be implement?

Or I need to change textfield to textview.

答:
You can use textfields delegate method to check when user start writing something in your textfield.</p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    if textField == txtUserName //compare with your textfield object which you have taken by outlet
    {
        if string.characters.count >= 1 {
        //make your button enable
        }else
        {
        // disable  your button
        }
    }

    return true
}
</code>```

Body:
I have two problems.I am a beginner of swift

First,I want to hide the send button until user input frist character.I use textfield delegate functions that they don't implement this idea.

And then, I want to creat a blank line when user input in textfield.I know to use "textFieldShouldReturn" function ,but I use "\n" that it doesn't work for me.How to do this?

this is my code:

func textFieldDidBeginEditing(_ textField: UITextField) {

if textField.text?.isEmpty == false {

        aButton.isHidden = true
        sendButton.isHidden = false
    }
}

update code:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    self.textField.text = "\n"

    return true
}

I also want the textfield change it height.let user can input their message. Does it can be implement?

Or I need to change textfield to textview.

Body:
You can use textfields delegate method to check when user start writing something in your textfield.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    if textField == txtUserName //compare with your textfield object which you have taken by outlet
    {
        if string.characters.count >= 1 {
        //make your button enable
        }else
        {
        // disable  your button
        }
    }

    return true
}


问:
Python find succesive numbers in array/list
I have an array like this arr = [1,2,3,10,11,15] from which I want to have the numbers left and right of each block of successive numbers, i.e. [0,4,9,12,14,16].

答:
```<code>from itertools import groupby
from operator import itemgetter
arr = [1,2,3,10,11,15]
new_list = []
for m, n in groupby(enumerate(arr), lambda (i, x): i-x):
    t = map(itemgetter(1), n)
    new_list.append(t[0]-1)
    new_list.append(t[-1]+1)

new_list
Out[]: [0, 4, 9, 12, 14, 16]
</code>```


问:
Stretch image (not background) to full browser width in Wordpress with HTML and CSS
I'm trying to make a GIF display to full browser size, however I want it below menu (site-header div) and above footer. In order to do that I hid the page-header div and am stuck in a small container. `

```<code><div id="content" class="site-content"><div class="page-header"><div class="container"><h1 class="entry-title">Kampania</h1></div></div><div id="content-inside" class="container no-sidebar"><div id="primary" class="content-area"><main id="main" class="site-main" role="main"><article id="post-1259" class="post-1259 page type-page status-publish hentry"><header class="entry-header"></header><div class="entry-content"><p><img src="https://shop.sin.org.pl/wp-content/uploads/2017/03/gif.gif" id="selector"></p></div></article></main></div></div></div>
</code>```

What is packed in div "content-area" I need to move to the "site-content" div. How do I achieve that?

https://shop.sin.org.pl/pl/kampania/

Thanks!

答:
Try to add this CSS:</p>

```<code>#content-inside {
   max-width: 100%!important;
   padding: 0px!important;
}
</code>```

Body:
I'm trying to make a GIF display to full browser size, however I want it below menu (site-header div) and above footer. In order to do that I hid the page-header div and am stuck in a small container. `

Kampania

What is packed in div "content-area" I need to move to the "site-content" div. How do I achieve that?

https://shop.sin.org.pl/pl/kampania/

Thanks!

Body:
Try to add this CSS:

#content-inside {
   max-width: 100%!important;
   padding: 0px!important;
}


问:
Pandas assert_frame_equal error
I'm building test cases and I want to compare 2 dataframes.
Even though dataframe have the same columns and values assert_frame_equal reports are not equal.
Column order is different, I tried reordering columns without any success.

In my test case Im using the following function:

```<code>testing.assert_frame_equal(expected, tested, check_dtype=False)
</code>```

The first dataframe is declared like this:

```<code>    df2 = pandas.DataFrame({
    'artista': [u'Beyoncé', 'Radiolab', 'Xmas', 'Beyonce'],
    'mid_sugerido': ['/g/11bz0dg4b_', '/g/11bt_6j9dk', '/g/11c2nz8jc2', '/g/11bt_6jXXX'],
    'texto': ['Lemonade', 'Radiolab', 'Merry Christmas Lil Mama', 'Beyonce'],
    'busqueda': [u'Beyoncé', 'Radiolab', 'Xmas', 'Beyonce'],
    'texto_sugerido': ['Lemonade', 'Radiolab', 'Merry Christmas Lil Mama', 'Beyonce'],
    'artista_sugerido': [u'Beyoncé', 'Radiolab', None, 'Beyonce'],
    'media_sugerido': ['album', 'album', 'track', 'album'],

})
</code>```

Pandas dataframe pd2:

```<code>    artista artista_sugerido  busqueda media_sugerido   mid_sugerido  \
0   Beyoncé          Beyoncé   Beyoncé          album  /g/11bz0dg4b_
1  Radiolab         Radiolab  Radiolab          album  /g/11bt_6j9dk
2      Xmas             None      Xmas          track  /g/11c2nz8jc2
3   Beyonce          Beyonce   Beyonce          album  /g/11bt_6jXXX

                      texto            texto_sugerido
0                  Lemonade                  Lemonade
1                  Radiolab                  Radiolab
2  Merry Christmas Lil Mama  Merry Christmas Lil Mama
3                   Beyonce                   Beyonce
</code>```

The second dataframe is the dataframe returned from function (result).

```<code>    artista  busqueda   mid_sugerido                     texto  \
0   Beyoncé   Beyoncé  /g/11bz0dg4b_                  Lemonade
1  Radiolab  Radiolab  /g/11bt_6j9dk                  Radiolab
2      Xmas      Xmas  /g/11c2nz8jc2  Merry Christmas Lil Mama
3   Beyonce   Beyonce  /g/11bt_6jXXX                   Beyonce

             texto_sugerido artista_sugerido media_sugerido
0                  Lemonade          Beyoncé          album
1                  Radiolab         Radiolab          album
2  Merry Christmas Lil Mama             None          track
3                   Beyonce          Beyonce          album
</code>```

I get the following error when i run: assert_frame_equal(df2, result)

```<code>Traceback (most recent call last):
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 158, in <module>
    assert_frame_equal(df6, _Normalize(df5, test_dict))
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 16, in assert_frame_equal
    testing.assert_frame_equal(expected, tested, check_dtype=False)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 1142, in assert_frame_equal
    obj='{0}.columns'.format(obj))
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 761, in assert_index_equal
    obj=obj, lobj=left, robj=right)
  File "pandas/src/testing.pyx", line 58, in pandas._testing.assert_almost_equal (pandas/src/testing.c:3887)
  File "pandas/src/testing.pyx", line 147, in pandas._testing.assert_almost_equal (pandas/src/testing.c:2769)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 915, in raise_assert_detail
    raise AssertionError(msg)
AssertionError: DataFrame.columns are different

DataFrame.columns values are different (85.71429 %)
[left]:  Index([u'artista', u'artista_sugerido', u'busqueda', u'media_sugerido',
       u'mid_sugerido', u'texto', u'texto_sugerido'],
      dtype='object')
[right]: Index([u'artista', u'busqueda', u'mid_sugerido', u'texto', u'texto_sugerido',
       u'artista_sugerido', u'media_sugerido'],
      dtype='object')
</code>```

Columns are the same, but different order, If I use df.sort_index(axis=1) to reorder columns I get:

```<code>Traceback (most recent call last):
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 154, in <module>
    assert_frame_equal(df6.sort_index(axis=1), _Normalize(df5, test_dict).sort_index(axis=1))
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 16, in assert_frame_equal
    testing.assert_frame_equal(expected, tested, check_dtype=False, check_like=False)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 1166, in assert_frame_equal
    obj='DataFrame.iloc[:, {0}]'.format(i))
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 1049, in assert_series_equal
    check_less_precise, obj='{0}'.format(obj))
  File "pandas/src/testing.pyx", line 58, in pandas._testing.assert_almost_equal (pandas/src/testing.c:3887)
  File "pandas/src/testing.pyx", line 147, in pandas._testing.assert_almost_equal (pandas/src/testing.c:2769)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 914, in raise_assert_detail
    [right]: {3}""".format(obj, message, left, right)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)
</code>```

答:
I solved it by replacing:

```<code>assert_frame_equal(df2.sort_index(axis=1), myfunction(df1).sort_index(axis=1))
</code>```

with

```<code>l  = myfunction(df1)
assert_frame_equal(df2.sort_index(axis=1), l.sort_index(axis=1))
</code>```

Title: Pandas assert_frame_equal error

Body:
I'm building test cases and I want to compare 2 dataframes.
Even though dataframe have the same columns and values assert_frame_equal reports are not equal.
Column order is different, I tried reordering columns without any success.

In my test case Im using the following function:

testing.assert_frame_equal(expected, tested, check_dtype=False)

The first dataframe is declared like this:

    df2 = pandas.DataFrame({
    'artista': [u'Beyoncé', 'Radiolab', 'Xmas', 'Beyonce'],
    'mid_sugerido': ['/g/11bz0dg4b_', '/g/11bt_6j9dk', '/g/11c2nz8jc2', '/g/11bt_6jXXX'],
    'texto': ['Lemonade', 'Radiolab', 'Merry Christmas Lil Mama', 'Beyonce'],
    'busqueda': [u'Beyoncé', 'Radiolab', 'Xmas', 'Beyonce'],
    'texto_sugerido': ['Lemonade', 'Radiolab', 'Merry Christmas Lil Mama', 'Beyonce'],
    'artista_sugerido': [u'Beyoncé', 'Radiolab', None, 'Beyonce'],
    'media_sugerido': ['album', 'album', 'track', 'album'],

})

Pandas dataframe pd2:

    artista artista_sugerido  busqueda media_sugerido   mid_sugerido  \
0   Beyoncé          Beyoncé   Beyoncé          album  /g/11bz0dg4b_
1  Radiolab         Radiolab  Radiolab          album  /g/11bt_6j9dk
2      Xmas             None      Xmas          track  /g/11c2nz8jc2
3   Beyonce          Beyonce   Beyonce          album  /g/11bt_6jXXX

                      texto            texto_sugerido
0                  Lemonade                  Lemonade
1                  Radiolab                  Radiolab
2  Merry Christmas Lil Mama  Merry Christmas Lil Mama
3                   Beyonce                   Beyonce

The second dataframe is the dataframe returned from function (result).

    artista  busqueda   mid_sugerido                     texto  \
0   Beyoncé   Beyoncé  /g/11bz0dg4b_                  Lemonade
1  Radiolab  Radiolab  /g/11bt_6j9dk                  Radiolab
2      Xmas      Xmas  /g/11c2nz8jc2  Merry Christmas Lil Mama
3   Beyonce   Beyonce  /g/11bt_6jXXX                   Beyonce

             texto_sugerido artista_sugerido media_sugerido
0                  Lemonade          Beyoncé          album
1                  Radiolab         Radiolab          album
2  Merry Christmas Lil Mama             None          track
3                   Beyonce          Beyonce          album

I get the following error when i run: assert_frame_equal(df2, result)

Traceback (most recent call last):
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 158, in <module>
    assert_frame_equal(df6, _Normalize(df5, test_dict))
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 16, in assert_frame_equal
    testing.assert_frame_equal(expected, tested, check_dtype=False)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 1142, in assert_frame_equal
    obj='{0}.columns'.format(obj))
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 761, in assert_index_equal
    obj=obj, lobj=left, robj=right)
  File "pandas/src/testing.pyx", line 58, in pandas._testing.assert_almost_equal (pandas/src/testing.c:3887)
  File "pandas/src/testing.pyx", line 147, in pandas._testing.assert_almost_equal (pandas/src/testing.c:2769)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 915, in raise_assert_detail
    raise AssertionError(msg)
AssertionError: DataFrame.columns are different

DataFrame.columns values are different (85.71429 %)
[left]:  Index([u'artista', u'artista_sugerido', u'busqueda', u'media_sugerido',
       u'mid_sugerido', u'texto', u'texto_sugerido'],
      dtype='object')
[right]: Index([u'artista', u'busqueda', u'mid_sugerido', u'texto', u'texto_sugerido',
       u'artista_sugerido', u'media_sugerido'],
      dtype='object')

Columns are the same, but different order, If I use df.sort_index(axis=1) to reorder columns I get:

Traceback (most recent call last):
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 154, in <module>
    assert_frame_equal(df6.sort_index(axis=1), _Normalize(df5, test_dict).sort_index(axis=1))
  File "/Users/spicyramen/Documents/Development/parzee/python/coverage/experimental/pandas_creation.py", line 16, in assert_frame_equal
    testing.assert_frame_equal(expected, tested, check_dtype=False, check_like=False)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 1166, in assert_frame_equal
    obj='DataFrame.iloc[:, {0}]'.format(i))
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 1049, in assert_series_equal
    check_less_precise, obj='{0}'.format(obj))
  File "pandas/src/testing.pyx", line 58, in pandas._testing.assert_almost_equal (pandas/src/testing.c:3887)
  File "pandas/src/testing.pyx", line 147, in pandas._testing.assert_almost_equal (pandas/src/testing.c:2769)
  File "/Library/Python/2.7/site-packages/pandas/util/testing.py", line 914, in raise_assert_detail
    [right]: {3}""".format(obj, message, left, right)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

Body:
I solved it by replacing:

assert_frame_equal(df2.sort_index(axis=1), myfunction(df1).sort_index(axis=1))

with

l  = myfunction(df1)
assert_frame_equal(df2.sort_index(axis=1), l.sort_index(axis=1))


问:
Function triggered onOpen stopped working
Some time ago I wrote a script for one of my spreadsheets, that uses installable trigger onOpen to initiate SpreadsheetApp.getUi function.

The function looks like that:

```<code>function addMenu()
{
  // adding custom menu
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('New menu')
  .addSubMenu(ui.createMenu('menu')
              .addItem('item', 'functionName')
              .addSubMenu(ui.createMenu('additive')
                          .addItem('subitem', 'subfunctionName')))
  .addToUi();
};
</code>```

This menu worked like a charm using installable trigger onOpen being fired from spreadsheet. The functions called by these menu items use UserProperties, so I made sure this is not running anonymously.

This week I noticed that the menu no longer works when I open the spreadsheet - it only works if I call it directly from the script editor.

I have no idea how to fix this - I made no changes to the script, and checked to be sure nobody else did meddle with it. It's the same script that worked up until now.

I would very much appreciate the help on this one, it's puzzling to say the least.

Thanks!

答:
Are the submenus supposed to be nested inside each other? If not, you're probably looking for:</p>

```<code>function addMenu() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('New menu')
    .addSubMenu(ui.createMenu('menu')
      .addItem('item', 'functionName')
    )
    .addSubMenu(ui.createMenu('additive')
      .addItem('subitem', 'subfunctionName')
    )
    .addToUi()
};
</code>```

Body:
Some time ago I wrote a script for one of my spreadsheets, that uses installable trigger onOpen to initiate SpreadsheetApp.getUi function.

The function looks like that:

function addMenu()
{
  // adding custom menu
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('New menu')
  .addSubMenu(ui.createMenu('menu')
              .addItem('item', 'functionName')
              .addSubMenu(ui.createMenu('additive')
                          .addItem('subitem', 'subfunctionName')))
  .addToUi();
};

This menu worked like a charm using installable trigger onOpen being fired from spreadsheet. The functions called by these menu items use UserProperties, so I made sure this is not running anonymously.

This week I noticed that the menu no longer works when I open the spreadsheet - it only works if I call it directly from the script editor.

I have no idea how to fix this - I made no changes to the script, and checked to be sure nobody else did meddle with it. It's the same script that worked up until now.

I would very much appreciate the help on this one, it's puzzling to say the least.

Thanks!

Body:
Are the submenus supposed to be nested inside each other? If not, you're probably looking for:

function addMenu() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('New menu')
    .addSubMenu(ui.createMenu('menu')
      .addItem('item', 'functionName')
    )
    .addSubMenu(ui.createMenu('additive')
      .addItem('subitem', 'subfunctionName')
    )
    .addToUi()
};


问:
pause/start AVAudioPlayer without glitchy pops
I'm playing back a longish audio file (20 seconds or so) using AVAudioPlayer. I need to be able to pause and start in the middle of the file. When I pause or start while the audio is playing, there's a noticeable "pop" as the audio starts or finishes.

I've been able to improve the situation by doing a very fast fade-out (setting the volume multiple times using performSelector: withObject: afterDelay. But the sound is still a little glitchy with this technique.

Is there a standard way to start/pause AVAudioPlayer without these glitches?

答:
Try sending the -prepareToPlay to your AVAudioPlayer object when it's paused. This will pre-load the sound.

If this doesn't work, try accelerating your fade-out by reducing the delay in the performSelector: withObject: afterDelay. Go crazy, milliseconds.

If this doesn't work too, try using a cleaner, higher-quality audio file (without irrelevant background noises)

If none of this works, please explain how the audio file in your app is being used in further detail.


问:
Is it possible to use Jenkins without Groovy
I've used Jenkins long ago and few days ago I've tried the current version. It seems that all build instructions now are made by Groovy scripts. I can't find in Jenkins documentation if it is possible to do it in the old way using UI? I believe Groovy has advantages but I don't know Groovy and old Jenkins functionality was enough to me.</p>

答: you need to choose freestyle job and then you can use it the old way</p>


问:
ActiveRecord::Enum - PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer:
I am having a strange error and was hoping someone could point me in the right direction. I have a model called Organizations, and a attribute called department, see the excerpt from the schema below:

```<code>t.integer  "department",  default: 0
</code>```

Inside my model have defined my enums for this attribute, as I am using ActiveRecord::Enum, like below:

```<code>enum department: [:conferences, :design_teams, :services, :clubs, :events, :communications]
</code>```

But when I query, JobPosting.joins(job: :organization).where(organizations: { department: 'conferences' }) I get an error that reads:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "conferences"

FYI: An Organization has_many Jobs, and Job has_many JobPostings.

But when I query Organization.where(department: 'conferences') it works.

Any help would be greatly appreciated.

答:
This works on ror5.

```<code>JobPosting.joins(job: :organization).where(organizations:
{ department: Organization.departments['conferences'] })
</code>```

I'm not even sure if enum was available in ror3.

Body:
I am having a strange error and was hoping someone could point me in the right direction. I have a model called Organizations, and a attribute called department, see the excerpt from the schema below:

t.integer  "department",  default: 0

Inside my model have defined my enums for this attribute, as I am using ActiveRecord::Enum, like below:

enum department: [:conferences, :design_teams, :services, :clubs, :events, :communications]

But when I query, JobPosting.joins(job: :organization).where(organizations: { department: 'conferences' }) I get an error that reads:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "conferences"

FYI: An Organization has_many Jobs, and Job has_many JobPostings.

But when I query Organization.where(department: 'conferences') it works.

Any help would be greatly appreciated.

Body:
This works on ror5.

JobPosting.joins(job: :organization).where(organizations:
{ department: Organization.departments['conferences'] })

I'm not even sure if enum was available in ror3.


问:
How to give a python script limited access to azure blob container
I want my python script to be able to append new blobs to my container in azure. Using Shared Access Signatures (SAS) seems to be the way to go.

But I can't figure out how to use them. I don't want to give the script full access to the azure account by giving it the storage account key so using a SAS and limiting the abilities of the script to create and removing delete, get and list seems to be ok.
But how to I use the token in the script?

Here is my test code:

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

import requests
from azure.storage.blob import BlockBlobService, ContainerPermissions, ContentSettings

# this is only for testing, account key will be removed later

account_name = 'myaccountname'
account_key = 'myaccountkey'
container_name = 'mycontainer'
existing_file = 'existing_file.jpg'
new_file = 'test.jpg'

service = BlockBlobService(
    account_name=account_name,
    account_key=account_key
)
# There are two ways to create a permission
# 1. Assign boolean values to `read`/`add`/`create`/`write`/`delete` operation
# permission = BlobPermissions(read=True, add=True, create=True, write=True, delete=True)
# 2. Just simply assign a string to `_str`(A string representing the permissions) like `racwd` which means assign True to all operation
permission = ContainerPermissions(write=True)
sas = service.generate_container_shared_access_signature(
    container_name=container_name,
    permission=permission,
    protocol='https'
)
print(sas)

# Here begins the real script

service = BlockBlobService(
    account_name=account_name,
    sas_token=sas
)

assert service.exists(container_name=container_name, blob_name=existing_file)

service.create_blob_from_path(
        container_name=container_name,
        blob_name=new_file,
        file_path='./%s' % new_file,
        content_settings=ContentSettings(content_type=mimetypes.guess_type('./%s' % new_file)[0]),
        validate_content=True
)

r = requests.head('https://%s.blob.core.windows.net/%s/%s' % (account_name, container_name, new_file), timeout=2)
assert r.status_code == 200
</code>```

This fails service.exists() call with: azure.common.AzureHttpError: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

答:
As @DavidMakogon said, it sounds like referring to the blog. Indeed, that helps for your question.

According to your description, it seems that you had known how to use these methods generate_account_shared_access_signature with AccountPermission, generate_container_shared_access_signature with ContainerPermission, generate_blob_shared_access_signature with BlobPermission to generate the SAS for different levels (account, container, blob), like the code below for blob level.

```<code>from azure.storage.blob import BlockBlobService, BlobPermissions

account_name = '<your storage account name>'
account_key = '<your storage account key>'
container_name = 'mycontainer'

service = BlockBlobService(account_name=account_name, account_key=account_key)
# There are two ways to create a permission
# 1. Assign boolean values to `read`/`add`/`create`/`write`/`delete` operation
# permission = BlobPermissions(read=True, add=True, create=True, write=True, delete=True)
# 2. Just simply assign a string to `_str`(A string representing the permissions) like `racwd` which means assign True to all operation
permission = BlobPermissions(_str="racwd")
sas = service.generate_blob_shared_access_signature(container_name, 'test.jpg', permission)
print sas
</code>```

For using SAS to access Azure Blob Storage in Python script, as below.

Using SAS for calling Blob Storgae REST API, you can refer to the document Service SAS Examples to append SAS to the blob url as query parameters to do the related operation, like as below.

```<code>GET https://myaccount.blob.core.windows.net/pictures/profile.jpg?sv=2012-02-12&st=2009-02-09&se=2009-02-10&sr=c&sp=r&si=YWJjZGVmZw%3d%3d&sig=dD80ihBh5jfNpymO5Hg1IdiJIEvHcJpCMiCMnN%2fRnbI%3d
HTTP/1.1
Host: myaccount.blob.core.windows.net
x-ms-date: <date>
</code>```

Using SAS in Python script with Azure Storage SDK,  the construct method of classes BlockBlobService & BaseBlobService have a parameter sas_token which be explained as below that you can pass sas value.

sas_token (str) – A shared access signature token to use to authenticate requests instead of the account key. If account key and sas token are both specified, account key will be used to sign. If neither are specified, anonymous access will be used.

So for example, the code for BlockBlobService using SAS as below.

```<code>service = BlockBlobService(sas_token=sas)
</code>```

Body:
I want my python script to be able to append new blobs to my container in azure. Using Shared Access Signatures (SAS) seems to be the way to go.

But I can't figure out how to use them. I don't want to give the script full access to the azure account by giving it the storage account key so using a SAS and limiting the abilities of the script to create and removing delete, get and list seems to be ok.
But how to I use the token in the script?

Here is my test code:

#!/usr/bin/env python3

import requests
from azure.storage.blob import BlockBlobService, ContainerPermissions, ContentSettings

# this is only for testing, account key will be removed later

account_name = 'myaccountname'
account_key = 'myaccountkey'
container_name = 'mycontainer'
existing_file = 'existing_file.jpg'
new_file = 'test.jpg'

service = BlockBlobService(
    account_name=account_name,
    account_key=account_key
)
# There are two ways to create a permission
# 1. Assign boolean values to `read`/`add`/`create`/`write`/`delete` operation
# permission = BlobPermissions(read=True, add=True, create=True, write=True, delete=True)
# 2. Just simply assign a string to `_str`(A string representing the permissions) like `racwd` which means assign True to all operation
permission = ContainerPermissions(write=True)
sas = service.generate_container_shared_access_signature(
    container_name=container_name,
    permission=permission,
    protocol='https'
)
print(sas)

# Here begins the real script

service = BlockBlobService(
    account_name=account_name,
    sas_token=sas
)

assert service.exists(container_name=container_name, blob_name=existing_file)

service.create_blob_from_path(
        container_name=container_name,
        blob_name=new_file,
        file_path='./%s' % new_file,
        content_settings=ContentSettings(content_type=mimetypes.guess_type('./%s' % new_file)[0]),
        validate_content=True
)

r = requests.head('https://%s.blob.core.windows.net/%s/%s' % (account_name, container_name, new_file), timeout=2)
assert r.status_code == 200

This fails service.exists() call with: azure.common.AzureHttpError: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

Body:
As @DavidMakogon said, it sounds like referring to the blog. Indeed, that helps for your question.

According to your description, it seems that you had known how to use these methods generate_account_shared_access_signature with AccountPermission, generate_container_shared_access_signature with ContainerPermission, generate_blob_shared_access_signature with BlobPermission to generate the SAS for different levels (account, container, blob), like the code below for blob level.

from azure.storage.blob import BlockBlobService, BlobPermissions

account_name = '<your storage account name>'
account_key = '<your storage account key>'
container_name = 'mycontainer'

service = BlockBlobService(account_name=account_name, account_key=account_key)
# There are two ways to create a permission
# 1. Assign boolean values to `read`/`add`/`create`/`write`/`delete` operation
# permission = BlobPermissions(read=True, add=True, create=True, write=True, delete=True)
# 2. Just simply assign a string to `_str`(A string representing the permissions) like `racwd` which means assign True to all operation
permission = BlobPermissions(_str="racwd")
sas = service.generate_blob_shared_access_signature(container_name, 'test.jpg', permission)
print sas

For using SAS to access Azure Blob Storage in Python script, as below.

Using SAS for calling Blob Storgae REST API, you can refer to the document Service SAS Examples to append SAS to the blob url as query parameters to do the related operation, like as below.

GET https://myaccount.blob.core.windows.net/pictures/profile.jpg?sv=2012-02-12&st=2009-02-09&se=2009-02-10&sr=c&sp=r&si=YWJjZGVmZw%3d%3d&sig=dD80ihBh5jfNpymO5Hg1IdiJIEvHcJpCMiCMnN%2fRnbI%3d
HTTP/1.1
Host: myaccount.blob.core.windows.net
x-ms-date: <date>

Using SAS in Python script with Azure Storage SDK,  the construct method of classes BlockBlobService & BaseBlobService have a parameter sas_token which be explained as below that you can pass sas value.

sas_token (str) – A shared access signature token to use to authenticate requests instead of the account key. If account key and sas token are both specified, account key will be used to sign. If neither are specified, anonymous access will be used.

So for example, the code for BlockBlobService using SAS as below.

service = BlockBlobService(sas_token=sas)


问:
PHP uploading large files, takes long and error
I'm uploading a large file via ajax. The upload speed is fine but when the progress bar get's to 100%, there is a long wait and then i get this error

Failed to load resource: the server responded with a status of 504 (Gateway Time-out) - upload.php.

The file does appear in the destination folder but there isn't a server response.

This doesn't happen to smaller files.  It seems to take long to move_uploaded_file from the Temp folder to the destination folder.

```<code>  var xhr, hUploadSpeed;
        function sendFile()
        {
            document.getElementById("serverresponse").innerHTML = "";//clear previous server response

            var url = "http://www.example.com/wp-content/themes/theme1/file-upload/upload.php";
            var formData = new FormData(document.getElementById("form1"));
            xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', uploadProgress, false);//EventListener for upload progress
            xhr.addEventListener('abort', uploadAbort, false);//EventListener for abort
            xhr.addEventListener('error', uploadError, false);//EventListener for error
            xhr.addEventListener('load', uploadThrough, false);//EventListener for completed upload

            xhr.open("POST", url, true);
            //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //no longer necessary here
            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4 && xhr.status == 200)
                {
                    document.getElementById("serverresponse").innerHTML = xhr.responseText;
                }
            }

            xhr.send(formData); //Send to server
            hUploadSpeed = setInterval(UploadSpeed, 1000); //per seconds
        }
</code>```

Upload.php

```<code>//You can access the uploaded files through $_FILES
if(isset($_FILES["file1"]))
    $target_file = $_SERVER['DOCUMENT_ROOT']."/videos/".$_FILES["file1"]['name'];
    move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file);

echo "File uploaded successfully.";
</code>```

This works perfectly with smaller files 50mb but when i get to files around 300mb.  It takes so long?

I have a dedicated server with this php.ini

```<code>upload_max_filesize = 1200M
post_max_size = 1200M
max_input_vars = 1000
memory_limit = -1
max_file_uploads = 20
max_execution_time = 7200
max_input_time = 7200
max_input_vars = 1000
</code>```

Why does it take so long?  How do i solve?

答:
There's also memory_limit in php.ini that can affect upload. php.ini is a server config file.

You have to increase the following values in your php.ini file:

```<code>php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_input_time 300
php_value max_execution_time 300
</code>```

and then restart the server.

Body:
I'm uploading a large file via ajax. The upload speed is fine but when the progress bar get's to 100%, there is a long wait and then i get this error

Failed to load resource: the server responded with a status of 504 (Gateway Time-out) - upload.php.

The file does appear in the destination folder but there isn't a server response.

This doesn't happen to smaller files.  It seems to take long to move_uploaded_file from the Temp folder to the destination folder.

  var xhr, hUploadSpeed;
        function sendFile()
        {
            document.getElementById("serverresponse").innerHTML = "";//clear previous server response

            var url = "http://www.example.com/wp-content/themes/theme1/file-upload/upload.php";
            var formData = new FormData(document.getElementById("form1"));
            xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', uploadProgress, false);//EventListener for upload progress
            xhr.addEventListener('abort', uploadAbort, false);//EventListener for abort
            xhr.addEventListener('error', uploadError, false);//EventListener for error
            xhr.addEventListener('load', uploadThrough, false);//EventListener for completed upload

            xhr.open("POST", url, true);
            //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //no longer necessary here
            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4 && xhr.status == 200)
                {
                    document.getElementById("serverresponse").innerHTML = xhr.responseText;
                }
            }

            xhr.send(formData); //Send to server
            hUploadSpeed = setInterval(UploadSpeed, 1000); //per seconds
        }

Upload.php

//You can access the uploaded files through $_FILES
if(isset($_FILES["file1"]))
    $target_file = $_SERVER['DOCUMENT_ROOT']."/videos/".$_FILES["file1"]['name'];
    move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file);

echo "File uploaded successfully.";

This works perfectly with smaller files 50mb but when i get to files around 300mb.  It takes so long?

I have a dedicated server with this php.ini

upload_max_filesize = 1200M
post_max_size = 1200M
max_input_vars = 1000
memory_limit = -1
max_file_uploads = 20
max_execution_time = 7200
max_input_time = 7200
max_input_vars = 1000

Why does it take so long?  How do i solve?

Body:
There's also memory_limit in php.ini that can affect upload. php.ini is a server config file.

You have to increase the following values in your php.ini file:

php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_input_time 300
php_value max_execution_time 300

and then restart the server.


问:
Array Size Not Defined? C++
Dumb question. but can you do this.
(these are global variables by the way)

```<code>int size;
double Values[size];
</code>```

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.

答:
You can do it if you allocate them dynamically:

```<code>double *Values = new double[size];
...

delete [] Values;
</code>```

but not statically.

Title: Array Size Not Defined? C++

Body:
Dumb question. but can you do this.
(these are global variables by the way)

int size;
double Values[size];

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.

Body:
You can do it if you allocate them dynamically:

double *Values = new double[size];
...

delete [] Values;

but not statically.


问:
Webpack 2 Module not found when using URL
I just updated my Angular 2 project to work with Webpack 2 which is working just fine. However, i'm facing a new problem when using the resolve: { alias: {...} } key.

When i used webpack 1, this code just worked fine:

webpack.config.js

```<code>    resolve: {
    // http://webpack.github.io/docs/configuration.html#resolve-extensions
    extensions: ['.ts', '.js', '.json', '.css', '.html'],
    alias: {
        "orion/editor/edit": "http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js"
    }
},
</code>```

angular component:

```<code>ngOnInit() {
    Promise.all([
        require('http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js'),
        require('http://eclipse.org/orion/editor/releases/current/built-editor.css')
    ]).then(function () {
        requirejs(['orion/editor/edit'], function (edit: any) {
            this.orionEditor = edit({className: 'editor', parent: 'xml'})[0];
            this.receiveXmlData();
        }.bind(this));
    }.bind(this));
}
</code>```

Now when using webpack 2, i always get an error that both files cannot be resolved. Does anyone have an idea?

Module not found: Error: Can't resolve 'http://eclipse.org/orion/editor/releases/current/built-editor.css' in [Angular-component file]

Module not found: Error: Can't resolve 'http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js' in 'C:\Applications\winery\enpro-winery\org.eclipse.winery.ui\src\app\instance\editXML'

My try up till now:

in the webpack.common.js
for webpack2 i tried:

```<code>    const path = require('path');

    resolve: {
        extensions: ['.ts', '.js', '.json', '.css', '.html'],
        alias: {
            "orion/editor/edit": path.resolve("http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js")
    }
</code>```

and

```<code>    resolve: {
        extensions: ['.ts', '.js', '.json', '.css', '.html'],
        modules: [
            path.join(__dirname, "src"),
            "node_modules",
            path.resolve("http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js"),
            path.resolve("http://eclipse.org/orion/editor/releases/current/built-editor.css")
    ]
},
</code>```

答:
Actually, I found the solution: I accidentally removed the resolve-url-loader dependency from my package.json.

I further found that I don't even need to include the alias or path.resolve in the resolve object.

Body:
I just updated my Angular 2 project to work with Webpack 2 which is working just fine. However, i'm facing a new problem when using the resolve: { alias: {...} } key.

When i used webpack 1, this code just worked fine:

webpack.config.js

    resolve: {
    // http://webpack.github.io/docs/configuration.html#resolve-extensions
    extensions: ['.ts', '.js', '.json', '.css', '.html'],
    alias: {
        "orion/editor/edit": "http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js"
    }
},

angular component:

ngOnInit() {
    Promise.all([
        require('http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js'),
        require('http://eclipse.org/orion/editor/releases/current/built-editor.css')
    ]).then(function () {
        requirejs(['orion/editor/edit'], function (edit: any) {
            this.orionEditor = edit({className: 'editor', parent: 'xml'})[0];
            this.receiveXmlData();
        }.bind(this));
    }.bind(this));
}

Now when using webpack 2, i always get an error that both files cannot be resolved. Does anyone have an idea?

Module not found: Error: Can't resolve 'http://eclipse.org/orion/editor/releases/current/built-editor.css' in [Angular-component file]

Module not found: Error: Can't resolve 'http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js' in 'C:\Applications\winery\enpro-winery\org.eclipse.winery.ui\src\app\instance\editXML'

My try up till now:

in the webpack.common.js
for webpack2 i tried:

    const path = require('path');

    resolve: {
        extensions: ['.ts', '.js', '.json', '.css', '.html'],
        alias: {
            "orion/editor/edit": path.resolve("http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js")
    }

and

    resolve: {
        extensions: ['.ts', '.js', '.json', '.css', '.html'],
        modules: [
            path.join(__dirname, "src"),
            "node_modules",
            path.resolve("http://www.eclipse.org/orion/editor/releases/current/built-editor.min.js"),
            path.resolve("http://eclipse.org/orion/editor/releases/current/built-editor.css")
    ]
},


问:
Is "type" a reserved word in mysql
in notepad++ SQL language it highlights the word "type" in a blue color but in mysql reserved word list/table* I can't find "type" in that

If "type" is not a reserved word in mysql should I avoid the word "type" and which alternative word should I use.

答: "type" and "types" are reserved keywords based on this link.</p>

Title: Is "type" a reserved word in mysql


问:
How can I add some html text to the highchart while exporting it to PNG, PDF,Jpeg?
I have used these options.

```<code> exporting: {
    enabled: false,
    allowHtml:true
}
</code>```

This is my export function.

```<code>export(type: any) {
     this.graph.exportChart({ type: type });
  }
</code>```

答:
If you want only on export (add title) then use

Fiddle link

```<code> exporting: {
    chartOptions: {
      chart: {
        events: {
          load: function() {
            var dynamic = document.getElementById('dynamic').value
            this.setTitle({
              text: dynamic
            });
          }
        }
      },
      title: {
        align: 'right',
      }
    }
  },
</code>```

Body:
I have used these options.

 exporting: {
    enabled: false,
    allowHtml:true
}

This is my export function.

export(type: any) {
     this.graph.exportChart({ type: type });
  }

Body:
If you want only on export (add title) then use

Fiddle link

 exporting: {
    chartOptions: {
      chart: {
        events: {
          load: function() {
            var dynamic = document.getElementById('dynamic').value
            this.setTitle({
              text: dynamic
            });
          }
        }
      },
      title: {
        align: 'right',
      }
    }
  },


问:
Symfony3 create form without entity in type file
I have created a form in my controller like this :

```<code>$data = array ();
$formBuilder = $this->createFormBuilder ( $data );
$formBuilder->add( 'Field1', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    ),
            ) )
            ->add ( 'Field2', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    )
...);
$form = $formBuilder->getForm ();
</code>```

I am trying to put my form creation in a Type file. I did this like this but the form is not created and I can't display form fields in my view.I don't understand why.

```<code>#in ControlController
$data = array ();
$formBuilder= $this->createFormBuilder(ControlType::class, $data);
$form = $formBuilder->getForm ();

#in ControlType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add( 'Field1', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    ),
            ) )
            ->add ( 'Field2', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    )....;
}
</code>```

Edit 1 :
I have tried all things you tell me, but it still doesn't work.
My code looks like this now :

```<code>#in ControlController
$data = ['Field1' => null, 'Field2' => null];
$formBuilder= $this->createFormBuilder(ControlType::class, $data);
$form = $formBuilder->getForm ();
return $this->render ( 'MeTestBundle:Control:index.html.twig', array (
            'form' => $form->createView ()
    ) );

#in ControlType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add( 'Field1', NumberType::class, array(
                            'mapped' => false,
    ) )
    ->add ( 'Field2', NumberType::class, array(
            'constraints' => array(
                    new NotBlank(),
            ),
            'mapped' => false
    ))
    ->add ( 'save', SubmitType::class, array (
            'label' => 'Control'
    ));
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
            'data_class' => Control::class,
    ));
}
</code>```

But now the error I have is:

```<code>The options "Field1", "Field2" do not exist. Defined options are: "action",
"allow_extra_fields", "attr", "auto_initialize", "block_name", "by_reference",
"compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection",
"csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled",
"empty_data", "error_bubbling", "error_mapping", "extra_fields_message",
"inherit_data", "invalid_message", "invalid_message_parameters", "label",
"label_attr", "label_format", "mapped", "method", "post_max_size_message",
"property_path", "required", "translation_domain", "trim",
"upload_max_size_message", "validation_groups".
</code>```

答:
Your Controller Code to create the Form seems to be wrong.

The Signature for createFormBuilder in Controller is defined like:

```<code>public function createFormBuilder($data = null, array $options = array())
</code>```

What you want should be:

```<code>$data = ['Field1' => null, 'Field2' => null];
$form = $this->createForm(ControlType::class, $data);
return $this->render ( 'MeTestBundle:Control:index.html.twig', array (
        'form' => $form->createView ()
));
</code>```

Edit:
Also you should not set a data_class if you're not gonna use a data object.
Just leave configureOptions empty in this case.
If you want to use an Entity you should pass an instance of it as $data instead of a simple array.

Body:
I have created a form in my controller like this :

$data = array ();
$formBuilder = $this->createFormBuilder ( $data );
$formBuilder->add( 'Field1', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    ),
            ) )
            ->add ( 'Field2', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    )
...);
$form = $formBuilder->getForm ();

I am trying to put my form creation in a Type file. I did this like this but the form is not created and I can't display form fields in my view.I don't understand why.

#in ControlController
$data = array ();
$formBuilder= $this->createFormBuilder(ControlType::class, $data);
$form = $formBuilder->getForm ();

#in ControlType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add( 'Field1', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    ),
            ) )
            ->add ( 'Field2', NumberType::class, array(
                    'constraints' => array(
                            new NotBlank(),
                    )....;
}

Edit 1 :
I have tried all things you tell me, but it still doesn't work.
My code looks like this now :

#in ControlController
$data = ['Field1' => null, 'Field2' => null];
$formBuilder= $this->createFormBuilder(ControlType::class, $data);
$form = $formBuilder->getForm ();
return $this->render ( 'MeTestBundle:Control:index.html.twig', array (
            'form' => $form->createView ()
    ) );

#in ControlType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add( 'Field1', NumberType::class, array(
                            'mapped' => false,
    ) )
    ->add ( 'Field2', NumberType::class, array(
            'constraints' => array(
                    new NotBlank(),
            ),
            'mapped' => false
    ))
    ->add ( 'save', SubmitType::class, array (
            'label' => 'Control'
    ));
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
            'data_class' => Control::class,
    ));
}

But now the error I have is:

The options "Field1", "Field2" do not exist. Defined options are: "action",
"allow_extra_fields", "attr", "auto_initialize", "block_name", "by_reference",
"compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection",
"csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled",
"empty_data", "error_bubbling", "error_mapping", "extra_fields_message",
"inherit_data", "invalid_message", "invalid_message_parameters", "label",
"label_attr", "label_format", "mapped", "method", "post_max_size_message",
"property_path", "required", "translation_domain", "trim",
"upload_max_size_message", "validation_groups".

Body:
Your Controller Code to create the Form seems to be wrong.

The Signature for createFormBuilder in Controller is defined like:

public function createFormBuilder($data = null, array $options = array())

What you want should be:

$data = ['Field1' => null, 'Field2' => null];
$form = $this->createForm(ControlType::class, $data);
return $this->render ( 'MeTestBundle:Control:index.html.twig', array (
        'form' => $form->createView ()
));

Edit:
Also you should not set a data_class if you're not gonna use a data object.
Just leave configureOptions empty in this case.
If you want to use an Entity you should pass an instance of it as $data instead of a simple array.


问:
Ruby loop question and dumping results into YAML file
I am working on a Ruby script that will dump a key, value pair into a yaml file. But for some reason my loop is only grabbing the last instance in the loop. There should be multiple key value pairs.

Code:

```<code># Model for languages Table
class Language < ActiveRecord::Base
end

# Model for elements Table
class Element < ActiveRecord::Base
  has_many :element_translations
end

# Model for element_translations Table
class ElementTranslation < ActiveRecord::Base
  belongs_to :element
end

# Find ALL languages
lang = Language.all
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
info = ''

elements.each do |el|
  lang.each do |l|
    et = el.element_translations.where("language_id = ?", l.id)
    et.each do |tran|
      info = {
        el.human_readable.to_s => tran.content.to_s
      }
    end
    File.open(l.code.to_s + ".yml", "w", :encoding => "UTF-8") do |f|
      YAML.dump(info, f)
    end
  end
end
</code>```

Any ideas?

答:
When you do:

```<code>info = {
  el.human_readable.to_s => tran.content.to_s
}
</code>```

did you mean:

```<code>info << {
  el.human_readable.to_s => tran.content.to_s
}
</code>```

Otherwise you're just re-assigning info each time.

If you're going to do this, make info an array: info = [] as opposed to info = ''.

Body:
I am working on a Ruby script that will dump a key, value pair into a yaml file. But for some reason my loop is only grabbing the last instance in the loop. There should be multiple key value pairs.

Code:

# Model for languages Table
class Language < ActiveRecord::Base
end

# Model for elements Table
class Element < ActiveRecord::Base
  has_many :element_translations
end

# Model for element_translations Table
class ElementTranslation < ActiveRecord::Base
  belongs_to :element
end

# Find ALL languages
lang = Language.all
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
info = ''

elements.each do |el|
  lang.each do |l|
    et = el.element_translations.where("language_id = ?", l.id)
    et.each do |tran|
      info = {
        el.human_readable.to_s => tran.content.to_s
      }
    end
    File.open(l.code.to_s + ".yml", "w", :encoding => "UTF-8") do |f|
      YAML.dump(info, f)
    end
  end
end

Any ideas?

Body:
When you do:

info = {
  el.human_readable.to_s => tran.content.to_s
}

did you mean:

info << {
  el.human_readable.to_s => tran.content.to_s
}

Otherwise you're just re-assigning info each time.

If you're going to do this, make info an array: info = [] as opposed to info = ''.


问:
how to export selenium webdriver phpunit test results to excel file
curently C:\xampp\htdocs\testcases\MySelenium>phpunit --verbose --log-tap tap.log LoginTest.php
by this command i can get results in text file ,
but I want results in excel file by using phpunit framework </p>

答:
```<code>// download phpexcel by composer and make file as below
<?php

/**
 * Description of General
 *
 * @author suchishah
 */
date_default_timezone_set('Asia/Kolkata');

class General {

    protected static $objPHPExcel;
    protected static $highestRow;
    protected static $filename;

    //put your code here
    public function createExcelReport11($fname) {
        /* @var $objPHPExcel type */
        self::$objPHPExcel = new PHPExcel();
        self::$filename = $fname;
// Set properties
        echo date('H:i:s') . " Set properties\n";
        self::$objPHPExcel->getProperties()->setCreator("Suchi Shah")
                ->setLastModifiedBy("Suchi Shah")
                ->setTitle("Test Case Report")
                ->setSubject("Excelsheet for testcase report")
                ->setDescription("Excel file contains testcase name,method name and all ")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");

        //Add some data
        echo date('H:i:s') . " Add some data\n";
        self::$objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', self::$filename)->mergeCells('A1:F1')
                ->setCellValue('A2', 'Action')
                ->setCellValue('B2', 'method')
                ->setCellValue('C2', 'DateTime')
                ->setCellValue('D2', 'Action pefromed')
                ->setCellValue('E2', 'Data Used')
                ->setCellValue('F2', 'Data Get')
                ->setCellValue('G2', 'Assertion')
                ->setCellValue('H2', 'Exe.Time(s)')
        ;
        foreach (range('A', 'F') as $columnID) {
            self::$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
                    ->setAutoSize(true);
        }

        echo date('H:i:s') . " Rename sheet\n";
        self::$objPHPExcel->getActiveSheet()->setTitle('Simple');

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
        self::$objPHPExcel->setActiveSheetIndex(0);

// Save Excel 2007 file
        echo date('H:i:s') . " Write to Excel2007 format\n";
        $objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, 'Excel2007');
        $objWriter->save(str_replace('.php', '.xlsx', __FILE__));

// Echo memory peak usage
        // echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";
// Echo done
        echo date('H:i:s') . " Done writing file.\r\n";
        $highestColumm = self::$objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();
        echo '        ' . $highestColumm . '      highest colum';
        self::$highestRow = self::$objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
        echo self::$highestRow . '  rowh';
    }

    public function writeData($action, $method, $performedon, $dataused,$dataget,$assert, $interval) {
        self::$objPHPExcel->setActiveSheetIndex(0)
                ->setCellValueByColumnAndRow('0', self::$highestRow + 1, $action)
                ->setCellValueByColumnAndRow('1', self::$highestRow + 1, $method)
                ->setCellValueByColumnAndRow('2', self::$highestRow + 1, date('m/d/Y h:i:s a', time()))
                ->setCellValueByColumnAndRow('3', self::$highestRow + 1, $performedon)
                ->setCellValueByColumnAndRow('4', self::$highestRow + 1, $dataused)
                ->setCellValueByColumnAndRow('5', self::$highestRow + 1, $dataget)
                ->setCellValueByColumnAndRow('6', self::$highestRow + 1, $assert)
                ->setCellValueByColumnAndRow('7', self::$highestRow + 1, $interval);
// Call callback method
        self::$highestRow = self::$highestRow + 1;
        // echo self::$highestRow;
        $objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, 'Excel2007');
        $a = 'Log' . self::$filename . date("Y-m-d") . '.xlsx';
        $objWriter->save($a);
    }
}

// include that file in the test case for which you want to generate report by
// create its object
<?php

require_once '../vendor/phpexcel/phpexcel/Classes/PHPExcel.php';
require_once 'General.php';

class Sample extends PHPUnit_Extensions_Selenium2TestCase {

    private $data = array(
        'username' => 'me'
    );
    private static $highestRow;
    private static $lib_obj;

    public static function setUpBeforeClass() {
        self::shareSession(true);
        self::$lib_obj = new General();
        self::$lib_obj->createExcelReport11(__CLASS__);
    }

    // set url you want to visit

    public function testSetUserName() {
        $start = time();
        $this->byId('username')->value($this->data['username']);
        $end = time();
        $a = $end - $start;
        self::$lib_obj->writeData('setvalue', __FUNCTION__, 'username', $this->data['username'], '', '', $a);
    }

}
</code>```


问:
How to display desired text in hyperlink using VBA code
I have displayed my hyperlink in the column E as shown
\\maroon\cgm images\mech.pdf

But I want to display only mech.pdf in the cell how to modify my code.

my code used for displaying above hyperlink is shown below:

```<code>str = "\\maroon\CGM Images\" & pn & ".pdf"
ActiveSheet.Hyperlinks.Add Range("e" & i), str
</code>```

In this I want to show only pn & str.

答:
You need to specify TextToDisplay

```<code>ActiveSheet.Hyperlinks.Add Anchor:=Range("e" & i), Address:=Str, TextToDisplay:=pn & ".pdf"
</code>```

Sometimes the Excel VBA reference is indeed helpful to find out on your own how functions and methods work: Hyperlinks.Add Method (Excel)

Body:
I have displayed my hyperlink in the column E as shown
\\maroon\cgm images\mech.pdf

But I want to display only mech.pdf in the cell how to modify my code.

my code used for displaying above hyperlink is shown below:

str = "\\maroon\CGM Images\" & pn & ".pdf"
ActiveSheet.Hyperlinks.Add Range("e" & i), str

In this I want to show only pn & str.

Body:
You need to specify TextToDisplay

ActiveSheet.Hyperlinks.Add Anchor:=Range("e" & i), Address:=Str, TextToDisplay:=pn & ".pdf"

Sometimes the Excel VBA reference is indeed helpful to find out on your own how functions and methods work: Hyperlinks.Add Method (Excel)


问:
How can I count pulse inputs with some interval time?
I'm develop a pulse counter(coin counter) in raspberry pi with windows 10 iot core, and i need to count pulses that have a interval time of 25 miliseconds like this:

0,05€ - 1 pulse
0,10€ - 2 pulses
0,20€ - 4 pulses
0,50€ - 10 pulses
1€ - 20 pulses
2€ - 40 pulses

like this image: pulses

I need to print the number of pulses(to have the value inserted) when the interval time is diferent of 25 miliseconds.

I have this code:

```<code>public MainPage()
    {
        this.InitializeComponent();
        InitGPIO();
    }

    private void InitGPIO()
    {
        var gpio = GpioController.GetDefault();

        if (gpio == null)
        {
            GpioStatus.Text = "There is no GPIO controller on this device.";
        }

        coinPin = gpio.OpenPin(coin_Pin);

        if (coinPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp))
        {
            coinPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
        } else
        {
            coinPin.SetDriveMode(GpioPinDriveMode.Input);
        }

        coinPin.DebounceTimeout = TimeSpan.FromMilliseconds(25);

        coinPin.ValueChanged += coinPin_ValueChanged;

        GpioStatus.Text = "GPIO pins initialized correctly.";
    }

    private void coinPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
    {
        if (e.Edge == GpioPinEdge.FallingEdge)
        {
            counter++;
        }

        var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            if (e.Edge == GpioPinEdge.FallingEdge)
            {
                //counter++;
                var time = PulseIn(coinPin, e.Edge);
                value = (counter * 5);
                value100 = value / 100;
                //money.Text = "Eur: " + (decimal)value100 + " €";

                if (time != 25)
                {
                    money.Text = "Eur: " + (decimal)value100 + " €";
                    GpioStatus.Text = "" + time;
                } else
                {
                    GpioStatus.IsEnabled = false;
                }
                //GpioStatus.Text = "" + time + "";
            } else
            {
                ///GpioStatus.Text = "" + coinPin.DebounceTimeout;
            }

        });
    }

    private double PulseIn(GpioPin pin, GpioPinEdge edge)
    {
        var sw = new Stopwatch();

        while (edge.Equals(GpioPinEdge.RisingEdge))
        {
            //sw.Start();
        }

        sw.Start();

        if (!edge.Equals(GpioPinEdge.RisingEdge))
        {
            //sw.Stop();
        }

        sw.Stop();

        return sw.Elapsed.TotalMilliseconds;
    }

    private const int coin_Pin = 24;
    private int counter = 0;
    private double value = 0;
    private double value100 = 0;
    private GpioPin coinPin;
</code>```

Can you help me please?
Thank you very much.

答:
From your code,

```<code>    sw.Start();

    if (!edge.Equals(GpioPinEdge.RisingEdge))
    {
        //sw.Stop();
    }

    sw.Stop();
</code>```

it actually measures the execute time of the if statement that between sw.Start() and sw.Stop(). This does not make sense. Record the watch.Elapsed.TotalMilliseconds when the falling edge arrived and restart the stopwatch to measure the pulse interval time. To do this, I add the following two code lines under counter++, remove var time = PulseIn(coinPin, e.Edge) and use timeinterval in GpioStatus.Text = "" + timeinterval instead.

```<code>            timeinterval = watch.Elapsed.TotalMilliseconds;
            watch.Restart();
</code>```

The following is complete code piece:

```<code>    private Stopwatch watch = new Stopwatch();
    private void coinPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
    {
        double timeinterval = 0;
        if (e.Edge == GpioPinEdge.FallingEdge)
        {
            counter++;
            timeinterval = watch.Elapsed.TotalMilliseconds;
            watch.Restart();
        }

        var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            if (e.Edge == GpioPinEdge.FallingEdge)
            {
                //var time = PulseIn(coinPin, e.Edge);
                value = (counter * 5);
                value100 = value / 100;

                if (timeinterval != 25)
                {
                    money.Text = "Eur: " + (decimal)value100 + " €";
                    GpioStatus.Text = "" + timeinterval;
                }
                //...
            }
        });
    }
</code>```

You can try above code piece to see if it meets your accuracy requirement.

Note: It is not suitable to measure hardware pulse interval in software level because the software jitter is always unpredictable.

Body:
I'm develop a pulse counter(coin counter) in raspberry pi with windows 10 iot core, and i need to count pulses that have a interval time of 25 miliseconds like this:

0,05€ - 1 pulse
0,10€ - 2 pulses
0,20€ - 4 pulses
0,50€ - 10 pulses
1€ - 20 pulses
2€ - 40 pulses

like this image: pulses

I need to print the number of pulses(to have the value inserted) when the interval time is diferent of 25 miliseconds.

I have this code:

public MainPage()
    {
        this.InitializeComponent();
        InitGPIO();
    }

    private void InitGPIO()
    {
        var gpio = GpioController.GetDefault();

        if (gpio == null)
        {
            GpioStatus.Text = "There is no GPIO controller on this device.";
        }

        coinPin = gpio.OpenPin(coin_Pin);

        if (coinPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp))
        {
            coinPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
        } else
        {
            coinPin.SetDriveMode(GpioPinDriveMode.Input);
        }

        coinPin.DebounceTimeout = TimeSpan.FromMilliseconds(25);

        coinPin.ValueChanged += coinPin_ValueChanged;

        GpioStatus.Text = "GPIO pins initialized correctly.";
    }

    private void coinPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
    {
        if (e.Edge == GpioPinEdge.FallingEdge)
        {
            counter++;
        }

        var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            if (e.Edge == GpioPinEdge.FallingEdge)
            {
                //counter++;
                var time = PulseIn(coinPin, e.Edge);
                value = (counter * 5);
                value100 = value / 100;
                //money.Text = "Eur: " + (decimal)value100 + " €";

                if (time != 25)
                {
                    money.Text = "Eur: " + (decimal)value100 + " €";
                    GpioStatus.Text = "" + time;
                } else
                {
                    GpioStatus.IsEnabled = false;
                }
                //GpioStatus.Text = "" + time + "";
            } else
            {
                ///GpioStatus.Text = "" + coinPin.DebounceTimeout;
            }

        });
    }

    private double PulseIn(GpioPin pin, GpioPinEdge edge)
    {
        var sw = new Stopwatch();

        while (edge.Equals(GpioPinEdge.RisingEdge))
        {
            //sw.Start();
        }

        sw.Start();

        if (!edge.Equals(GpioPinEdge.RisingEdge))
        {
            //sw.Stop();
        }

        sw.Stop();

        return sw.Elapsed.TotalMilliseconds;
    }

    private const int coin_Pin = 24;
    private int counter = 0;
    private double value = 0;
    private double value100 = 0;
    private GpioPin coinPin;

Can you help me please?
Thank you very much.

Body:
From your code,

    sw.Start();

    if (!edge.Equals(GpioPinEdge.RisingEdge))
    {
        //sw.Stop();
    }

    sw.Stop();

it actually measures the execute time of the if statement that between sw.Start() and sw.Stop(). This does not make sense. Record the watch.Elapsed.TotalMilliseconds when the falling edge arrived and restart the stopwatch to measure the pulse interval time. To do this, I add the following two code lines under counter++, remove var time = PulseIn(coinPin, e.Edge) and use timeinterval in GpioStatus.Text = "" + timeinterval instead.

            timeinterval = watch.Elapsed.TotalMilliseconds;
            watch.Restart();

The following is complete code piece:

    private Stopwatch watch = new Stopwatch();
    private void coinPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
    {
        double timeinterval = 0;
        if (e.Edge == GpioPinEdge.FallingEdge)
        {
            counter++;
            timeinterval = watch.Elapsed.TotalMilliseconds;
            watch.Restart();
        }

        var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            if (e.Edge == GpioPinEdge.FallingEdge)
            {
                //var time = PulseIn(coinPin, e.Edge);
                value = (counter * 5);
                value100 = value / 100;

                if (timeinterval != 25)
                {
                    money.Text = "Eur: " + (decimal)value100 + " €";
                    GpioStatus.Text = "" + timeinterval;
                }
                //...
            }
        });
    }

You can try above code piece to see if it meets your accuracy requirement.

Note: It is not suitable to measure hardware pulse interval in software level because the software jitter is always unpredictable.


问:
Duplicate column name 'NULL' while importing the csv
I try to import file in mysql but every time it give me error of Duplicate column name 'NULL'
Kindly check the image for more

答:
Clean your csv  file by deleting the column from the right most after your last column.
or
Copy all your column fields data to a new file then save as csv.</p>


问:
boost::shared_array<char> to std::string
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

```<code>boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}
</code>```

答:
According to "Some Programmer dude"'s answer I coded the solution.
Please notice that the boostString string is zero-terminated.

```<code>boost::shared_array<char> boostString = str.GetCString(CZString::eAscii);
std::string stdStr(boostString.get());
</code>```

Body:
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}

Body:
According to "Some Programmer dude"'s answer I coded the solution.
Please notice that the boostString string is zero-terminated.

boost::shared_array<char> boostString = str.GetCString(CZString::eAscii);
std::string stdStr(boostString.get());


问:
Issue when trying to iterate through textfile lines
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

```<code>Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
</code>```

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

```<code>with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])
</code>```

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

答:
Try this.</p>

```<code>f = open("Input file path")

l = f.read().split("=============================")

for each_line in l:
    if each_line.strip():
        print(each_line.split()[2])

f.close()
</code>```

Body:
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

Body:
Try this.

f = open("Input file path")

l = f.read().split("=============================")

for each_line in l:
    if each_line.strip():
        print(each_line.split()[2])

f.close()


问:
With angular component and ui-router, can a single controller have multiple templates?
In a component I would like to associate templates to CRUD actions, but use a single controller that handles data for all all of them. Does this make sense with angular components, or should I use several components ?
How would the ui-router state configuration look like ?

EDIT:
Components have templates, and ui-router states too. I am confused about the articulation of those 2 concepts.

EDIT 2:
trying to clarify my understanding so far :

component are controller + template + bindings. Controller can be omitted.

states are url + template + controller or url + component. Controller can be omitted.

So it seems that components are taking away some of the responsabilities that use to belong to ui-router.

My goal here:

```<code> - url1 --> controller foo + template x;
 - url2 --> controller foo + template y;
 - url3 --> controller foo + template z;
</code>```

should I do :

components:

```<code>component x --> controller foo + template x;
component y --> controller foo + template y;
component z --> controller foo + template z;
</code>```

and then routing:

```<code>url 1 --> component x
url 2 --> component y
url 3 --> component z
</code>```

?

EDIT 3:
quote from https://docs.angularjs.org/guide/component :

"In a component-based application, every view is a component"

quote from https://ui-router.github.io/guide/ng1/route-to-component :

"The component model enforces separation of concerns and encapsulation by using an isolate scope. Data from parent scopes can no longer be directly accessed. Instead, it needs to be explicitly wired in"

答:
Yes, it is possible. Your ui-router config would look something like this: (Multiple states having same controllers.)

```<code>.state('add', {
    url: '/add',
    templateUrl: 'templates/add.html',
    controller: 'contactCtrl'
})
.state('edit', {
    url: '/edit',
    templateUrl: 'templates/edit.html',
    controller: 'contactCtrl'
})
</code>```

Here's a working example of having multiple states and templates using same controller.

Edit: You don't have to use components. Why create three different extra components while you can achieve the same thing without them? I would still recommend the approach I mentioned above. Getting the same outcome with lesser code should always be chosen. :)

Quoting Eric Elliot on twitter,

Code is temporary. It exists while it is useful.
  If code is replaced by better code, good!
  If code can be deleted, celebrate!

Body:
In a component I would like to associate templates to CRUD actions, but use a single controller that handles data for all all of them. Does this make sense with angular components, or should I use several components ?
How would the ui-router state configuration look like ?

EDIT:
Components have templates, and ui-router states too. I am confused about the articulation of those 2 concepts.

EDIT 2:
trying to clarify my understanding so far :

component are controller + template + bindings. Controller can be omitted.

states are url + template + controller or url + component. Controller can be omitted.

So it seems that components are taking away some of the responsabilities that use to belong to ui-router.

My goal here:

 - url1 --> controller foo + template x;
 - url2 --> controller foo + template y;
 - url3 --> controller foo + template z;

should I do :

components:

component x --> controller foo + template x;
component y --> controller foo + template y;
component z --> controller foo + template z;

and then routing:

url 1 --> component x
url 2 --> component y
url 3 --> component z

?

EDIT 3:
quote from https://docs.angularjs.org/guide/component :

"In a component-based application, every view is a component"

quote from https://ui-router.github.io/guide/ng1/route-to-component :

"The component model enforces separation of concerns and encapsulation by using an isolate scope. Data from parent scopes can no longer be directly accessed. Instead, it needs to be explicitly wired in"

Body:
Yes, it is possible. Your ui-router config would look something like this: (Multiple states having same controllers.)

.state('add', {
    url: '/add',
    templateUrl: 'templates/add.html',
    controller: 'contactCtrl'
})
.state('edit', {
    url: '/edit',
    templateUrl: 'templates/edit.html',
    controller: 'contactCtrl'
})

Here's a working example of having multiple states and templates using same controller.

Edit: You don't have to use components. Why create three different extra components while you can achieve the same thing without them? I would still recommend the approach I mentioned above. Getting the same outcome with lesser code should always be chosen. :)

Quoting Eric Elliot on twitter,

Code is temporary. It exists while it is useful.
  If code is replaced by better code, good!
  If code can be deleted, celebrate!


问:
How do I convert the time stamps from a PostgreSQL DB into user-time-zone times?
I'm using SQLAlchemy and PostgreSQL here, in a web application.

My SQLA model is defined (roughly) as follows:

```<code>class MyModel(Base):
    ts_field = Column(DateTime(timezone=True))
    # more here, obviously
</code>```

My web app users have a timezone property whose format I have not yet specified (that's part of this question) that determines how to display time stamps to them. They're not all in the locale of the server, obviously, so the system time zone isn't exactly useful.

I want to have an easy way to get out timestamps formatted for each user depending on their selected time zone.

(I'm a bit fuzzy on a lot of the terminology of time zone conversion, so if I'm asking this vaguely -- and I'll bet I am! -- please feel free to comment and help me clarify!)

答: You can use pytz to do the conversions.</p>

Body:
I'm using SQLAlchemy and PostgreSQL here, in a web application.

My SQLA model is defined (roughly) as follows:

class MyModel(Base):
    ts_field = Column(DateTime(timezone=True))
    # more here, obviously

My web app users have a timezone property whose format I have not yet specified (that's part of this question) that determines how to display time stamps to them. They're not all in the locale of the server, obviously, so the system time zone isn't exactly useful.

I want to have an easy way to get out timestamps formatted for each user depending on their selected time zone.

(I'm a bit fuzzy on a lot of the terminology of time zone conversion, so if I'm asking this vaguely -- and I'll bet I am! -- please feel free to comment and help me clarify!)

Body: You can use pytz to do the conversions.