问:
Enable ckeditor keyboard shortcut for headings?
I want my editors to be able to use keyboard shortcuts for applying headings.

I've been experimenting with the "keystrokes" approach on the ckeditor site. It works for some things, but not the headings. For instance, the following applies an additional mapping for 'bold' using Ctrl + Shift + u:

```<code>config.keystrokes = [
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
];
</code>```

Why can't I enable the headings?

Right now this is what my config.js looks like:

```<code>CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here.
    // For complete reference see:
    // http://docs.ckeditor.com/#!/api/CKEDITOR.config

    // The toolbar groups arrangement, optimized for two toolbar rows.
    config.toolbarGroups = [
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
        { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
        { name: 'document',    groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'others' },
        { name: 'forms' },
        { name: 'tools' }
    ];

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline,Styles,Strike,Image,Outdent,Indent,Blockquote,Cut,Copy,Paste,PasteFromWord,Undo,Redo';

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4';

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:advanced;link:advanced';

    // Whether to escape basic HTML entities in the document, including:
    // (nbsp,gt,lt,amp)
    config.basicEntities = false;
    config.entities_additional = 'lt,gt,amp,quot'
    config.entities_latin = false;
    config.entities_greek = false;
    config.disableNativeSpellChecker = false;
    config.removePlugins = 'wsc,scayt';
    config.scayt_autoStartup = false;
    config.height = 1000;

    config.keystrokes =
        [
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 73 /*I*/, 'h1' ],
        ];
};
</code>```

I'm hoping to keep my changes restricted to the ckeditor directory (ideally only inside config.js).

答:
There is surprisingly little documentation around the intricacies of ckeditor's keystrokes so I'm going to share some code that demonstrates two approaches to adding keyboard shortcuts.

The first approach can be done for some elements simply by editing the config.js file.  The second uses a custom plugin.

ckeditor/config.js

```<code>CKEDITOR.editorConfig = function( config ) {

   [ ... ]

    /* This is the easy way to add keystrokes, but it only works for
     * default commands like bold, italic, link (shown here), etc.
     * This is the approach recommended in the ckeditor docs.
     *
     * @see: http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.keystrokes
     */
    config.keystrokes = [ [ CKEDITOR.CTRL + 75 /*K*/, 'link' ] ];

    /* It's hard to get keyboard shortcuts for elements that don't have
     * default ckeditor commands - headings included.  I created
     * a simple plugin that lets me define additional shortcuts. The
     * plugin needs to be declared as follows:
     */
    config.extraPlugins = 'customkeyboardshortcuts';
};
</code>```

This is an extraordinarily simple plugin, so all it requires is:

being added to config.js as in the example above

a directory name that matches the plugin name (eg "customkeyboardshortcuts")

a js file named plugin.js with the following contents

ckeditor/plugins/customkeyboardshortcuts/plugin.js

```<code>CKEDITOR.plugins.add( 'customkeyboardshortcuts', {

    // The plugin initialization logic goes inside this method.
    init: function( editor ) {

        /* The heading formats do not have ckeditor commands associated with them
         * by default in ckeditor. We use a plugin to give them command names
         * in order to set the keystrokes below.
         *
         * (If the headings had command names by default then we wouldn't need a plugin
         * at all and could just take the "keystrokes" approach in config.js - see
         * http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.keystrokes)
         */
        editor.addCommand( 'h1' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h1' } )) );
        editor.addCommand( 'h2' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h2' } )) );
        editor.addCommand( 'h3' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h3' } )) );

        /* Then we need to add a keystroke for the headings
         *
         * The hard part is finding a viable keyboard combination.  In my
         * tests I wasn't able to use any combination that included a number
         * (regardless of which modifier keys I choose). The letters 'H' (for
         * "heading") and 'F' (for "format") are reserved for OSX 'hide' and chrome
         * 'find' respectively. Also the function keys don't work on a mac, and the
         * 'fn' modifier key doesn't exist on a windows machine.
         *
         * I picked 'B' because h1 is _like_ bold, and gave h2 and h3 to 'V' and
         * 'C' respectively because it feels like a fairly natural progression to
         * me (even though it's kind of backwards).
         */
        editor.setKeystroke( CKEDITOR.SHIFT + CKEDITOR.CTRL + 66 /* B */, 'h1');
        editor.setKeystroke( CKEDITOR.SHIFT + CKEDITOR.CTRL + 86 /* V */, 'h2');
        editor.setKeystroke( CKEDITOR.SHIFT + CKEDITOR.CTRL + 67 /* C */, 'h3');

    }
});
</code>```

And thanks to @Wizard for getting me onto the right track.  As he mentioned in his post, you can add JS to the page that ckeditor is located on also.  I didn't want to muck up our view files with ckeditor js inserts, so that didn't work for me, but it might work for you.

Body:
I want my editors to be able to use keyboard shortcuts for applying headings.

I've been experimenting with the "keystrokes" approach on the ckeditor site. It works for some things, but not the headings. For instance, the following applies an additional mapping for 'bold' using Ctrl + Shift + u:

config.keystrokes = [
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
];

Why can't I enable the headings?

Right now this is what my config.js looks like:

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here.
    // For complete reference see:
    // http://docs.ckeditor.com/#!/api/CKEDITOR.config

    // The toolbar groups arrangement, optimized for two toolbar rows.
    config.toolbarGroups = [
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
        { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
        { name: 'document',    groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'others' },
        { name: 'forms' },
        { name: 'tools' }
    ];

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline,Styles,Strike,Image,Outdent,Indent,Blockquote,Cut,Copy,Paste,PasteFromWord,Undo,Redo';

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4';

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:advanced;link:advanced';

    // Whether to escape basic HTML entities in the document, including:
    // (nbsp,gt,lt,amp)
    config.basicEntities = false;
    config.entities_additional = 'lt,gt,amp,quot'
    config.entities_latin = false;
    config.entities_greek = false;
    config.disableNativeSpellChecker = false;
    config.removePlugins = 'wsc,scayt';
    config.scayt_autoStartup = false;
    config.height = 1000;

    config.keystrokes =
        [
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 73 /*I*/, 'h1' ],
        ];
};

I'm hoping to keep my changes restricted to the ckeditor directory (ideally only inside config.js).

Body:
There is surprisingly little documentation around the intricacies of ckeditor's keystrokes so I'm going to share some code that demonstrates two approaches to adding keyboard shortcuts.

The first approach can be done for some elements simply by editing the config.js file.  The second uses a custom plugin.

ckeditor/config.js

CKEDITOR.editorConfig = function( config ) {

   [ ... ]

    /* This is the easy way to add keystrokes, but it only works for
     * default commands like bold, italic, link (shown here), etc.
     * This is the approach recommended in the ckeditor docs.
     *
     * @see: http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.keystrokes
     */
    config.keystrokes = [ [ CKEDITOR.CTRL + 75 /*K*/, 'link' ] ];

    /* It's hard to get keyboard shortcuts for elements that don't have
     * default ckeditor commands - headings included.  I created
     * a simple plugin that lets me define additional shortcuts. The
     * plugin needs to be declared as follows:
     */
    config.extraPlugins = 'customkeyboardshortcuts';
};

This is an extraordinarily simple plugin, so all it requires is:

being added to config.js as in the example above

a directory name that matches the plugin name (eg "customkeyboardshortcuts")

a js file named plugin.js with the following contents

ckeditor/plugins/customkeyboardshortcuts/plugin.js

CKEDITOR.plugins.add( 'customkeyboardshortcuts', {

    // The plugin initialization logic goes inside this method.
    init: function( editor ) {

        /* The heading formats do not have ckeditor commands associated with them
         * by default in ckeditor. We use a plugin to give them command names
         * in order to set the keystrokes below.
         *
         * (If the headings had command names by default then we wouldn't need a plugin
         * at all and could just take the "keystrokes" approach in config.js - see
         * http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.keystrokes)
         */
        editor.addCommand( 'h1' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h1' } )) );
        editor.addCommand( 'h2' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h2' } )) );
        editor.addCommand( 'h3' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h3' } )) );

        /* Then we need to add a keystroke for the headings
         *
         * The hard part is finding a viable keyboard combination.  In my
         * tests I wasn't able to use any combination that included a number
         * (regardless of which modifier keys I choose). The letters 'H' (for
         * "heading") and 'F' (for "format") are reserved for OSX 'hide' and chrome
         * 'find' respectively. Also the function keys don't work on a mac, and the
         * 'fn' modifier key doesn't exist on a windows machine.
         *
         * I picked 'B' because h1 is _like_ bold, and gave h2 and h3 to 'V' and
         * 'C' respectively because it feels like a fairly natural progression to
         * me (even though it's kind of backwards).
         */
        editor.setKeystroke( CKEDITOR.SHIFT + CKEDITOR.CTRL + 66 /* B */, 'h1');
        editor.setKeystroke( CKEDITOR.SHIFT + CKEDITOR.CTRL + 86 /* V */, 'h2');
        editor.setKeystroke( CKEDITOR.SHIFT + CKEDITOR.CTRL + 67 /* C */, 'h3');

    }
});

And thanks to @Wizard for getting me onto the right track.  As he mentioned in his post, you can add JS to the page that ckeditor is located on also.  I didn't want to muck up our view files with ckeditor js inserts, so that didn't work for me, but it might work for you.


来源: stackexchange

问:
Select data using a regular expression
I have a dataframe like this

```<code>import pandas as pd

df = pd.DataFrame({'a': ['abc', 'r00001', 'r00010', 'rfoo', 'r01234', 'r1234'], 'b': range(6)})

        a  b
0     abc  0
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5
</code>```

I now want to select all columns of this dataframe where the entries in column a start with r followed by five numbers.

From here I learned how one would do this if it started just with r without the numbers:

```<code>print df.loc[df['a'].str.startswith('r'), :]

        a  b
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5
</code>```

Something like this

```<code>print df.loc[df['a'].str.startswith(r'[r]\d{5}'), :]
</code>```

does of course not work. How would one do this properly?

答:
Option 1

pd.Series.str.match

```<code>df.a.str.match('^r\d{5}$')

1     True
2     True
3    False
4     True
5    False
Name: a, dtype: bool
</code>```

Use it as a filter

```<code>df[df.a.str.match('^r\d{5}$')]

        a  b
1  r00001  1
2  r00010  2
4  r01234  4
</code>```

Option 2

Custom list comprehension using string methods

```<code>f = lambda s: s.startswith('r') and (len(s) == 6) and s[1:].isdigit()
[f(s) for s in df.a.values.tolist()]

[False, True, True, False, True, False]
</code>```

Use it as a filter

```<code>df[[f(s) for s in df.a.values.tolist()]]

        a  b
1  r00001  1
2  r00010  2
4  r01234  4
</code>```

Timing

```<code>df = pd.concat([df] * 10000, ignore_index=True)

%timeit df[[s.startswith('r') and (len(s) == 6) and s[1:].isdigit() for s in df.a.values.tolist()]]
%timeit df[df.a.str.match('^r\d{5}$')]
%timeit df[df.a.str.contains('^r\d{5}$')]

10 loops, best of 3: 22.8 ms per loop
10 loops, best of 3: 33.8 ms per loop
10 loops, best of 3: 34.8 ms per loop
</code>```

ContentLicense: CC BY-SA 3.0

Title: Select data using a regular expression

Body:
I have a dataframe like this

import pandas as pd

df = pd.DataFrame({'a': ['abc', 'r00001', 'r00010', 'rfoo', 'r01234', 'r1234'], 'b': range(6)})

        a  b
0     abc  0
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5

I now want to select all columns of this dataframe where the entries in column a start with r followed by five numbers.

From here I learned how one would do this if it started just with r without the numbers:

print df.loc[df['a'].str.startswith('r'), :]

        a  b
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5

Something like this

print df.loc[df['a'].str.startswith(r'[r]\d{5}'), :]

does of course not work. How would one do this properly?

Body:
Option 1

pd.Series.str.match

df.a.str.match('^r\d{5}$')

1     True
2     True
3    False
4     True
5    False
Name: a, dtype: bool

Use it as a filter

df[df.a.str.match('^r\d{5}$')]

        a  b
1  r00001  1
2  r00010  2
4  r01234  4

Option 2

Custom list comprehension using string methods

f = lambda s: s.startswith('r') and (len(s) == 6) and s[1:].isdigit()
[f(s) for s in df.a.values.tolist()]

[False, True, True, False, True, False]

Use it as a filter

df[[f(s) for s in df.a.values.tolist()]]

        a  b
1  r00001  1
2  r00010  2
4  r01234  4

Timing

df = pd.concat([df] * 10000, ignore_index=True)

%timeit df[[s.startswith('r') and (len(s) == 6) and s[1:].isdigit() for s in df.a.values.tolist()]]
%timeit df[df.a.str.match('^r\d{5}$')]
%timeit df[df.a.str.contains('^r\d{5}$')]

10 loops, best of 3: 22.8 ms per loop
10 loops, best of 3: 33.8 ms per loop
10 loops, best of 3: 34.8 ms per loop


问:
multiple TransactionScopes in in different classes C#
Good day,
I have a method which contains several database commits (about 15) in a different classes, I need a way to make all the db changes only if the the method did not throw any exception, I am thinking about using a Transaction Scope, and my question is weather i can use a single instance of that Transaction Scope in all the different classes and if not what is the best practice to perform a rollback in case of an exception?
Thanks!</p>

答:
You usually don't need to perform rollback explicitly, methods that perform database operations might not even be aware of ambient transaction (that is - you don't need to pass TransactionScope to them). Just do:

```<code>using (var tran = new TransactionScope()) {
    FirstDatabaseOperation();
    SecondDatabaseOperation();
    // etc
    tran.Complete();
}
</code>```

If exception happens in any operation - transaction will be rolled back for you, because TransactionScope will be disposed.

Body:
You usually don't need to perform rollback explicitly, methods that perform database operations might not even be aware of ambient transaction (that is - you don't need to pass TransactionScope to them). Just do:

using (var tran = new TransactionScope()) {
    FirstDatabaseOperation();
    SecondDatabaseOperation();
    // etc
    tran.Complete();
}

If exception happens in any operation - transaction will be rolled back for you, because TransactionScope will be disposed.


问:
Caliburn.Micro & Infragistics XamDockManager + TabGroupPane
I'm trying to get the Infragistics TabGroupPane to integrate with Caliburn.Micro as per the standard WPF TabControl.

I've tried adding a new convention in the bootstrapper (a modification of the standard WPF one) but have not had any success.

My TabGroupPane is defined as:

```<code><igDock:TabGroupPane x:Name="Items"/>
</code>```

When an item is added to the collection an exception is thrown "InvalidOperationException: A TabGroupPane can only contain 'ContentPane' and 'ContentPanePlaceholder' instances".

Also, if my TabGroupPane is inside a DockManager:

```<code><igDock:XamDockManager>
    <igDock:DocumentContentHost>
        <igDock:SplitPane>
            <igDock:TabGroupPane x:Name="Items" />
        </igDock:SplitPane>
    </igDock:DocumentContentHost>
</igDock:XamDockManager>
</code>```

It doesn't appear to be found by Caliburn at all.

Has anyone else done this before?

Cheers!

Update

I have created my own dock manager class, a blog post explaining it or just the code on bitbucket. Hopefully this will be useful to someone!

答:
If you can't get the ContentPaneFactory suggested in Infragistics blog to fill the TabGroupPane through binding, you might consider these alternative approaches:

keep your VM with BindableCollection in place, subscribe VM change notification in code-behind and change the TabGroupPane programmatically according to the actual change occurred in observed collection

build a custom IResult and invoke it from VM (using Coroutine.Execute) according to the desired TabGroupPane variation.

In IResult.Execute body you have access to ActionExecutionContext.View, so you can reach the TabGroupPane by name and operate whathever action you need on it.

This way you keep your VM free from direct reference to the particular UI control library.

define an interface abstracting the whole Docking Manager, and use it as a service from VM (see this post about the implementation of a Docking Manager). This approach diverges quite a lot from the MVVM idea, but unfortunately most docking library are not very MVVM friendly...

Body:
I'm trying to get the Infragistics TabGroupPane to integrate with Caliburn.Micro as per the standard WPF TabControl.

I've tried adding a new convention in the bootstrapper (a modification of the standard WPF one) but have not had any success.

My TabGroupPane is defined as:

<igDock:TabGroupPane x:Name="Items"/>

When an item is added to the collection an exception is thrown "InvalidOperationException: A TabGroupPane can only contain 'ContentPane' and 'ContentPanePlaceholder' instances".

Also, if my TabGroupPane is inside a DockManager:

<igDock:XamDockManager>
    <igDock:DocumentContentHost>
        <igDock:SplitPane>
            <igDock:TabGroupPane x:Name="Items" />
        </igDock:SplitPane>
    </igDock:DocumentContentHost>
</igDock:XamDockManager>

It doesn't appear to be found by Caliburn at all.

Has anyone else done this before?

Cheers!

Update

I have created my own dock manager class, a blog post explaining it or just the code on bitbucket. Hopefully this will be useful to someone!

ContentLicense: CC BY-SA 2.5


问:
How do i filter an array inside of a array of objects?
I'm trying to filter a list by tags:

```<code>const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]
</code>```

I can filter the list by name using map and filter, my problem is when i try to list the products by tags. Do i have to use foreach inside of my products filter? There's another way of doing it?

答:
Firstly to get all the tags and filter the duplicate tags from initialState. Save the array into uniqueTags.

Then compare the uniqueTags with initialState names, to create another array productTags with objects and its properties tags and products.

```<code>const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'winter', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'family', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

   let allTags = [];
   initialState.map((t)=>t.tags).forEach((a)=>a.forEach((b)=>allTags.push(b)))
   let uniqueTags = allTags.filter((a,i,arr)=>arr.indexOf(a,i+1)===-1)

   productTags = [];
   uniqueTags.forEach((u)=>{
       initialState.forEach((t)=>{
           if(t.tags.includes(u))
            productTags.push({'tag': u, 'product':t.name});
       })
   })

   console.log(JSON.stringify(productTags));

   /*
   [
    { "tag": "nature", "product": "Product A" },
    { "tag": "outdoor", "product": "Product A" },
    { "tag": "winter", "product": "Product A" },
    { "tag": "winter", "product": "Product B" },
    { "tag": "hiking", "product": "Product B" },
    { "tag": "camping", "product": "Product A" },
    { "tag": "camping", "product": "Product B" },
    { "tag": "snow", "product": "Product B" },
    { "tag": "vacation", "product": "Product C" },
    { "tag": "family", "product": "Product B" },
    { "tag": "family", "product": "Product C" },
    { "tag": "kids", "product": "Product C" },
    { "tag": "river", "product": "Product C" },
    { "tag": "lake", "product": "Product C" },
    { "tag": "fishing", "product": "Product C" }
] */
</code>```

(Edited later) Correction:

To form the correct object, I have changed the code to:

```<code>const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'winter', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'family', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

   let allTags = [];
   initialState.map((t)=>t.tags).forEach((a)=>a.forEach((b)=>allTags.push(b)))
   let uniqueTags = allTags.filter((a,i,arr)=>!arr.includes(a,i+1))

   productTags = [];
   uniqueTags.forEach((u)=>{
       let productName = [];
       initialState.forEach((t)=>{
           if(t.tags.includes(u))
            productName.push(t.name);
       })
       productTags.push({tag:u, products:productName});
   })

   console.log(JSON.stringify(productTags));

   /*
    productTags = [
        {"tag":"nature","products":["Product A"]},
        {"tag":"outdoor","products":["Product A"]},
        {"tag":"winter","products":["Product A","Product B"]},
        {"tag":"hiking","products":["Product B"]},
        {"tag":"camping","products":["Product A","Product B"]},
        {"tag":"snow","products":["Product B"]},
        {"tag":"vacation","products":["Product C"]},
        {"tag":"family","products":["Product B","Product C"]},
        {"tag":"kids","products":["Product C"]},
        {"tag":"river","products":["Product C"]},
        {"tag":"lake","products":["Product C"]},
        {"tag":"fishing","products":["Product C"]}
    ]
    */
</code>```

Body:
I'm trying to filter a list by tags:

const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

I can filter the list by name using map and filter, my problem is when i try to list the products by tags. Do i have to use foreach inside of my products filter? There's another way of doing it?

Body:
Firstly to get all the tags and filter the duplicate tags from initialState. Save the array into uniqueTags.

Then compare the uniqueTags with initialState names, to create another array productTags with objects and its properties tags and products.

const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'winter', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'family', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

   let allTags = [];
   initialState.map((t)=>t.tags).forEach((a)=>a.forEach((b)=>allTags.push(b)))
   let uniqueTags = allTags.filter((a,i,arr)=>arr.indexOf(a,i+1)===-1)

   productTags = [];
   uniqueTags.forEach((u)=>{
       initialState.forEach((t)=>{
           if(t.tags.includes(u))
            productTags.push({'tag': u, 'product':t.name});
       })
   })

   console.log(JSON.stringify(productTags));

   /*
   [
    { "tag": "nature", "product": "Product A" },
    { "tag": "outdoor", "product": "Product A" },
    { "tag": "winter", "product": "Product A" },
    { "tag": "winter", "product": "Product B" },
    { "tag": "hiking", "product": "Product B" },
    { "tag": "camping", "product": "Product A" },
    { "tag": "camping", "product": "Product B" },
    { "tag": "snow", "product": "Product B" },
    { "tag": "vacation", "product": "Product C" },
    { "tag": "family", "product": "Product B" },
    { "tag": "family", "product": "Product C" },
    { "tag": "kids", "product": "Product C" },
    { "tag": "river", "product": "Product C" },
    { "tag": "lake", "product": "Product C" },
    { "tag": "fishing", "product": "Product C" }
] */

(Edited later) Correction:

To form the correct object, I have changed the code to:

const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'winter', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'family', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

   let allTags = [];
   initialState.map((t)=>t.tags).forEach((a)=>a.forEach((b)=>allTags.push(b)))
   let uniqueTags = allTags.filter((a,i,arr)=>!arr.includes(a,i+1))

   productTags = [];
   uniqueTags.forEach((u)=>{
       let productName = [];
       initialState.forEach((t)=>{
           if(t.tags.includes(u))
            productName.push(t.name);
       })
       productTags.push({tag:u, products:productName});
   })

   console.log(JSON.stringify(productTags));

   /*
    productTags = [
        {"tag":"nature","products":["Product A"]},
        {"tag":"outdoor","products":["Product A"]},
        {"tag":"winter","products":["Product A","Product B"]},
        {"tag":"hiking","products":["Product B"]},
        {"tag":"camping","products":["Product A","Product B"]},
        {"tag":"snow","products":["Product B"]},
        {"tag":"vacation","products":["Product C"]},
        {"tag":"family","products":["Product B","Product C"]},
        {"tag":"kids","products":["Product C"]},
        {"tag":"river","products":["Product C"]},
        {"tag":"lake","products":["Product C"]},
        {"tag":"fishing","products":["Product C"]}
    ]
    */


问:
Javascript Splitting a string into multiple object properties
I am working on a Shopify app and part of the order info that I need to get into Mongo is coming as a property that contains a single string via their API. As an example:

"note": "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n",```
</div>
</div>
</p>

<p>I actually need this string to look something like this in Mongo: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>mongoExDoc: {
  child1FirstName: "Ali",
  child1Gender: "Female",
  child1HairColor: "Blonde",
  child1HairStyle: "Wavy",
  child1SkinTone: "Tan",
  child2FirstName: "Morgan",
  child2Gender: "Female",
  child2HairColor: "Brown",
  child2HairStyle: "Ponytail",
  child2SkinTone: "Light",
  relationship1To2: "Brother",
  relationship2To1: "Brother"
}</code>```

Or something along these lines. The property values themselves will NOT change. As you can see each value is separated by \n and each actual value is preceded by a:.  I would really appreciate suggestions!

答:
At a glance:

var data = {"note": "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n"};

var mongoExDoc = data.note.split("\n").reduce(function(obj, str, index) {
 var strParts = str.split(":");
  obj[strParts[0].replace(/\s+/g, '')] = strParts[1];
  return obj;
}, {})

console.log(mongoExDoc);```

Body:
I am working on a Shopify app and part of the order info that I need to get into Mongo is coming as a property that contains a single string via their API. As an example:

"note": "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n",

I actually need this string to look something like this in Mongo:

mongoExDoc: {
  child1FirstName: "Ali",
  child1Gender: "Female",
  child1HairColor: "Blonde",
  child1HairStyle: "Wavy",
  child1SkinTone: "Tan",
  child2FirstName: "Morgan",
  child2Gender: "Female",
  child2HairColor: "Brown",
  child2HairStyle: "Ponytail",
  child2SkinTone: "Light",
  relationship1To2: "Brother",
  relationship2To1: "Brother"
}

Or something along these lines. The property values themselves will NOT change. As you can see each value is separated by \n and each actual value is preceded by a:.  I would really appreciate suggestions!


问:
Cell appears blank in the UITableView
I am making a view controller with tableView for presenting individual news cards.  I want to load cells once and for all (without reusing it as usual). So I do this:

```<code>    tableView.register(UINib(nibName: "RatingNewsCell", bundle: nil), forCellReuseIdentifier: "RatingNewsCell")
    tableView.register(UINib(nibName: "PromoNewsCell", bundle: nil), forCellReuseIdentifier: "PromoNewsCell")

    var cells = [UITableViewCell]()

    let rating = RatingNewsCell()
    rating.delegate = self
    cells.append(rating)

    etc...

    self.items = cells
</code>```

Cells are loaded like this:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    return items[indexPath.section]
}
</code>```

Cell code looks like this:

```<code>class RatingNewsCell: UITableViewCell
{
    var delegate: RatingNewsCellDelegate?

    @IBOutlet weak var shopNameLabel: UILabel!
    @IBOutlet weak var bouquetImageView: RoundImageView!
    @IBOutlet weak var floristImageView: RoundImageView!
    @IBOutlet weak var ratingControl: RatingPicker!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: "RatingNewsCell")
    }

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
    }

    override func awakeFromNib()
    {
        super.awakeFromNib()

        ratingControl.setSelected(newIndex: 0)
    }
}
</code>```

In the result I've got a table view, but cell just appears blank:

Any ideas?

答:
You need to call

```<code>tableView.delegate = self
</code>```

and

```<code>tableView.dataSource = self
</code>```

Title: Cell appears blank in the UITableView

Body:
I am making a view controller with tableView for presenting individual news cards.  I want to load cells once and for all (without reusing it as usual). So I do this:

    tableView.register(UINib(nibName: "RatingNewsCell", bundle: nil), forCellReuseIdentifier: "RatingNewsCell")
    tableView.register(UINib(nibName: "PromoNewsCell", bundle: nil), forCellReuseIdentifier: "PromoNewsCell")

    var cells = [UITableViewCell]()

    let rating = RatingNewsCell()
    rating.delegate = self
    cells.append(rating)

    etc...

    self.items = cells

Cells are loaded like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    return items[indexPath.section]
}

Cell code looks like this:

class RatingNewsCell: UITableViewCell
{
    var delegate: RatingNewsCellDelegate?

    @IBOutlet weak var shopNameLabel: UILabel!
    @IBOutlet weak var bouquetImageView: RoundImageView!
    @IBOutlet weak var floristImageView: RoundImageView!
    @IBOutlet weak var ratingControl: RatingPicker!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: "RatingNewsCell")
    }

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
    }

    override func awakeFromNib()
    {
        super.awakeFromNib()

        ratingControl.setSelected(newIndex: 0)
    }
}

In the result I've got a table view, but cell just appears blank:

Any ideas?

Body:
You need to call

tableView.delegate = self

and

tableView.dataSource = self


问:
Filtering duplicates from pandas dataframe with preference based on additional column
I would like to filter rows containing a duplicate in column X from a dataframe. However, if there are duplicates for a value in X, I would like to give preference to one of them based on the value of another column Y. For example:

```<code>import pandas as pd
print pd.__version__
x = pd.DataFrame([
    ['best', 'a', 'x'],
    ['worst', 'b', 'y'],
    ['best', 'c', 'x'],
    ['worst','d', 'y'],
    ['best','d', 'y'],
    ['worst','d', 'y'],
    ['best','d', 'z'],
    ['best','d', 'z'],
], columns=['a', 'b', 'c'])
print x
x.drop_duplicates(cols='c', inplace=True)
print x

       a  b  c
0   best  a  x
1  worst  b  y
2   best  c  x
3  worst  d  y
4   best  d  y
5  worst  d  y
6   best  d  z
7   best  d  z

       a  b  c
0   best  a  x
1  worst  b  y
6   best  d  z
</code>```

I would like to give precedence to the duplicate with column a equal to best. Which would give the result:

```<code>       a  b  c
0   best  a  x
4   best  d  y
6   best  d  z
</code>```

Any idea what is the correct way to do this in pandas? Is there a more general way than just sorting the rows such that removing all but the first occurrence of the duplicate does what you want?

答:
I think a more straightforward way is to first sort the DataFrame, then drop duplicates keeping the first entry. This is pretty robust (here, 'a' was a string with two values but you could apply a function that makes an integer column from the string if there were more string values to sort).</p>

```<code>x = x.sort_values(['a']).drop_duplicates(cols='c')
</code>```

Body:
I would like to filter rows containing a duplicate in column X from a dataframe. However, if there are duplicates for a value in X, I would like to give preference to one of them based on the value of another column Y. For example:

import pandas as pd
print pd.__version__
x = pd.DataFrame([
    ['best', 'a', 'x'],
    ['worst', 'b', 'y'],
    ['best', 'c', 'x'],
    ['worst','d', 'y'],
    ['best','d', 'y'],
    ['worst','d', 'y'],
    ['best','d', 'z'],
    ['best','d', 'z'],
], columns=['a', 'b', 'c'])
print x
x.drop_duplicates(cols='c', inplace=True)
print x

       a  b  c
0   best  a  x
1  worst  b  y
2   best  c  x
3  worst  d  y
4   best  d  y
5  worst  d  y
6   best  d  z
7   best  d  z

       a  b  c
0   best  a  x
1  worst  b  y
6   best  d  z

I would like to give precedence to the duplicate with column a equal to best. Which would give the result:

       a  b  c
0   best  a  x
4   best  d  y
6   best  d  z

Any idea what is the correct way to do this in pandas? Is there a more general way than just sorting the rows such that removing all but the first occurrence of the duplicate does what you want?

Body:
I think a more straightforward way is to first sort the DataFrame, then drop duplicates keeping the first entry. This is pretty robust (here, 'a' was a string with two values but you could apply a function that makes an integer column from the string if there were more string values to sort).

x = x.sort_values(['a']).drop_duplicates(cols='c')


问:
JSX Unexpected token - Webpack and babel-loader
I'm getting JSX parse error after upgrading webpack from ^1.14.0 to "^3.0.0"

```<code>ERROR in ./shared/Application.js
Module parse failed: /Users/arjunkumar/Documents/Work/test/web/shared/Application.js Unexpected token (25:2)
You may need an appropriate loader to handle this file type.
</code>```

The related code in Application.js looks like this

```<code>ReactDOM.render(
  <Provider store={store}>
    <Router routes={Routes(store)} history={history} />
  </Provider>,
  document.getElementById('app-shell')
);
</code>```

Relevant part of webpack.config.js file looks as follows (all the required plugins are imported properly to webpack config file, not present in the following code).

```<code>module.exports = {
  entry: {
    app:['./shared/Application.js'],
    vendors:[// vendors like react and other libs ]
  },
  output: {
    path: __dirname + '/public/build',
    filename: 'app.[chunkhash].js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'autoprefixer-loader',
            'sass-loader'
          ],
          exclude: /node_modules/
        }),
      },
      {
        test: /\.js$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              ['es2015', {modules: false}],
              'react'
            ],
            babelrc: false
          }
        }]
      },
      {
        test: /\.jsx$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              'es2015',
              'react'
            ],
            babelrc: false
          }
        }]
      },
    ]
  },
  devtool: ( process.env.NODE_ENV === 'production' ) ? false : 'eval',
  plugins: [
    new ExtractTextPlugin(
      'app.[chunkhash].css',
      {
        allChunks: true
      }
    ),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['utilities','vendors'],
      filename: '[name].[chunkhash].js',
      minChunks: Infinity
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      },
      output: {
        comments:false
      },
      comments: false
    }),
    new AssetsPlugin({
      filename: 'assets.json',
      fullPath: false,
      path: __dirname + '/public/build',
      prettyPrint: true
    })
  ]

};
</code>```

Relevant dependencies for the issue from package.json file is as follows.

```<code>{
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-object-assign": "^6.8.0",
    "babel-plugin-transform-react-constant-elements": "^6.9.1",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.2.9",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2015-loose": "^8.0.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.24.1",
    "extract-text-webpack-plugin": "^2.1.2",
    "html-webpack-plugin": "^2.21.0",
    "husky": "^0.13.1",
    "lodash-webpack-plugin": "^0.10.6",
    "node-sass": "^3.13.1",
    "postcss-loader": "^2.0.6",
    "purifycss-webpack": "^0.4.2",
    "sass-loader": "^4.1.1",
    "webpack": "^3.0.0",
    "webpack-bundle-analyzer": "^2.3.0",
    "webpack-dev-server": "^2.5.0"
  },
  "dependencies": {
    "react": "^15.1.0"
  }
}
</code>```

Just in case anyone wants to check .babelrc file ( I think babel-loader respects babelrc: false flag in webpack.config.js).

```<code>{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-react-constant-elements",
        "transform-react-inline-elements",
        "transform-react-remove-prop-types"
      ]
    }
  },
  "comments": false,
  "compact": false
}
</code>```

Any thoughts or leads on what might be wrong?

Another important thing I noticed is even though my webpack project and global dependency is at 3.0.0, when I run the webpack in the project it shows Version: webpack 1.15.0 at the top. Screenshot below.

答:
If it says Webpack 1.x in the output when you compile, then that is why it isn't working. Your config is for Webpack 3, so Webpack 1 doesn't know what to do with it.

This is likely because you've installed webpack@1.x as a global module, e.g. npm i webpack -g which means the version of it is unrelated to the version in your package.json. Installing dependencies globally is generally not a good idea because of this type of issues unless you are installing a truly global application from npm.

The first step would be to npm uninstall -g webpack so you don't accidentally run the global version anymore, then you need to explicitly run your local version when building, e.g.

instead of just running

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

you should run

```<code>$(npm bin)/webpack
</code>```

so that you run the version of Webpack installed into node_modules.

Body:
I'm getting JSX parse error after upgrading webpack from ^1.14.0 to "^3.0.0"

ERROR in ./shared/Application.js
Module parse failed: /Users/arjunkumar/Documents/Work/test/web/shared/Application.js Unexpected token (25:2)
You may need an appropriate loader to handle this file type.

The related code in Application.js looks like this

ReactDOM.render(
  <Provider store={store}>
    <Router routes={Routes(store)} history={history} />
  </Provider>,
  document.getElementById('app-shell')
);

Relevant part of webpack.config.js file looks as follows (all the required plugins are imported properly to webpack config file, not present in the following code).

module.exports = {
  entry: {
    app:['./shared/Application.js'],
    vendors:[// vendors like react and other libs ]
  },
  output: {
    path: __dirname + '/public/build',
    filename: 'app.[chunkhash].js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'autoprefixer-loader',
            'sass-loader'
          ],
          exclude: /node_modules/
        }),
      },
      {
        test: /\.js$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              ['es2015', {modules: false}],
              'react'
            ],
            babelrc: false
          }
        }]
      },
      {
        test: /\.jsx$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              'es2015',
              'react'
            ],
            babelrc: false
          }
        }]
      },
    ]
  },
  devtool: ( process.env.NODE_ENV === 'production' ) ? false : 'eval',
  plugins: [
    new ExtractTextPlugin(
      'app.[chunkhash].css',
      {
        allChunks: true
      }
    ),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['utilities','vendors'],
      filename: '[name].[chunkhash].js',
      minChunks: Infinity
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      },
      output: {
        comments:false
      },
      comments: false
    }),
    new AssetsPlugin({
      filename: 'assets.json',
      fullPath: false,
      path: __dirname + '/public/build',
      prettyPrint: true
    })
  ]

};

Relevant dependencies for the issue from package.json file is as follows.

{
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-object-assign": "^6.8.0",
    "babel-plugin-transform-react-constant-elements": "^6.9.1",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.2.9",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2015-loose": "^8.0.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.24.1",
    "extract-text-webpack-plugin": "^2.1.2",
    "html-webpack-plugin": "^2.21.0",
    "husky": "^0.13.1",
    "lodash-webpack-plugin": "^0.10.6",
    "node-sass": "^3.13.1",
    "postcss-loader": "^2.0.6",
    "purifycss-webpack": "^0.4.2",
    "sass-loader": "^4.1.1",
    "webpack": "^3.0.0",
    "webpack-bundle-analyzer": "^2.3.0",
    "webpack-dev-server": "^2.5.0"
  },
  "dependencies": {
    "react": "^15.1.0"
  }
}

Just in case anyone wants to check .babelrc file ( I think babel-loader respects babelrc: false flag in webpack.config.js).

{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-react-constant-elements",
        "transform-react-inline-elements",
        "transform-react-remove-prop-types"
      ]
    }
  },
  "comments": false,
  "compact": false
}

Any thoughts or leads on what might be wrong?

Another important thing I noticed is even though my webpack project and global dependency is at 3.0.0, when I run the webpack in the project it shows Version: webpack 1.15.0 at the top. Screenshot below.

Body:
If it says Webpack 1.x in the output when you compile, then that is why it isn't working. Your config is for Webpack 3, so Webpack 1 doesn't know what to do with it.

This is likely because you've installed webpack@1.x as a global module, e.g. npm i webpack -g which means the version of it is unrelated to the version in your package.json. Installing dependencies globally is generally not a good idea because of this type of issues unless you are installing a truly global application from npm.

The first step would be to npm uninstall -g webpack so you don't accidentally run the global version anymore, then you need to explicitly run your local version when building, e.g.

instead of just running

webpack

you should run

$(npm bin)/webpack

so that you run the version of Webpack installed into node_modules.


问:
Can connect to database with sqlplus directly, but not when setting ORACLE_SID
I am trying to connect to a database in a shell script.  I can connect fine if I use this:

```<code>sqlplus user/pass@db_service_name
</code>```

However, when I try something like this, it is not working:

```<code>ORACLE_SID=db_sid
export ORACLE_SID
sqlplus /nolog
connect user/pass
</code>```

I get an error:

```<code>ERROR:
ORA-12545: Connect failed because target host or object does not exist
</code>```

Obviously I am missing something, but this is an area I am not fully familiar with, so I am not sure where I am going wrong.  My assumption was that if I set the ORACLE_SID, that I would not need to identify my db when connecting in sqlplus.  Is my assumption incorrect?  Or am I missing some required step or configuration?

答:
Using sqlplus user/pass@db_sid refers to a TNS alias in $ORACLE_HOME/network/admin/tnsnames.ora. If the instance is running on the same host as your sqlplus command, then you need to look at the text of the TNS alias in tnsnames.ora and set ORACLE_SID to the SID referenced in the file and then execute . oraenv. If the instance is not running on the same host as your sqlplus command, then your latter attempt will never work.

If you want more secure connections, you might consider using a wallet.

Body:
I am trying to connect to a database in a shell script.  I can connect fine if I use this:

sqlplus user/pass@db_service_name

However, when I try something like this, it is not working:

ORACLE_SID=db_sid
export ORACLE_SID
sqlplus /nolog
connect user/pass

I get an error:

ERROR:
ORA-12545: Connect failed because target host or object does not exist

Obviously I am missing something, but this is an area I am not fully familiar with, so I am not sure where I am going wrong.  My assumption was that if I set the ORACLE_SID, that I would not need to identify my db when connecting in sqlplus.  Is my assumption incorrect?  Or am I missing some required step or configuration?


问:
How to create NFC tag that contains NDEF data?
Recently, Apple has opened NFC for iPhone 7. I have been experimenting this feature. I don't know how to create NFC tags which contain NDEF data. If anyone knows, please share your knowledge</p>

答:
Depends on the devices you have at hand; there are Android apps, like https://play.google.com/store/apps/details?id=com.nxp.nfc.tagwriter&hl=de or https://play.google.com/store/apps/details?id=org.ndeftools.boilerplate -  obviously you need an Android phone with NFC functionality for that.
Or you could use desktop-based tools, like http://ndefeditor.grundid.de/ or https://github.com/skjolber/nfc-eclipse-plugin
In this case you have to use a contactless reader.</p>


问:
Getting rid of \n when using .readlines()
I have a .txt file with values in it.

The values are listed like so:

Value1
Value2
Value3
Value4
```
<p>My goal is to put the values in a list. When I do so, the list looks like this:</p>
<p><code>['Value1\n', 'Value2\n', ...]</code></p>
<p>The <code>\n</code> is not needed.</p>
<p>Here is my code:</p>
```t = open('filename.txt')
contents = t.readlines()
```

答:
I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

```<code>with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():
        print(apps.strip())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a .txt file with values in it.

The values are listed like so:

Value1
Value2
Value3
Value4

My goal is to put the values in a list. When I do so, the list looks like this:

['Value1\n', 'Value2\n', ...]

The \n is not needed.

Here is my code:

t = open('filename.txt')
contents = t.readlines()

Body:
I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():
        print(apps.strip())


问:
Git rebase when previous commit changed
I frequently find myself working on two different work tickets that are on different git branches, but one is dependent on another, like this:

```<code>* later-branch
|
* earlier-branch
|
* some prior commit
|
</code>```

(Each is a single commit here because we are using gerrit, but this question might apply to multiple commits for each as well.)  The earlier branch may be going through review, and so I might have to go back and modify it at some point with a git commit --amend.  As must happen, this will fork the history:

```<code>* earlier-branch
|
|  * later-branch
|  |
|  * previous version of earlier-branch
| /
* some prior commit
|
</code>```

At this point I want to rebase the later-branch on top of the new version of earlier-branch.  But if I just do a git checkout later-branch followed by a git rebase earlier-branch, it always gets conflicts, because (I think) it must first apply the previous version of earlier-branch commit to the most recent version of earlier-branch.

What I end up doing is git checkout earlier-branch -b new-later-branch-name followed by git cherry-pick later-branch and git br -D later-branch.  Which is a pain.  Can anyone suggest a better way to handle this?

答:
Aside from interactive rebase (as in houtanb's answer), there are two more ways to do this somewhat, or much, more automatically:

using git rebase --onto, or

using the "fork-point" code (in Git since Git version 2.0).

To use the latter, you can run git rebase --fork-point earlier-branch when on later-branch.

(You can instead set earlier-branch as the upstream for later-branch—presumably just temporarily, for the duration of the rebasing—and then just run git rebase when on later-branch.  The reason is that --fork-point is the default when using the automatic upstream mode, but must be explicitly requested when using an explicit <upstream> argument to git rebase.)

Unfortunately, the last is especially magical-seeming, especially to those new to Git.  Fortunately, your diagram has in it the seeds to understanding it—and with it, git rebase --onto.

Defining fork-point

Let's take what you drew above and turn it sideways, then turn it even a little a bit more.  This gives me some room to draw in the branch names.  I'll replace the *s for each commit with round o nodes or uppercase letters and numbers.  I'll add a third commit, C, to the later branch as well just for illustration.

```<code>:
 .
  \
   o
    \
     A1   <-- earlier-branch
      \
       B--C   <-- later-branch
</code>```

Now you are forced, for whatever reason, to copy commit A1 to new commit A2, and move the branch label earlier-branch to point to the new copy:

```<code>:
 .
  \
   o--A2  <-- earlier-branch
    \
     A1
      \
       B--C   <-- later-branch
</code>```

If only Git would remember that commit A1 exists because earlier-branch used to contain commit A1, we could tell Git: "when copying later-branch, drop any commits that are still on it now, but used to be on it only because of earlier-branch".

But Git does remember this, for 30 days at least, by default.  Git has reflogs—logs of what used to be stored in each reference (including both regular branches and Git's so-called remote tracking branches).  If we add the reflog information to the drawing, it looks like this:

```<code>:
 .
  \
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- later-branch
</code>```

In fact, if for some reason you must copy A2 to A3, the diagram just grows another reflog entry, renumbering the existing one:

```<code>:
 .   A3    <-- earlier-branch
  \ /
   o--A2   <-- [earlier-branch@{1}]
    \
     A1    <-- [earlier-branch@{2}]
      \
       B--C   <-- later-branch
</code>```

What the fork-point code does is to scan the reflog for some other reference, such as earlier-branch, and find these commits (in this case A1—it actually finds both A1 and A2, in the latter case, but then winnows it down to the A1 that's on both branches; see also Git rebase - commit select in fork-point mode).  It then runs git rebase --onto for you, as if you had manually run:

```<code>git rebase --onto earlier-branch hash-of-A1
</code>```

which gets us into how the --onto argument works.

Regular rebase, without --onto

Normally, you would run git rebase with one argument, as in git rebase branch-name, or even no arguments at all.  With no arguments at all, git rebase uses the current branch's upstream setting.  With a branch-name argument, git rebase calls that argument <upstream>.  (As an odd side effect, this also—since Git version 2.0 anyway—automatically enables or disables the --fork-point option, requiring you to use an explicit --no-fork-point or --fork-point if you want the other mode.)

In any case, Git uses the <upstream>—selected automatically if you did not specify one—for two purposes.  One is to limit the set of commits that will be copied: Git will consider copying the set of commits listed by running:

```<code>git rev-list <upstream>..HEAD
</code>```

To see them in a more friendly fashion, use git log, or my preferred method, git log --oneline --decorate --graph, instead of git rev-list here:

```<code>git log --oneline --decorate --graph earlier-branch..HEAD
</code>```

Ideally, we would see commits B and C here, with C listed first (Git has to use --reverse to make sure it copies B first).  If you copied A1 to A2 and/or on to A3, though, and moved the branch earlier-branch, we will see all of A1, B, and C.  (Git excludes A2 or A3—whichever earlier-branch points to—but they're not on the list anyway.  It then uses the excluded A2 or A3 to exclude the commits before A1, so that's why we don't see those.)

The other purpose for this <upstream> branch name (or commit hash) is to select where the copies go.  When we copy one or more commits, each copied commit has to go after some existing commit.  The <upstream> argument provides the ID of the commit that will be the parent of the first commit we copy.

Hence, running git rebase earlier-branch makes Git list commits A1, B, and C, in that order.  It then—using the "detached HEAD" mode—copies A1 to go after earlier-branch:

```<code>:
 .       A1'  <-- HEAD
  \     /
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- later-branch
</code>```

and then copies B to go after A1':

```<code>:
 .       A1'--B'  <-- HEAD
  \     /
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- later-branch
</code>```

Rebase then copies C to C' and moves the branch label, later-branch, to wherever HEAD winds up, re-attaching your HEAD in the process:

```<code>:
 .       A1'--B'--C'  <-- later-branch (HEAD)
  \     /
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- [later-branch@{1}]
</code>```

The --onto argument lets you tell Git where the copies go.

Using --onto with git rebase

When you add --onto, you tell Git rebase where to put the copies.  This frees up the <upstream> argument so that it now specifies only what not to copy!  So now you are free to tell Git: "copy everything that's after commit A1" by writing:

```<code>:
 .
  \
   o--A2  <-- earlier-branch
    \
     A1
      \
       B--C   <-- later-branch
</code>```0

Git does its usual thing, listing the commits to be copied (B and C), detaching your HEAD from later-branch, copying the commits one at a time with the copies going after the tip of earlier-branch, and finally moving the name later-branch to reattach your HEAD.

This is exactly what we wanted, all done semi-automatically: we tell Git not to copy A1 itself, so that it copies just B and C.

When we specify an upstream, as in git rebase earlier-branch, Git disables the fork-point mode.  If we explicitly enable it, Git will fish through the earlier-branch reflog.  As long as the reflog entry for commit A1 has not yet expired, Git will discover that A1 used to be on earlier-branch and will use --onto for us to discard it from the to-copy list.

Note that there is a bit of danger here.  What if we really wanted A1 after all, e.g., what if we backed earlier-branch up over A1 only because we realized A1 did not belong on the other branch?  Git will still think we copied it to some other commit, and don't want it copied now, and will toss off the list.  Fortunately, you can always undo a rebase: rebase doesn't discard anything at all, it just copies.  It then updates a branch, which saves the previous value in the branch's reflog.  But fishing around through reflogs, trying to find one particular set of commits, in a twisty maze of commits that are all alike, is not a lot of fun—so it is wise to think a bit before running rebase, with or without --fork-point.

Side note

In a few (rare) cases Git you don't have to do anything (no fork point mode, no manual --onto separation, no --interactive).  Specifically, if the patch itself did not change at all, but only the wording in the commit message changed, Git will detect the already-copied commit and skip it.  This happens because git rebase actually uses the symmetric difference mode of git rev-list with the --cherry-pick --right-only --no-merges options.  That is, rather than:

```<code>:
 .
  \
   o--A2  <-- earlier-branch
    \
     A1
      \
       B--C   <-- later-branch
</code>```1

Git actually runs:

```<code>:
 .
  \
   o--A2  <-- earlier-branch
    \
     A1
      \
       B--C   <-- later-branch
</code>```2

(note the three dots).  I don't have time to go into any more detail here, though.

Title: Git rebase when previous commit changed

Body:
I frequently find myself working on two different work tickets that are on different git branches, but one is dependent on another, like this:

* later-branch
|
* earlier-branch
|
* some prior commit
|

(Each is a single commit here because we are using gerrit, but this question might apply to multiple commits for each as well.)  The earlier branch may be going through review, and so I might have to go back and modify it at some point with a git commit --amend.  As must happen, this will fork the history:

* earlier-branch
|
|  * later-branch
|  |
|  * previous version of earlier-branch
| /
* some prior commit
|

At this point I want to rebase the later-branch on top of the new version of earlier-branch.  But if I just do a git checkout later-branch followed by a git rebase earlier-branch, it always gets conflicts, because (I think) it must first apply the previous version of earlier-branch commit to the most recent version of earlier-branch.

What I end up doing is git checkout earlier-branch -b new-later-branch-name followed by git cherry-pick later-branch and git br -D later-branch.  Which is a pain.  Can anyone suggest a better way to handle this?

Body:
Aside from interactive rebase (as in houtanb's answer), there are two more ways to do this somewhat, or much, more automatically:

using git rebase --onto, or

using the "fork-point" code (in Git since Git version 2.0).

To use the latter, you can run git rebase --fork-point earlier-branch when on later-branch.

(You can instead set earlier-branch as the upstream for later-branch—presumably just temporarily, for the duration of the rebasing—and then just run git rebase when on later-branch.  The reason is that --fork-point is the default when using the automatic upstream mode, but must be explicitly requested when using an explicit <upstream> argument to git rebase.)

Unfortunately, the last is especially magical-seeming, especially to those new to Git.  Fortunately, your diagram has in it the seeds to understanding it—and with it, git rebase --onto.

Defining fork-point

Let's take what you drew above and turn it sideways, then turn it even a little a bit more.  This gives me some room to draw in the branch names.  I'll replace the *s for each commit with round o nodes or uppercase letters and numbers.  I'll add a third commit, C, to the later branch as well just for illustration.

:
 .
  \
   o
    \
     A1   <-- earlier-branch
      \
       B--C   <-- later-branch

Now you are forced, for whatever reason, to copy commit A1 to new commit A2, and move the branch label earlier-branch to point to the new copy:

:
 .
  \
   o--A2  <-- earlier-branch
    \
     A1
      \
       B--C   <-- later-branch

If only Git would remember that commit A1 exists because earlier-branch used to contain commit A1, we could tell Git: "when copying later-branch, drop any commits that are still on it now, but used to be on it only because of earlier-branch".

But Git does remember this, for 30 days at least, by default.  Git has reflogs—logs of what used to be stored in each reference (including both regular branches and Git's so-called remote tracking branches).  If we add the reflog information to the drawing, it looks like this:

:
 .
  \
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- later-branch

In fact, if for some reason you must copy A2 to A3, the diagram just grows another reflog entry, renumbering the existing one:

:
 .   A3    <-- earlier-branch
  \ /
   o--A2   <-- [earlier-branch@{1}]
    \
     A1    <-- [earlier-branch@{2}]
      \
       B--C   <-- later-branch

What the fork-point code does is to scan the reflog for some other reference, such as earlier-branch, and find these commits (in this case A1—it actually finds both A1 and A2, in the latter case, but then winnows it down to the A1 that's on both branches; see also Git rebase - commit select in fork-point mode).  It then runs git rebase --onto for you, as if you had manually run:

git rebase --onto earlier-branch hash-of-A1

which gets us into how the --onto argument works.

Regular rebase, without --onto

Normally, you would run git rebase with one argument, as in git rebase branch-name, or even no arguments at all.  With no arguments at all, git rebase uses the current branch's upstream setting.  With a branch-name argument, git rebase calls that argument <upstream>.  (As an odd side effect, this also—since Git version 2.0 anyway—automatically enables or disables the --fork-point option, requiring you to use an explicit --no-fork-point or --fork-point if you want the other mode.)

In any case, Git uses the <upstream>—selected automatically if you did not specify one—for two purposes.  One is to limit the set of commits that will be copied: Git will consider copying the set of commits listed by running:

git rev-list <upstream>..HEAD

To see them in a more friendly fashion, use git log, or my preferred method, git log --oneline --decorate --graph, instead of git rev-list here:

git log --oneline --decorate --graph earlier-branch..HEAD

Ideally, we would see commits B and C here, with C listed first (Git has to use --reverse to make sure it copies B first).  If you copied A1 to A2 and/or on to A3, though, and moved the branch earlier-branch, we will see all of A1, B, and C.  (Git excludes A2 or A3—whichever earlier-branch points to—but they're not on the list anyway.  It then uses the excluded A2 or A3 to exclude the commits before A1, so that's why we don't see those.)

The other purpose for this <upstream> branch name (or commit hash) is to select where the copies go.  When we copy one or more commits, each copied commit has to go after some existing commit.  The <upstream> argument provides the ID of the commit that will be the parent of the first commit we copy.

Hence, running git rebase earlier-branch makes Git list commits A1, B, and C, in that order.  It then—using the "detached HEAD" mode—copies A1 to go after earlier-branch:

:
 .       A1'  <-- HEAD
  \     /
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- later-branch

and then copies B to go after A1':

:
 .       A1'--B'  <-- HEAD
  \     /
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- later-branch

Rebase then copies C to C' and moves the branch label, later-branch, to wherever HEAD winds up, re-attaching your HEAD in the process:

:
 .       A1'--B'--C'  <-- later-branch (HEAD)
  \     /
   o--A2   <-- earlier-branch
    \
     A1    <-- [earlier-branch@{1}]
      \
       B--C   <-- [later-branch@{1}]

The --onto argument lets you tell Git where the copies go.

Using --onto with git rebase

When you add --onto, you tell Git rebase where to put the copies.  This frees up the <upstream> argument so that it now specifies only what not to copy!  So now you are free to tell Git: "copy everything that's after commit A1" by writing:

git rebase --onto earlier-branch <hash-of-A1>

Git does its usual thing, listing the commits to be copied (B and C), detaching your HEAD from later-branch, copying the commits one at a time with the copies going after the tip of earlier-branch, and finally moving the name later-branch to reattach your HEAD.

This is exactly what we wanted, all done semi-automatically: we tell Git not to copy A1 itself, so that it copies just B and C.

When we specify an upstream, as in git rebase earlier-branch, Git disables the fork-point mode.  If we explicitly enable it, Git will fish through the earlier-branch reflog.  As long as the reflog entry for commit A1 has not yet expired, Git will discover that A1 used to be on earlier-branch and will use --onto for us to discard it from the to-copy list.

Note that there is a bit of danger here.  What if we really wanted A1 after all, e.g., what if we backed earlier-branch up over A1 only because we realized A1 did not belong on the other branch?  Git will still think we copied it to some other commit, and don't want it copied now, and will toss off the list.  Fortunately, you can always undo a rebase: rebase doesn't discard anything at all, it just copies.  It then updates a branch, which saves the previous value in the branch's reflog.  But fishing around through reflogs, trying to find one particular set of commits, in a twisty maze of commits that are all alike, is not a lot of fun—so it is wise to think a bit before running rebase, with or without --fork-point.

Side note

In a few (rare) cases Git you don't have to do anything (no fork point mode, no manual --onto separation, no --interactive).  Specifically, if the patch itself did not change at all, but only the wording in the commit message changed, Git will detect the already-copied commit and skip it.  This happens because git rebase actually uses the symmetric difference mode of git rev-list with the --cherry-pick --right-only --no-merges options.  That is, rather than:

git rev-list <upstream>..HEAD

Git actually runs:

git rev-list --cherry-pick --right-only --no-merges <upstream>...HEAD

(note the three dots).  I don't have time to go into any more detail here, though.


问:
Django Image Upload Form not valid
For some reason in django the form that I am trying to use is not considered valid. This code is taken almost directly from a site that claims that it works but is still not functional.
my code is as follows.

VIEWS

```<code>def display_update_image(request, pk):
if request.method == 'POST':
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        display = Display.objects.get(pk = pk)
        display.image = form.cleaned_data['image']
        display.save()
    return HttpResponseRedirect(reverse('displays'))
else :
    form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})
</code>```

TEMPLATE (template name is update_display_image.html)

```<code><form method = "post" enctype = "multipart/form-data">{% csrf_token %}
<p>
    <input id = "id" type = "file" class = "" name = "image">
</p>
<input type = "submit" value = "Submit" />
</code>```

MODELS

```<code>class Display(models.Model):
    title = models.CharField(max_length = 50,)
    image = models.ImageField(upload_to = 'images')
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

    def __str__(self):
        return self.title
</code>```

edit: forget to post Forms code sorry

```<code>class ImageForm(forms.Form):
    image = forms.ImageField()
</code>```

further edit: changing my forms class to this

```<code>class ImageForm(forms.Form):
    class Meta:
        model = Display
        fields = ('image',)
</code>```

Allows the form to be read as valid for some reason though I don't understand why. Unfortunately that causes my views method to be unable to function properly as it can no longer read

```<code>display.image = form.cleaned_data['image']
</code>```

答:
In forms.py check that you have a Django Form like this one:

```<code>class ImageForm(forms.ModelForm):
    class Meta:
        model = Display
        fields = ['image',]
</code>```

In template add {{ form }} instead of manually using input, like this one:

```<code><form method='post' enctype='multipart-formdata>
{% csrf_token %}
{{ form }}
<input type='submit' value='Update Image'>
</code>```

Title: Django Image Upload Form not valid

Body:
For some reason in django the form that I am trying to use is not considered valid. This code is taken almost directly from a site that claims that it works but is still not functional.
my code is as follows.

VIEWS

def display_update_image(request, pk):
if request.method == 'POST':
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        display = Display.objects.get(pk = pk)
        display.image = form.cleaned_data['image']
        display.save()
    return HttpResponseRedirect(reverse('displays'))
else :
    form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})

TEMPLATE (template name is update_display_image.html)

<form method = "post" enctype = "multipart/form-data">{% csrf_token %}

    <input id = "id" type = "file" class = "" name = "image">

<input type = "submit" value = "Submit" />

MODELS

class Display(models.Model):
    title = models.CharField(max_length = 50,)
    image = models.ImageField(upload_to = 'images')
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

    def __str__(self):
        return self.title

edit: forget to post Forms code sorry

class ImageForm(forms.Form):
    image = forms.ImageField()

further edit: changing my forms class to this

class ImageForm(forms.Form):
    class Meta:
        model = Display
        fields = ('image',)

Allows the form to be read as valid for some reason though I don't understand why. Unfortunately that causes my views method to be unable to function properly as it can no longer read

display.image = form.cleaned_data['image']

Body:
In forms.py check that you have a Django Form like this one:

class ImageForm(forms.ModelForm):
    class Meta:
        model = Display
        fields = ['image',]

In template add {{ form }} instead of manually using input, like this one:

<form method='post' enctype='multipart-formdata>
{% csrf_token %}
{{ form }}
<input type='submit' value='Update Image'>


问:
Unity problems with port to android
Can somebody help mi solve these problems
List of erros:

UnityException: Build failure!
Unable to locate Android SDK.
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, UnityEditor.Android.CommandInvokationFailure ex)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSdk.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessAndroidPlayer.PrepareForBuild (BuildOptions options, BuildTarget target)
UnityEditor.Android.AndroidBuildPostprocessor.PrepareForBuild (BuildOptions options, BuildTarget target)
UnityEditor.PostprocessBuildPlayer.PrepareForBuild (BuildOptions options, BuildTargetGroup targetGroup, BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:97)
UnityEditor.HostView:OnGUI()

CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
C:/Program Files/Java/jdk1.8.0_131\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/karik/AppData/Local/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "D:\1.Programy\5.Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

Error building Player: CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
C:/Program Files/Java/jdk1.8.0_131\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/karik/AppData/Local/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "D:\1.Programy\5.Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64

SDK path: C:\Users\karik\AppData\Local\Android\sdk
JDK path: C:\Program Files\Java\jdk1.8.0_131

答:
Okay so the issue seems to be that the SDK updates deprecated a command line tool that Unity's build process uses. This was evident from the forum post Here

Rename your tools folder in the SDK to some arbitrary name.

Download the downgraded tools and extract them to the SDK root folder.

See if your issue is resolved!

If that does not work, try downgrading to the next lower version of SDK tools from the SDK manager.

Title: Unity problems with port to android


答:
You can use str.contains and pass a regex pattern:

```<code>In[112]:
df.loc[df['a'].str.contains(r'^r\d{5}')]

Out[112]:
        a  b
1  r00001  1
2  r00010  2
4  r01234  4
</code>```

Here the pattern evaluates to ^r - start with character r, and then \d{5} looks for 5 digits

startswith looks for a character pattern, not a regex pattern which is why it fails

Regarding the difference between str.contains and str.match, they are analagous but str.contains uses re.search whilst str.match uses re.match which is more strict, see the docs.

edit

To answer your comment add $ so that it matches a specific number of characters, see related:

```<code>In[117]:
df = pd.DataFrame({'a': ['abc', 'r000010', 'r00010', 'rfoo', 'r01234', 'r1234'], 'b': range(6)})
df

Out[117]:
         a  b
0      abc  0
1  r000010  1
2   r00010  2
3     rfoo  3
4   r01234  4
5    r1234  5

In[118]:
df.loc[df['a'].str.match(r'r\d{5}$')]

Out[118]:
        a  b
2  r00010  2
4  r01234  4
</code>```

Title: Select data using a regular expression

Body:
I have a dataframe like this

import pandas as pd

df = pd.DataFrame({'a': ['abc', 'r00001', 'r00010', 'rfoo', 'r01234', 'r1234'], 'b': range(6)})

        a  b
0     abc  0
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5

I now want to select all columns of this dataframe where the entries in column a start with r followed by five numbers.

From here I learned how one would do this if it started just with r without the numbers:

print df.loc[df['a'].str.startswith('r'), :]

        a  b
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5

Something like this

print df.loc[df['a'].str.startswith(r'[r]\d{5}'), :]

does of course not work. How would one do this properly?

Body:
You can use str.contains and pass a regex pattern:

In[112]:
df.loc[df['a'].str.contains(r'^r\d{5}')]

Out[112]:
        a  b
1  r00001  1
2  r00010  2
4  r01234  4

Here the pattern evaluates to ^r - start with character r, and then \d{5} looks for 5 digits

startswith looks for a character pattern, not a regex pattern which is why it fails

Regarding the difference between str.contains and str.match, they are analagous but str.contains uses re.search whilst str.match uses re.match which is more strict, see the docs.

edit

To answer your comment add $ so that it matches a specific number of characters, see related:

In[117]:
df = pd.DataFrame({'a': ['abc', 'r000010', 'r00010', 'rfoo', 'r01234', 'r1234'], 'b': range(6)})
df

Out[117]:
         a  b
0      abc  0
1  r000010  1
2   r00010  2
3     rfoo  3
4   r01234  4
5    r1234  5

In[118]:
df.loc[df['a'].str.match(r'r\d{5}$')]

Out[118]:
        a  b
2  r00010  2
4  r01234  4


问:
Iterate webpages through selenium python to get position of search result
I am searching a generic keyword and finding my products rank on an an e-commerce site. Here is my code for that which works successfully.

```<code>from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://web.com/searchall?b=1&kw=printer')
items = driver.find_elements_by_class_name('productResult')
for i, item in enumerate( items ):
if 'EPSON' in item.text:
print( i )
</code>```

This only fetches rank on first page but now I want to go to every page and fetch the rank of my product. I know I have to use a loop which is somewhat like this:

```<code>while True:
try: driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
except:
break
</code>```

I am finding difficulty in exact placement of the loop. Please help me with the syntax. I am a newbie.

答:
Try below code:

```<code>from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://shop.techdata.com/searchall?b=1&kw=printer')

items_count = 0

while True:
    items = driver.find_elements_by_class_name('productResult')
    for i, item in enumerate( items ):
        if 'EPSON' in item.text:
            print(items_count + i)
    items_count += len(items)
    try:
        driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
    except:
        break
</code>```

This should allow you to integrate your second part into first one with correct indentation

Body:
I am searching a generic keyword and finding my products rank on an an e-commerce site. Here is my code for that which works successfully.

from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://web.com/searchall?b=1&kw=printer')
items = driver.find_elements_by_class_name('productResult')
for i, item in enumerate( items ):
if 'EPSON' in item.text:
print( i )

This only fetches rank on first page but now I want to go to every page and fetch the rank of my product. I know I have to use a loop which is somewhat like this:

while True:
try: driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
except:
break

I am finding difficulty in exact placement of the loop. Please help me with the syntax. I am a newbie.

Body:
Try below code:

from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://shop.techdata.com/searchall?b=1&kw=printer')

items_count = 0

while True:
    items = driver.find_elements_by_class_name('productResult')
    for i, item in enumerate( items ):
        if 'EPSON' in item.text:
            print(items_count + i)
    items_count += len(items)
    try:
        driver.find_element_by_xpath('//div[@class="pageNavigation nextPage"]/a').click()
    except:
        break

This should allow you to integrate your second part into first one with correct indentation


问:
django.db.utils.IntegrityError: NOT NULL constraint failed
i'm trying to build a customised registration to my site, so i'm using a sign Up with Profile Model.

Traceback:

```<code>Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line
 41, in inner
 response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187,
 in _get_response
 response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185,
 in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\dev1\mysite\mysite\core\views.py", line 74, in
 complete_profile
 form.save()
File "C:\Python36\lib\site-packages\django\forms\models.py", line 451, in
 save
 self.instance.save()
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 806, in
 save
force_update=force_update, update_fields=update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 836, in
 save_base
 updated = self._save_table(raw, cls, force_insert, force_update, using,
 update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 922, in
 _save_table
 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 961, in
 _do_insert
 using=using, raw=raw)
File "C:\Python36\lib\site-packages\django\db\models\manager.py", line 85,
 in manager_method
 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python36\lib\site-packages\django\db\models\query.py", line 1060,
 in _insert
 return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py", line
 1099, in execute_sql
 cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 80,
 in execute
 return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\utils.py", line 94, in
 __exit__
 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python36\lib\site-packages\django\utils\six.py", line 685, in
 reraise
 raise value.with_traceback(tb)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py",
 line 328, in execute
 return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed:
core_profile.user_id
</code>```

i'm having this ERROR after submit a form that i made to let user complete profile information just after SignUp's email confirmation.
Look at this diagram

some of my code:

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  birth_date = models.DateField(null=True, blank=True)
  birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de
    Naissance"))
  email_confirmed = models.BooleanField(default=False)
  adress = models.CharField(max_length=80, verbose_name=("Adresse"))
  adress_complement = models.CharField(max_length=80, verbose_name=
    ("Complément d'Adresse"))
  city = models.CharField(max_length=80, verbose_name=("Ville"))
  zip_code = models.IntegerField(null=True, blank=True)
  drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du
     Permis de conduire"))
  social_secu_num = models.IntegerField(null=True, blank=True)
  phone_number = models.IntegerField(null=True, blank=True)

  @receiver(post_save, sender=User)
  def update_user_profile(sender, instance, created, **kwargs):
     if created:
     Profile.objects.create(user=instance)
     instance.profile.save()
</code>```

forms.py

```<code>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import Profile

class SignUpForm(UserCreationForm):
  email = forms.EmailField(max_length=254, help_text='Required. Inform a
          valid email address.')
  class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'username', 'password1',
                'password2',)

class ProfileForm(forms.ModelForm):
  class Meta:
    model = Profile
    fields = ('birth_date','birth_place', 'adress', 'adress_complement',
              'city', 'zip_code', 'drive_licence_num', 'social_secu_num',
              'phone_number')
</code>```

views.py (complete_profile view)

```<code>def complete_profile(request):
  #if email_confirmed == True:
  if request.user.is_authenticated():
      if request.method == 'POST':

          form = ProfileForm(request.POST)
          if form.is_valid():
              form.save()

              return render(request, 'home.html')
      else:
          form = ProfileForm()
          return render(request, 'complete_profile.html', {'form': form})
  else:
      return render(request, 'login.html')
</code>```

答:
```<code>form = ProfileForm(request.POST,instance=request.user.profile)
          if form.is_valid():
              form.save()
</code>```

try this

Body:
i'm trying to build a customised registration to my site, so i'm using a sign Up with Profile Model.

Traceback:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line
 41, in inner
 response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187,
 in _get_response
 response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185,
 in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\dev1\mysite\mysite\core\views.py", line 74, in
 complete_profile
 form.save()
File "C:\Python36\lib\site-packages\django\forms\models.py", line 451, in
 save
 self.instance.save()
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 806, in
 save
force_update=force_update, update_fields=update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 836, in
 save_base
 updated = self._save_table(raw, cls, force_insert, force_update, using,
 update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 922, in
 _save_table
 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 961, in
 _do_insert
 using=using, raw=raw)
File "C:\Python36\lib\site-packages\django\db\models\manager.py", line 85,
 in manager_method
 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python36\lib\site-packages\django\db\models\query.py", line 1060,
 in _insert
 return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py", line
 1099, in execute_sql
 cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 80,
 in execute
 return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\utils.py", line 94, in
 __exit__
 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python36\lib\site-packages\django\utils\six.py", line 685, in
 reraise
 raise value.with_traceback(tb)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65,
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py",
 line 328, in execute
 return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed:
core_profile.user_id

i'm having this ERROR after submit a form that i made to let user complete profile information just after SignUp's email confirmation.
Look at this diagram

some of my code:

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  birth_date = models.DateField(null=True, blank=True)
  birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de
    Naissance"))
  email_confirmed = models.BooleanField(default=False)
  adress = models.CharField(max_length=80, verbose_name=("Adresse"))
  adress_complement = models.CharField(max_length=80, verbose_name=
    ("Complément d'Adresse"))
  city = models.CharField(max_length=80, verbose_name=("Ville"))
  zip_code = models.IntegerField(null=True, blank=True)
  drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du
     Permis de conduire"))
  social_secu_num = models.IntegerField(null=True, blank=True)
  phone_number = models.IntegerField(null=True, blank=True)

  @receiver(post_save, sender=User)
  def update_user_profile(sender, instance, created, **kwargs):
     if created:
     Profile.objects.create(user=instance)
     instance.profile.save()

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import Profile

class SignUpForm(UserCreationForm):
  email = forms.EmailField(max_length=254, help_text='Required. Inform a
          valid email address.')
  class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'username', 'password1',
                'password2',)

class ProfileForm(forms.ModelForm):
  class Meta:
    model = Profile
    fields = ('birth_date','birth_place', 'adress', 'adress_complement',
              'city', 'zip_code', 'drive_licence_num', 'social_secu_num',
              'phone_number')

views.py (complete_profile view)

def complete_profile(request):
  #if email_confirmed == True:
  if request.user.is_authenticated():
      if request.method == 'POST':

          form = ProfileForm(request.POST)
          if form.is_valid():
              form.save()

              return render(request, 'home.html')
      else:
          form = ProfileForm()
          return render(request, 'complete_profile.html', {'form': form})
  else:
      return render(request, 'login.html')

Body:
form = ProfileForm(request.POST,instance=request.user.profile)
          if form.is_valid():
              form.save()

try this


问:
Django HMAC Registration with Unique Email
Is it possible to use RegistrationFormUniqueEmail with the HMAC activation workflow?

My urls.py looks like this:

```<code>from django.conf.urls import url, include
from app.registration import RegistrationViewUniqueEmail

urlpatterns = [
    url(r'^accounts/register/$', RegistrationViewUniqueEmail.as_view(), name='registration_register'),
    url(r'^accounts/', include('registration.backends.hmac.urls')),
]
</code>```

I have a file app/registration.py

```<code>from registration.backends.hmac.views import RegistrationView
from registration.forms import RegistrationFormUniqueEmail

class RegistrationViewUniqueEmail(RegistrationView):
    form_class = RegistrationFormUniqueEmail
</code>```

I am able to complete registration i.e. the user is created in the auth_user table and I am unable to create more than one user with the same email address as expected, but I believe it is failing when the authentication email is being sent.

```<code>SMTPAuthenticationError at /accounts/register/
(535, b'5.7.8 Error: authentication failed: UGFzc3dvcmQ6')
</code>```

Does anyone know what's going wrong here?

答:
(original answer here by seddonym)

The only thing to do is replace

```<code>from registration.backends.default.views import RegistrationView
</code>```

with

```<code>from registration.backends.hmac.views import RegistrationView
</code>```

Body:
Is it possible to use RegistrationFormUniqueEmail with the HMAC activation workflow?

My urls.py looks like this:

from django.conf.urls import url, include
from app.registration import RegistrationViewUniqueEmail

urlpatterns = [
    url(r'^accounts/register/$', RegistrationViewUniqueEmail.as_view(), name='registration_register'),
    url(r'^accounts/', include('registration.backends.hmac.urls')),
]

I have a file app/registration.py

from registration.backends.hmac.views import RegistrationView
from registration.forms import RegistrationFormUniqueEmail

class RegistrationViewUniqueEmail(RegistrationView):
    form_class = RegistrationFormUniqueEmail

I am able to complete registration i.e. the user is created in the auth_user table and I am unable to create more than one user with the same email address as expected, but I believe it is failing when the authentication email is being sent.

SMTPAuthenticationError at /accounts/register/
(535, b'5.7.8 Error: authentication failed: UGFzc3dvcmQ6')

Does anyone know what's going wrong here?

Body:
(original answer here by seddonym)

The only thing to do is replace

from registration.backends.default.views import RegistrationView

with

from registration.backends.hmac.views import RegistrationView


问:
Given a file, find the ten most frequently occurring words as efficiently as possible
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.

答:
Says building a Hash and sorting the values is best. I'm inclined to agree.
http://www.allinterview.com/showanswers/56657.html

Here is a Bash implementation that does something similar...I think
http://www.commandlinefu.com/commands/view/5994/computes-the-most-frequent-used-words-of-a-text-file