问:
Passing a varchar full of comma delimited values to a SQL Server IN function

Duplicate of

  Dynamic SQL Comma Delimited Value Query

  Parameterized Queries with Like and In

I have a SQL Server Stored Procedure where I would like to pass a varchar full of comma delimited values to an IN function. For example:

```<code>DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';

SELECT *
FROM sometable
WHERE tableid IN (@Ids);
</code>```

This does not work of course. I get the error:

Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.

How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?

答:
The simplest way i found was to use FIND_IN_SET</p>

```<code>FIND_IN_SET(column_name, values)

values=(1,2,3)

SELECT name WHERE FIND_IN_SET(id, values)
</code>```

Body:
Duplicate of

  Dynamic SQL Comma Delimited Value Query

  Parameterized Queries with Like and In

I have a SQL Server Stored Procedure where I would like to pass a varchar full of comma delimited values to an IN function. For example:

DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';

SELECT *
FROM sometable
WHERE tableid IN (@Ids);

This does not work of course. I get the error:

Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.

How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?

Body:
The simplest way i found was to use FIND_IN_SET

FIND_IN_SET(column_name, values)

values=(1,2,3)

SELECT name WHERE FIND_IN_SET(id, values)


来源: stackexchange

问:
Input type button not working within table tds
I do refers to this fiddle and this post but this doesn't solve my problems. I'm well informed since I used CSP, onclick attribute is not working, thus I use jQuery .on('click') to get this done but still no satisfied results.
Here is the structure of my code(will include only codes related to this issues):-

html

```<code><td><input value="Resend" class="btn btn-primary btn-xs" id="resend_sms" name="resend_sms" type="button"></td>
</code>```

script

```<code>$(function(){
            $('#resend_sms').on('click', function(e){
                console.log('clicked');
            });
        });
</code>```

Above is the codes related. For your notice, this part of html is generated by server-side script. Again, I re-test the this guy but still no results upon clicked.

答:
Its working fine. I just added the jquery file to your code

$(function() {
  $('#resend_sms').on('click', function(e) {
    console.log('clicked');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input value="Resend" class="btn btn-primary btn-xs" id="resend_sms" name="resend_sms" type="button"></td></code>```

ContentLicense: CC BY-SA 3.0

Body:
I do refers to this fiddle and this post but this doesn't solve my problems. I'm well informed since I used CSP, onclick attribute is not working, thus I use jQuery .on('click') to get this done but still no satisfied results.
Here is the structure of my code(will include only codes related to this issues):-

html

<input value="Resend" class="btn btn-primary btn-xs" id="resend_sms" name="resend_sms" type="button">

script

$(function(){
            $('#resend_sms').on('click', function(e){
                console.log('clicked');
            });
        });

Above is the codes related. For your notice, this part of html is generated by server-side script. Again, I re-test the this guy but still no results upon clicked.

Body:
Its working fine. I just added the jquery file to your code

$(function() {
  $('#resend_sms').on('click', function(e) {
    console.log('clicked');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input value="Resend" class="btn btn-primary btn-xs" id="resend_sms" name="resend_sms" type="button"></td>


问:
Laravel : Removing an element from a collection array
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

```<code>```
Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}
```
</code>```

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

答:
Here $users is an Std Class Object, you can iterate over it and push its properties to an array like:

```<code>$userDetails = array();
foreach($users as $user)
{
  $userDetails[] = (array)$user;
  // or
  $userDetails[] = $user->index;
}
</code>```

You can also put an If block inside foreach() to check some condition.

Body:
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

Body:
Here $users is an Std Class Object, you can iterate over it and push its properties to an array like:

$userDetails = array();
foreach($users as $user)
{
  $userDetails[] = (array)$user;
  // or
  $userDetails[] = $user->index;
}

You can also put an If block inside foreach() to check some condition.


问:
Multiple Bindings to a GridView DataSource
I am trying to bind three queries to a GridView DataSource. From my understanding you can't bind more then one query to a GridView DataSource, Is this true? Is so, how would you go about taking multiple queries and binding them to one GridView. For example:

```<code>var query1 = select * from table 1
var query2 = select * from table 2
var query3 = select * from table 3

GridView.DataSource = query1;
GridView.DataSource = query2;
GridView.DataSource  = query3;
</code>```

This is basically what I want to do, but from what I can find this is possible. Is there a good way to do something like this? Thanks!

So, basically I have multiple queries and I need certain results from all of them to go into one GridView.

答:
That's right, you cannot do multi bindings.

However, you can concatenate the query to bring in ALL the records into a single DataTable and then bind to it.

ie

Assuming <asp:SqlDataSource... where your SELECT has the entire data in a single query

```<code>        DataSourceSelectArguments dss = new DataSourceSelectArguments();
        SqlDataSource sds = (SqlDataSource)YourControl.FindControl("your datasource control");
        if (sds != null)
        {
            DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);
            if (dv != null)
            {
                DataTable dt = (DataTable)dv.ToTable();
                if (dt != null)
                {
                  myGridView.DataSource = dt;
                  myGridView.DataSourceID = null; //won't be needed
                  myGridView.DataBind();
etc
</code>```

Body:
I am trying to bind three queries to a GridView DataSource. From my understanding you can't bind more then one query to a GridView DataSource, Is this true? Is so, how would you go about taking multiple queries and binding them to one GridView. For example:

var query1 = select * from table 1
var query2 = select * from table 2
var query3 = select * from table 3

GridView.DataSource = query1;
GridView.DataSource = query2;
GridView.DataSource  = query3;

This is basically what I want to do, but from what I can find this is possible. Is there a good way to do something like this? Thanks!

So, basically I have multiple queries and I need certain results from all of them to go into one GridView.

Body:
That's right, you cannot do multi bindings.

However, you can concatenate the query to bring in ALL the records into a single DataTable and then bind to it.

ie

Assuming <asp:SqlDataSource... where your SELECT has the entire data in a single query

        DataSourceSelectArguments dss = new DataSourceSelectArguments();
        SqlDataSource sds = (SqlDataSource)YourControl.FindControl("your datasource control");
        if (sds != null)
        {
            DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);
            if (dv != null)
            {
                DataTable dt = (DataTable)dv.ToTable();
                if (dt != null)
                {
                  myGridView.DataSource = dt;
                  myGridView.DataSourceID = null; //won't be needed
                  myGridView.DataBind();
etc


问:
Cordova iOS plugins not found
I recently upgraded to Cordova 2.9.0 from 2.3.0. After following all the upgrade instructions, I was able to get the app to launch in the simulator. However, in Xcode I see the following errors:

```<code>ERROR: Plugin 'Device' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["Device1776032119","Device","getDeviceInfo",[]]
ERROR: Plugin 'NetworkStatus' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["NetworkStatus1776032120","NetworkStatus","getConnectionInfo",[]]
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["INVALID","Logger","logLevel",["LOG","deviceready has not fired after 5 seconds."]]
ERROR: Plugin 'Logger' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["INVALID","Logger","logLevel",["LOG","Channel not fired: onCordovaConnectionReady"]]
ERROR: Plugin 'Logger' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["INVALID","Logger","logLevel",["LOG","Channel not fired: onCordovaInfoReady"]]
</code>```

This is my config.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<widget>
    <feature name="Geolocation">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Device">
        <param name="ios-package" value="CDVDevice" />
    </feature>
    <feature name="Accelerometer">
        <param name="ios-package" value="CDVAccelerometer" />
    </feature>
    <feature name="Compass">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Media">
        <param name="ios-package" value="CDVSound" />
    </feature>
    <feature name="Camera">
        <param name="ios-package" value="CDVCamera" />
    </feature>
    <feature name="Contacts">
        <param name="ios-package" value="CDVContacts" />
    </feature>
    <feature name="File">
        <param name="ios-package" value="CDVFile" />
    </feature>
    <feature name="NetworkStatus">
        <param name="ios-package" value="CDVConnection" />
    </feature>
    <feature name="Notification">
        <param name="ios-package" value="CDVNotification" />
    </feature>
    <feature name="FileTransfer">
        <param name="ios-package" value="CDVFileTransfer" />
    </feature>
    <feature name="Capture">
        <param name="ios-package" value="CDVCapture" />
    </feature>
    <feature name="Battery">
        <param name="ios-package" value="CDVBattery" />
    </feature>
    <feature name="SplashScreen">
        <param name="ios-package" value="CDVSplashScreen" />
    </feature>
    <feature name="Echo">
        <param name="ios-package" value="CDVEcho" />
    </feature>
    <feature name="Globalization">
        <param name="ios-package" value="CDVGlobalization" />
    </feature>
    <feature name="InAppBrowser">
        <param name="ios-package" value="CDVInAppBrowser" />
    </feature>
    <feature name="Logger">
        <param name="ios-package" value="CDVLogger" />
    </feature>
    <feature name="LocalStorage">
        <param name="ios-package" value="CDVLocalStorage" />
    </feature>
    <plugins>
    </plugins>
    <preference name="KeyboardDisplayRequiresUserAction" value="true" />
    <preference name="SuppressesIncrementalRendering" value="false" />
    <preference name="UIWebViewBounce" value="true" />
    <preference name="TopActivityIndicator" value="gray" />
    <preference name="EnableLocation" value="false" />
    <preference name="EnableViewportScale" value="false" />
    <preference name="AutoHideSplashScreen" value="true" />
    <preference name="ShowSplashScreenSpinner" value="true" />
    <preference name="MediaPlaybackRequiresUserAction" value="false" />
    <preference name="AllowInlineMediaPlayback" value="false" />
    <preference name="OpenAllWhitelistURLsInWebView" value="false" />
    <preference name="BackupWebStorage" value="cloud" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
    <access origin="*.googleapis.com"/>
    <access origin="*.gstatic.com"/>
    <access origin="*.s3.amazonaws.com"/>
</widget>
</code>```

答: I had the very same problem with the SQLitePlugin. I tried some of the proposed solutions in this post but none of them exactly worked for me. Then I tried to remove the platform/ios dir (I am developing for an iPhone), added the ios platform again (ionic add platform ios) and rebuilt the project. Suddenly, everything worked like a charm. I didn't had to create a new project nor had to remove the plugins.</p>

Title: Cordova iOS plugins not found

Body:
I recently upgraded to Cordova 2.9.0 from 2.3.0. After following all the upgrade instructions, I was able to get the app to launch in the simulator. However, in Xcode I see the following errors:

ERROR: Plugin 'Device' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["Device1776032119","Device","getDeviceInfo",[]]
ERROR: Plugin 'NetworkStatus' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["NetworkStatus1776032120","NetworkStatus","getConnectionInfo",[]]
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["INVALID","Logger","logLevel",["LOG","deviceready has not fired after 5 seconds."]]
ERROR: Plugin 'Logger' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["INVALID","Logger","logLevel",["LOG","Channel not fired: onCordovaConnectionReady"]]
ERROR: Plugin 'Logger' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 103] FAILED pluginJSON = ["INVALID","Logger","logLevel",["LOG","Channel not fired: onCordovaInfoReady"]]

This is my config.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<widget>
    <feature name="Geolocation">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Device">
        <param name="ios-package" value="CDVDevice" />
    </feature>
    <feature name="Accelerometer">
        <param name="ios-package" value="CDVAccelerometer" />
    </feature>
    <feature name="Compass">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Media">
        <param name="ios-package" value="CDVSound" />
    </feature>
    <feature name="Camera">
        <param name="ios-package" value="CDVCamera" />
    </feature>
    <feature name="Contacts">
        <param name="ios-package" value="CDVContacts" />
    </feature>
    <feature name="File">
        <param name="ios-package" value="CDVFile" />
    </feature>
    <feature name="NetworkStatus">
        <param name="ios-package" value="CDVConnection" />
    </feature>
    <feature name="Notification">
        <param name="ios-package" value="CDVNotification" />
    </feature>
    <feature name="FileTransfer">
        <param name="ios-package" value="CDVFileTransfer" />
    </feature>
    <feature name="Capture">
        <param name="ios-package" value="CDVCapture" />
    </feature>
    <feature name="Battery">
        <param name="ios-package" value="CDVBattery" />
    </feature>
    <feature name="SplashScreen">
        <param name="ios-package" value="CDVSplashScreen" />
    </feature>
    <feature name="Echo">
        <param name="ios-package" value="CDVEcho" />
    </feature>
    <feature name="Globalization">
        <param name="ios-package" value="CDVGlobalization" />
    </feature>
    <feature name="InAppBrowser">
        <param name="ios-package" value="CDVInAppBrowser" />
    </feature>
    <feature name="Logger">
        <param name="ios-package" value="CDVLogger" />
    </feature>
    <feature name="LocalStorage">
        <param name="ios-package" value="CDVLocalStorage" />
    </feature>
    <plugins>
    </plugins>
    <preference name="KeyboardDisplayRequiresUserAction" value="true" />
    <preference name="SuppressesIncrementalRendering" value="false" />
    <preference name="UIWebViewBounce" value="true" />
    <preference name="TopActivityIndicator" value="gray" />
    <preference name="EnableLocation" value="false" />
    <preference name="EnableViewportScale" value="false" />
    <preference name="AutoHideSplashScreen" value="true" />
    <preference name="ShowSplashScreenSpinner" value="true" />
    <preference name="MediaPlaybackRequiresUserAction" value="false" />
    <preference name="AllowInlineMediaPlayback" value="false" />
    <preference name="OpenAllWhitelistURLsInWebView" value="false" />
    <preference name="BackupWebStorage" value="cloud" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
    <access origin="*.googleapis.com"/>
    <access origin="*.gstatic.com"/>
    <access origin="*.s3.amazonaws.com"/>
</widget>


问:
How to resolve a undefined offset: 1 error php
I have the following code that uses regular expression to do some matching and  I think should be working. But I am getting an undefined offset error which I can't fix. Can I have some help understanding why and how to fix the issue? I think the issue might have to with the $match but i'm not sure.</p>

```<code>$states = "Mississippi Alabama Texas Massachusetts Kansas";
$statesArray = array();

if(preg_match( '/xas$/', $states,$match )){
 $statesArray[0] = $match[ 1 ];
}

if(preg_match('/^k.*s$/i', $states,$match )){
 $statesArray[1] = $match[ 1 ];
}

if(preg_match('/^M.*s$/', $states,$match )){
  $statesArray[2] = $match[ 1 ];
}

if(preg_match('/a$/', $states,$match )){
 $statesArray[3] = $match[ 1 ];
}

if(preg_match('/^M/', $states,$match )){
 $statesArray[4] = $match[ 1 ];
}

foreach ( $statesArray as $element => $value )
   print( "$value <br />");
</code>```

答:
You code is working fine under php 7.0, but I think you'd better write such code like this below for better maintainability:</p>

```<code><?php
$states = "Mississippi Alabama Texas Massachusetts Kansas";
$statesArray = array();

$i=0;
if(preg_match( '/xas$/', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^k.*s$/i', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^M.*s$/', $states,$match )){
      $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/a$/', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^M/', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

foreach ( $statesArray as $element => $value )
       print( "$value <br />");
</code>```

Body:
I have the following code that uses regular expression to do some matching and  I think should be working. But I am getting an undefined offset error which I can't fix. Can I have some help understanding why and how to fix the issue? I think the issue might have to with the $match but i'm not sure.

$states = "Mississippi Alabama Texas Massachusetts Kansas";
$statesArray = array();

if(preg_match( '/xas$/', $states,$match )){
 $statesArray[0] = $match[ 1 ];
}

if(preg_match('/^k.*s$/i', $states,$match )){
 $statesArray[1] = $match[ 1 ];
}

if(preg_match('/^M.*s$/', $states,$match )){
  $statesArray[2] = $match[ 1 ];
}

if(preg_match('/a$/', $states,$match )){
 $statesArray[3] = $match[ 1 ];
}

if(preg_match('/^M/', $states,$match )){
 $statesArray[4] = $match[ 1 ];
}

foreach ( $statesArray as $element => $value )
   print( "$value
");

Body:
You code is working fine under php 7.0, but I think you'd better write such code like this below for better maintainability:

<?php
$states = "Mississippi Alabama Texas Massachusetts Kansas";
$statesArray = array();

$i=0;
if(preg_match( '/xas$/', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^k.*s$/i', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^M.*s$/', $states,$match )){
      $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/a$/', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^M/', $states,$match )){
     $statesArray[$i++] = $match[ 0 ];
}

foreach ( $statesArray as $element => $value )
       print( "$value <br />");


问:
How to convert normal string to datetime in Pandas
I have normal strings with more than millions data points from .csv file with format as below:

```<code>Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00
</code>```

I loaded into pandas and tried to converted into datetime format by using pandas.to_datetime(df['Datetime']). However, the new time series data I got that is not correct. There are some new Datetime produced during converting process. For example, 2016-12-11 23:30:00 that does not contain in original data.

Body:
I have normal strings with more than millions data points from .csv file with format as below:

Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00

I loaded into pandas and tried to converted into datetime format by using pandas.to_datetime(df['Datetime']). However, the new time series data I got that is not correct. There are some new Datetime produced during converting process. For example, 2016-12-11 23:30:00 that does not contain in original data.

Body:
You want to use the option dayfirst=True

pd.to_datetime(df.Datetime, dayfirst=True)

This:

Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00
11/12/2015  23:30:00

Gets converted to

0   2015-12-22 17:00:00
1   2015-12-22 18:00:00
2   2015-12-11 23:30:00
Name: Datetime, dtype: datetime64[ns]


问:
Log to both Xcode console and file
I'm trying to get my logs to both Xcode console and a file with Swift. Solutions I found are either console or redirect to file only.

How can I get the log goes to both?

Note: Some logs are from other 3rd libraries and frameworks in my app, not just Swift's print(). So using macro or logging framework like CocoaLumberjack on the app won't help.

e.g. This will redirect all the log in the console to file when called, the console then becomes empty

```<code>  func logToFile() {
    var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "app_log.txt"
    let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)

    freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stderr)
    freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stdin)
    freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stdout)
  }
</code>```

答:
I have extended your method a bit, now you would write a given string to an output file and also log it to the console.

I like to have another functions, which takes care of the given string, to use Parameters like

```<code>__FILE__ - String - The name of the file in which it appears.
__LINE__ - Int - The line number on which it appears.
__COLUMN__ - Int - The column number in which it begins.
__FUNCTION__ - String - The name of the declaration in which it appears.
</code>```

Your extended method could now look like the following.

```<code>func logToFile(message: String) -> Void {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0]
        let fileName = "app_log.txt"
        let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)

        let fileUrl = URL(fileURLWithPath: logFilePath)
        var error:NSError?

        // simply create the file, here you could add first line or something
        // just make sure it exists
        if (!FileManager.default.fileExists(atPath: logFilePath)) {
            let data = new Data();
            do {
                try data.write(to:fileUrl , options: .atomic)
            } catch {
                println("Can't create file \(error)")
            }
        }

        // start writing
        if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {

            let data = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
            fileHandle.seekToEndOfFile()
            fileHandle.writeData(data)
            fileHandle.closeFile()
        }
        else {

        }

        // Now also print the result to console
        print(message)
    }
</code>```

Title: Log to both Xcode console and file

Body:
I'm trying to get my logs to both Xcode console and a file with Swift. Solutions I found are either console or redirect to file only.

How can I get the log goes to both?

Note: Some logs are from other 3rd libraries and frameworks in my app, not just Swift's print(). So using macro or logging framework like CocoaLumberjack on the app won't help.

e.g. This will redirect all the log in the console to file when called, the console then becomes empty

  func logToFile() {
    var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "app_log.txt"
    let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)

    freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stderr)
    freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stdin)
    freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stdout)
  }

Body:
I have extended your method a bit, now you would write a given string to an output file and also log it to the console.

I like to have another functions, which takes care of the given string, to use Parameters like

__FILE__ - String - The name of the file in which it appears.
__LINE__ - Int - The line number on which it appears.
__COLUMN__ - Int - The column number in which it begins.
__FUNCTION__ - String - The name of the declaration in which it appears.

Your extended method could now look like the following.

func logToFile(message: String) -> Void {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0]
        let fileName = "app_log.txt"
        let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)

        let fileUrl = URL(fileURLWithPath: logFilePath)
        var error:NSError?

        // simply create the file, here you could add first line or something
        // just make sure it exists
        if (!FileManager.default.fileExists(atPath: logFilePath)) {
            let data = new Data();
            do {
                try data.write(to:fileUrl , options: .atomic)
            } catch {
                println("Can't create file \(error)")
            }
        }

        // start writing
        if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {

            let data = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
            fileHandle.seekToEndOfFile()
            fileHandle.writeData(data)
            fileHandle.closeFile()
        }
        else {

        }

        // Now also print the result to console
        print(message)
    }


问:
react - how to correctly use event.preventDefault? Should it be used on <button> onClick?
I'm confused after reading the documentation for both react and some HTML stuff about how on click event handling should work.

For buttons, for example a button that onClick will dispatch an action to submit a form, is a preventDefault necessary?

Thanks

答:
e.preventDefault is used when you want to stop actual action of thing.

Eg: Form submission
You want to work on that so use e.preventDefault and form will not submit as if it automatically submit with submit button then data will go in url which you do not want.

Also for checking validation during form submission.


问:
Create a vb class using a text file. The values for class name and attributes should come from database
I want to create an executable that will use a text file as a template and create a class in vb.net
The class name and its attributes are stored in the database. The user should be able to input the class name. The ClassName and AttributeName tags in the template are to be replaced by the corresponding values from the database.
Any lead would be appreciated. Thank You.</p>

答:
Code files are just text files. Generating code files is a bit confusing because you have source code appearing as string literals, but in a technical sense it isn't very difficult:</p>

```<code>  Sub GenerateCode()
    Dim dtb As New DataTable
    dtb.Columns.Add("ClassName")
    dtb.Columns.Add("PropertyName")
    dtb.Columns.Add("PropertyType")
    'NOTE: datatable must be sorted by ClassName
    dtb.Rows.Add("ClassOne", "PropertyOne", "String")
    dtb.Rows.Add("ClassOne", "PropertyTwo", "Integer")
    dtb.Rows.Add("ClassOne", "PropertyThree", "String")
    dtb.Rows.Add("ClassTwo", "AnotherPropertyOne", "String")
    dtb.Rows.Add("ClassTwo", "AnotherPropertyTwo", "Integer")
    dtb.Rows.Add("ClassTwo", "AnotherPropertyThree", "String")

    Dim strFilename As String = ""
    Dim strParentFolder As String = "C:\Junk"
    If Not System.IO.Directory.Exists(strParentFolder) Then
      System.IO.Directory.CreateDirectory(strParentFolder)
    End If
    Dim strPreviousClassName As String = ""
    Dim sb As New System.Text.StringBuilder
    For Each drwProperty As DataRow In dtb.Rows
      Dim strThisClassName As String = drwProperty("ClassName").ToString
      If strThisClassName <> strPreviousClassName Then
        'class name has changed
        If strPreviousClassName > "" Then
          'write previous class
          sb.AppendLine("End Class")
          strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
          My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
        End If
        'start new class
        sb = New System.Text.StringBuilder
        sb.AppendLine("Class " & strThisClassName)
        strPreviousClassName = strThisClassName
      End If
      'append property
      sb.AppendLine("  Property " & drwProperty("PropertyName").ToString & " As " & drwProperty("PropertyType").ToString)
    Next drwProperty
    'Write last class
    sb.AppendLine("End Class")
    strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
    My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
  End Sub
</code>```

Body:
Code files are just text files. Generating code files is a bit confusing because you have source code appearing as string literals, but in a technical sense it isn't very difficult:

  Sub GenerateCode()
    Dim dtb As New DataTable
    dtb.Columns.Add("ClassName")
    dtb.Columns.Add("PropertyName")
    dtb.Columns.Add("PropertyType")
    'NOTE: datatable must be sorted by ClassName
    dtb.Rows.Add("ClassOne", "PropertyOne", "String")
    dtb.Rows.Add("ClassOne", "PropertyTwo", "Integer")
    dtb.Rows.Add("ClassOne", "PropertyThree", "String")
    dtb.Rows.Add("ClassTwo", "AnotherPropertyOne", "String")
    dtb.Rows.Add("ClassTwo", "AnotherPropertyTwo", "Integer")
    dtb.Rows.Add("ClassTwo", "AnotherPropertyThree", "String")

    Dim strFilename As String = ""
    Dim strParentFolder As String = "C:\Junk"
    If Not System.IO.Directory.Exists(strParentFolder) Then
      System.IO.Directory.CreateDirectory(strParentFolder)
    End If
    Dim strPreviousClassName As String = ""
    Dim sb As New System.Text.StringBuilder
    For Each drwProperty As DataRow In dtb.Rows
      Dim strThisClassName As String = drwProperty("ClassName").ToString
      If strThisClassName <> strPreviousClassName Then
        'class name has changed
        If strPreviousClassName > "" Then
          'write previous class
          sb.AppendLine("End Class")
          strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
          My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
        End If
        'start new class
        sb = New System.Text.StringBuilder
        sb.AppendLine("Class " & strThisClassName)
        strPreviousClassName = strThisClassName
      End If
      'append property
      sb.AppendLine("  Property " & drwProperty("PropertyName").ToString & " As " & drwProperty("PropertyType").ToString)
    Next drwProperty
    'Write last class
    sb.AppendLine("End Class")
    strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
    My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
  End Sub


问:
Using library JasperReport Version 6.3 for Java
I need to use JasperReport. I had used IReport5.5 some time ago, but now with Java 8 iReport does not run. Instead, I installed JasperSoftStudio 6.3.1 to design my jrxml files.

The Problem is that before I used the jasperreport 5.2 that accept very well for the java code:

```<code>import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import net.sf.jasperreports.engine.JasperCompileManager;

public class Main {

    public static void main(String[] argv) throws Exception {

        Class.forName("org.postgresql.Driver");
        Connection conexion = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/database", "postgres",
                "password");

        JasperCompileManager.compileReportToFile(
                "input.jrxml",
                "input.jasper");

        JasperReport reporte = (JasperReport) JRLoader.loadObject("input.jasper");
        JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion);

        JRExporter exporter = new JRPdfExporter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File("output.pdf"));
        exporter.exportReport();

    }
}
</code>```

However, designing my reports with JasperSoftStudio the old version of jasperreport 5.2 does not accept it. I update my jasperversion to 6.3.0 from https://sourceforge.net/projects/jasperreports/files/jasperreports/  but now the function loadObject is deprecated. Searching a posible solution a found in http://amanuva.blogspot.cl/2016/10/060-conexion-con-informes-desde-java.html the following way

```<code>import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

public class JavaMainClass {
    public static void main(String[] argv) throws Exception {
        Class.forName("org.postgresql.Driver");
        Connection conexion = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/database", "postgres",
                "password");

        JasperReport jasperReport = JasperCompileManager.compileReport("input.jrxml");
        JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport("input.jasper", null, conexion);
        JasperExportManager.exportReportToPdfFile(jprint, "output.pdf");

    }
}
</code>```

But, I get this error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at net.sf.jasperreports.engine.util.JRLoader.<clinit>(JRLoader.java:81)
    at net.sf.jasperreports.engine.JRPropertiesUtil.loadProperties(JRPropertiesUtil.java:102)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.initProperties(DefaultJasperReportsContext.java:99)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.<init>(DefaultJasperReportsContext.java:76)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.<clinit>(DefaultJasperReportsContext.java:59)
    at net.sf.jasperreports.engine.JasperCompileManager.getDefaultInstance(JasperCompileManager.java:200)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:575)
    at JavaMainClass.main(JavaMainClass.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 13 more
</code>```

Any suggestion is welcome

答: You seem to be missing the Apache commons-logging library from your classpath. Are you using a dependency management tool like Maven? If not, it might be a good time to start... :)</p>

Body:
I need to use JasperReport. I had used IReport5.5 some time ago, but now with Java 8 iReport does not run. Instead, I installed JasperSoftStudio 6.3.1 to design my jrxml files.

The Problem is that before I used the jasperreport 5.2 that accept very well for the java code:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import net.sf.jasperreports.engine.JasperCompileManager;

public class Main {

    public static void main(String[] argv) throws Exception {

        Class.forName("org.postgresql.Driver");
        Connection conexion = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/database", "postgres",
                "password");

        JasperCompileManager.compileReportToFile(
                "input.jrxml",
                "input.jasper");

        JasperReport reporte = (JasperReport) JRLoader.loadObject("input.jasper");
        JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion);

        JRExporter exporter = new JRPdfExporter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File("output.pdf"));
        exporter.exportReport();

    }
}

However, designing my reports with JasperSoftStudio the old version of jasperreport 5.2 does not accept it. I update my jasperversion to 6.3.0 from https://sourceforge.net/projects/jasperreports/files/jasperreports/  but now the function loadObject is deprecated. Searching a posible solution a found in http://amanuva.blogspot.cl/2016/10/060-conexion-con-informes-desde-java.html the following way

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

public class JavaMainClass {
    public static void main(String[] argv) throws Exception {
        Class.forName("org.postgresql.Driver");
        Connection conexion = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/database", "postgres",
                "password");

        JasperReport jasperReport = JasperCompileManager.compileReport("input.jrxml");
        JasperPrint jprint = (JasperPrint) JasperFillManager.fillReport("input.jasper", null, conexion);
        JasperExportManager.exportReportToPdfFile(jprint, "output.pdf");

    }
}

But, I get this error

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at net.sf.jasperreports.engine.util.JRLoader.<clinit>(JRLoader.java:81)
    at net.sf.jasperreports.engine.JRPropertiesUtil.loadProperties(JRPropertiesUtil.java:102)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.initProperties(DefaultJasperReportsContext.java:99)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.<init>(DefaultJasperReportsContext.java:76)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.<clinit>(DefaultJasperReportsContext.java:59)
    at net.sf.jasperreports.engine.JasperCompileManager.getDefaultInstance(JasperCompileManager.java:200)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:575)
    at JavaMainClass.main(JavaMainClass.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 13 more

Any suggestion is welcome


问:
Comments on Overridden method in Java
Should we comment the overridden method or not? If yes, then whether the comment will be a Java Doc or simple comment?</p>

答:
From How to Write Doc Comments for the Javadoc Tool:

Automatic re-use of method comments

You can avoid re-typing doc comments
  by being aware of how the Javadoc tool
  duplicates (inherits) comments for
  methods that override or implement
  other methods. This occurs in three
  cases: When a method in a class
  overrides a method in a superclass
  When a method in an interface
  overrides a method in a superinterface
  When a method in a class implements a
  method in an interface In the first
  two cases, if a method m() overrides
  another method, The Javadoc tool will
  generate a subheading "Overrides" in
  the documentation for m(), with a link
  to the method it is overriding.

In the third case, if a method m() in
  a given class implements a method in
  an interface, the Javadoc tool will
  generate a subheading "Specified by"
  in the documentation for m(), with a
  link to the method it is implementing.

In all three of these cases, if the
  method m() contains no doc comments or
  tags, the Javadoc tool will also copy
  the text of the method it is
  overriding or implementing to the
  generated documentation for m(). So if
  the documentation of the overridden or
  implemented method is sufficient, you
  do not need to add documentation for
  m(). If you add any documentation
  comment or tag to m(), the "Overrides"
  or "Specified by" subheading and link
  will still appear, but no text will be
  copied.

Title: Comments on Overridden method in Java

ContentLicense: CC BY-SA 2.5


问:
how to check If checkbox is checked or not laravel 5.4
I want to show a button if checkbox gets checked and if not checked button will not appear in laravel 5.4. How can I do this. </p>

答:
Suppose you html

```<code><input type="checkbox" name="checkbox" id="checkbox">
</code>```

In front-end you can check using jQuery

```<code>if ($('#checkbox').is(':checked')){
   //
}
</code>```

In back-end you can check using:

```<code>if (isset($request->checkbox) {
     //
}
</code>```

Body:
Suppose you html

<input type="checkbox" name="checkbox" id="checkbox">

In front-end you can check using jQuery

if ($('#checkbox').is(':checked')){
   //
}

In back-end you can check using:

if (isset($request->checkbox) {
     //
}


答:
The event.preventDefault() method stops the default action of an element from happening.

In your case, prevent a submit button from submitting a form.
Another example - prevent a link from following the URL.

So it is preferred to use it on onClick method. It'll stop a form from automatically submitting the form.

Title: react - how to correctly use event.preventDefault? Should it be used on <button> onClick?

Body:
I'm confused after reading the documentation for both react and some HTML stuff about how on click event handling should work.

For buttons, for example a button that onClick will dispatch an action to submit a form, is a preventDefault necessary?

Thanks


问:
Joomla 3.x get params from style sheet to custom article layout
I have started a new project using Joomla 3.6 but I am stuck with this problem.
I have added some feilds in template style layout.
I retrived in template index.php using

```<code>$logo           = $this->params->get('logo');
$navposition    = $this->params->get('navposition');
$headerImage    = $this->params->get('headerImage');
</code>```

but I didn't get that in newly created custom article alternative layout.
How do I call this in the custom layout?

答:
You cannot use the same method to retrieve template params from anywhere. To do that you can use this method</p>

```<code>$app        = JFactory::getApplication();//Initiate the Application class
$template   = $app->getTemplate(true);//get the current template
$params     = $template->params;// get the template params
//Retrieve the variables using $params
$logo           = $params->get('logo');
$navposition    = $params->get('navposition');
$headerImage    = $params->get('headerImage');
</code>```

Body:
I have started a new project using Joomla 3.6 but I am stuck with this problem.
I have added some feilds in template style layout.
I retrived in template index.php using

$logo           = $this->params->get('logo');
$navposition    = $this->params->get('navposition');
$headerImage    = $this->params->get('headerImage');

but I didn't get that in newly created custom article alternative layout.
How do I call this in the custom layout?

Body:
You cannot use the same method to retrieve template params from anywhere. To do that you can use this method

$app        = JFactory::getApplication();//Initiate the Application class
$template   = $app->getTemplate(true);//get the current template
$params     = $template->params;// get the template params
//Retrieve the variables using $params
$logo           = $params->get('logo');
$navposition    = $params->get('navposition');
$headerImage    = $params->get('headerImage');


问:
whay we need root url
I am little confuse about root url as people make it by $_server['server_name'] etc.So I just want to know that how to make baseurl in our config php file that work on both server and local side and also how link external file like css,js,images in website. </p>

答:
This will be in your config file.

```<code>public function base_url(){

    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://'. $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
    return $base_url;
}
</code>```

In your view you can simply use

```<code>echo base_url().'images/abc.jpg';
</code>```

Title: whay we need root url

Body:
This will be in your config file.

public function base_url(){

    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://'. $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
    return $base_url;
}

In your view you can simply use

echo base_url().'images/abc.jpg';


问:
How do I disable END blocks in child processes?
I frequently use fork in programs that also have END { ... } blocks:

```<code>...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}
</code>```

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

```<code>END { unless (i_am_a_child_process()) { &some_cleanup_code } }
</code>```

?

答:
In a manner of speaking, the customary way to avoid them in forked children is with something like:

```<code>exec "true";
</code>```

Or, should you find that too untrustworthy, these all work and are even use use strict compliant:

```<code>exec    $^X =>  -eexit;

exec ~~echo => ~~-echo;

exec ~~echo => !!-echo;
</code>```

and the onomatopoetic

```<code>exec reverse reverse echo => ~~-echo;
</code>```

Rebmemer- In Perl, there are no silly questions, but there may be silly answers… ☺

```<code>$ perl -Mstrict '-leprint ucfirst lc reverse-Remember'
</code>```

Body:
I frequently use fork in programs that also have END { ... } blocks:

...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

END { unless (i_am_a_child_process()) { &some_cleanup_code } }

?

Body:
In a manner of speaking, the customary way to avoid them in forked children is with something like:

exec "true";

Or, should you find that too untrustworthy, these all work and are even use use strict compliant:

exec    $^X =>  -eexit;

exec ~~echo => ~~-echo;

exec ~~echo => !!-echo;

and the onomatopoetic

exec reverse reverse echo => ~~-echo;

Rebmemer- In Perl, there are no silly questions, but there may be silly answers… ☺

$ perl -Mstrict '-leprint ucfirst lc reverse-Remember'


问:
A better way to access n-d array element with a 1-d index array in C++?
Recently, I'm doing something about C++ pointers, I got this question when I want to access elements in multi-dimensional array with a 1-dimensional array which contains index.

Say I have a array arr, which is a 4-dimensional array with all elements set to 0 except for arr[1][2][3][4] is 1, and a array idx which contains index in every dimension for arr, I can access this element by using arr[idx[0]][idx[1]][idx[2]][idx[3]], or by using *(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3]).

The question comes with when n is large, this would be not so good, so I wonder if there is a better way to work with multi-dimensional accessing?

```<code>#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;
    return 0;
}
</code>```

output

```<code>Expected: 1 at 0x7fff54c61f28
Got with ****: 1
</code>```

答:
I figured out a way to solve this myself.

The idea is that use void * pointers, we know that every memory cell holds value or an address of a memory cell, so we can directly compute the offset of the target to the base address.

In this case, we use void *p = arr to get the base address of the n-d array, and then loop over the array idx, to calculate the offset.

For arr[10][10][10][10], the offset between arr[0] and arr[1] is 10 * 10 * 10 * sizeof(int), since arr is 4-d, arr[0] and arr[1] is 3-d, so there is 10 * 10 * 10 = 1000 elements between arr[0] and arr[1], after that, we should know that the offset between two void * adjacent addresses is 1 byte, so we should multiply sizeof(int) to get the correct offset, according to this, we finally get the exact address of the memory cell we want to access.

Finally, we have to cast void * pointer to int * pointer and access the address to get the correct int value, that's it!

With void *(not so good)

```<code>#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;

    void *p = arr;
    for(int i = 0; i < 4; i++)
        p += idx[i] * int(pow(10, 3-i)) * sizeof(int);
    cout<<"Got with void *:";
    cout<<*((int*)p)<<" at "<<p<<endl;

    return 0;
}
</code>```

Output

```<code>Expected: 1 at 0x7fff5e3a3f18
Got with ****: 1
Got with void *:1 at 0x7fff5e3a3f18
</code>```

Notice:
There is a warning when compiling it, but I choose to ignore it.

```<code>test.cpp: In function 'int main()':
test.cpp:23:53: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
         p += idx[i] * int(pow(10, 3-i)) * sizeof(int);
</code>```

Use char * instead of void *(better)

Since we want to manipulate pointer byte by byte, it would be better to use char * to replace void *.

```<code>#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;

    char *p = (char *)arr;
    for(int i = 0; i < 4; i++)
        p += idx[i] * int(pow(10, 3-i)) * sizeof(int);
    cout<<"Got with char *:";
    cout<<*((int*)p)<<" at "<<(void *)p<<endl;

    return 0;
}
</code>```

Output

```<code>Expected: 1 at 0x7fff4ffd7f18
Got with char *:1 at 0x7fff4ffd7f18
</code>```

With int *(In this specific case)

I have been told it's not a good practice for void * used in arithmetic, it would be better to use int *, so I cast arr into int * pointer and also replace pow.

```<code>#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;
    int *p = (int *)arr;
    int offset = 1e3;
    for(int i = 0; i < 4; i++)
    {
        p += idx[i] * offset;
        offset /= 10;
    }
    cout<<"Got with int *:";
    cout<<*p<<" at "<<p<<endl;

    return 0;
}
</code>```

Output

```<code>Expected: 1 at 0x7fff5eaf9f08
Got with ****: 1
Got with int *:1 at 0x7fff5eaf9f08
</code>```

Body:
Recently, I'm doing something about C++ pointers, I got this question when I want to access elements in multi-dimensional array with a 1-dimensional array which contains index.

Say I have a array arr, which is a 4-dimensional array with all elements set to 0 except for arr[1][2][3][4] is 1, and a array idx which contains index in every dimension for arr, I can access this element by using arr[idx[0]][idx[1]][idx[2]][idx[3]], or by using *(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3]).

The question comes with when n is large, this would be not so good, so I wonder if there is a better way to work with multi-dimensional accessing?

#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;
    return 0;
}

output

Expected: 1 at 0x7fff54c61f28
Got with ****: 1

Body:
I figured out a way to solve this myself.

The idea is that use void * pointers, we know that every memory cell holds value or an address of a memory cell, so we can directly compute the offset of the target to the base address.

In this case, we use void *p = arr to get the base address of the n-d array, and then loop over the array idx, to calculate the offset.

For arr[10][10][10][10], the offset between arr[0] and arr[1] is 10 * 10 * 10 * sizeof(int), since arr is 4-d, arr[0] and arr[1] is 3-d, so there is 10 * 10 * 10 = 1000 elements between arr[0] and arr[1], after that, we should know that the offset between two void * adjacent addresses is 1 byte, so we should multiply sizeof(int) to get the correct offset, according to this, we finally get the exact address of the memory cell we want to access.

Finally, we have to cast void * pointer to int * pointer and access the address to get the correct int value, that's it!

With void *(not so good)

#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;

    void *p = arr;
    for(int i = 0; i < 4; i++)
        p += idx[i] * int(pow(10, 3-i)) * sizeof(int);
    cout<<"Got with void *:";
    cout<<*((int*)p)<<" at "<<p<<endl;

    return 0;
}

Output

Expected: 1 at 0x7fff5e3a3f18
Got with ****: 1
Got with void *:1 at 0x7fff5e3a3f18

Notice:
There is a warning when compiling it, but I choose to ignore it.

test.cpp: In function 'int main()':
test.cpp:23:53: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
         p += idx[i] * int(pow(10, 3-i)) * sizeof(int);

Use char * instead of void *(better)

Since we want to manipulate pointer byte by byte, it would be better to use char * to replace void *.

#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;

    char *p = (char *)arr;
    for(int i = 0; i < 4; i++)
        p += idx[i] * int(pow(10, 3-i)) * sizeof(int);
    cout<<"Got with char *:";
    cout<<*((int*)p)<<" at "<<(void *)p<<endl;

    return 0;
}

Output

Expected: 1 at 0x7fff4ffd7f18
Got with char *:1 at 0x7fff4ffd7f18

With int *(In this specific case)

I have been told it's not a good practice for void * used in arithmetic, it would be better to use int *, so I cast arr into int * pointer and also replace pow.

#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;
    int *p = (int *)arr;
    int offset = 1e3;
    for(int i = 0; i < 4; i++)
    {
        p += idx[i] * offset;
        offset /= 10;
    }
    cout<<"Got with int *:";
    cout<<*p<<" at "<<p<<endl;

    return 0;
}

Output

Expected: 1 at 0x7fff5eaf9f08
Got with ****: 1
Got with int *:1 at 0x7fff5eaf9f08


问:
After exclude module 'answer-shim' in the android gradle for io.branch.sdk couldn't build with proguard
When try to build the release build with proguard enable getting below warning and couldn't build the APK successfully.</p>

```<code>Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:there were 14 unresolved references to classes or interfaces.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: Please correct the above warnings first.
</code>```

答:
add
-dontwarn com.crashlytics.android.answers.shim.**

to the proguard file

Body:
When try to build the release build with proguard enable getting below warning and couldn't build the APK successfully.

Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:there were 14 unresolved references to classes or interfaces.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: Please correct the above warnings first.


问:
What algorithm to use for getting a sub CIDR from a base CIDR?
I have a VPC and let's say its CIDR block is 10.0.0.0/16. And I have a couple of random subnets in that VPC. Their CIDRs could be something like 10.0.128.0/19, 10.0.32.0/19, 10.0.208.0/22. CIDR blocks for subnets must be covered by the CIDR block of the VPC. Also, no overlap of CIDRs among subnets is allowed.

My question is:
Given such a VPC and subnets, how to find a good CIDR block with specific size for a new subnets I want to create(let's say /22). The good, from my point of view, means better using of space. Let's say if I just want a small CIDR block, it shouldn't return me a CIDR right in the middle of the VPC CIDR, which prevent potential big CIDR block being placed in the future. Other definitions of good are welcomed. There is no guarantee for any initial states.

I don't know if there is a standard algorithm for such problem. What I am currently thinking of is making use of a binary tree. The left child means 0 while right child means 1. All leaves represent CIDR blocks that are in used. To get a new CIDR block, the problem is basically creating a leave at some level depends on the desired size of the block. How to create a good leaves I still don't know yet.

BTW, I am writing Java code. I couldn't find a library for this. If there is an existing library, please also let me know!

答:
I think if you can find Knuth's description of https://en.wikipedia.org/wiki/Buddy_memory_allocation (in "The Art of Computer Programming" Volume I) you will see various properties proved about it, and some of them might apply to the sort of tree-based allocator you are thinking about, which I think would boil down to something like this.

Keep track of the available address ranges as a set of blocks whose size is a power of two, aligned on a multiple of that power of two. If you ever have two blocks which can be merged to produce a legal block of the next largest size, you should do this.

When asked for a block of address space, allocate it from the smallest possible block in your set, and allocate a block whose size is a power of two. If you have space left over after the allocation, turn it into address-aligned power of two size blocks.

If a block of previously allocated address space is returned to you, add it to your set of blocks of size a power of two, merging it if possible with its neighbour block (its buddy).


问:
How Pass parameters and access them in javascript
```<code><html>
<body>
<form action="">
<script>
 for(i=0;i<50;i++)
 {
  document.writeln("<input type='button' value ='"+i+"'        onclick='clicked(i)'/>");

 }
function clicked(Number x)
{
 alert("selected:" +x);
}
</script>
</form>
</body>
</html>
</code>```

I want to know which button is selected in this code how to perform that please can someone help me

答:
You can just do the same in this method:

for (i = 0; i < 10; i++) {
  document.writeln("<input type='button' value='" + i + "' onclick='alert(this.value)'>");
}```

Body:
<form action="">

</form>

I want to know which button is selected in this code how to perform that please can someone help me


问:
Extracting nested values in a Javascript object
I have the following object:

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];
</code>```

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

```<code>[ '89304', '102524', '9' ]
</code>```

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

答:
Retrieving Values by < Key/Type >

Setup

One helper function:

.flatten(), flattens the array from multi-dimensions to only one

Two different method of retrieving values:

.search(), retrieves all values that match a certain key

.scalars(), retrieve all scalar values

Note: It's generally a bad idea to prototype the built-in objects.  It is done in the following for distinction (array vs object association) as well as for readability and simplicity, but heed this warning.

Example

(function() {
  "use strict";

  // Makes multi-dimensional array, one-dimensional
  Array.prototype.flatten = function() {
    return this.reduce((acc, val) => {
      return acc.concat(
        Array.isArray(val) ? val.flatten() : val
      )
    }, []);
  };

  // Iterate over keys and values
  // Return value that matches search_key if not an object
  Object.prototype.search = function(search_key) {
    var obj = this;

    var vals = Object.keys(obj).map(key => {
      if (typeof obj[key] === 'object' && obj[key] !== null)
        return obj[key].search(search_key);
      else if (search_key === key)
        return obj[key];
    });
    return vals.filter(val => (val !== undefined));
  };

  // Iterate over keys and values
  // Return scalars
  Object.prototype.scalars = function() {
    var obj = this;

    var vals = Object.keys(obj).reduce((acc, key) => {
      if (typeof obj[key] !== 'object')
        acc[acc.length] = obj[key];
      else if (obj[key] !== null)
        acc[acc.length] = obj[key].scalars();
      return acc;
    }, []);
    return vals.filter(val => (val !== undefined));
  };

  // Dataset
  var result = [{
    "id": 89304,
    "employeeDetails": {
      "id": 102524,
      "version": 9
    }
  }];

  // Test 1: values of a key
  console.log(
    "obj.search('id'):",
    result.map(obj => {
      return obj.search('id')
    }).flatten()
  );

  // Test 2: all scalar values
  console.log(
    "obj.scalars():",
    result.map(obj => {
      return obj.scalars()
    }).flatten()
  );

}());```

Explanation

Both examples are recursive calls.  One method evaluates the key, returning the value when it equals the search key.  The other method evaluates the type and returns a value if it is not an object (it's a scalar).

Because map() is used, there is the possibility for undefined values.  This is why filter() is called, in order to filter out those values.  What's returned by the search functions is an array (potentially an array-of-arrays), which is why flatten() is called, to ensure it is a one-dimentional array.

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

Body:
Retrieving Values by < Key/Type >

Setup

One helper function:

.flatten(), flattens the array from multi-dimensions to only one

Two different method of retrieving values:

.search(), retrieves all values that match a certain key

.scalars(), retrieve all scalar values

Note: It's generally a bad idea to prototype the built-in objects.  It is done in the following for distinction (array vs object association) as well as for readability and simplicity, but heed this warning.

Example

(function() {
  "use strict";

  // Makes multi-dimensional array, one-dimensional
  Array.prototype.flatten = function() {
    return this.reduce((acc, val) => {
      return acc.concat(
        Array.isArray(val) ? val.flatten() : val
      )
    }, []);
  };

  // Iterate over keys and values
  // Return value that matches search_key if not an object
  Object.prototype.search = function(search_key) {
    var obj = this;

    var vals = Object.keys(obj).map(key => {
      if (typeof obj[key] === 'object' && obj[key] !== null)
        return obj[key].search(search_key);
      else if (search_key === key)
        return obj[key];
    });
    return vals.filter(val => (val !== undefined));
  };

  // Iterate over keys and values
  // Return scalars
  Object.prototype.scalars = function() {
    var obj = this;

    var vals = Object.keys(obj).reduce((acc, key) => {
      if (typeof obj[key] !== 'object')
        acc[acc.length] = obj[key];
      else if (obj[key] !== null)
        acc[acc.length] = obj[key].scalars();
      return acc;
    }, []);
    return vals.filter(val => (val !== undefined));
  };

  // Dataset
  var result = [{
    "id": 89304,
    "employeeDetails": {
      "id": 102524,
      "version": 9
    }
  }];

  // Test 1: values of a key
  console.log(
    "obj.search('id'):",
    result.map(obj => {
      return obj.search('id')
    }).flatten()
  );

  // Test 2: all scalar values
  console.log(
    "obj.scalars():",
    result.map(obj => {
      return obj.scalars()
    }).flatten()
  );

}());

Explanation

Both examples are recursive calls.  One method evaluates the key, returning the value when it equals the search key.  The other method evaluates the type and returns a value if it is not an object (it's a scalar).

Because map() is used, there is the possibility for undefined values.  This is why filter() is called, in order to filter out those values.  What's returned by the search functions is an array (potentially an array-of-arrays), which is why flatten() is called, to ensure it is a one-dimentional array.


问:
css position:fixed

```

I can add anything inside that div tag and it will rise above the top and stay fixed to the bottom left, but the javascript file will just stay where I've placed it within the webpage as if it can't be bothered to adhere to the .css rule.

I was wondering how I could get around this. Thank you for all your help.

答:
script tag not add in div mention bottom after footer try this one

div.fixed {
position: fixed;
bottom: 0;
height:50px; width:50px; background:#888;
left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fixed">
<h3> hii </h3>
</div>

<script src="http://my.gblearn.com/js/javascript.js"></script></code>```

Title: css position:fixed <script> tag within does not stay fixed

Body:
I'm having an issue trying to get a .js validation script to stay in a fixed location within a webpage.

My code for the css is:

div.fixed {
position: fixed;
bottom: 0;
left: 0;
}

HTML

I can add anything inside that div tag and it will rise above the top and stay fixed to the bottom left, but the javascript file will just stay where I've placed it within the webpage as if it can't be bothered to adhere to the .css rule.

I was wondering how I could get around this. Thank you for all your help.

Body:
script tag not add in div mention bottom after footer try this one

div.fixed {
position: fixed;
bottom: 0;
height:50px; width:50px; background:#888;
left: 0;
}

<div class="fixed">
<h3> hii </h3>
</div>

<script src="http://my.gblearn.com/js/javascript.js"></script>


问:
Forcing unaligned bitfield packing in MSVC
I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.

The struct seen below consists of three 15-bit numbers, one 2-bit number, and a 1-bit sign. 15+15+15+2+1 = 48, so in theory it should fit into six bytes, right?

```<code>struct S
{
  unsigned short a:15;
  unsigned short b:15;
  unsigned short c:15;
  unsigned short d:2;
  unsigned short e:1;
};
</code>```

However, compiling this on both GCC and MSVC results in sizeof(S) == 8. Thinking that this might have to do with alignment, I tried using #pragma pack(1) before the struct declaration, telling the compiler to back to byte, not int, boundaries. On GCC, this worked, resulting in sizeof(S) == 6.

However, on MSVC05, the sizeof still came out to 8, even with pack(1) set! After reading this other SO answer, I tried replacing unsigned short d with unsigned char and unsigned short e with bool. The result is sizeof(S) == 7!

I found that if I split d into two one-bit fields and wedged them in between the other members, the struct finally packed properly.

```<code>struct S
{
  unsigned short a:15;
  unsigned short dHi : 1;
  unsigned short b:15;
  unsigned short dLo : 1;
  unsigned short c:15;
  unsigned short e:1;
};

printf( "%d\n", sizeof(S) ); // "6"
</code>```

But having d split like that is cumbersome and causes trouble for me later on when I have to work on the struct.  Is there some way I can force MSVC to pack this struct into 6 bytes, exactly as GCC does?

答: It is implementation defined how fields will be placed in the structure. Visual Studio will fit consecutive bitfields into an underlying type, if it can, and waste the leftover space. (C++ Bit Fields in VS)</p>

Body:
I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.

The struct seen below consists of three 15-bit numbers, one 2-bit number, and a 1-bit sign. 15+15+15+2+1 = 48, so in theory it should fit into six bytes, right?

struct S
{
  unsigned short a:15;
  unsigned short b:15;
  unsigned short c:15;
  unsigned short d:2;
  unsigned short e:1;
};

However, compiling this on both GCC and MSVC results in sizeof(S) == 8. Thinking that this might have to do with alignment, I tried using #pragma pack(1) before the struct declaration, telling the compiler to back to byte, not int, boundaries. On GCC, this worked, resulting in sizeof(S) == 6.

However, on MSVC05, the sizeof still came out to 8, even with pack(1) set! After reading this other SO answer, I tried replacing unsigned short d with unsigned char and unsigned short e with bool. The result is sizeof(S) == 7!

I found that if I split d into two one-bit fields and wedged them in between the other members, the struct finally packed properly.

struct S
{
  unsigned short a:15;
  unsigned short dHi : 1;
  unsigned short b:15;
  unsigned short dLo : 1;
  unsigned short c:15;
  unsigned short e:1;
};

printf( "%d\n", sizeof(S) ); // "6"

But having d split like that is cumbersome and causes trouble for me later on when I have to work on the struct.  Is there some way I can force MSVC to pack this struct into 6 bytes, exactly as GCC does?


问:
Get data type of field in select statement in ORACLE
Can I get data types of each column I selected instead of the values, using a select statement?

FOR EXAMPLE:

```<code>SELECT a.name, a.surname, b.ordernum
FROM customer a
JOIN orders b
ON a.id = b.id
</code>```

and result should be like this

```<code>name    | NVARCHAR(100)
surname | NVARCHAR(100)
ordernum| INTEGER
</code>```

or it can be in row like this, it isn't important:

```<code>name           |   surname     |  ordernum
NVARCHAR(100)  | NVARCHAR(100) |   INTEGER
</code>```

Thanks

答:
I found a not-very-intuitive way to do this by using DUMP()

```<code>SELECT DUMP(A.NAME),
       DUMP(A.surname),
       DUMP(B.ordernum)
FROM   customer A
       JOIN orders B
         ON A.id = B.id
</code>```

It will return something like:

'Typ=1 Len=2: 0,48' for each column.

Type=1 means VARCHAR2/NVARCHAR2

Type=2 means NUMBER/FLOAT

Type=12 means DATE, etc.

You can refer to this oracle doc for information Datatype Code

or this for a simple mapping Oracle Type Code Mappings

Body:
Can I get data types of each column I selected instead of the values, using a select statement?

FOR EXAMPLE:

SELECT a.name, a.surname, b.ordernum
FROM customer a
JOIN orders b
ON a.id = b.id

and result should be like this

name    | NVARCHAR(100)
surname | NVARCHAR(100)
ordernum| INTEGER

or it can be in row like this, it isn't important:

name           |   surname     |  ordernum
NVARCHAR(100)  | NVARCHAR(100) |   INTEGER

Thanks

Body:
I found a not-very-intuitive way to do this by using DUMP()

SELECT DUMP(A.NAME),
       DUMP(A.surname),
       DUMP(B.ordernum)
FROM   customer A
       JOIN orders B
         ON A.id = B.id

It will return something like:

'Typ=1 Len=2: 0,48' for each column.

Type=1 means VARCHAR2/NVARCHAR2

Type=2 means NUMBER/FLOAT

Type=12 means DATE, etc.

You can refer to this oracle doc for information Datatype Code

or this for a simple mapping Oracle Type Code Mappings

ContentLicense: CC BY-SA 4.0


问:
How to remove character from last array element
I need to remove the last element comma in Javascript array

```<code>var arr =  ["AAA,","BBB,"];
</code>```

I need the result below

```<code>var arr =  ["AAA,","BBB"];
</code>```

Any help is appreciated...

答:
var arr =  ["AAA,","BBB,"];

arr[arr.length - 1] = arr[arr.length - 1].replace(',', '');

console.log(arr);```

Body:
I need to remove the last element comma in Javascript array

var arr =  ["AAA,","BBB,"];

I need the result below

var arr =  ["AAA,","BBB"];

Any help is appreciated...


问:
Javascript short circuiting in if statement
I am confused about the below if statement code. Not sure what it is exactly doing

```<code>if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
</code>```

Can someone please help me to understand this?

Is it a short-circuiting in if statement:
i.e

1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?

答:
In case of AND operator it evaluates the second expression only if the first one is true.

In your case,

```<code>if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
</code>```

can be interpreted as if(expr1 && expr2)
where expr1= this.props.filterURL and expr2 = nextProps.filterURL !== this.props.filterURL

for first expression expr1 it evaluates whether it is not null or undefined...

for the second expression expr2 nextProps.filterURL !== this.props.filterURL it checks both the value and data type. So for example if you have both value as same 1234 but for one it is of type String and for another it is for number, this condition would be true.

Body:
I am confused about the below if statement code. Not sure what it is exactly doing

if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}

Can someone please help me to understand this?

Is it a short-circuiting in if statement:
i.e

1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?

Body:
In case of AND operator it evaluates the second expression only if the first one is true.

In your case,

if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}

can be interpreted as if(expr1 && expr2)
where expr1= this.props.filterURL and expr2 = nextProps.filterURL !== this.props.filterURL

for first expression expr1 it evaluates whether it is not null or undefined...

for the second expression expr2 nextProps.filterURL !== this.props.filterURL it checks both the value and data type. So for example if you have both value as same 1234 but for one it is of type String and for another it is for number, this condition would be true.


问:
How to search for subarrays with a specific ids and generate a new array from their elements?
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

```<code>$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);
</code>```

And the output for the following is:

```<code>Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)
</code>```

Although what I'm trying to accomplish is:

```<code>Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

I tried the following:

```<code>function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}
</code>```

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

```<code>Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

答:
Try this one. </p>

```<code>function getFiles($productIDs, $urlIDs)
{
$newDara = [];
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
                $newData[] = $data;
            }
        }
    }
    return array($newData);
}
</code>```

Body:
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);

And the output for the following is:

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)

Although what I'm trying to accomplish is:

Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

I tried the following:

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

Body:
Try this one.

function getFiles($productIDs, $urlIDs)
{
$newDara = [];
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
                $newData[] = $data;
            }
        }
    }
    return array($newData);
}


问:
My device read Electroconductivity values like 478.1 but highchart always display it rounded. i got 478. how can i format my axis?
```<code>yAxis: {
    title: {
        text: 'Visits'
    },
     labels: {
        format: '{value:.2f}'
     },
    plotLines: [{
        value: 0,
        width: 1,
        color: '#808080'
    }]
}
</code>```

答:
Use Highcharts.numberFormat() . For example :

```<code>$("#container").highcharts({
    // ...
   yAxis: {
            labels: {
                    formatter: function () {
                        return Highcharts.numberFormat(this.value, 2);
                        //First parameter is the raw number to format and second parameter is the desired number of decimals.
                    }
              }
         }
});
</code>```

Hope this helps you. Please check out this sample fiddle : http://jsfiddle.net/wGLgE/2/

Body:
Use Highcharts.numberFormat() . For example :

$("#container").highcharts({
    // ...
   yAxis: {
            labels: {
                    formatter: function () {
                        return Highcharts.numberFormat(this.value, 2);
                        //First parameter is the raw number to format and second parameter is the desired number of decimals.
                    }
              }
         }
});

Hope this helps you. Please check out this sample fiddle : http://jsfiddle.net/wGLgE/2/


问:
Creating a grid from map model with obstacles
I have a simple tower defense map with the road is for the enemy (which is the player can't build the tower there), and the other is for the tower can build there and with any obstacles (trees, rocks, etc).. However, i am not sure on how to make a grid (probably 2x2) loop through the map size and with differentiate with "red" for the obstacles and the road (I am thinking on using the Layer Mask to achieve this), and "white" for the tower can build there.

My map is like below (the red color is for the obstacles and the road, and the green color is for the tower that can build)

Image:

But the problem is, I can't get it started and I am not sure where to start.

Create a grid (probably 2x2) loop through the map size.

Place a tower within the "white" color, and not "red" color.

Any idea on how to achieve this?

Your answer much appreciated.

Thanks

答:
It's not an easy task so I think you'd better use an existing grid generating and path-finding solution. I recommend Aron Granberg's A* Pathfinding Project.

It can create a grid from you map mesh and mark regions as red or obstacles.


问:
Get sunday date between two date and last day from one month mysql
I want to get all sunday date between two dates and get last day between two date, how can i do that in mysql?
Example :

```<code>start date | end date
2017-03-01 | 2017-03-31
</code>```

then the results are :

```<code>2017-03-05
2017-03-12
2017-03-19
2017-03-26
2017-03-31
</code>```

Start date and end date possible to change, please advise me.
Thank you

答:
Since you now mentioned that you don't have a table for the dates, you could approach it like this if you don't want to add a generic calendar table on your database.

```<code>declare @startdate datetime
declare @enddate datetime
DECLARE @startdateLoop datetime

select @startdate = CAST(start as DATE), @enddate = CAST(end_date as DATE) from #t
set @startdateLoop = @startdate
CREATE TABLE #tempCal
  (dates datetime)

  WHILE @startdateLoop != @enddate
  BEGIN
  INSERT INTO #tempCal
  SELECT @startdateLoop

  SET @startdateLoop = DATEADD(dd, 1, @startdateLoop)
  END

  SELECT * FROM #tempCal
  WHERE dates between @startdate and @enddate and DAYOFWEEK(dates) = 1
</code>```

You may turn this into a procedure if you want to.

Would still be nice if you DO HAVE a calendar table; as Tim has suggested.

Body:
I want to get all sunday date between two dates and get last day between two date, how can i do that in mysql?
Example :

start date | end date
2017-03-01 | 2017-03-31

then the results are :

2017-03-05
2017-03-12
2017-03-19
2017-03-26
2017-03-31

Start date and end date possible to change, please advise me.
Thank you

Body:
Since you now mentioned that you don't have a table for the dates, you could approach it like this if you don't want to add a generic calendar table on your database.

declare @startdate datetime
declare @enddate datetime
DECLARE @startdateLoop datetime

select @startdate = CAST(start as DATE), @enddate = CAST(end_date as DATE) from #t
set @startdateLoop = @startdate
CREATE TABLE #tempCal
  (dates datetime)

  WHILE @startdateLoop != @enddate
  BEGIN
  INSERT INTO #tempCal
  SELECT @startdateLoop

  SET @startdateLoop = DATEADD(dd, 1, @startdateLoop)
  END

  SELECT * FROM #tempCal
  WHERE dates between @startdate and @enddate and DAYOFWEEK(dates) = 1

You may turn this into a procedure if you want to.

Would still be nice if you DO HAVE a calendar table; as Tim has suggested.


问:
react - how to correctly use event.preventDefault? Should it be used on <button> onClick?
I'm confused after reading the documentation for both react and some HTML stuff about how on click event handling should work.

For buttons, for example a button that onClick will dispatch an action to submit a form, is a preventDefault necessary?

Thanks

答:
function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }```

preventDefault is not that much necessary
if you want then just make a function above add preventDefault in that and call that function in button OnClick

Body:
function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

preventDefault is not that much necessary
if you want then just make a function above add preventDefault in that and call that function in button OnClick


问:
DevExpress - Unable to Load Document Preview Control in WPF 16.2
I've added a DocumentPreviewControl as per the sample instructions for static report; however when I run our application It's crashed bug when I run the application from a client machine (not developer).
enter image description here

All dll Files are Attched in deployed exe

enter image description here

答:
Problem Solved by using This Method DevExpress-->All Platforme-->DevExpress Assembly Deployment Tool

*Chose Path

*Click Analyze

*Goto Path

*Copy all files and Replace them on Client Machine [installed directory]

(^_^)


答:
Simply use with replace()

var arr =  ["AAA,","BBB,"];

arr[arr.length-1] = arr[arr.length-1].replace(/\,/g,"");

console.log(arr)```

Title: How to remove character from last array element