问:
SQLiteException failed to insert row
What are the possible reasons for a failed insertion into an sqlite3 database? The trace from the SQLiteException isn't especially helpful.

Is there any way to obtain better information about what caused the exception?

Where the table is created (sorry for any wonky spacing):

http://pastebin.com/QqUgdDz0

Where the values are parsed in endElement of a SAX parser:

http://pastebin.com/iN1M8QMe

Where the insert is called:

http://pastebin.com/xUqrmexw

Insert case in the provider:

```<code>case SUBMATERIAL_SINGLE_URI:
            rowId = db.insert(jobName+JobMetaData.SubmaterialTableMetaData.TABLE_NAME_SUFFIX,
                              JobMetaData.SubmaterialTableMetaData.TYPE, validValues);
            if (rowId > 0)
            {
                Uri submaterialUri = ContentUris.withAppendedId(JobMetaData.SubmaterialTableMetaData.CONTENT_URI,
                        rowId);
                getContext().getContentResolver().notifyChange(submaterialUri, null);
                return submaterialUri;
            }
            break;
</code>```

Stacktrace:

```<code>System.err( 8048): android.database.SQLException: Failed to insert row into content://dsndata.sds2mobile.jobprovider/C_1/submaterial/NULL
System.err( 8048):  at dsndata.sds2mobile.JobProvider.insert(JobProvider.java:341)
System.err( 8048):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:180)
System.err( 8048):  at android.content.ContentResolver.insert(ContentResolver.java:587)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.endElement(MobileParser.java:227)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.endElement(XMLReaderAdapter.java:355)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.endElement(ExpatParser.java:160)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.append(Native Method)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:505)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:492)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:308)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:264)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.parse(XMLReaderAdapter.java:225)
System.err( 8048):  at javax.xml.parsers.SAXParser.parse(SAXParser.java:361)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.parse(MobileParser.java:120)
System.err( 8048):  at dsndata.sds2mobile.UI.onClick(UI.java:90)
System.err( 8048):  at android.view.View.performClick(View.java:2408)
System.err( 8048):  at android.view.View$PerformClick.run(View.java:8817)
System.err( 8048):  at android.os.Handler.handleCallback(Handler.java:587)
System.err( 8048):  at android.os.Handler.dispatchMessage(Handler.java:92)
System.err( 8048):  at android.os.Looper.loop(Looper.java:144)
System.err( 8048):  at android.app.ActivityThread.main(ActivityThread.java:4937)
System.err( 8048):  at java.lang.reflect.Method.invokeNative(Native Method)
System.err( 8048):  at java.lang.reflect.Method.invoke(Method.java:521)
System.err( 8048):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
System.err( 8048):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
System.err( 8048):  at dalvik.system.NativeStart.main(Native Method)
</code>```

I should note that NULL in the URI here is a string value and is acceptable according to the URI matching scheme. This is a test run and isn't using real values yet.

Update:
It turns out that my partner (who was producing the XML) left out a few items. Got it all figured out.

Thanks for your help! I appreciate the time.

答:
A few:

Out of space in storage being used by SQLite db

No permission to use sdcard and using an sdcard backed db

Requesting to insert a row on a read only copy of a database

There could be many more.

Title: SQLiteException failed to insert row

Body:
What are the possible reasons for a failed insertion into an sqlite3 database? The trace from the SQLiteException isn't especially helpful.

Is there any way to obtain better information about what caused the exception?

Where the table is created (sorry for any wonky spacing):

http://pastebin.com/QqUgdDz0

Where the values are parsed in endElement of a SAX parser:

http://pastebin.com/iN1M8QMe

Where the insert is called:

http://pastebin.com/xUqrmexw

Insert case in the provider:

case SUBMATERIAL_SINGLE_URI:
            rowId = db.insert(jobName+JobMetaData.SubmaterialTableMetaData.TABLE_NAME_SUFFIX,
                              JobMetaData.SubmaterialTableMetaData.TYPE, validValues);
            if (rowId > 0)
            {
                Uri submaterialUri = ContentUris.withAppendedId(JobMetaData.SubmaterialTableMetaData.CONTENT_URI,
                        rowId);
                getContext().getContentResolver().notifyChange(submaterialUri, null);
                return submaterialUri;
            }
            break;

Stacktrace:

System.err( 8048): android.database.SQLException: Failed to insert row into content://dsndata.sds2mobile.jobprovider/C_1/submaterial/NULL
System.err( 8048):  at dsndata.sds2mobile.JobProvider.insert(JobProvider.java:341)
System.err( 8048):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:180)
System.err( 8048):  at android.content.ContentResolver.insert(ContentResolver.java:587)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.endElement(MobileParser.java:227)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.endElement(XMLReaderAdapter.java:355)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.endElement(ExpatParser.java:160)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.append(Native Method)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:505)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:492)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:308)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:264)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.parse(XMLReaderAdapter.java:225)
System.err( 8048):  at javax.xml.parsers.SAXParser.parse(SAXParser.java:361)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.parse(MobileParser.java:120)
System.err( 8048):  at dsndata.sds2mobile.UI.onClick(UI.java:90)
System.err( 8048):  at android.view.View.performClick(View.java:2408)
System.err( 8048):  at android.view.View$PerformClick.run(View.java:8817)
System.err( 8048):  at android.os.Handler.handleCallback(Handler.java:587)
System.err( 8048):  at android.os.Handler.dispatchMessage(Handler.java:92)
System.err( 8048):  at android.os.Looper.loop(Looper.java:144)
System.err( 8048):  at android.app.ActivityThread.main(ActivityThread.java:4937)
System.err( 8048):  at java.lang.reflect.Method.invokeNative(Native Method)
System.err( 8048):  at java.lang.reflect.Method.invoke(Method.java:521)
System.err( 8048):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
System.err( 8048):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
System.err( 8048):  at dalvik.system.NativeStart.main(Native Method)

I should note that NULL in the URI here is a string value and is acceptable according to the URI matching scheme. This is a test run and isn't using real values yet.

Update:
It turns out that my partner (who was producing the XML) left out a few items. Got it all figured out.

Thanks for your help! I appreciate the time.


来源: stackexchange

问:
RestTemplate GET request with custom headers and parameters resulted in 400 (null)
I am writing a client for my REST service using Spring. When I try to consume the service I get 400 response error. It's Bad Request so there must be something wrong with my headers or parameters but I can't figure out what in particular.

My REST controller method:

```<code>@RequestMapping(value = "/menu/{count}", method = RequestMethod.GET)
    public String showMenu(@RequestHeader(required = false) String locale, @RequestParam boolean includeVegan,
                           @RequestParam boolean includeMeat, @RequestParam boolean includeGlutenFree,
                           @PathVariable(value = "count") int count) {

        List<Meal> filteredMeals = new ArrayList<>();

        if (count == 0) count = menuService.getMeals().size();

        // Tworzenie przefiltrowanego menu.
        for (Meal meal : menuService.getMeals()) {
            if (count <= 0) break;
            if (meal.isVegan() && includeVegan) filteredMeals.add(meal);
            if (!meal.isVegan() && includeMeat) filteredMeals.add(meal);
            if (meal.isGlutenFree() && includeGlutenFree) filteredMeals.add(meal);
            count--;
        }

        // Tworzenie nazw pozycji posiłków w wybranym języku.
        List<String> menu = new ArrayList<>();
        for (Meal meal : filteredMeals) {
            if (locale == null) {
                // BOTH LANGUAGES
                menu.add(meal.toString(true));
                menu.add(meal.toString(false));
            } else if (locale.equals("pl-PL")) {
                // POLISH LANG
                menu.add(meal.toString(true));
            } else if (locale.equals("en-US")) {
                // ENGLISH LANG
                menu.add(meal.toString(false));
            }
        }

        return menu.toString();
    }
</code>```

Client fetch method:

```<code>private void fetchMenu() {

        String locale = languageComboBox.getSelectedItem().toString();
        boolean includeVegan = includeVeganCheckBox.isSelected();
        boolean includeMeat = includeMeatCheckBox.isSelected();
        boolean includeGlutenFree = includeGlutenFreeCheckBox.isSelected();
        int limit = (int) limitSpinner.getValue();

        System.out.println("DEBUG: locale: " + locale + ", vegan " + includeVegan + ", meat: " + includeMeat +
                ", glutenFree: " + includeGlutenFree + ", limit: " + limit);

        HttpHeaders headers = new HttpHeaders();
        headers.add("locale", locale);

        HttpEntity entity = new HttpEntity(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("includeVegan", includeVegan);
        parameters.put("includeMeat", includeMeat);
        parameters.put("includeGlutenFree", includeGlutenFree);

        RestTemplate template = new RestTemplate();
        ResponseEntity<String> response = template.exchange(
                "http://localhost:8080/menu/" + limit,
                HttpMethod.GET,
                entity,
                String.class,
                parameters
        );

        menu.setText(response.getBody());
    }
</code>```

Console when calling fetchMenu()

```<code>DEBUG: locale: pl-PL, vegan false, meat: true, glutenFree: false, limit: 0
16:57:37.082 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://localhost:8080/menu/0"
16:57:37.082 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
16:57:37.097 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/menu/0" resulted in 400 (null); invoking error handler
Exception in thread "AWT-EventQueue-0" org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:540)
    at ait.lab3.SwingClient.fetchMenu(SwingClient.java:101)
    at ait.lab3.SwingClient.access$000(SwingClient.java:16)
    at ait.lab3.SwingClient$5.actionPerformed(SwingClient.java:65)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:308)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Service method response is String as you can see. This is for my college classes so I need to use @RequestHeader and @PathVariable. I think something might be wrong with my headers/parameters or with path variable count which in fetchMenu() method is represented as limit.

I have no idea what might be wrong with my code. Please developers, help ;)

答:
Please make the following change in the fetchMenu() method.</p>
```<code>ResponseEntity<String> response = template.exchange(
                    "http://localhost:8080/menu/" + limit +"?includeVegan={includeVegan}&includeMeat={includeMeat}&includeGlutenFree={includeGlutenFree}",
                    HttpMethod.GET,
                    entity,
                    String.class,
                    parameters
            );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a client for my REST service using Spring. When I try to consume the service I get 400 response error. It's Bad Request so there must be something wrong with my headers or parameters but I can't figure out what in particular.

My REST controller method:

@RequestMapping(value = "/menu/{count}", method = RequestMethod.GET)
    public String showMenu(@RequestHeader(required = false) String locale, @RequestParam boolean includeVegan,
                           @RequestParam boolean includeMeat, @RequestParam boolean includeGlutenFree,
                           @PathVariable(value = "count") int count) {

        List<Meal> filteredMeals = new ArrayList<>();

        if (count == 0) count = menuService.getMeals().size();

        // Tworzenie przefiltrowanego menu.
        for (Meal meal : menuService.getMeals()) {
            if (count <= 0) break;
            if (meal.isVegan() && includeVegan) filteredMeals.add(meal);
            if (!meal.isVegan() && includeMeat) filteredMeals.add(meal);
            if (meal.isGlutenFree() && includeGlutenFree) filteredMeals.add(meal);
            count--;
        }

        // Tworzenie nazw pozycji posiłków w wybranym języku.
        List<String> menu = new ArrayList<>();
        for (Meal meal : filteredMeals) {
            if (locale == null) {
                // BOTH LANGUAGES
                menu.add(meal.toString(true));
                menu.add(meal.toString(false));
            } else if (locale.equals("pl-PL")) {
                // POLISH LANG
                menu.add(meal.toString(true));
            } else if (locale.equals("en-US")) {
                // ENGLISH LANG
                menu.add(meal.toString(false));
            }
        }

        return menu.toString();
    }

Client fetch method:

private void fetchMenu() {

        String locale = languageComboBox.getSelectedItem().toString();
        boolean includeVegan = includeVeganCheckBox.isSelected();
        boolean includeMeat = includeMeatCheckBox.isSelected();
        boolean includeGlutenFree = includeGlutenFreeCheckBox.isSelected();
        int limit = (int) limitSpinner.getValue();

        System.out.println("DEBUG: locale: " + locale + ", vegan " + includeVegan + ", meat: " + includeMeat +
                ", glutenFree: " + includeGlutenFree + ", limit: " + limit);

        HttpHeaders headers = new HttpHeaders();
        headers.add("locale", locale);

        HttpEntity entity = new HttpEntity(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("includeVegan", includeVegan);
        parameters.put("includeMeat", includeMeat);
        parameters.put("includeGlutenFree", includeGlutenFree);

        RestTemplate template = new RestTemplate();
        ResponseEntity<String> response = template.exchange(
                "http://localhost:8080/menu/" + limit,
                HttpMethod.GET,
                entity,
                String.class,
                parameters
        );

        menu.setText(response.getBody());
    }

Console when calling fetchMenu()

DEBUG: locale: pl-PL, vegan false, meat: true, glutenFree: false, limit: 0
16:57:37.082 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://localhost:8080/menu/0"
16:57:37.082 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
16:57:37.097 [AWT-EventQueue-0] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/menu/0" resulted in 400 (null); invoking error handler
Exception in thread "AWT-EventQueue-0" org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:540)
    at ait.lab3.SwingClient.fetchMenu(SwingClient.java:101)
    at ait.lab3.SwingClient.access$000(SwingClient.java:16)
    at ait.lab3.SwingClient$5.actionPerformed(SwingClient.java:65)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:308)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Service method response is String as you can see. This is for my college classes so I need to use @RequestHeader and @PathVariable. I think something might be wrong with my headers/parameters or with path variable count which in fetchMenu() method is represented as limit.

I have no idea what might be wrong with my code. Please developers, help ;)

Body:
Please make the following change in the fetchMenu() method.

ResponseEntity<String> response = template.exchange(
                    "http://localhost:8080/menu/" + limit +"?includeVegan={includeVegan}&includeMeat={includeMeat}&includeGlutenFree={includeGlutenFree}",
                    HttpMethod.GET,
                    entity,
                    String.class,
                    parameters
            );

ContentLicense: CC BY-SA 4.0


问:
NPM Best Practices for Continuous Integration
I am building a HTML5 front-end using NPM-based tools (grunt).

One of the first steps of my continuous integration build process is to run an npm install.

npm install is SLOW. Even with a local NPM proxy caching artifacts (Sonatype's Nexus 3), it is still taking 4 minutes!

```<code>$> time npm install
real    4m17.427s
user    0m0.170s
sys     0m0.290s
</code>```

If I follow my usual best practices for continuous integration, I would start from a pristine SCM repository and run the build. This means that each time the CI build will have to do a fresh npm install and take on the cost of 4 minutes.

This is a significant proportion of my build time. I am discontent that the build is taking so long.

The alternative seems to be to keep the node_modules around between builds. However, I've had problems with the build becoming unstable as a result.

Removing dependencies from package.json does not remove them from node_modules with a simple npm install. I can work-around this with an npm prune first.

What is considered to be best practice here?

答: You should install npm packages offline in local machine or local network, you can found some tips here => Offline installation of npm packages

Body:
I am building a HTML5 front-end using NPM-based tools (grunt).

One of the first steps of my continuous integration build process is to run an npm install.

npm install is SLOW. Even with a local NPM proxy caching artifacts (Sonatype's Nexus 3), it is still taking 4 minutes!

$> time npm install
real    4m17.427s
user    0m0.170s
sys     0m0.290s

If I follow my usual best practices for continuous integration, I would start from a pristine SCM repository and run the build. This means that each time the CI build will have to do a fresh npm install and take on the cost of 4 minutes.

This is a significant proportion of my build time. I am discontent that the build is taking so long.

The alternative seems to be to keep the node_modules around between builds. However, I've had problems with the build becoming unstable as a result.

Removing dependencies from package.json does not remove them from node_modules with a simple npm install. I can work-around this with an npm prune first.

What is considered to be best practice here?


问:
Convert a numpy array to generate a image
I have a tensorflow prediction results which is of type tuple.

```<code>np_pred_boxes == (1024, 1, 4)
np_pred_boxes == <type 'tuple'>
</code>```

Now, I want to convert this array into to a image object.I use np.asarray to convert the tensorflow predicted box of type tuple to numpy array but get the below error.

```<code>np_pred_boxes = np.asarray(np_pred_boxes)
print 'type == ', type(np_pred_boxes)
img = Image.fromarray(np.asarray(np_pred_boxes))
img.save('/Users/prem/Downloads/tf_image.png')
</code>```

Error:-

```<code>  File "/Users/em/Documents//crop_image.py", line 91, in <module>
    img = Image.fromarray(np.asarray(np_pred_boxes))
  File "/usr/local/lib/python2.7/site-packages/PIL/Image.py", line 2361, in fromarray
    raise TypeError("Cannot handle this data type")
</code>```

答:
Take a look at the modes supported by Pillow.  The only floating point mode is for grayscale images (mode 'F').  You'll have to either convert your array to 8-bit integers, or give the mode argument to fromarray and let Pillow do the conversion to 8-bit integers for you.  For example,

```<code>img = Image.fromarray(np_pred_boxes, mode='RGBA')
</code>```

Be sure to verify that that does what you want.  You could check by converting img back to an array and inspecting the 8-bit values.  E.g.

```<code>a = np.array(img)
print(a)
</code>```

Body:
I have a tensorflow prediction results which is of type tuple.

np_pred_boxes == (1024, 1, 4)
np_pred_boxes == <type 'tuple'>

Now, I want to convert this array into to a image object.I use np.asarray to convert the tensorflow predicted box of type tuple to numpy array but get the below error.

np_pred_boxes = np.asarray(np_pred_boxes)
print 'type == ', type(np_pred_boxes)
img = Image.fromarray(np.asarray(np_pred_boxes))
img.save('/Users/prem/Downloads/tf_image.png')

Error:-

  File "/Users/em/Documents//crop_image.py", line 91, in <module>
    img = Image.fromarray(np.asarray(np_pred_boxes))
  File "/usr/local/lib/python2.7/site-packages/PIL/Image.py", line 2361, in fromarray
    raise TypeError("Cannot handle this data type")

Body:
Take a look at the modes supported by Pillow.  The only floating point mode is for grayscale images (mode 'F').  You'll have to either convert your array to 8-bit integers, or give the mode argument to fromarray and let Pillow do the conversion to 8-bit integers for you.  For example,

img = Image.fromarray(np_pred_boxes, mode='RGBA')

Be sure to verify that that does what you want.  You could check by converting img back to an array and inspecting the 8-bit values.  E.g.

a = np.array(img)
print(a)


问:
Understanding Enums in Java
What are java enums? How do they work? Where could I used them and how?

Can I do without using enums in an app or are they so powerful that Its better to use them than ignore them?

答:
To add some additional information to find out it more, it is better to start with concept of a variable and its values. As I am sure you now, each variable has a declared type (such as Java primitive types). Each type has its own corresponding values. For example a variables with the char type can accept all individual characters as its values. So it is very helpful when you want to declare a variable can accept all set of character constants. For instance all character constants are acceptable and meaningful for aCharToStopProgram variable:

```<code>char aCharToStopProgram = getUserInput();
</code>```

However, what about when you have a limited value, I mean value's domain of your variable is restricted to special values. For example you have userChoice which keeps value of system multiple choice question. So just 'a', 'b', 'c', 'd' is meaningful. You don't want in another section of your program code(or any other reason) this variable is assigned with meaningless values such as 's'. Now is it true to use a char primitive type for our variable which can accept any character constant, such following.

```<code>char userChoice = getUserChoice();
</code>```

In this situations Java provides Enumerated Types. It means via enum keyword you can define a new class that has limited and fixed instances which is call named values(you can not creat new objects). For example:

```<code>enum MultipleChoiceAnswer { A, B, C, D };
</code>```

or

```<code>public enum MultipleChoiceAnswer {

    A('a'), B('b'), C('c'), D('d');

    private char choice;

    private MultipleChoiceAnswer(char choice) {
        this.choice = choice;
    }

    public String getChoice() {
        return choice;
    }
}
</code>```

As result you can define a variable with your own type:

```<code>MultipleChoiceAnswer userChoice = getUserChoice();//OR MultipleChoiceAnswer.A
</code>```

ContentLicense: CC BY-SA 2.5

Title: Understanding Enums in Java

Body:
To add some additional information to find out it more, it is better to start with concept of a variable and its values. As I am sure you now, each variable has a declared type (such as Java primitive types). Each type has its own corresponding values. For example a variables with the char type can accept all individual characters as its values. So it is very helpful when you want to declare a variable can accept all set of character constants. For instance all character constants are acceptable and meaningful for aCharToStopProgram variable:

char aCharToStopProgram = getUserInput();

However, what about when you have a limited value, I mean value's domain of your variable is restricted to special values. For example you have userChoice which keeps value of system multiple choice question. So just 'a', 'b', 'c', 'd' is meaningful. You don't want in another section of your program code(or any other reason) this variable is assigned with meaningless values such as 's'. Now is it true to use a char primitive type for our variable which can accept any character constant, such following.

char userChoice = getUserChoice();

In this situations Java provides Enumerated Types. It means via enum keyword you can define a new class that has limited and fixed instances which is call named values(you can not creat new objects). For example:

enum MultipleChoiceAnswer { A, B, C, D };

or

public enum MultipleChoiceAnswer {

    A('a'), B('b'), C('c'), D('d');

    private char choice;

    private MultipleChoiceAnswer(char choice) {
        this.choice = choice;
    }

    public String getChoice() {
        return choice;
    }
}

As result you can define a variable with your own type:

MultipleChoiceAnswer userChoice = getUserChoice();//OR MultipleChoiceAnswer.A


问:
Join voice channel (discord.py)
When I try to let my bot join my voice channel, I get this error:

await client.join_voice_channel(voice_channel) (line that generates the error)

```<code>Traceback (most recent call last):
   File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
 ret = yield from coro(*args, **kwargs)
 File "bot.py", line 215, in sfx
vc = await client.join_voice_channel(voice_channel)
File "/usr/local/lib/python3.5/site-packages/discord/client.py", line 3176, in join_voice_channel
session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found)
AttributeError: 'NoneType' object has no attribute 'wait_for'
</code>```

The above exception was the direct cause of the following exception:

```<code>Traceback (most recent call last):
 File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 848, in process_commands
yield from command.invoke(ctx)
 File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 369, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
 File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'wait_for'
</code>```

I'm getting this error with channel name and channel ID

Function:

```<code>description = "Bot"
bot_prefix = "!"

client = discord.Client()
bot = commands.Bot(description=description, command_prefix=bot_prefix)

@bot.command(pass_context=True)
async def join(ctx):
   author = ctx.message.author
   voice_channel = author.voice_channel
   vc = await client.join_voice_channel(voice_channel)
</code>```

答:
This is the code i use to make it work.</p>

```<code>#Bot.py
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.voice_client import VoiceClient
import asyncio

bot = commands.Bot(command_prefix="|")

async def on_ready():
    print ("Ready")

@bot.command(pass_context=True)
async def join(ctx):
    author = ctx.message.author
    channel = author.voice_channel
    await bot.join_voice_channel(channel)

bot.run("token")
</code>```

Title: Join voice channel (discord.py)

Body:
When I try to let my bot join my voice channel, I get this error:

await client.join_voice_channel(voice_channel) (line that generates the error)

Traceback (most recent call last):
   File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
 ret = yield from coro(*args, **kwargs)
 File "bot.py", line 215, in sfx
vc = await client.join_voice_channel(voice_channel)
File "/usr/local/lib/python3.5/site-packages/discord/client.py", line 3176, in join_voice_channel
session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found)
AttributeError: 'NoneType' object has no attribute 'wait_for'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 848, in process_commands
yield from command.invoke(ctx)
 File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 369, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
 File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'wait_for'

I'm getting this error with channel name and channel ID

Function:

description = "Bot"
bot_prefix = "!"

client = discord.Client()
bot = commands.Bot(description=description, command_prefix=bot_prefix)

@bot.command(pass_context=True)
async def join(ctx):
   author = ctx.message.author
   voice_channel = author.voice_channel
   vc = await client.join_voice_channel(voice_channel)

Body:
This is the code i use to make it work.

#Bot.py
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.voice_client import VoiceClient
import asyncio

bot = commands.Bot(command_prefix="|")

async def on_ready():
    print ("Ready")

@bot.command(pass_context=True)
async def join(ctx):
    author = ctx.message.author
    channel = author.voice_channel
    await bot.join_voice_channel(channel)

bot.run("token")


问:
Data type size impact on performance
I'm running intensive numerical simulations. I often use long integers, but I realized it would be safe to use integers instead. Would this improve the speed of my simulations significantly?</p>

答:
This is why typedef is your friend. :-)

If mathematically possible, try using floats instead of integers. I read somewhere that floating point arithmetic (esp. multiplication) can actually be faster on some processors.

The best thing is to experiment and benchmark. It's damn near impossible to figure out analytically which micro-optimizations work best.

EDIT: This post discusses the performance difference between integer and float.

Title: Data type size impact on performance


问:
Javascript - Websockets error ERR_NAME_NOT_RESOLVED
I am currently using a raspberry pi (RPI) with LAMP to host my webpage on my local network which uses websocket to stream some data representing the state of an LED. My problem is that, upon trying to establish the websocket connection, I get the following error:

WebSocket connection to 'ws://raspberrypi:8080/' failed: Error in
  connection establishment: net::ERR_NAME_NOT_RESOLVED

I believe my error is just due to incorrect URL but I did not find another example of how to solve this error in my research.

This error occurs when I try to establish a connection on my laptop over LAN. If I go to my browser on my raspberry pi and try to establish the websocket, this error does not occur. So does this mean that perhaps my server (apache2) is getting in the way?

Here is my Javascript file for the client:

```<code>addEventListener('load',init);

function init() {
    console.log('page ready');
    var ws = new WebSocket('ws://raspberrypi:8080/');

    console.log(ws);
}
</code>```

Here is my python script which outputs the data I want to stream:

```<code>from gpiozero import LED
import time
import sys
if __name__ == "__main__":

    led = LED(3);
    while True:
        led.on()
        print 1
        sys.stdout.flush() #flush: print to screen immediately
        time.sleep(1.5)

        led.off()
        print 0
        sys.stdout.flush() #flush: print to screen immediately
        time.sleep(1.5)
</code>```

And here is the terminal feedback from establishing the websocket on the pi:
snapshot

答: Turns out Apache is a http server, and cannot support websockets (without 3rd party software). I have now successfully set up a websocket using Flask-SocketIO.</p>

Body:
I am currently using a raspberry pi (RPI) with LAMP to host my webpage on my local network which uses websocket to stream some data representing the state of an LED. My problem is that, upon trying to establish the websocket connection, I get the following error:

WebSocket connection to 'ws://raspberrypi:8080/' failed: Error in
  connection establishment: net::ERR_NAME_NOT_RESOLVED

I believe my error is just due to incorrect URL but I did not find another example of how to solve this error in my research.

This error occurs when I try to establish a connection on my laptop over LAN. If I go to my browser on my raspberry pi and try to establish the websocket, this error does not occur. So does this mean that perhaps my server (apache2) is getting in the way?

Here is my Javascript file for the client:

addEventListener('load',init);

function init() {
    console.log('page ready');
    var ws = new WebSocket('ws://raspberrypi:8080/');

    console.log(ws);
}

Here is my python script which outputs the data I want to stream:

from gpiozero import LED
import time
import sys
if __name__ == "__main__":

    led = LED(3);
    while True:
        led.on()
        print 1
        sys.stdout.flush() #flush: print to screen immediately
        time.sleep(1.5)

        led.off()
        print 0
        sys.stdout.flush() #flush: print to screen immediately
        time.sleep(1.5)

And here is the terminal feedback from establishing the websocket on the pi:
snapshot


问:
$(this) is looping through everything instead of returning the specific div information?
When I click on the p tag in the first div, it console.logs all of the remaining divs gameIds instead of just logging the one that I have clicked on. I'm not sure what I am doing wrong here, does anyone have any suggestions? </p>

```<code>getGames().done(function(results){
        $.each(results, function (i, gameData){
            $.each(gameData, function(key, game){

                var gamesHome = game.home_team_division;
                var gamesAway = game.away_team_division;

                if(gamesHome == "NCAA Division I" || gamesAway == "NCAA Division I"){
                    // console.log(this);
                    var gameId = game.id;
                    var homeTeam = game.home_team;
                    var awayTeam = game.away_team;
                    var pointTotal = game.total_points_bet;
                    var gameTime = game.game_time_hour;
                    var gameDate = game.game_time_date;
                    var gameId = game.id;
                    var network = game.broadcast_network;
                    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var self = $(this);

                $('.wrapper').append('\
                    <div class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
                    <div class="game-cards">\
                    <div class="chart-container">\
                    <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
                    </div>\
                    <div class="right-info">\
                    <h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\
                    <h5 id="time-channel">'+ gameDate +' @ ' + gameTime  + '<br>' + ' On ' + network +'</h5>\
                    <div class="total-points-live">\
                    <h5>Total Points Bet</h5>\
                    <h5 id="point-total">'+ pointTotal +'</h5>\
                    <p>'+ awayTeam +'</p>\
                    <input class="bet-input" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
                    <p>'+ homeTeam +'</p>\
                    <input class="bet-input" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
                    <p class="bet-button">Click To Place Bet</p>\
                    </div>\
                    </div>\
                    </div>\
                    ');

                $('p').click(function(){
                    var self1 = $(this);
                    console.log(gameId);
                    console.log(self1);

                });
</code>```

答:
First, you need to move your $('p').click out of each block. Currently, you are binding click event multiple times. Second, you have to modify your event handler a little bit, like below.

Also, you need to save gameId, somewhere in p tag so that it can be retrieved later on.

```<code>...
<p gameid="' + gameId + '">'+ awayTeam +'</p>\
<input class="bet-input" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
<p gameid="' + gameId + '">'+ homeTeam +'</p>\
...
...
$('.wrapper').on('click', 'p', function() {
    var self = $(this);
    var gameId = self.attr('gameid');
    console.log(gameId);
});
</code>```

Body:
When I click on the p tag in the first div, it console.logs all of the remaining divs gameIds instead of just logging the one that I have clicked on. I'm not sure what I am doing wrong here, does anyone have any suggestions?

getGames().done(function(results){
        $.each(results, function (i, gameData){
            $.each(gameData, function(key, game){

                var gamesHome = game.home_team_division;
                var gamesAway = game.away_team_division;

                if(gamesHome == "NCAA Division I" || gamesAway == "NCAA Division I"){
                    // console.log(this);
                    var gameId = game.id;
                    var homeTeam = game.home_team;
                    var awayTeam = game.away_team;
                    var pointTotal = game.total_points_bet;
                    var gameTime = game.game_time_hour;
                    var gameDate = game.game_time_date;
                    var gameId = game.id;
                    var network = game.broadcast_network;
                    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var self = $(this);

                $('.wrapper').append('\

\

\

\
                    <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\

\

\

' + awayTeam + '
' + " @ " + '
' + homeTeam +'
\

'+ gameDate +' @ ' + gameTime  + '
' + ' On ' + network +'
\

\

Total Points Bet
\

'+ pointTotal +'
\

'+ awayTeam +'
\
                    <input class="bet-input" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\

'+ homeTeam +'
\
                    <input class="bet-input" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\

Click To Place Bet
\

\

\

\
                    ');

                $('p').click(function(){
                    var self1 = $(this);
                    console.log(gameId);
                    console.log(self1);

                });

Body:
First, you need to move your $('p').click out of each block. Currently, you are binding click event multiple times. Second, you have to modify your event handler a little bit, like below.

Also, you need to save gameId, somewhere in p tag so that it can be retrieved later on.

...
<p gameid="' + gameId + '">'+ awayTeam +'</p>\
<input class="bet-input" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
<p gameid="' + gameId + '">'+ homeTeam +'</p>\
...
...
$('.wrapper').on('click', 'p', function() {
    var self = $(this);
    var gameId = self.attr('gameid');
    console.log(gameId);
});


问:
base64 binary decode 32 bit array
I got an array which is 32 bit, big endian unsigned integers, basically in plain text is like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

That 32bit endian array itself is encoded in binary base64 AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==

Initially, if I receive this from heaven, now how can I decode/unpack everything to that understandable plain text representation in JavaScript.

In ruby I can simply use Base64.decode and String#Unpack

```<code>encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='

decoded_string = Base64.strict_decode64(encoded_string)
  => "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\x00\x00\x00\b\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\v\x00\x00\x00\f\x00\x00\x00\r\x00\x00\x00\x0E\x00\x00\x00\x0F\x00\x00\x00\x10"

decoded_string.unpack('N*') #32-bit unsigned, network (big-endian) byte order
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
</code>```

Is there an equivalent of this simple step in JavaScript?

答:
You could decode the given string and take onyl four characters for convering to a 32 bit number by using ArrayBuffer and DataView

function getInt(string) {
    var view = new DataView(new ArrayBuffer(4)),
        i;

    for (i = 0; i < string.length; i++) {
        view.setUint8(i, string.charCodeAt(i));
    }
    return view.getInt32(0);
}

var encodedData = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==',
    decodedData = window.atob(encodedData),
    result = [],
    i = 0;

while (i < decodedData.length) {
    result.push(getInt(decodedData.slice(i, i += 4)));
}

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: base64 binary decode 32 bit array

Body:
I got an array which is 32 bit, big endian unsigned integers, basically in plain text is like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

That 32bit endian array itself is encoded in binary base64 AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==

Initially, if I receive this from heaven, now how can I decode/unpack everything to that understandable plain text representation in JavaScript.

In ruby I can simply use Base64.decode and String#Unpack

encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='

decoded_string = Base64.strict_decode64(encoded_string)
  => "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\x00\x00\x00\b\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\v\x00\x00\x00\f\x00\x00\x00\r\x00\x00\x00\x0E\x00\x00\x00\x0F\x00\x00\x00\x10"

decoded_string.unpack('N*') #32-bit unsigned, network (big-endian) byte order
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Is there an equivalent of this simple step in JavaScript?

Body:
You could decode the given string and take onyl four characters for convering to a 32 bit number by using ArrayBuffer and DataView

function getInt(string) {
    var view = new DataView(new ArrayBuffer(4)),
        i;

    for (i = 0; i < string.length; i++) {
        view.setUint8(i, string.charCodeAt(i));
    }
    return view.getInt32(0);
}

var encodedData = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==',
    decodedData = window.atob(encodedData),
    result = [],
    i = 0;

while (i < decodedData.length) {
    result.push(getInt(decodedData.slice(i, i += 4)));
}

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Dismiss imagePicker when button is inside a UITableViewCell
I am trying to dismiss the view. I have been able to add a target to the button which brings up an action sheet that let's user choose their photo from the library. However after I "choose" an image the view doesn't get dismissed.

Here is what's inside my the didFinishPickingMediaWithInfo:

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var  chosenImage = UIImage()
    chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    profileImageView.image = chosenImage

    // This doesn't work...
    self.window?.rootViewController?.dismiss(animated: true, completion: nil)

    print("Should dismiss")
}
</code>```

I present the alertController like this:

```<code>self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
</code>```

答: You are presenting and dismissing the UIImagePickerController correctly. The issue must be with how you are presenting it and which view controller is on the top of the stack when you dismiss it. Try presenting it on the current ViewController that contains the delegate.</p>

Body:
I am trying to dismiss the view. I have been able to add a target to the button which brings up an action sheet that let's user choose their photo from the library. However after I "choose" an image the view doesn't get dismissed.

Here is what's inside my the didFinishPickingMediaWithInfo:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var  chosenImage = UIImage()
    chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    profileImageView.image = chosenImage

    // This doesn't work...
    self.window?.rootViewController?.dismiss(animated: true, completion: nil)

    print("Should dismiss")
}

I present the alertController like this:

self.window?.rootViewController?.present(alertController, animated: true, completion: nil)


问:
Random days in date or datetime
Is it possible to random only days in date or Datetime within a range of days in sql server, t-sql.
For example if dates have days between 1to15 i want to randomise days creating a day number between 16 and 30. Example: 2017-7-10 to 2017-7-21(random day within 16to30). Thank you</p>

答:
```<code>SELECT RandomDate16To30DaysFromToday = DATEADD(DAY, FLOOR(RAND()*(30-16)+16), GETDATE())
</code>```

Title: Random days in date or datetime


问:
Rotating a drawable in Android
How can a Drawable loaded from a resource be rotated when it is drawn? For example, I would like to draw an arrow and be able to rotate it to face in different directions when it is drawn?

答:
You need to use Bitmap and Canvas Class functions to prepare drawable:

```<code>Bitmap bmpOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.image2);
Bitmap bmResult = Bitmap.createBitmap(bmpOriginal.getWidth(), bmpOriginal.getHeight(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(bmResult);
tempCanvas.rotate(90, bmpOriginal.getWidth()/2, bmpOriginal.getHeight()/2);
tempCanvas.drawBitmap(bmpOriginal, 0, 0, null);

mImageView.setImageBitmap(bmResult);
</code>```

In this code sample rotation for 90 degrees over image center occurs.

Title: Rotating a drawable in Android

Body:
You need to use Bitmap and Canvas Class functions to prepare drawable:

Bitmap bmpOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.image2);
Bitmap bmResult = Bitmap.createBitmap(bmpOriginal.getWidth(), bmpOriginal.getHeight(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(bmResult);
tempCanvas.rotate(90, bmpOriginal.getWidth()/2, bmpOriginal.getHeight()/2);
tempCanvas.drawBitmap(bmpOriginal, 0, 0, null);

mImageView.setImageBitmap(bmResult);

In this code sample rotation for 90 degrees over image center occurs.


问:
Iterating Through a C# Object
I am looking for the most efficient way of iterating through attributes within an object and checking to see if it has a custom decorator. The challenge is that my object has other objects within it that may have this custom decorator and the SUB-Objects may have objects as well with decorators.

For now the code down below is only reaching into the first layer of sub objects is there a particular way in which I can go within the loop N times efficiently?

```<code>List<PropertyInfo> allProperties = type.GetProperties().ToList();

Dictionary<string, List<string>> groupIndexes = new Dictionary<string, List<string>>();

foreach (var property in type.GetProperties())
{
    var nestedProperties = property.PropertyType.GetProperties();
    foreach (var nestedProperty in nestedProperties)
    {
        var singleNestedPropertyIndex = nestedProperty.GetCustomAttribute<SingleIndexAttribute>();
        var groupNestedIndex = nestedProperty.GetCustomAttribute<GroupIndexAttribute>();
        var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

        if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
        {
            allProperties.Add(nestedProperty);
        }
    }
}
</code>```

答:
You can perform it by creating recursive method;

```<code>    public static void FindSpecialProperties(PropertyInfo property, List<PropertyInfo> allProperties, HashSet<PropertyInfo> recursivedProperties)
    {
        if (recursivedProperties.Contains(property))//Eliminate already recursived property
        {
            return;
        }
        recursivedProperties.Add(property);
        var properties = property.PropertyType.GetProperties();
        if (properties.Length == 0)
        {
            return;
        }
        foreach (var propertyInfo in properties)
        {
            var singleNestedPropertyIndex = propertyInfo.GetCustomAttribute<SingleIndexAttribute>();
            var groupNestedIndex = propertyInfo.GetCustomAttribute<GroupIndexAttribute>();
            var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

            if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
            {
                allProperties.Add(propertyInfo);
            }
            allProperties.Add(propertyInfo);
            FindSpecialProperties(propertyInfo, allProperties, recursivedProperties);
        }
    }
</code>```

Usage

```<code>        var recursivedProperties = new HashSet<PropertyInfo>();
        var allProperties = type.GetProperties().ToList();
        foreach (var property in type.GetProperties())
        {
            FindSpecialProperties(property, allProperties, recursivedProperties);
        }
</code>```

Title: Iterating Through a C# Object

Body:
I am looking for the most efficient way of iterating through attributes within an object and checking to see if it has a custom decorator. The challenge is that my object has other objects within it that may have this custom decorator and the SUB-Objects may have objects as well with decorators.

For now the code down below is only reaching into the first layer of sub objects is there a particular way in which I can go within the loop N times efficiently?

List<PropertyInfo> allProperties = type.GetProperties().ToList();

Dictionary<string, List<string>> groupIndexes = new Dictionary<string, List<string>>();

foreach (var property in type.GetProperties())
{
    var nestedProperties = property.PropertyType.GetProperties();
    foreach (var nestedProperty in nestedProperties)
    {
        var singleNestedPropertyIndex = nestedProperty.GetCustomAttribute<SingleIndexAttribute>();
        var groupNestedIndex = nestedProperty.GetCustomAttribute<GroupIndexAttribute>();
        var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

        if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
        {
            allProperties.Add(nestedProperty);
        }
    }
}

Body:
You can perform it by creating recursive method;

    public static void FindSpecialProperties(PropertyInfo property, List<PropertyInfo> allProperties, HashSet<PropertyInfo> recursivedProperties)
    {
        if (recursivedProperties.Contains(property))//Eliminate already recursived property
        {
            return;
        }
        recursivedProperties.Add(property);
        var properties = property.PropertyType.GetProperties();
        if (properties.Length == 0)
        {
            return;
        }
        foreach (var propertyInfo in properties)
        {
            var singleNestedPropertyIndex = propertyInfo.GetCustomAttribute<SingleIndexAttribute>();
            var groupNestedIndex = propertyInfo.GetCustomAttribute<GroupIndexAttribute>();
            var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

            if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
            {
                allProperties.Add(propertyInfo);
            }
            allProperties.Add(propertyInfo);
            FindSpecialProperties(propertyInfo, allProperties, recursivedProperties);
        }
    }

Usage

        var recursivedProperties = new HashSet<PropertyInfo>();
        var allProperties = type.GetProperties().ToList();
        foreach (var property in type.GetProperties())
        {
            FindSpecialProperties(property, allProperties, recursivedProperties);
        }


问:
What's the lodash/fp equivalent of Ramda's 'when' function?
Looking at lodash and it's fp facilities., I am searching for when or ifElse equivalent.

In Ramda, one can use when to do semi shorthand if. Check predicate on sent data, and when true, do something. When false, return input data unchanged.

```<code>// truncate :: String -> String
var truncate = R.when(
  R.propSatisfies(R.gt(R.__, 10), 'length'),
  R.pipe(R.take(10), R.append('…'), R.join(''))
);
truncate('12345');         //=> '12345'
truncate('0123456789ABC'); //=> '0123456789…'
</code>```

How this will be accomplished in lodash?

答:
I don't know how to do this in lodash/fp.  (One of these days, I swear I spend some time learning more about it!)  But do note that the version as written could well be simplified.

First, keeping it in Ramda (disclaimer: I'm one of the authors), but simplifying your functions with simple ES6-style lambdas:

```<code>// truncate :: String -> String
var truncate = R.when(
  s => s.length > 10,
  s => s.slice(0, 10) + '…'
);
truncate('12345');         //=> '12345'
truncate('0123456789ABC'); //=> '0123456789…'
</code>```

I find this version extremely readable, and might leave it at that.  But you can also remove the library altogether by replacing the when with another ES6-lambda and using a conditional expression:

```<code>// truncate :: String -> String
var truncate = s => s.length > 10 ? s.slice(0, 10) + '…' : s;
</code>```

Point-free is a great technique that can often add readability.  But there are few reasons to use it when it obscures meaning.

Body:
Looking at lodash and it's fp facilities., I am searching for when or ifElse equivalent.

In Ramda, one can use when to do semi shorthand if. Check predicate on sent data, and when true, do something. When false, return input data unchanged.

// truncate :: String -> String
var truncate = R.when(
  R.propSatisfies(R.gt(R.__, 10), 'length'),
  R.pipe(R.take(10), R.append('…'), R.join(''))
);
truncate('12345');         //=> '12345'
truncate('0123456789ABC'); //=> '0123456789…'

How this will be accomplished in lodash?

Body:
I don't know how to do this in lodash/fp.  (One of these days, I swear I spend some time learning more about it!)  But do note that the version as written could well be simplified.

First, keeping it in Ramda (disclaimer: I'm one of the authors), but simplifying your functions with simple ES6-style lambdas:

// truncate :: String -> String
var truncate = R.when(
  s => s.length > 10,
  s => s.slice(0, 10) + '…'
);
truncate('12345');         //=> '12345'
truncate('0123456789ABC'); //=> '0123456789…'

I find this version extremely readable, and might leave it at that.  But you can also remove the library altogether by replacing the when with another ES6-lambda and using a conditional expression:

// truncate :: String -> String
var truncate = s => s.length > 10 ? s.slice(0, 10) + '…' : s;

Point-free is a great technique that can often add readability.  But there are few reasons to use it when it obscures meaning.


问:
Javascript code for change css width of a class not working
The simple code for change width of a class in css code using javascript is not working. I have given the width is 200px. Then i want to change the width to 50px. i want to use a javascript code to change width. But it is not working.

document.getElementsByClassName("main").style.width = "50px";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  width: 200px;
  height: 200px;
  background-color: red;
}</code>```

```

fiddle: https://jsfiddle.net/33zc0efq/

答:
document.getElementsByClassName returns an array of object so you need to specify index for that. Change it to document.getElementsByClassName("main")[0].style.width="50px";

document.getElementsByClassName("main")[0].style.width="50px";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main{
  width:200px;
  height:200px;
  background-color:red;
}</code>```

```

Body:
The simple code for change width of a class in css code using javascript is not working. I have given the width is 200px. Then i want to change the width to 50px. i want to use a javascript code to change width. But it is not working.

document.getElementsByClassName("main").style.width = "50px";

.main {
  width: 200px;
  height: 200px;
  background-color: red;
}

fiddle: https://jsfiddle.net/33zc0efq/

Body:
document.getElementsByClassName returns an array of object so you need to specify index for that. Change it to document.getElementsByClassName("main")[0].style.width="50px";

document.getElementsByClassName("main")[0].style.width="50px";

.main{
  width:200px;
  height:200px;
  background-color:red;
}

<div class="main">
</div>


问:
CUDA Vision Studio Trouble with Kernel
I have a project where I have to create a program in Visual Studio/CUDA using GPU Threads and Blocks that contain 2 random Arrays A and B used for computation before storing the result in a third Array C the values based on this equation:

C(1,j)=max(A(:,j)+max(B(:,j))  (Note: the ":" operator means for all the lines)

Here is my Kernel function

```<code>           __global__ void mykernel(int **a, int **b,int **c,const int width)
             {
int col= threadIdx.x;
int tempa=0;
int tempb=0;

for(int k=0;k<width;k++){

    int maxA=a[k][col];

    if  (maxA>tempa){
    tempa=maxA;
    }

    int maxB=b[k][col];

    if  (maxB>tempb){
    tempb=maxB;
    }

    }

c[0][col] =tempa+tempb;
}
</code>```

And my main

```<code>      int main()
       {
const int  dim= 5;
const int rows=5;
const int columns=5;
size_t dsize = rows*columns*sizeof(int);
//Αντίγραφα πινάκων δεδομένων της CPU
int *A[dim][dim];
int *B[dim][dim];
int *C[1][dim];

//Αντίγραφα πινάκων δεδομένων της GPU
int *d_A[dim][dim],*d_B[dim][dim],*d_C[1][dim];

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της CPU
A[dim][dim]= (int *)malloc(dsize);
B[dim][dim] = (int *)malloc(dsize);
C[1][dim]= (int *)malloc(dsize);

//Γέμισμα των πινάκων με τυχαίες τιμές μεταξυ
 for (int i=0;i<rows;i++)
   for (int j=0;j<columns;j++){

  *A[i][j]=rand() %5+1;
  *B[i][j]=rand() %5+1;

 }

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της GPU και αντιγραφή δεδομένων CPU προς GPU
cudaMalloc((void **)&d_A, dsize);
cudaMemcpy(d_A, A, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_B, dsize);
cudaMemcpy(d_B, B, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_C, dsize);

//Κλήση Kernel συνάρτησης στην GPU με χρήση 5 Threads σε 1 Block

mykernel<<<1,5>>>(d_A,d_B,d_C,dim);

//Αντιγραφή αποτελέσματος στην μνήμη της CPU
cudaMemcpy(C, d_C, dsize, cudaMemcpyDeviceToHost);

//Εκκαθάριση Μνήμης για CPU και GPU
free(A);
free(B);
free(C);

cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);

while(1){};
return 0;
  }
</code>```

I think I got the algorithm right but in this line I get the following error:

Line

```<code>mykernel<<<1,5>>>(d_A,d_B,d_C,dim);
</code>```

Error

```<code>argument of type "int *(*)[5]" is incompatible with parameter of type "int **"
</code>```

Any suggestions on what I should do?

答:
First of all, any time you are having trouble with a CUDA code, I recommend using proper CUDA error checking and running your code with cuda-memcheck (e.g. from the command line).

This isn't doing what you think:

```<code>int *A[dim][dim];
</code>```

this is creating a 2-dimensional array of pointers.  What you want is a pointer to a 2-dimensional array (of int).

In C, when you define an array, you cannot assign anything to elements at the array dimension:

```<code>A[dim][dim]= (int *)malloc(dsize);
</code>```

arrays only go up to size of dim- 1.  A[dim][dim] does not exist and is out-of-range for your array definition.  This appears to be related to your general confusion around using 2D arrays in C or C++.

This line is similarly broken (assigning a numerical value to a region associated with an unallocated pointer) and is further evidence of your confusion around 2D arrays in C:

```<code>*A[i][j]=rand() %5+1;
</code>```

Your handling of d_A, d_B and d_C are similarly broken.

It's evident that you are wanting to use a 2D array in your CUDA kernel, so the right approach here is to probably pick a method from a set of canonical examples.  Since you appear to know the array dimensions at compile time, we'll leverage that.  Here is a fully worked example showing the mods:

```<code>$ cat t1344.cu
#include <iostream>
const int dim = 5;
typedef int my_arr[dim];

__global__ void mykernel(my_arr *a, my_arr *b, my_arr *c,const int width)
{
int col= threadIdx.x;
int tempa=0;
int tempb=0;

for(int k=0;k<width;k++){

    int maxA=a[k][col];

    if  (maxA>tempa){
    tempa=maxA;
    }

    int maxB=b[k][col];

    if  (maxB>tempb){
    tempb=maxB;
    }

    }

c[0][col] =tempa+tempb;
}

int main()
       {
const int rows=dim;
const int columns=dim;
size_t dsize = rows*columns*sizeof(int);
//Αντίγραφα πινάκων δεδομένων της CPU;
my_arr *A, *B, *C;

//Αντίγραφα πινάκων δεδομένων της GPU
my_arr *d_A,*d_B,*d_C;

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της CPU
A = (my_arr *)malloc(dsize);
B = (my_arr *)malloc(dsize);
C = (my_arr *)malloc(dsize);

//Γέμισμα των πινάκων με τυχαίες τιμές μεταξυ
 for (int i=0;i<rows;i++)
   for (int j=0;j<columns;j++){

  A[i][j]=rand() %5+1;
  B[i][j]=rand() %5+1;

 }

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της GPU και αντιγραφή δεδομένων CPU προς GPU
cudaMalloc((void **)&d_A, dsize);
cudaMemcpy(d_A, A, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_B, dsize);
cudaMemcpy(d_B, B, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_C, dsize);

//Κλήση Kernel συνάρτησης στην GPU με χρήση 5 Threads σε 1 Block

mykernel<<<1,5>>>(d_A,d_B,d_C,dim);

//Αντιγραφή αποτελέσματος στην μνήμη της CPU
cudaMemcpy(C, d_C, dsize, cudaMemcpyDeviceToHost);
for (int i = 0; i < dim; i++)  std::cout << C[0][i] << std::endl;
//Εκκαθάριση Μνήμης για CPU και GPU
free(A);
free(B);
free(C);

cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);

return 0;
  }
$ nvcc -arch=sm_35 -o t1344 t1344.cu
$ cuda-memcheck ./t1344
========= CUDA-MEMCHECK
9
8
8
9
8
========= ERROR SUMMARY: 0 errors
$
</code>```

I haven't fully verified the results, but they seem plausible to me.

Title: CUDA Vision Studio Trouble with Kernel

Body:
I have a project where I have to create a program in Visual Studio/CUDA using GPU Threads and Blocks that contain 2 random Arrays A and B used for computation before storing the result in a third Array C the values based on this equation:

C(1,j)=max(A(:,j)+max(B(:,j))  (Note: the ":" operator means for all the lines)

Here is my Kernel function

           __global__ void mykernel(int **a, int **b,int **c,const int width)
             {
int col= threadIdx.x;
int tempa=0;
int tempb=0;

for(int k=0;k<width;k++){

    int maxA=a[k][col];

    if  (maxA>tempa){
    tempa=maxA;
    }

    int maxB=b[k][col];

    if  (maxB>tempb){
    tempb=maxB;
    }

    }

c[0][col] =tempa+tempb;
}

And my main

      int main()
       {
const int  dim= 5;
const int rows=5;
const int columns=5;
size_t dsize = rows*columns*sizeof(int);
//Αντίγραφα πινάκων δεδομένων της CPU
int *A[dim][dim];
int *B[dim][dim];
int *C[1][dim];

//Αντίγραφα πινάκων δεδομένων της GPU
int *d_A[dim][dim],*d_B[dim][dim],*d_C[1][dim];

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της CPU
A[dim][dim]= (int *)malloc(dsize);
B[dim][dim] = (int *)malloc(dsize);
C[1][dim]= (int *)malloc(dsize);

//Γέμισμα των πινάκων με τυχαίες τιμές μεταξυ
 for (int i=0;i<rows;i++)
   for (int j=0;j<columns;j++){

  *A[i][j]=rand() %5+1;
  *B[i][j]=rand() %5+1;

 }

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της GPU και αντιγραφή δεδομένων CPU προς GPU
cudaMalloc((void **)&d_A, dsize);
cudaMemcpy(d_A, A, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_B, dsize);
cudaMemcpy(d_B, B, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_C, dsize);

//Κλήση Kernel συνάρτησης στην GPU με χρήση 5 Threads σε 1 Block

mykernel<<<1,5>>>(d_A,d_B,d_C,dim);

//Αντιγραφή αποτελέσματος στην μνήμη της CPU
cudaMemcpy(C, d_C, dsize, cudaMemcpyDeviceToHost);

//Εκκαθάριση Μνήμης για CPU και GPU
free(A);
free(B);
free(C);

cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);

while(1){};
return 0;
  }

I think I got the algorithm right but in this line I get the following error:

Line

mykernel<<<1,5>>>(d_A,d_B,d_C,dim);

Error

argument of type "int *(*)[5]" is incompatible with parameter of type "int **"

Any suggestions on what I should do?

Body:
First of all, any time you are having trouble with a CUDA code, I recommend using proper CUDA error checking and running your code with cuda-memcheck (e.g. from the command line).

This isn't doing what you think:

int *A[dim][dim];

this is creating a 2-dimensional array of pointers.  What you want is a pointer to a 2-dimensional array (of int).

In C, when you define an array, you cannot assign anything to elements at the array dimension:

A[dim][dim]= (int *)malloc(dsize);

arrays only go up to size of dim- 1.  A[dim][dim] does not exist and is out-of-range for your array definition.  This appears to be related to your general confusion around using 2D arrays in C or C++.

This line is similarly broken (assigning a numerical value to a region associated with an unallocated pointer) and is further evidence of your confusion around 2D arrays in C:

*A[i][j]=rand() %5+1;

Your handling of d_A, d_B and d_C are similarly broken.

It's evident that you are wanting to use a 2D array in your CUDA kernel, so the right approach here is to probably pick a method from a set of canonical examples.  Since you appear to know the array dimensions at compile time, we'll leverage that.  Here is a fully worked example showing the mods:

$ cat t1344.cu
#include <iostream>
const int dim = 5;
typedef int my_arr[dim];

__global__ void mykernel(my_arr *a, my_arr *b, my_arr *c,const int width)
{
int col= threadIdx.x;
int tempa=0;
int tempb=0;

for(int k=0;k<width;k++){

    int maxA=a[k][col];

    if  (maxA>tempa){
    tempa=maxA;
    }

    int maxB=b[k][col];

    if  (maxB>tempb){
    tempb=maxB;
    }

    }

c[0][col] =tempa+tempb;
}

int main()
       {
const int rows=dim;
const int columns=dim;
size_t dsize = rows*columns*sizeof(int);
//Αντίγραφα πινάκων δεδομένων της CPU;
my_arr *A, *B, *C;

//Αντίγραφα πινάκων δεδομένων της GPU
my_arr *d_A,*d_B,*d_C;

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της CPU
A = (my_arr *)malloc(dsize);
B = (my_arr *)malloc(dsize);
C = (my_arr *)malloc(dsize);

//Γέμισμα των πινάκων με τυχαίες τιμές μεταξυ
 for (int i=0;i<rows;i++)
   for (int j=0;j<columns;j++){

  A[i][j]=rand() %5+1;
  B[i][j]=rand() %5+1;

 }

//Εξασφάλιση μνήμης για τα αντίγραφα δεδομένων της GPU και αντιγραφή δεδομένων CPU προς GPU
cudaMalloc((void **)&d_A, dsize);
cudaMemcpy(d_A, A, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_B, dsize);
cudaMemcpy(d_B, B, dsize, cudaMemcpyHostToDevice);

cudaMalloc((void **)&d_C, dsize);

//Κλήση Kernel συνάρτησης στην GPU με χρήση 5 Threads σε 1 Block

mykernel<<<1,5>>>(d_A,d_B,d_C,dim);

//Αντιγραφή αποτελέσματος στην μνήμη της CPU
cudaMemcpy(C, d_C, dsize, cudaMemcpyDeviceToHost);
for (int i = 0; i < dim; i++)  std::cout << C[0][i] << std::endl;
//Εκκαθάριση Μνήμης για CPU και GPU
free(A);
free(B);
free(C);

cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);

return 0;
  }
$ nvcc -arch=sm_35 -o t1344 t1344.cu
$ cuda-memcheck ./t1344
========= CUDA-MEMCHECK
9
8
8
9
8
========= ERROR SUMMARY: 0 errors
$

I haven't fully verified the results, but they seem plausible to me.


问:
UnsupportedOperationException: Use MenuItemCompat.setOnActionExpandListener()
I had previous success creating a search item and calling the .setOnActionExpandListener(), however now I am receiving an UnsupportedOperationException and do not know how to resolve. It may have to do with conflicts in my gradle between compileSDKVersion, targetSDKVersion, but I am not sure. I have read other SO posts that indicate it is actually a bug in Google's support library and that it has been fixed, but I cannot confirm. I recently updated the Android Support Library I am using, which may also be contributing to the issue, please see below for details:

```<code> @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    // Retrieve the SearchView and plug it into SearchManager

    SupportMenuItem searchItem = (SupportMenuItem) menu.findItem(R.id.search);

    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem menuItem) {
            Toast.makeText(getApplicationContext(), "OPEN", Toast.LENGTH_LONG).show();

            return false;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem menuItem) {
            Toast.makeText(getApplicationContext(), "Close", Toast.LENGTH_LONG).show();
            finish();
            return false;
        }
    });
</code>```

Exception:

```<code>12-03 17:31:55.743 18797-18797/com.troychuinard.fanpolls E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.troychuinard.fanpolls, PID: 18797
                                                                       java.lang.UnsupportedOperationException: This is not supported, use MenuItemCompat.setOnActionExpandListener()
                                                                           at android.support.v7.view.menu.MenuItemImpl.setOnActionExpandListener(MenuItemImpl.java:743)
                                                                           at com.troychuinard.fanpolls.NewImageActivity.onCreateOptionsMenu(NewImageActivity.java:90)
                                                                           at android.app.Activity.onCreatePanelMenu(Activity.java:2881)
                                                                           at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:328)
                                                                           at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:98)
                                                                           at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:335)
                                                                           at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1368)
                                                                           at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1648)
                                                                           at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:140)
                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
</code>```

App Gradle:

```<code>apply plugin: 'com.android.application'

  android {
compileSdkVersion 25
buildToolsVersion '26.0.2'

defaultConfig {
    vectorDrawables.useSupportLibrary = true
    applicationId "xxxxxxxx"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}

dexOptions {
    javaMaxHeapSize "2g"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')

// Support library
compile "com.android.support:design:$supportLibVersion"
compile "com.android.support:cardview-v7:$supportLibVersion"
compile "com.android.support:support-v4:$supportLibVersion"

// Firebase
compile "com.google.firebase:firebase-storage:$playServicesVersion"
 //    compile 'com.github.SUPERCILEX.FirebaseUI-Android:firebase-ui-
database:e3c0feaddae3c7cc0fc7b3333bf3c4c11e4ae406'
compile "com.google.firebase:firebase-core:$playServicesVersion"
compile "com.google.firebase:firebase-auth:$playServicesVersion"
compile "com.google.android.gms:play-services-
 auth:$playServicesVersion"
compile "com.google.firebase:firebase-database:$playServicesVersion"
compile "com.google.firebase:firebase-appindexing:$playServicesVersion"
    //    compile "com.google.firebase:firebase-
firestore:$playServicesVersion"
 //    compile 'com.firebaseui:firebase-ui-firestore:3.1.0'
compile 'com.firebaseui:firebase-ui-database:3.1.0'

// Third party
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.facebook.android:facebook-android-sdk:4.+'
compile 'jp.wasabeef:recyclerview-animators:2.2.3'
compile 'com.github.clans:fab:1.6.2'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.github.PhilJay:MPAndroidChart:v2.2.2'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
compile 'com.android.support:multidex:1.0.1'
 }

apply plugin: 'com.google.gms.google-services'
</code>```

Root Gradle:

```<code>buildscript {
repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.1.0'
     }
 }

 allprojects {
    repositories {
     jcenter()
    maven { url 'https://maven.fabric.io/public' }
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" }

    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}
  }

task clean(type: Delete) {
delete rootProject.buildDir
  }

ext {
supportLibVersion = "25.3.1"
playServicesVersion = "11.4.2"
  }
</code>```

答:
The error log describes the cause of exception pretty well:

This is not supported, use MenuItemCompat.setOnActionExpandListener()

Which means, that instead of:

```<code>searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {...});
</code>```

You should do:

```<code>MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {...})
</code>```

Body:
I had previous success creating a search item and calling the .setOnActionExpandListener(), however now I am receiving an UnsupportedOperationException and do not know how to resolve. It may have to do with conflicts in my gradle between compileSDKVersion, targetSDKVersion, but I am not sure. I have read other SO posts that indicate it is actually a bug in Google's support library and that it has been fixed, but I cannot confirm. I recently updated the Android Support Library I am using, which may also be contributing to the issue, please see below for details:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    // Retrieve the SearchView and plug it into SearchManager

    SupportMenuItem searchItem = (SupportMenuItem) menu.findItem(R.id.search);

    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem menuItem) {
            Toast.makeText(getApplicationContext(), "OPEN", Toast.LENGTH_LONG).show();

            return false;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem menuItem) {
            Toast.makeText(getApplicationContext(), "Close", Toast.LENGTH_LONG).show();
            finish();
            return false;
        }
    });

Exception:

12-03 17:31:55.743 18797-18797/com.troychuinard.fanpolls E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.troychuinard.fanpolls, PID: 18797
                                                                       java.lang.UnsupportedOperationException: This is not supported, use MenuItemCompat.setOnActionExpandListener()
                                                                           at android.support.v7.view.menu.MenuItemImpl.setOnActionExpandListener(MenuItemImpl.java:743)
                                                                           at com.troychuinard.fanpolls.NewImageActivity.onCreateOptionsMenu(NewImageActivity.java:90)
                                                                           at android.app.Activity.onCreatePanelMenu(Activity.java:2881)
                                                                           at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:328)
                                                                           at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:98)
                                                                           at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:335)
                                                                           at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1368)
                                                                           at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1648)
                                                                           at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:140)
                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

App Gradle:

apply plugin: 'com.android.application'

  android {
compileSdkVersion 25
buildToolsVersion '26.0.2'

defaultConfig {
    vectorDrawables.useSupportLibrary = true
    applicationId "xxxxxxxx"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}

dexOptions {
    javaMaxHeapSize "2g"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')

// Support library
compile "com.android.support:design:$supportLibVersion"
compile "com.android.support:cardview-v7:$supportLibVersion"
compile "com.android.support:support-v4:$supportLibVersion"

// Firebase
compile "com.google.firebase:firebase-storage:$playServicesVersion"
 //    compile 'com.github.SUPERCILEX.FirebaseUI-Android:firebase-ui-
database:e3c0feaddae3c7cc0fc7b3333bf3c4c11e4ae406'
compile "com.google.firebase:firebase-core:$playServicesVersion"
compile "com.google.firebase:firebase-auth:$playServicesVersion"
compile "com.google.android.gms:play-services-
 auth:$playServicesVersion"
compile "com.google.firebase:firebase-database:$playServicesVersion"
compile "com.google.firebase:firebase-appindexing:$playServicesVersion"
    //    compile "com.google.firebase:firebase-
firestore:$playServicesVersion"
 //    compile 'com.firebaseui:firebase-ui-firestore:3.1.0'
compile 'com.firebaseui:firebase-ui-database:3.1.0'

// Third party
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.facebook.android:facebook-android-sdk:4.+'
compile 'jp.wasabeef:recyclerview-animators:2.2.3'
compile 'com.github.clans:fab:1.6.2'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.github.PhilJay:MPAndroidChart:v2.2.2'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
compile 'com.android.support:multidex:1.0.1'
 }

apply plugin: 'com.google.gms.google-services'

Root Gradle:

buildscript {
repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.1.0'
     }
 }

 allprojects {
    repositories {
     jcenter()
    maven { url 'https://maven.fabric.io/public' }
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" }

    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}
  }

task clean(type: Delete) {
delete rootProject.buildDir
  }

ext {
supportLibVersion = "25.3.1"
playServicesVersion = "11.4.2"
  }

Body:
The error log describes the cause of exception pretty well:

This is not supported, use MenuItemCompat.setOnActionExpandListener()

Which means, that instead of:

searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {...});

You should do:

MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {...})


问:
Merging log data in python
I have log data in 7 separate files which I need to merge into one file before I can conduct any page analysis on it. Below I have provided an example of a line within one of the log data files

```<code>207.46.13.124 - - [01/Jun/2015:00:00:04 +0000] "GET /maritime/collections/hmsconway/hiscock/index.aspx HTTP/1.0" 200 "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
</code>```

The names of the files are u_ex150601, u_ex150602, u_ex150603, u_ex1506014, u_ex150605, u_ex150606, and u_ex150607.

How do I merge all of these together using just Python?

答:
I would personally recommend using bash. Something like,

```<code>cat u_ex15* >> all_logs
</code>```

But in python you can simply use the following:

```<code>import glob
all_log_filename = 'all_logs'
log_files = glob.glob('u_ex15*')
for filename in log_files:
    with open(filename) as reader:
        with open(all_log_filename, 'a') as writer:
             writer.write(reader.read())
</code>```

NOTE: This is the simplest case where your log files aren't that large. If your log files are large, you may want to iterate over each line or chunks so that you don't run into memory issues. The simplest thing you could do is something like:

```<code>for filename in log_files:
    with open(filename) as reader:
        with open(all_log_filename, 'a') as writer:
            for line in reader:
                writer.write(line)
</code>```

Title: Merging log data in python

Body:
I have log data in 7 separate files which I need to merge into one file before I can conduct any page analysis on it. Below I have provided an example of a line within one of the log data files

207.46.13.124 - - [01/Jun/2015:00:00:04 +0000] "GET /maritime/collections/hmsconway/hiscock/index.aspx HTTP/1.0" 200 "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"

The names of the files are u_ex150601, u_ex150602, u_ex150603, u_ex1506014, u_ex150605, u_ex150606, and u_ex150607.

How do I merge all of these together using just Python?

Body:
I would personally recommend using bash. Something like,

cat u_ex15* >> all_logs

But in python you can simply use the following:

import glob
all_log_filename = 'all_logs'
log_files = glob.glob('u_ex15*')
for filename in log_files:
    with open(filename) as reader:
        with open(all_log_filename, 'a') as writer:
             writer.write(reader.read())

NOTE: This is the simplest case where your log files aren't that large. If your log files are large, you may want to iterate over each line or chunks so that you don't run into memory issues. The simplest thing you could do is something like:

for filename in log_files:
    with open(filename) as reader:
        with open(all_log_filename, 'a') as writer:
            for line in reader:
                writer.write(line)


问:
arrange items by two values in Python dictionary
I practice python recently. for a few days my script has stopped, because I'm struggling on a problem.
I want to sort the items by both values which has in common. like an chain. as you can see lower.

what I have:

```<code>dic= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]}
</code>```

what I want:

```<code>dic={'A': [62, 17], 'E': [31, 62],'C': [60, 31],'B': [3, 60],'F': [58, 3],'D': [57, 58]}
</code>```

to see clearly:

```<code>'A': [62, 17]

'E': [*31*, 62]

'C': [60, *31*]

'B': [3, 60]

'F': [58, 3]

'D': [57, 58]
</code>```

there is a simple method to sort them ? if the topic already exists,
can you send me the link. i haven't found it.
thank you in advance.
nb. in all case, I know the first and the last value of the chain (17 and 57)

答:
in fact i don't need a new dictionary. but a ordered list by the common value of the item.
it must be look like that:
list=[17,62,32,60,3,58,57]</p>

Body:
I practice python recently. for a few days my script has stopped, because I'm struggling on a problem.
I want to sort the items by both values which has in common. like an chain. as you can see lower.

what I have:

dic= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]}

what I want:

dic={'A': [62, 17], 'E': [31, 62],'C': [60, 31],'B': [3, 60],'F': [58, 3],'D': [57, 58]}

to see clearly:

'A': [62, 17]

'E': [*31*, 62]

'C': [60, *31*]

'B': [3, 60]

'F': [58, 3]

'D': [57, 58]

there is a simple method to sort them ? if the topic already exists,
can you send me the link. i haven't found it.
thank you in advance.
nb. in all case, I know the first and the last value of the chain (17 and 57)