问:
Why is the non persistent ejb timer not triggering?
I'm trying to replace an existing logic in our application that makes use of persistent proggramatic timers to non persistent timers due to a recent issue that we encountered.
The file system that WAS uses to write the persistent information of the timers was full and the Derby database got restarted in read only mode , making our application not able to trigger the timers post that, we had to restart the server to fix the same.

this is the current piece of code that is used to trigger the programmatic timer

```<code>Timer timer = timerService.createTimer(100,eventContextWrapper);
</code>```

As per the examples quoted in http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html, changed our code to

```<code>TimerConfig tC = new TimerConfig(eventContextWrapper, false);
Timer timer = timerService.createSingleActionTimer(100,  tC);
</code>```

but we are facing the below exception

```<code>[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R org.omg.CORBA.MARSHAL: Unable to read value from underlying bridge : null  vmcid: IBM  minor code: 896  completed: No
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.rmi.iiop.CDRReader.read_value(CDRReader.java:771)
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.rmi.iiop.EncoderInputStream.read_value(EncoderInputStream.java:840)
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ws.ejbcontainer.util.ORBObjectCopierImpl.copy(ORBObjectCopierImpl.java:52)
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ws.ejbcontainer.util.ObjectUtil.copy(ObjectUtil.java:159)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ejs.container.TimerNpImpl.<init>(TimerNpImpl.java:240)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ejs.container.TimerNpImpl.<init>(TimerNpImpl.java:276)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ws.runtime.component.WASEJBRuntimeImpl.createTimer(WASEJBRuntimeImpl.java:1371)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ejs.container.BeanO.createSingleActionTimer(BeanO.java:2551)
com.test.customer.event.EventTimerBean.triggerTimer(EventTimerBean.java:62)
</code>```

Line 62 is where the createSingleActionTimer is invoked.

Have done some analysis and unable to fix the same. any lead would be helpful..

答: Eventually found that one of the classes in the EventContextWrapper is not serializable and that's why we were getting the above error. We changed that class to implement serializable and it worked. Still ain't sure , how come it worked when  persistent timer was used.</p>

Body:
I'm trying to replace an existing logic in our application that makes use of persistent proggramatic timers to non persistent timers due to a recent issue that we encountered.
The file system that WAS uses to write the persistent information of the timers was full and the Derby database got restarted in read only mode , making our application not able to trigger the timers post that, we had to restart the server to fix the same.

this is the current piece of code that is used to trigger the programmatic timer

Timer timer = timerService.createTimer(100,eventContextWrapper);

As per the examples quoted in http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html, changed our code to

TimerConfig tC = new TimerConfig(eventContextWrapper, false);
Timer timer = timerService.createSingleActionTimer(100,  tC);

but we are facing the below exception

[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R org.omg.CORBA.MARSHAL: Unable to read value from underlying bridge : null  vmcid: IBM  minor code: 896  completed: No
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.rmi.iiop.CDRReader.read_value(CDRReader.java:771)
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.rmi.iiop.EncoderInputStream.read_value(EncoderInputStream.java:840)
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ws.ejbcontainer.util.ORBObjectCopierImpl.copy(ORBObjectCopierImpl.java:52)
[5/31/17 22:18:23:348 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ws.ejbcontainer.util.ObjectUtil.copy(ObjectUtil.java:159)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ejs.container.TimerNpImpl.<init>(TimerNpImpl.java:240)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ejs.container.TimerNpImpl.<init>(TimerNpImpl.java:276)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ws.runtime.component.WASEJBRuntimeImpl.createTimer(WASEJBRuntimeImpl.java:1371)
[5/31/17 22:18:23:349 GMT+08:00] 000000bf SystemErr     R       at com.ibm.ejs.container.BeanO.createSingleActionTimer(BeanO.java:2551)
com.test.customer.event.EventTimerBean.triggerTimer(EventTimerBean.java:62)

Line 62 is where the createSingleActionTimer is invoked.

Have done some analysis and unable to fix the same. any lead would be helpful..


来源: stackexchange

问:
Index was outside the bounds of the array.C#
I've a part of program that have method to generate code (HelmID), to generate it, i've to read from text file to get the latest HelmID. Here's my text file.

```<code>T001#C001#H001#FullFace#S001#
T001#C001#H002#FullFace#S002#
</code>```

The problem is, the method wont generate to H003 (after H002) and give error message 'Index was outside the bounds of the array'. Here's my method code.

```<code>public string newHelmetCode()
        {
            string Str, HelmetCode;
            int HelmetInt;
            string[] strArray = new string[5];
            if (new FileInfo("TransDetail.txt").Length == 0)
            {
                HelmetCode = "H001";
                return HelmetCode;
            }
            else
            {
                Str = File.ReadLines("TransDetail.txt").Last();
                strArray = Str.Split(new string[] { "#" }, StringSplitOptions.None);

                HelmetCode = strArray[2].Substring(1, 3);
                HelmetInt = Convert.ToInt32(HelmetCode) + 1;

                if (HelmetInt <= 9)
                {
                    HelmetCode = "H00" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 99)
                {
                    HelmetCode = "H0" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 999)
                {
                    HelmetCode = "H" + HelmetInt.ToString();
                }
                return HelmetCode;
            }
        }
</code>```

The error come from this code HelmetCode = strArray[2].Substring(1, 3);. It should generate cause i'm using Substring (and convert to int) to get latest number on last row on text file. Any reply would appricate

答:
Maybe there is a linebreak after the last line or something like that. You can use LINQ to the only the relvant lines:</p>

```<code>var lineFields = File.ReadLines("TransDetail.txt")
    .Select(line => line.Split(new string[] { "#" }, StringSplitOptions.None))
    .Where(arr => arr.Length >= 5)
    .ToArray();

if(lineFields.Length > 0)
{
    string[] lastFields = lineFields.Last();
    int helmetInt;
    bool valid = int.TryParse(lastFields[2].Substring(1), out helmetInt);
    // check if it's valid otherwise log/throw error

    // you dont need the if...else if...else if... part, this is enough:
    string helmetCode = "H" + helmetInt.ToString("D3");
    // ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've a part of program that have method to generate code (HelmID), to generate it, i've to read from text file to get the latest HelmID. Here's my text file.

T001#C001#H001#FullFace#S001#
T001#C001#H002#FullFace#S002#

The problem is, the method wont generate to H003 (after H002) and give error message 'Index was outside the bounds of the array'. Here's my method code.

public string newHelmetCode()
        {
            string Str, HelmetCode;
            int HelmetInt;
            string[] strArray = new string[5];
            if (new FileInfo("TransDetail.txt").Length == 0)
            {
                HelmetCode = "H001";
                return HelmetCode;
            }
            else
            {
                Str = File.ReadLines("TransDetail.txt").Last();
                strArray = Str.Split(new string[] { "#" }, StringSplitOptions.None);

                HelmetCode = strArray[2].Substring(1, 3);
                HelmetInt = Convert.ToInt32(HelmetCode) + 1;

                if (HelmetInt <= 9)
                {
                    HelmetCode = "H00" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 99)
                {
                    HelmetCode = "H0" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 999)
                {
                    HelmetCode = "H" + HelmetInt.ToString();
                }
                return HelmetCode;
            }
        }

The error come from this code HelmetCode = strArray[2].Substring(1, 3);. It should generate cause i'm using Substring (and convert to int) to get latest number on last row on text file. Any reply would appricate

Body:
Maybe there is a linebreak after the last line or something like that. You can use LINQ to the only the relvant lines:

var lineFields = File.ReadLines("TransDetail.txt")
    .Select(line => line.Split(new string[] { "#" }, StringSplitOptions.None))
    .Where(arr => arr.Length >= 5)
    .ToArray();

if(lineFields.Length > 0)
{
    string[] lastFields = lineFields.Last();
    int helmetInt;
    bool valid = int.TryParse(lastFields[2].Substring(1), out helmetInt);
    // check if it's valid otherwise log/throw error

    // you dont need the if...else if...else if... part, this is enough:
    string helmetCode = "H" + helmetInt.ToString("D3");
    // ...
}


问:
MKMapView setRegion: causes app to crash in iOS SDK
I want to zoom MKMapView on custom coordinates. So I using following code.

```<code>CLLocationCoordinate2D myCurrentLocationCordinate = CLLocationCoordinate2DMake(latitude, longtitude);
[myMapView setCenterCoordinate:myCurrentLocationCordinate animated:YES];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500, 500);
MKCoordinateRegion adjustedRegion = [myMapView regionThatFits:viewRegion];
[myMapView setRegion:adjustedRegion animated:YES];
</code>```

But my app is randomly crashing on setRegion: Method. And getting this log when it is crashing :-

adjustedRegion description: (MKCoordinateRegion) adjustedRegion = {

  center = (latitude = 23.066432958888399, longitude =
  72.531898498535213)   span = (latitudeDelta = 0.0051205743267423998, longitudeDelta = 0.0048793707173899747) }

Also sometimes getting following error :-

* Terminating app due to uncaught exception 'NSGenericException',
  reason: '(null) must implement title when canShowCallout is YES on
  corresponding view >'
  * First throw call stack: (0x18e8b91b8 0x18d2f055c 0x19ab76244 0x19abb2c74 0x19ab74d44 0x19ab8db58 0x19477c7dc 0x19abb041c
  0x19abb0290 0x19abb1588 0x1001ae010 0x1001ad318 0x101265258
  0x101265218 0x101275080 0x101274b78 0x18d94b2a0 0x18d94ad8c)
  libc++abi.dylib: terminating with uncaught exception of type
  NSException

I am sure not why it is crashing randomly. Let me know if any other proper solution for zooming the MKMapView on custom coordinates.

Any help would be appreciated.

答:
I also got the same issue, but solved using this

```<code> CLLocationCoordinate2D startCoord = CLLocationCoordinate2DMake(latitudeAPI, longtitudeAPI);
   [myMapView setRegion:MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500.0, 500.0) animated:NO];
</code>```

There is no need to use this line

```<code>MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500, 500);
MKCoordinateRegion adjustedRegion = [myMapView regionThatFits:viewRegion];
</code>```

Hope it works and thanks to @Firoze Lafeer to help me to solve this.

Body:
I want to zoom MKMapView on custom coordinates. So I using following code.

CLLocationCoordinate2D myCurrentLocationCordinate = CLLocationCoordinate2DMake(latitude, longtitude);
[myMapView setCenterCoordinate:myCurrentLocationCordinate animated:YES];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500, 500);
MKCoordinateRegion adjustedRegion = [myMapView regionThatFits:viewRegion];
[myMapView setRegion:adjustedRegion animated:YES];

But my app is randomly crashing on setRegion: Method. And getting this log when it is crashing :-

adjustedRegion description: (MKCoordinateRegion) adjustedRegion = {

  center = (latitude = 23.066432958888399, longitude =
  72.531898498535213)   span = (latitudeDelta = 0.0051205743267423998, longitudeDelta = 0.0048793707173899747) }

Also sometimes getting following error :-

* Terminating app due to uncaught exception 'NSGenericException',
  reason: '(null) must implement title when canShowCallout is YES on
  corresponding view >'
  * First throw call stack: (0x18e8b91b8 0x18d2f055c 0x19ab76244 0x19abb2c74 0x19ab74d44 0x19ab8db58 0x19477c7dc 0x19abb041c
  0x19abb0290 0x19abb1588 0x1001ae010 0x1001ad318 0x101265258
  0x101265218 0x101275080 0x101274b78 0x18d94b2a0 0x18d94ad8c)
  libc++abi.dylib: terminating with uncaught exception of type
  NSException

I am sure not why it is crashing randomly. Let me know if any other proper solution for zooming the MKMapView on custom coordinates.

Any help would be appreciated.

Body:
I also got the same issue, but solved using this

 CLLocationCoordinate2D startCoord = CLLocationCoordinate2DMake(latitudeAPI, longtitudeAPI);
   [myMapView setRegion:MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500.0, 500.0) animated:NO];

There is no need to use this line

MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500, 500);
MKCoordinateRegion adjustedRegion = [myMapView regionThatFits:viewRegion];

Hope it works and thanks to @Firoze Lafeer to help me to solve this.


问:
What does "{Exif}" indicate from [NSArray objectAtIndex:]
I'm on a quest to see if I can figure out how to access Exif Metadata information from an image captured by my iphone. The apple documentation seems to lack the necessary information I'm looking for. I'm probably going about this stupidly, but I'm relatively new to iPhone programming and objective-c so I'm still figuring everything out.

```<code>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

//EXPERIMENTATION
NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
NSArray *metaDataKeys = [metadata allKeys];

for (NSUInteger i=0; i  [metaDataKeys count]; i++)
{
    NSLog(@"%@", [metaDataKeys objectAtIndex:i]);
}
</code>```

This code produces the following output:

2010-10-21 14:42:56.354 _[3607:307] DPIHeight

2010-10-21 14:42:56.355 _[3607:307] {Exif}

2010-10-21 14:42:56.356 _[3607:307] DPIWidth

2010-10-21 14:42:56.357 _[3607:307] Orientation

2010-10-21 14:42:56.358 _[3607:307] {TIFF}

What does '{Exif}' indicate? Is the key literally a string "{Exif}"? I'm guessing no because when I try to extract that the object with that key I receive a NULL. And does anyone happen to know what type the Exif tag will be when I eventually get it from this NSDictionary? Is there any documentation anywhere that is helpful for learning how to work with Exif tags? Thanks!

答:
You can log dictionaries directly:

```<code>NSLog(@"metadata : %@", metadata);
</code>```

which is simpler (and better) than listing the keys like you do, and also shows their contents!

```<code>Metadata {
    ColorModel = RGB;
    DPIHeight = 72;
    DPIWidth = 72;
    Depth = 8;
    Orientation = 6;
    PixelHeight = 55;
    PixelWidth = 116;
    "{Exif}" =     {
        ColorSpace = 1;
        ComponentsConfiguration =         (
            1,
            2,
            3,
            0
        );
        ExifVersion =         (
            2,
            2,
            1
        );
        FlashPixVersion =         (
            1,
            0
        );
        PixelXDimension = 55;
        PixelYDimension = 116;
        SceneCaptureType = 0;
    };
    "{TIFF}" =     {
        Orientation = 6;
        ResolutionUnit = 2;
        XResolution = 72;
        YResolution = 72;
        "_YCbCrPositioning" = 1;
    };
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm on a quest to see if I can figure out how to access Exif Metadata information from an image captured by my iphone. The apple documentation seems to lack the necessary information I'm looking for. I'm probably going about this stupidly, but I'm relatively new to iPhone programming and objective-c so I'm still figuring everything out.

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

//EXPERIMENTATION
NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
NSArray *metaDataKeys = [metadata allKeys];

for (NSUInteger i=0; i  [metaDataKeys count]; i++)
{
    NSLog(@"%@", [metaDataKeys objectAtIndex:i]);
}

This code produces the following output:

2010-10-21 14:42:56.354 _[3607:307] DPIHeight

2010-10-21 14:42:56.355 _[3607:307] {Exif}

2010-10-21 14:42:56.356 _[3607:307] DPIWidth

2010-10-21 14:42:56.357 _[3607:307] Orientation

2010-10-21 14:42:56.358 _[3607:307] {TIFF}

What does '{Exif}' indicate? Is the key literally a string "{Exif}"? I'm guessing no because when I try to extract that the object with that key I receive a NULL. And does anyone happen to know what type the Exif tag will be when I eventually get it from this NSDictionary? Is there any documentation anywhere that is helpful for learning how to work with Exif tags? Thanks!

Body:
You can log dictionaries directly:

NSLog(@"metadata : %@", metadata);

which is simpler (and better) than listing the keys like you do, and also shows their contents!

Metadata {
    ColorModel = RGB;
    DPIHeight = 72;
    DPIWidth = 72;
    Depth = 8;
    Orientation = 6;
    PixelHeight = 55;
    PixelWidth = 116;
    "{Exif}" =     {
        ColorSpace = 1;
        ComponentsConfiguration =         (
            1,
            2,
            3,
            0
        );
        ExifVersion =         (
            2,
            2,
            1
        );
        FlashPixVersion =         (
            1,
            0
        );
        PixelXDimension = 55;
        PixelYDimension = 116;
        SceneCaptureType = 0;
    };
    "{TIFF}" =     {
        Orientation = 6;
        ResolutionUnit = 2;
        XResolution = 72;
        YResolution = 72;
        "_YCbCrPositioning" = 1;
    };
}


问:
Powershell Remoting and WinRM
New-PSSession does not work when using the HostName of a server, but does with the IP. Both local and remote machines are on the same domain.

PS C:\Windows\system32> new-PSSession -ComputerName "SERVERNAME"
  new-PSSession : [SERVERNAME] Connecting to remote server SERVERNAME failed with the following error message : WinRM
  cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer
  SERVERNAME. Verify that the computer exists on the network and that the name provided is spelled correctly. For more
  information, see the about_Remote_Troubleshooting Help topic.

I've also tried Ping, RDP and Test-WSMan which are all successful using the servers Hostname.

Any ideas on what could be going wrong?

答:
Seems like SelfSignedCertificate issue.

Delete the old WinRM listener

```<code>winrm delete winrm/config/Listener?Address=*+Transport=HTTPS
</code>```

Create New-SelfSignedCertificate with Domain name

```<code>New-SelfSignedCertificate -DnsName "<YOUR_DNS_NAME>" -CertStoreLocation Cert:\LocalMachine\My
</code>```

Update the SelfSignedCertificate _THUMBPRINT

```<code>winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="<YOUR_DNS_NAME>"; CertificateThumbprint="<COPIED_CERTIFICATE_THUMBPRINT>"
</code>```

3.Add a new firewall rule

```<code>$port=5986
netsh advfirewall firewall add rule name="Windows Remote Management (HTTPS-In)" dir=in action=allow protocol=TCP localport=$port
</code>```

Please refer to this link for more info:

http://www.visualstudiogeeks.com/devops/how-to-configure-winrm-for-https-manually

Title: Powershell Remoting and WinRM

Body:
Seems like SelfSignedCertificate issue.

Delete the old WinRM listener

winrm delete winrm/config/Listener?Address=*+Transport=HTTPS

Create New-SelfSignedCertificate with Domain name

New-SelfSignedCertificate -DnsName "<YOUR_DNS_NAME>" -CertStoreLocation Cert:\LocalMachine\My

Update the SelfSignedCertificate _THUMBPRINT

winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="<YOUR_DNS_NAME>"; CertificateThumbprint="<COPIED_CERTIFICATE_THUMBPRINT>"

3.Add a new firewall rule

$port=5986
netsh advfirewall firewall add rule name="Windows Remote Management (HTTPS-In)" dir=in action=allow protocol=TCP localport=$port

Please refer to this link for more info:

http://www.visualstudiogeeks.com/devops/how-to-configure-winrm-for-https-manually

ContentLicense: CC BY-SA 4.0


答:
I think you need custom function with apply and axis=1 for expand DataFrame to list, last use concat with reindex_axis:

```<code>tech = ['blur', 'noise', 'sharpen', 'affine']
df = pd.read_csv('data.csv')
print (df)
                                     id    ocr raw_value manual_raw_value
0  00219b14-37d1-42b2-95e8-65fe2a94b7a5  ABBYY      6,35             6,35
1  402048fd-868d-446a-8468-07a57f5386bf  ABBYY     11,68            11,68
2  33405269-c273-4c13-83d4-a973c42b72eb  ABBYY     VOTRE            VOTRE

dfs = []
def f(x):
    df = pd.DataFrame({'id':[x['id'] + '_' + t for t in tech],
                       'ocr':x['ocr'],
                       'manual_raw_value':x['manual_raw_value'],
                       'raw_value':''})
    #print (df)
    dfs.append(df)

df.apply(f, axis=1)

df1 = pd.concat(dfs)
#print (df1)

df2 = pd.concat([df, df1], ignore_index=True).reindex_axis(df.columns, axis=1)
</code>```

```<code>print (df2)
                                              id    ocr raw_value  \
0           00219b14-37d1-42b2-95e8-65fe2a94b7a5  ABBYY      6,35
1           402048fd-868d-446a-8468-07a57f5386bf  ABBYY     11,68
2           33405269-c273-4c13-83d4-a973c42b72eb  ABBYY     VOTRE
3      00219b14-37d1-42b2-95e8-65fe2a94b7a5_blur  ABBYY
4     00219b14-37d1-42b2-95e8-65fe2a94b7a5_noise  ABBYY
5   00219b14-37d1-42b2-95e8-65fe2a94b7a5_sharpen  ABBYY
6    00219b14-37d1-42b2-95e8-65fe2a94b7a5_affine  ABBYY
7      402048fd-868d-446a-8468-07a57f5386bf_blur  ABBYY
8     402048fd-868d-446a-8468-07a57f5386bf_noise  ABBYY
9   402048fd-868d-446a-8468-07a57f5386bf_sharpen  ABBYY
10   402048fd-868d-446a-8468-07a57f5386bf_affine  ABBYY
11     33405269-c273-4c13-83d4-a973c42b72eb_blur  ABBYY
12    33405269-c273-4c13-83d4-a973c42b72eb_noise  ABBYY
13  33405269-c273-4c13-83d4-a973c42b72eb_sharpen  ABBYY
14   33405269-c273-4c13-83d4-a973c42b72eb_affine  ABBYY

   manual_raw_value
0              6,35
1             11,68
2             VOTRE
3              6,35
4              6,35
5              6,35
6              6,35
7             11,68
8             11,68
9             11,68
10            11,68
11            VOTRE
12            VOTRE
13            VOTRE
14            VOTRE
</code>```

Title: Add a new rows and copy the values of cells under certain conditions

Body:
l have a csv file that l process using pandas.

id                                    raw_value     manual_raw_value
00219b14-37d1-42b2-95e8-65fe2a94b7a5    6,35        6,35
402048fd-868d-446a-8468-07a57f5386bf    11,68        11,68
33405269-c273-4c13-83d4-a973c42b72eb    VOTRE        VOTRE
8727fae7-4427-4285-945b-61c8a97b0017    AVELARVRO   AVELARVRO
006d9acb-9fed-44cd-8cc0-3f0710380484    2292        2292
9cf97fc4-d79b-4125-85d2-7dabc056caa3    questions.  questions.
6f63010b-2ccc-4e7a-bfe6-aab1dfc65ea3    nb            nb
a76d4f54-5036-4212-ab5a-921724c05910    tes          les
75d8b257-9bc3-431b-9bf6-1cc64c647292    937,99     937,99
4f6c38e9-6500-4172-a472-ba8532db05d2    à           à
229a883a-5e46-4c16-a74c-22936b6bb491    et         et
47293ec7-c2d5-4312-94a2-1bc963069096    TTC        TTC
d6841ca2-8dec-416f-ad20-3ce2da8d3e27    1          1
d7c152ed-4718-4430-9b54-b8289af78cb8    620       620
f8771e48-c17d-45c9-9f08-1e512197e998    Echéance    Echéance
fa821937-5f98-4249-abcf-f662a693c2b0    vos        vos
417a087a-3948-46aa-bfdf-27cf6c011d5c    ROB21     ROB21
f93c4e8c-b803-4501-bbee-67860c1ad065    Pièce     Pièce
2fb756fe-596b-4ed5-86f0-a9cb26e7098c    AGRIAL     AGRIAL
38dd4cde-ed72-4d07-be87-ee54cdb3eb5f    désignation désignation
66f395d7-aeb1-4ec9-a38a-d59a57244c5e    des         des
1858c031-488a-4f8c-9f51-76e7dc30648b    taux       taux
af853348-6212-4f58-9ba1-6a8d9a14e033    13s          13s
372c9afa-0f3d-4514-b9e3-6c0516d16f9c    2            2
918d3724-a739-4cd4-b4dd-68078d0398da    par         par
4cac4573-6d98-453a-82b3-61d2619af96c    le           le
d8a303ca-701c-441b-9697-649358d0fe9e    mois,       mois,
f5ff6420-bd55-43c7-a5f4-1f10828daa7e    32           32
ca48d1f7-333f-4af4-8654-892414cad579    21/07/2016  21/07/2016
a78daadd-7194-4e27-820f-ed97a6cfd109    FR           FR

Now, l want to add new rows with respect to the id column as follow :
for each id l have a set of ids. Fpr instance let's take as an example  first id :

00219b14-37d1-42b2-95e8-65fe2a94b7a5

this is id is the name of an image :

00219b14-37d1-42b2-95e8-65fe2a94b7a5.png

then l have  variant of ids of the same image as follow :
00219b14-37d1-42b2-95e8-65fe2a94b7a5_blur.png
00219b14-37d1-42b2-95e8-65fe2a94b7a5_noise.png
00219b14-37d1-42b2-95e8-65fe2a94b7a5_sharpen.png
00219b14-37d1-42b2-95e8-65fe2a94b7a5_affine.png

all what l want to do
is to add the ids of these images to the csv file by setting manual raw value as the original id then l get the following

for instance for the first id

id                                        raw_value     manual_raw_value
00219b14-37d1-42b2-95e8-65fe2a94b7a5          6,35        6,35
00219b14-37d1-42b2-95e8-65fe2a94b7a5`_blur`               6,35
00219b14-37d1-42b2-95e8-65fe2a94b7a5`_noise`              6,35
00219b14-37d1-42b2-95e8-65fe2a94b7a5`_sharpen`            6,35
00219b14-37d1-42b2-95e8-65fe2a94b7a5`_affine`             6,35

l thought about this solution

import glob
import os
path="/home/images/"
os.chdir(path)
images=glog.glob("*.png")
id_img,variant_img = set([x.rsplit('.', 1)[0].rsplit('_') for x in images_name_valid])
for img in id_img:
   if (df_valid.id == img):
       value = df_valid.loc[df_valid.id == img, 'manual_raw_value'].item()
       # here l need to add rows and associate them the `value`

       00219b14-37d1-42b2-95e8-65fe2a94b7a5_blur
       00219b14-37d1-42b2-95e8-65fe2a94b7a5_noise
       00219b14-37d1-42b2-95e8-65fe2a94b7a5_sharpen
       00219b14-37d1-42b2-95e8-65fe2a94b7a5_affine

Thank you

Body:
I think you need custom function with apply and axis=1 for expand DataFrame to list, last use concat with reindex_axis:

tech = ['blur', 'noise', 'sharpen', 'affine']
df = pd.read_csv('data.csv')
print (df)
                                     id    ocr raw_value manual_raw_value
0  00219b14-37d1-42b2-95e8-65fe2a94b7a5  ABBYY      6,35             6,35
1  402048fd-868d-446a-8468-07a57f5386bf  ABBYY     11,68            11,68
2  33405269-c273-4c13-83d4-a973c42b72eb  ABBYY     VOTRE            VOTRE

dfs = []
def f(x):
    df = pd.DataFrame({'id':[x['id'] + '_' + t for t in tech],
                       'ocr':x['ocr'],
                       'manual_raw_value':x['manual_raw_value'],
                       'raw_value':''})
    #print (df)
    dfs.append(df)

df.apply(f, axis=1)

df1 = pd.concat(dfs)
#print (df1)

df2 = pd.concat([df, df1], ignore_index=True).reindex_axis(df.columns, axis=1)

print (df2)
                                              id    ocr raw_value  \
0           00219b14-37d1-42b2-95e8-65fe2a94b7a5  ABBYY      6,35
1           402048fd-868d-446a-8468-07a57f5386bf  ABBYY     11,68
2           33405269-c273-4c13-83d4-a973c42b72eb  ABBYY     VOTRE
3      00219b14-37d1-42b2-95e8-65fe2a94b7a5_blur  ABBYY
4     00219b14-37d1-42b2-95e8-65fe2a94b7a5_noise  ABBYY
5   00219b14-37d1-42b2-95e8-65fe2a94b7a5_sharpen  ABBYY
6    00219b14-37d1-42b2-95e8-65fe2a94b7a5_affine  ABBYY
7      402048fd-868d-446a-8468-07a57f5386bf_blur  ABBYY
8     402048fd-868d-446a-8468-07a57f5386bf_noise  ABBYY
9   402048fd-868d-446a-8468-07a57f5386bf_sharpen  ABBYY
10   402048fd-868d-446a-8468-07a57f5386bf_affine  ABBYY
11     33405269-c273-4c13-83d4-a973c42b72eb_blur  ABBYY
12    33405269-c273-4c13-83d4-a973c42b72eb_noise  ABBYY
13  33405269-c273-4c13-83d4-a973c42b72eb_sharpen  ABBYY
14   33405269-c273-4c13-83d4-a973c42b72eb_affine  ABBYY

   manual_raw_value
0              6,35
1             11,68
2             VOTRE
3              6,35
4              6,35
5              6,35
6              6,35
7             11,68
8             11,68
9             11,68
10            11,68
11            VOTRE
12            VOTRE
13            VOTRE
14            VOTRE


问:
Php form data not submitting on mysql databse with username check
The form is loading on the registration page. But after giving any input it's not storing on MySQL database plus it also doesn't check for username availability.

Here is HTML code part:

```<code><html>
    <link type="text/css" rel="stylesheet" href="design.css">
    <div class ="cus_head">   </div>
<body>
<center> <h1 style="color:#1AAB30;">Register </h1>
 <form method="post" action="reg_process.php">
  UserName: <input type="text" name="cus_username" >
  <span class="error">* <?php echo $cus_username_err;?></span>
  <span id="username_status"></span>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/users.js"></script>
  <br><br>
  First Name: <input type="text" name="firstname">
  <span class="error">* <?php echo $firstname_err;?></span>
  <br><br>
  Last Name: <input type="text" name="lastname">
  <span class="error">* <?php echo $lastname_err;?></span>
  <br><br>
  Email Id: <input type="email" name="email">
  <span class="error">* <?php echo $email_err;?></span>
  <br><br>
  Password: <input type="password" name="password">
  <span class="error">* <?php echo $password_err;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">
</form>
</center>
</body>
<div class ="cus_head">   </div>
</code>```

Here is the Javascript file code for username availability: users.js

```<code>$('#username').keyup( function() {
    var username = $(this).val();

    $('#username_status').text('Searching...');

    if(username !== '') {
        $.post('php/username_check.php', { username: username}, function(data) {
            $('#username_status').text(data);
        });
    }
    else {
        $('#username_status').text('');
    }
});
</code>```

Here is the PHP Part: register.php

```<code><?php
$link = mysqli_connect("%", "****", "****", "****");
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
require 'username_check.php';
// define variables and set to empty values
$cus_username = $firstname = $lastname = $email = $password = "";
// defining variable and set to empty value for error
$cus_username_err = $firstname_err = $lastname_err = $email_err = $password_err = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 if (empty($_POST['cus_username'])) {
    $cus_username_err = "UserName is required";
  } else {
    $cus_username = sanitize($_POST['cus_username']);
  }

  if (empty($_POST['firstname'])) {
    $firstname_err = "First Name is required";
  } else {
   $firstname = sanitize($_POST['firstname']);
  }

  if (empty($_POST['lastname'])) {
    $lastname_err = "Last Name is required";
  } else {
    $lastname = sanitize($_POST['lastname']);
  }

   if (empty($_POST['email'])) {
    $email_err = "Email is required";
  } else {
    $email = sanitize($_POST['email']);
  }

   if (empty($_POST['password'])) {
    $password_err = "password is required";
  } else {
  $password = sanitize($_POST['password']);
  }

}
// attempt insert query execution
$sql = "INSERT INTO ***** (`cus_username`, `firstname`, `lastname`, `email`, `password`) VALUES ('$cus_username', '$firstname', '$lastname','$email,'$password')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

function sanitize($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
mysqli_close($link);
?>
</code>```

Here is the username_check.php

            <?php
$link = mysqli_connect("%", "****", "*****", "*****");

    if (isset($_POST['username']))
    {
        $username = sanitize($_POST['username']);

        if (!empty($cus_username))
    {
            $sql = "SELECT *FROM ***** WHERE username = '$username'";

             $count=mysqli_num_rows( $sql);
             if($count==0)
             {
               echo "Username doesn't exist";
               exit;
             }
            else
            {
              echo "Username already exists";
              exit;
            }
    }
}
function sanitize($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>   ```

答:
With reference to your username check script - as the ajax function is being triggered on keyup it is not likely that the entire field has been completed so using a like operator in the sql makes more sense.
Rather than directly embedding a variable in the sql statement it is a far better option to use prepared statements - the statement here uses a questionmark as a placeholder which is later bound to a constructed string variable containing the contents of $_POST['username'] at the time of the keyup

```<code><?php
    /*
        username_check.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $rows=0;
        /*
            sql prepared statement using `LIKE` operator
        */
        $sql='select * from `TABLE` where `username` like ?';
        $stmt = $db->prepare( $sql );

        if( $stmt ){
            /* Bind the placeholder to an as yet undefined variable - $username */
            $stmt->bind_param( 's', $username );

            /* Generate the $username variable with trailing % */
            $username = $_POST['username']."%";

            /* Query the db */
            $result = $stmt->execute();

            if( $result ){
                /* If the query succeeded, get the row count */
                $stmt->store_result();
                $rows=$stmt->num_rows;
            }
            /* tidy up */
            $stmt->free_result();
            $stmt->close();
        }
        $db->close();

        /* Send response back to javascript callback */
        exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
    }
?>
</code>```

For the register.php script - again using prepared statements to avoid sql injection. Neither script is tested - they are for your guidance on how you might accomplish your goals

```<code><?php
    /*
        register.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $sql = 'insert into `TABLE` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';
        $stmt = $db->prepare( $sql );

        if( $stmt ){

            $username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
            $firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
            $lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
            $email=!empty($_POST['email']) ? $_POST['email'] : false;
            $password=!empty($_POST['password']) ? $_POST['password'] : false;

            $errors=array();
            if( !$username )$errors[]='Please enter a username';
            if( !$password )$errors[]='Please enter your password';
            if( !$email )$errors[]='Please enter your email';
            if( !$firstname )$errors[]='Your firstname is required';
            if( !$lastname )$errors[]='Your lastname is required';

            if( empty( $errors ) ){

                /* bind the variables and execute the sql statement */
                $stmt->bind_param('sssss',$username,$firstname,$lastname,$email,$password);
                $result = $stmt->execute();

                echo $result ? 'Success' : 'Failed';

            } else {
                foreach( $errors as $error ){
                    echo $error . '<br />';
                }
            }
            $stmt->close();
            $db->close();
        }
    }
?>
</code>```

-- Updates

The html/php page to add a new user

```<code><?php

?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Add a user</title>
        <script src='//code.jquery.com/jquery-latest.js' type='text/javascript'></script>
        <style>
            html, html *{font-family:calibri,verdana,arial;font-size:0.85rem;}

            label{clear:both;margin:0.25rem;padding:0.25rem;display:block;width:30%;float:left;}
            input[type='submit']{margin:3rem 0;background:green;color:white;clear:both;float:left;}
            input[type='text'],
            input[type='email'],
            input[type='password']{float:right;}
            #username_status{color:red;margin:0 0 0 2rem;}

        </style>
    </head>
    <body>
        <h1>Register</h1>
        <form method='post' action='reg_process.php'>
            <!-- the text field needs an id for the ajax function to glom onto -->
            <label for='cus_username'>UserName: <input type='text' name='cus_username' id='username' /><span id='username_status'></span></label>
            <label for='firstname'>First Name: <input type='text' name='firstname' /></label>
            <label for='lastname'>Last Name: <input type='text' name='lastname' /></label>
            <label for='email'>Email Id: <input type='email' name='email' /></label>
            <label for='password'>Password: <input type='password' name='password' /></label>
            <!--

                various spans removed for testing
                and slight rearrangement using `label`

            -->
            <input type='submit' />
        </form>
        <!--
            rather than sending an ajax request with each character typed
            I updated this to check for a minimal length before sending the
            request and also changed the event listener to listen for blur events
            so there should only be one request when the user moves to the next
            field in the form
        -->
        <script type='text/javascript'>
            $('#username').blur( function(e) {
                var status=$('#username_status');
                    status.text( 'Searching...' );

                if( $( this ).val() !== '' && $( this ).val().length > 3 ) {
                    $.post('php/username_check.php', { username: $(this).val() }, function(data) {
                        status.text( data );
                    });
                } else {
                    status.text('');
                }
            });
        </script>
    </body>
</html>

<?php
    /*
        username_check.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $rows=0;
        /*
            sql prepared statement using `LIKE` operator
        */
        $sql='select * from `users` where `username` like ?';
        $stmt = $db->prepare( $sql );

        if( $stmt ){
            /* Bind the placeholder to an as yet undefined variable - $username */
            $stmt->bind_param( 's', $username );

            /* Generate the $username variable with trailing % */
            $username = $_POST['username']."%";

            /* Query the db */
            $result = $stmt->execute();

            if( $result ){
                /* If the query succeeded, get the row count */
                $stmt->store_result();
                $rows=$stmt->num_rows;
            }
            /* tidy up */
            $stmt->free_result();
            $stmt->close();
        }
        $db->close();

        /* Send response back to javascript callback */
        exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
    }
?>

<?php
    /*
        reg_process.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $sql = 'insert into `users` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';

        $stmt = $db->prepare( $sql );

        if( $stmt ){

            $username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
            $firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
            $lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
            $email=!empty($_POST['email']) ? $_POST['email'] : false;
            $password=!empty($_POST['password']) ? $_POST['password'] : false;

            $errors=array();
            if( !$username )$errors[]='Please enter a username';
            if( !$password )$errors[]='Please enter your password';
            if( !$email )$errors[]='Please enter your email';
            if( !$firstname )$errors[]='Your firstname is required';
            if( !$lastname )$errors[]='Your lastname is required';

            if( empty( $errors ) ){

                /* bind the variables and execute the sql statement */
                $stmt->bind_param('sssss', $username, $firstname, $lastname, $email, $password );
                $result = $stmt->execute();

                echo $result ? 'Success' : 'Failed';

            } else {
                foreach( $errors as $error ){
                    echo $error . '<br />';
                }
            }
            $stmt->close();
            $db->close();
        }
    }
?>
</code>```

I created these three pages following the directory structure suggested by the javascript function and form target, changed the db details to suit dev environment and assumed a table called users - ran the page and completed the form. A new user was successfully added.

Body:
The form is loading on the registration page. But after giving any input it's not storing on MySQL database plus it also doesn't check for username availability.

Here is HTML code part:

    <link type="text/css" rel="stylesheet" href="design.css">

Register

 <form method="post" action="reg_process.php">
  UserName: <input type="text" name="cus_username" >
  * <?php echo $cus_username_err;?>

  First Name: <input type="text" name="firstname">
  * <?php echo $firstname_err;?>

  Last Name: <input type="text" name="lastname">
  * <?php echo $lastname_err;?>

  Email Id: <input type="email" name="email">
  * <?php echo $email_err;?>

  Password: <input type="password" name="password">
  * <?php echo $password_err;?>

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

Here is the Javascript file code for username availability: users.js

$('#username').keyup( function() {
    var username = $(this).val();

    $('#username_status').text('Searching...');

    if(username !== '') {
        $.post('php/username_check.php', { username: username}, function(data) {
            $('#username_status').text(data);
        });
    }
    else {
        $('#username_status').text('');
    }
});

Here is the PHP Part: register.php

<?php
$link = mysqli_connect("%", "****", "****", "****");
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
require 'username_check.php';
// define variables and set to empty values
$cus_username = $firstname = $lastname = $email = $password = "";
// defining variable and set to empty value for error
$cus_username_err = $firstname_err = $lastname_err = $email_err = $password_err = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 if (empty($_POST['cus_username'])) {
    $cus_username_err = "UserName is required";
  } else {
    $cus_username = sanitize($_POST['cus_username']);
  }

  if (empty($_POST['firstname'])) {
    $firstname_err = "First Name is required";
  } else {
   $firstname = sanitize($_POST['firstname']);
  }

  if (empty($_POST['lastname'])) {
    $lastname_err = "Last Name is required";
  } else {
    $lastname = sanitize($_POST['lastname']);
  }

   if (empty($_POST['email'])) {
    $email_err = "Email is required";
  } else {
    $email = sanitize($_POST['email']);
  }

   if (empty($_POST['password'])) {
    $password_err = "password is required";
  } else {
  $password = sanitize($_POST['password']);
  }

}
// attempt insert query execution
$sql = "INSERT INTO ***** (`cus_username`, `firstname`, `lastname`, `email`, `password`) VALUES ('$cus_username', '$firstname', '$lastname','$email,'$password')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

function sanitize($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
mysqli_close($link);
?>

Here is the username_check.php

            <?php
$link = mysqli_connect("%", "****", "*****", "*****");

    if (isset($_POST['username']))
    {
        $username = sanitize($_POST['username']);

        if (!empty($cus_username))
    {
            $sql = "SELECT *FROM ***** WHERE username = '$username'";

             $count=mysqli_num_rows( $sql);
             if($count==0)
             {
               echo "Username doesn't exist";
               exit;
             }
            else
            {
              echo "Username already exists";
              exit;
            }
    }
}
function sanitize($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

Body:
With reference to your username check script - as the ajax function is being triggered on keyup it is not likely that the entire field has been completed so using a like operator in the sql makes more sense.
Rather than directly embedding a variable in the sql statement it is a far better option to use prepared statements - the statement here uses a questionmark as a placeholder which is later bound to a constructed string variable containing the contents of $_POST['username'] at the time of the keyup

<?php
    /*
        username_check.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $rows=0;
        /*
            sql prepared statement using `LIKE` operator
        */
        $sql='select * from `TABLE` where `username` like ?';
        $stmt = $db->prepare( $sql );

        if( $stmt ){
            /* Bind the placeholder to an as yet undefined variable - $username */
            $stmt->bind_param( 's', $username );

            /* Generate the $username variable with trailing % */
            $username = $_POST['username']."%";

            /* Query the db */
            $result = $stmt->execute();

            if( $result ){
                /* If the query succeeded, get the row count */
                $stmt->store_result();
                $rows=$stmt->num_rows;
            }
            /* tidy up */
            $stmt->free_result();
            $stmt->close();
        }
        $db->close();

        /* Send response back to javascript callback */
        exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
    }
?>

For the register.php script - again using prepared statements to avoid sql injection. Neither script is tested - they are for your guidance on how you might accomplish your goals

<?php
    /*
        register.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $sql = 'insert into `TABLE` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';
        $stmt = $db->prepare( $sql );

        if( $stmt ){

            $username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
            $firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
            $lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
            $email=!empty($_POST['email']) ? $_POST['email'] : false;
            $password=!empty($_POST['password']) ? $_POST['password'] : false;

            $errors=array();
            if( !$username )$errors[]='Please enter a username';
            if( !$password )$errors[]='Please enter your password';
            if( !$email )$errors[]='Please enter your email';
            if( !$firstname )$errors[]='Your firstname is required';
            if( !$lastname )$errors[]='Your lastname is required';

            if( empty( $errors ) ){

                /* bind the variables and execute the sql statement */
                $stmt->bind_param('sssss',$username,$firstname,$lastname,$email,$password);
                $result = $stmt->execute();

                echo $result ? 'Success' : 'Failed';

            } else {
                foreach( $errors as $error ){
                    echo $error . '<br />';
                }
            }
            $stmt->close();
            $db->close();
        }
    }
?>

-- Updates

The html/php page to add a new user

<?php

?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Add a user</title>
        <script src='//code.jquery.com/jquery-latest.js' type='text/javascript'></script>
        <style>
            html, html *{font-family:calibri,verdana,arial;font-size:0.85rem;}

            label{clear:both;margin:0.25rem;padding:0.25rem;display:block;width:30%;float:left;}
            input[type='submit']{margin:3rem 0;background:green;color:white;clear:both;float:left;}
            input[type='text'],
            input[type='email'],
            input[type='password']{float:right;}
            #username_status{color:red;margin:0 0 0 2rem;}

        </style>
    </head>
    <body>
        <h1>Register</h1>
        <form method='post' action='reg_process.php'>
            <!-- the text field needs an id for the ajax function to glom onto -->
            <label for='cus_username'>UserName: <input type='text' name='cus_username' id='username' /><span id='username_status'></span></label>
            <label for='firstname'>First Name: <input type='text' name='firstname' /></label>
            <label for='lastname'>Last Name: <input type='text' name='lastname' /></label>
            <label for='email'>Email Id: <input type='email' name='email' /></label>
            <label for='password'>Password: <input type='password' name='password' /></label>
            <!--

                various spans removed for testing
                and slight rearrangement using `label`

            -->
            <input type='submit' />
        </form>
        <!--
            rather than sending an ajax request with each character typed
            I updated this to check for a minimal length before sending the
            request and also changed the event listener to listen for blur events
            so there should only be one request when the user moves to the next
            field in the form
        -->
        <script type='text/javascript'>
            $('#username').blur( function(e) {
                var status=$('#username_status');
                    status.text( 'Searching...' );

                if( $( this ).val() !== '' && $( this ).val().length > 3 ) {
                    $.post('php/username_check.php', { username: $(this).val() }, function(data) {
                        status.text( data );
                    });
                } else {
                    status.text('');
                }
            });
        </script>
    </body>
</html>

<?php
    /*
        username_check.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $rows=0;
        /*
            sql prepared statement using `LIKE` operator
        */
        $sql='select * from `users` where `username` like ?';
        $stmt = $db->prepare( $sql );

        if( $stmt ){
            /* Bind the placeholder to an as yet undefined variable - $username */
            $stmt->bind_param( 's', $username );

            /* Generate the $username variable with trailing % */
            $username = $_POST['username']."%";

            /* Query the db */
            $result = $stmt->execute();

            if( $result ){
                /* If the query succeeded, get the row count */
                $stmt->store_result();
                $rows=$stmt->num_rows;
            }
            /* tidy up */
            $stmt->free_result();
            $stmt->close();
        }
        $db->close();

        /* Send response back to javascript callback */
        exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
    }
?>

<?php
    /*
        reg_process.php
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){

        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        $sql = 'insert into `users` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';

        $stmt = $db->prepare( $sql );

        if( $stmt ){

            $username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
            $firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
            $lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
            $email=!empty($_POST['email']) ? $_POST['email'] : false;
            $password=!empty($_POST['password']) ? $_POST['password'] : false;

            $errors=array();
            if( !$username )$errors[]='Please enter a username';
            if( !$password )$errors[]='Please enter your password';
            if( !$email )$errors[]='Please enter your email';
            if( !$firstname )$errors[]='Your firstname is required';
            if( !$lastname )$errors[]='Your lastname is required';

            if( empty( $errors ) ){

                /* bind the variables and execute the sql statement */
                $stmt->bind_param('sssss', $username, $firstname, $lastname, $email, $password );
                $result = $stmt->execute();

                echo $result ? 'Success' : 'Failed';

            } else {
                foreach( $errors as $error ){
                    echo $error . '<br />';
                }
            }
            $stmt->close();
            $db->close();
        }
    }
?>

I created these three pages following the directory structure suggested by the javascript function and form target, changed the db details to suit dev environment and assumed a table called users - ran the page and completed the form. A new user was successfully added.


问:
What can we do about a randomly crashing app without source code?
I am trying to help a client with a problem, but I am running out of ideas. They have a custom, written in house application that runs on a schedule, but it crashes. I don't know how long it has been like this, so I don't think I can trace the crashes back to any particular software updates. The most unfortunate part is there is no longer any source code for the VB6 DLL which contains the meat of the logic.

This VB6 DLL is kicked off by 2-3 function calls from a VB Script. Obviously, I can modify the VB Script to add error logging, but I'm not having much luck getting quality information to pinpoint the source of the crash. I have put logging messages on either side of all of the function calls and determined which of the calls is causing the crash. However, nothing is ever returned in the err object because the call is crashing wscript.exe.

I'm not sure if there is anything else I can do. Any ideas?

Edit: The main reason I care, even though I don't have the source code is that there may be some external factor causing the crash (insufficient credentials, locked file, etc). I have checked the log file that is created in drwtsn32.log as a result of wscript.exe crashing, and the only information I get is an "Access Violation".

I first tend to think this is something to do with security permissions, but couldn't this also be a memory access violation?

答:
Reverse engineering is one possibility, although a tough one.

In theory you can decompile and even debug/trace a compiled VB6 application - this is the easy part, modifying it without source, in all but the most simple cases, is the hard part.

Free compilers/decompilers:

VB decompilers

VB debuggers

Rewrite would be, in most cases, a more successful and faster way to solve the problem.

OwnerDisplayName: Brad Barker

LastEditorDisplayName: Brad Barker

OwnerDisplayName: Hrvoje Prgeša


问:
Error when extending superclass to subclass in Java - polymorphism
I'm currently tackling polymorphism on my java journey and I'm trying out these example codes in Eclipse. I just copied the codes but I'm really wondering why my codes wouldn't compile.

So I got three files: Example.java, Animals.java and Dog.java.

Example.java contains the main method:

```<code>public class Example {
    public static void main(String[] args) {
        Animal myDog = new Dog();
    }
}
</code>```

Then I created two other classes for Animal and Dog as follows

Animal Class

```<code>public class Animal {

    public void makeNoise() {
    }

    public void eat(){
    }

    public void sleep() {
    }

    public void roam() {

    }

}
</code>```

Dog Class

```<code>public class Dog {

}
</code>```

The way I understand it is that I can make Dog my subclass that extends the superclass Animal. But why wouldn't my codes compile?

Am I missing something in these codes?

答:
Your Dog class doesnt extend animal class so this is invalid:

```<code>Animal myDog = new Dog();
</code>```

you need to modify the class Dog in order to inherit the Animal Class

you achieve that doing:

```<code>public class Dog extends Animal{
</code>```

Body:
I'm currently tackling polymorphism on my java journey and I'm trying out these example codes in Eclipse. I just copied the codes but I'm really wondering why my codes wouldn't compile.

So I got three files: Example.java, Animals.java and Dog.java.

Example.java contains the main method:

public class Example {
    public static void main(String[] args) {
        Animal myDog = new Dog();
    }
}

Then I created two other classes for Animal and Dog as follows

Animal Class

public class Animal {

    public void makeNoise() {
    }

    public void eat(){
    }

    public void sleep() {
    }

    public void roam() {

    }

}

Dog Class

public class Dog {

}

The way I understand it is that I can make Dog my subclass that extends the superclass Animal. But why wouldn't my codes compile?

Am I missing something in these codes?

Body:
Your Dog class doesnt extend animal class so this is invalid:

Animal myDog = new Dog();

you need to modify the class Dog in order to inherit the Animal Class

you achieve that doing:

public class Dog extends Animal{


问:
Lots of open file handlers on deleted files in jenkins
I am using jenkins to run pipeline groovy scripts. One of the first step is a checkout via the checkout plugin. The checkout happens into the <workspace>/source-repo folder.

Now, when I do lsof (it is a linux machine) I get a lot of open file handlers like this:

```<code>java      16932     1000  567r      REG             202,80         91    7996215 <workspace>/source-repo@tmp/durable-a06b8b8d/output.txt (deleted)
</code>```

They are building up over time ... Why? And what can i do?

答:
I found the problem, it seems to be related to sh in combination with returnStdout: true. So I replaced calls like this:

```<code>def ret = sh script: "command", returnStdout: true
</code>```

with

```<code>sh "command > output.txt"
def ret = readFile "output.txt"
sh "rm output.txt"
</code>```

Feels a bit hacky, but now I am fine.

Body:
I am using jenkins to run pipeline groovy scripts. One of the first step is a checkout via the checkout plugin. The checkout happens into the <workspace>/source-repo folder.

Now, when I do lsof (it is a linux machine) I get a lot of open file handlers like this:

java      16932     1000  567r      REG             202,80         91    7996215 <workspace>/source-repo@tmp/durable-a06b8b8d/output.txt (deleted)

They are building up over time ... Why? And what can i do?

Body:
I found the problem, it seems to be related to sh in combination with returnStdout: true. So I replaced calls like this:

def ret = sh script: "command", returnStdout: true

with

sh "command > output.txt"
def ret = readFile "output.txt"
sh "rm output.txt"

Feels a bit hacky, but now I am fine.


问:
Need help in searching using php
I need a little help with my code. It seems like my code is not workingbut I don't know which part is wrong.

Here's my stock.php: (include connection is there, but i don't post it in here)

```<code><body>
<fieldset>
<legend><h1>Cari Data Barang</h1></legend>
 <div style="margin-bottom:15px;" align="right">
  <form action="" method="post">
   <input type="text" name="input_cari" placeholder="Cari Berdasar Nama Barang" class="css-input" style="width:250px;" />
   <input type="submit" name="cari" value="cari" class="btn" style="padding:3px;" margin="6px;" width="50px;"  />
  </form>
 </div>

   <?php

    $input_cari = @$_POST['input_cari'];
    $cari = @$_POST['cari'];
    $mencari = "SELECT * FROM barang where nama_barang like '%$input_cari%'";
    $result = mysqli_query($connection, $mencari) or die("Error");
    ?>
    <table width="100%" border="1px solid #000" style="border-collapse:collapse;">
        <tr style="background-color:#fc0;">
            <th>Id Barang</th>
            <th>Nama Barang</th>
            <th>Harga Jual</th>
            <th>Stock</th>
        </tr>
        <?php while($dat=mysqli_fetch_assoc($result)){
            echo "<tr>
                    <td><center>{$dat['id_barang']}</center></td>
                    <td><center>{$dat['nama_barang']}</center></td>
                    <td><center>{$dat['harga_jual']}</center></td>
                    <td><center>{$dat['stock']}</center></td>
                    <td><center><input type="submit" name="edit" value="Edit"><a href="Edit.php"></a></center></td>
                    </tr>"
        ?>
    <tbody>

                    <?php

                  }
                  ?>

    </table>
    <table>
    <th><a href = "kasir.php"><button type="submit">Back</button></th>
    <th><a href= "#"><button onclick="window.print()"> Print </a></th>
    </table>
    </fieldset>
    </body>
</html>
</code>```

答:
Firstly, you should add the php like below with a . connecting the string and the variable. Next you should have single quotes inside of double quotes or your string will end prematurely. See below.</p>

```<code>                <?php while($dat=mysqli_fetch_assoc($result)){
        echo "<tr>
                <td><center>".$dat['id_barang']."</center></td>
                <td><center>".$dat['nama_barang']."</center></td>
                <td><center>".$dat['harga_jual']."</center></td>
                <td><center>".$dat['stock']."</center></td>
                <td><center><input type='submit' name='edit' value='Edit'><a href='Edit.php'></a></center></td>
                </tr>";
    ?>
</code>```

Title: Need help in searching using php

Body:
I need a little help with my code. It seems like my code is not workingbut I don't know which part is wrong.

Here's my stock.php: (include connection is there, but i don't post it in here)

<fieldset>
<legend>
Cari Data Barang
</legend>

  <form action="" method="post">
   <input type="text" name="input_cari" placeholder="Cari Berdasar Nama Barang" class="css-input" style="width:250px;" />
   <input type="submit" name="cari" value="cari" class="btn" style="padding:3px;" margin="6px;" width="50px;"  />
  </form>

   <?php

    $input_cari = @$_POST['input_cari'];
    $cari = @$_POST['cari'];
    $mencari = "SELECT * FROM barang where nama_barang like '%$input_cari%'";
    $result = mysqli_query($connection, $mencari) or die("Error");
    ?>

            Id Barang
            Nama Barang
            Harga Jual
            Stock

        <?php while($dat=mysqli_fetch_assoc($result)){
            echo "

                    {$dat['id_barang']}
                    {$dat['nama_barang']}
                    {$dat['harga_jual']}
                    {$dat['stock']}
                    <input type="submit" name="edit" value="Edit">

"
        ?>

                    <?php

                  }
                  ?>

    <button type="submit">Back</button>
    <button onclick="window.print()"> Print

    </fieldset>

Body:
Firstly, you should add the php like below with a . connecting the string and the variable. Next you should have single quotes inside of double quotes or your string will end prematurely. See below.

                <?php while($dat=mysqli_fetch_assoc($result)){
        echo "<tr>
                <td><center>".$dat['id_barang']."</center></td>
                <td><center>".$dat['nama_barang']."</center></td>
                <td><center>".$dat['harga_jual']."</center></td>
                <td><center>".$dat['stock']."</center></td>
                <td><center><input type='submit' name='edit' value='Edit'><a href='Edit.php'></a></center></td>
                </tr>";
    ?>


问:
C Encrypt data in file.txt
I have problem in encrypting my plain text in C.
I am able to write and read the file in C
Inside the text:

```<code>ID  Promo   Points  Password    Name
1   NONE    0       awdawdawd   daw
</code>```

Which in this case it just print password in plain text, Is it possible to encrypt the data any method, which shows like this:

```<code>ID  Promo   Points  Password    Name
1   NONE    0      ENCRYPTEDDATA daw
</code>```

Of course the password wont be "ENCRYPTEDDATA", I just want it avoid plain text which user can easily see the file.
The reason I create file cause I need to read it from the file and make a login function.
My program itself able to decrypt the password when in request of checking id and password.
It can use any method only the program can encrypt and decrypt the data
Any solution guys?
If possible I also need to limit the encrypted text

答:
If you want to protect your login then you should use a password hash, also known as a Password Based Key Derivation Function. These functions are often, but not always, based on a secure hash. You should not use a cryptographic hash such as SHA-2 for this purposes.

Common password hashes are PBKDF2, bcrypt, scrypt and Argon2. Argon2 is the most advanced one as winner of the password hashing competition. A password hash differs from a normal hash in two important aspects:

it uses key strengthening techniques to make it harder for adversaries to use a dictionary or brute force attack (in the form of an iteration count or work factor and possibly additional memory / threading related parameters);

it uses a salt - stored with the password hash - to avoid rainbow table attacks and to avoid duplicate hash values - which would show that an identical password is being used.

So although Pras is right about not using encryption I would not recommend a secure hash unless you are sure that the password is large enough and unique. In general those restrictions can nor should be enforced on password based authentication systems.

Title: C Encrypt data in file.txt

Body:
I have problem in encrypting my plain text in C.
I am able to write and read the file in C
Inside the text:

ID  Promo   Points  Password    Name
1   NONE    0       awdawdawd   daw

Which in this case it just print password in plain text, Is it possible to encrypt the data any method, which shows like this:

ID  Promo   Points  Password    Name
1   NONE    0      ENCRYPTEDDATA daw

Of course the password wont be "ENCRYPTEDDATA", I just want it avoid plain text which user can easily see the file.
The reason I create file cause I need to read it from the file and make a login function.
My program itself able to decrypt the password when in request of checking id and password.
It can use any method only the program can encrypt and decrypt the data
Any solution guys?
If possible I also need to limit the encrypted text


答:
Problem cause

You need to check how assignment works in Python. This talk by Brandon Rhodes is pretty enlightening.

When you do df = df['X'].unstack() you assign to df the unstacked version of df1 or df2, depending on the iteration, so you have 2 options

Solution

Do it inplace, but there doesn't seem to be an inplace unstack

Keep another reference to the unstacked version and assign df1 and df2 to these

This can be done with either a tuple, list or a dict.

Extract the reshaping

The easiest would be to extract the operation itself to a seperate method

```<code>def my_reshape(df):
    df_copy = df.copy() # so as to leave the original DataFrame intact
    df_copy.index = [df.index.date, df.index.hour + df.index.minute / 60]
    return df_copy['X'].unstack()
</code>```

as a tuple

```<code>df1, df2 = tuple(my_reshape(df) for df in (df1, df2))
</code>```

variant with a dict

```<code>df_dict = {'df1': df1, 'df2': df2}
for key, df in df_dict.items():
    df_dict[key] = my_reshape(df)
</code>```

and if you need them outside of the dict afterwards

```<code>df1 = df_dict['df1']
df2 = df_dict['df2']
</code>```

Title: Iterating a list of Pandas dataframes / reshaping dataframe with .unstack

Body:
I have a dataframe with a DatetimeIndex:

                          X
timestamp
2013-01-01 00:00:00  0.788500
2013-01-01 00:30:00  0.761525
2013-01-01 01:00:00  0.751850
2013-01-01 01:30:00  0.746445
2013-01-01 02:00:00  0.688677

and I am using unstack to reshape it with half-hourly intervals as the columns, and dates as the rows - as suggested in this answer.

df.index = [df.index.date, df.index.hour + df.index.minute / 60]
df = df['X'].unstack()
df.head()
              0.0       0.5       1.0       1.5       2.0       2.5   \
2013-01-01  0.788500  0.761525  0.751850  0.746445  0.688677  0.652226
2013-01-02  0.799029  0.705590  0.661059  0.627001  0.606560  0.592116
2013-01-03  0.645102  0.597785  0.563410  0.516707  0.495896  0.492416
2013-01-04  0.699592  0.649553  0.598019  0.576290  0.561023  0.537802
2013-01-05  0.782781  0.706697  0.645172  0.627405  0.605972  0.583536

All good.
BUT I now want to carry out the same procedure for a number of dataframes. Initially, I'm using 2:

for df in [df1,df2]:
        df.index = [df.index.date, df.index.hour + df.index.minute / 60]
        df = df['X'].unstack()

The reindexing works, but the reshaping does not:

df1.head()

                      X
2013-01-01 0.0  0.788500
           0.5  0.761525
           1.0  0.751850
           1.5  0.746445
           2.0  0.688677

I think maybe I need some equivalent of inplace so the unstacked dataframes are passed back to df1 and df2

Any suggestions?

Body:
Problem cause

You need to check how assignment works in Python. This talk by Brandon Rhodes is pretty enlightening.

When you do df = df['X'].unstack() you assign to df the unstacked version of df1 or df2, depending on the iteration, so you have 2 options

Solution

Do it inplace, but there doesn't seem to be an inplace unstack

Keep another reference to the unstacked version and assign df1 and df2 to these

This can be done with either a tuple, list or a dict.

Extract the reshaping

The easiest would be to extract the operation itself to a seperate method

def my_reshape(df):
    df_copy = df.copy() # so as to leave the original DataFrame intact
    df_copy.index = [df.index.date, df.index.hour + df.index.minute / 60]
    return df_copy['X'].unstack()

as a tuple

df1, df2 = tuple(my_reshape(df) for df in (df1, df2))

variant with a dict

df_dict = {'df1': df1, 'df2': df2}
for key, df in df_dict.items():
    df_dict[key] = my_reshape(df)

and if you need them outside of the dict afterwards

df1 = df_dict['df1']
df2 = df_dict['df2']


问:
Click anywhere remove class jQuery
I am trying to take a mobile open menu and close it by clicking anywhere except for the actual navigation items.

Here is my HTML

```<code><nav class="site-nav">
  <ul>
    <li><a title="About Riad Kilani - Front End Developer" href="#">About</a></li>
    <li><a title="Portfolio of Riad Kilani - Front End Developer" href="#">Portfolio</a></li>
    <li><a title="Front End Development News and Tutorials from Riad Kilani" href="#">Blog</a></li>
    <li><a title="Contact Riad Kilani" href="#">Contact</a></li>
  </ul>
</nav>

<div id="content">
  <section id="featured">
    <a href="#" class="mobile-button"><i class="fa fa-bars"> Site Name</i></a>
  </section>
</div>
</code>```

And Here is my JS

```<code>$(document).ready(function(e) {
  $(".mobile-button").click(function() {
    $("#content").addClass("mobile-open");
  });

  $(document).click(function(event){
    if (event.target.id === 'site-nav') {
    } else {
        $("#content").removeClass("mobile-open");
    }
  });
});
</code>```

What am I doing wrong??

答:
Here is your code:</p>

```<code>$(document).ready(function (e) {
    $(".mobile-button").click(function () {
        $("#content").addClass("mobile-open");
    });

     $(document).click(function (e) {
        if (!$(e.target).is('.site-nav').length) {
            $("#content").removeClass("mobile-open");
        }
    });
});
</code>```

Title: Click anywhere remove class jQuery

Body:
I am trying to take a mobile open menu and close it by clicking anywhere except for the actual navigation items.

Here is my HTML

About

Portfolio

Blog

Contact

     Site Name

And Here is my JS

$(document).ready(function(e) {
  $(".mobile-button").click(function() {
    $("#content").addClass("mobile-open");
  });

  $(document).click(function(event){
    if (event.target.id === 'site-nav') {
    } else {
        $("#content").removeClass("mobile-open");
    }
  });
});

What am I doing wrong??

Body:
Here is your code:

$(document).ready(function (e) {
    $(".mobile-button").click(function () {
        $("#content").addClass("mobile-open");
    });

     $(document).click(function (e) {
        if (!$(e.target).is('.site-nav').length) {
            $("#content").removeClass("mobile-open");
        }
    });
});


问:
Simple Login using Spring Security
I am new to spring and I need to secure my application with Simple Login Form.
I went over lots of resources and found them little complex.

Can anybody suggest me an article / tutorail that shows simple way to get the app behind login?

Thanks in advance!

答: You can follow its own guide. I'd found petclinic tutorial very simple and useful.</p>

Title: Simple Login using Spring Security


问:
How to show selected action in UIAlertAction?
I am trying to achieve the view with a few green actions, and get the selected action to be bold in UIAlertController. And one of the actions, which is dismiss button has to be divided from others and be colored with red.

I am trying to add them with the styles .cancel allows to show dismiss button, but it is bold, but green.
How do I achieve this?

expected view:

my current code:

```<code>let alertController
        = UIAlertController(title: nil,
                            message: nil,
                            preferredStyle: .actionSheet)

    let sortByDateAction = UIAlertAction(title: "По дате",
                                         style: .default,
                                         handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "date" {
                                                self.page = 1
                                                self.sortBy = "date"
                                                self.loadTenders()
                                            }
    })
    let moreExpensiveSortAction = UIAlertAction(title: "Дороже",
                                                style: .destructive,
                                                handler: {(action: UIAlertAction!) in
                                                    if self.sortBy != "priceHigh" {
                                                        self.page = 1
                                                        self.sortBy = "priceHigh"
                                                        self.loadTenders()
                                                    }
    })
    let cheaperSortAction = UIAlertAction(title: "Дешевле",
                                          style: .default,
                                          handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "priceLow" {
                                                self.page = 1
                                                self.sortBy = "priceLow"
                                                self.loadTenders()
                                            }
    })

    alertController
        .addAction(sortByDateAction)
    alertController
        .addAction(moreExpensiveSortAction)
    alertController
        .addAction(cheaperSortAction)

    alertController.preferredAction = sortByDateAction

    alertController
        .addAction(UIAlertAction(title: "Dismiss",
                                 style: .cancel,
                                 handler: nil))
</code>```

答:
```<code>let cancelAlert = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:nil)
        cancelAlert.setValue(UIColor.red, forKey: "titleTextColor")
        alertController.addAction(cancelAlert)
</code>```

<p>try this code. </p>

Body:
I am trying to achieve the view with a few green actions, and get the selected action to be bold in UIAlertController. And one of the actions, which is dismiss button has to be divided from others and be colored with red.

I am trying to add them with the styles .cancel allows to show dismiss button, but it is bold, but green.
How do I achieve this?

expected view:

my current code:

let alertController
        = UIAlertController(title: nil,
                            message: nil,
                            preferredStyle: .actionSheet)

    let sortByDateAction = UIAlertAction(title: "По дате",
                                         style: .default,
                                         handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "date" {
                                                self.page = 1
                                                self.sortBy = "date"
                                                self.loadTenders()
                                            }
    })
    let moreExpensiveSortAction = UIAlertAction(title: "Дороже",
                                                style: .destructive,
                                                handler: {(action: UIAlertAction!) in
                                                    if self.sortBy != "priceHigh" {
                                                        self.page = 1
                                                        self.sortBy = "priceHigh"
                                                        self.loadTenders()
                                                    }
    })
    let cheaperSortAction = UIAlertAction(title: "Дешевле",
                                          style: .default,
                                          handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "priceLow" {
                                                self.page = 1
                                                self.sortBy = "priceLow"
                                                self.loadTenders()
                                            }
    })

    alertController
        .addAction(sortByDateAction)
    alertController
        .addAction(moreExpensiveSortAction)
    alertController
        .addAction(cheaperSortAction)

    alertController.preferredAction = sortByDateAction

    alertController
        .addAction(UIAlertAction(title: "Dismiss",
                                 style: .cancel,
                                 handler: nil))

Body:
let cancelAlert = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:nil)
        cancelAlert.setValue(UIColor.red, forKey: "titleTextColor")
        alertController.addAction(cancelAlert)

try this code.


问:
Calling a function from another in ReactJs
I have the following ReactJS component:

articles_list.jsx

```<code>import React from 'react';
import marked from 'marked';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  handleClick(e) {
    e.preventDefault();
    var elem = e.target;
    var file = elem.getAttribute('data-file').split('.')[0];
    fetch('/article/'+file, {
      headers: {
        'Accept': 'text/markdown'
      }
    })
    .then(res => res.text())
    .then(txt => marked(txt))
    .then(html => document.getElementById('article-text').innerHTML = html)
  }

  render() {

    var teste = []

    if (this.state.articles === null) {
      teste.push(<div id="no-articles" key="1">No articles</div>)
    } else {
      {this.state.articles.forEach( function(element, index) {
        teste.push(<div onClick={this.handleClick} data-file={element.file} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
      }.bind(this))}
    }

    return(
      <div className="articles-list">
        <div className="articles-list-title">
          ARTICLES
        </div>
        <div id="menu-body" className="menu-body">{teste}</div>
      </div>
    );
  }
}
</code>```

As you may see, it fetches as list of articles and creates links. When these links are clicked the corresponding article is load in a certain area of the page.

The code is working perfectly, but now I need to load a certain article before any of the links to be clicked. Then I decided to break the code inside handleClick like this:

```<code>   loadArticle(file) {
     fetch('/article/'+file, {
       headers: {
         'Accept': 'text/markdown'
       }
     })
     .then(res => res.text())
     .then(txt => marked(txt))
     .then(html => document.getElementById('article-text').innerHTML = html)
   }

   handleClick(e) {
    e.preventDefault();
    var elem = e.target;
    var file = elem.getAttribute('data-file').split('.')[0];
    loadArticle(file);
  }
</code>```

My idea with this is to invoke loadArticle inside render to load an specific article when the component loads, like this:

```<code>return(
  <div className="articles-list">
    <div className="articles-list-title">
      ARTICLES
    </div>
    <div id="menu-body" className="menu-body">{teste}{this.loadArticle('my_specific_article')}</div>
  </div>
);
</code>```

It works and now my_specific_article loads correctly when I navigate to the page. But...

But now when I click the links, that were working fine before, I got an error

Uncaught ReferenceError: loadArticle is not defined

And if I do

```<code>   handleClick(e) {
    e.preventDefault();
    var elem = e.target;
    var file = elem.getAttribute('data-file').split('.')[0];
    this.loadArticle(file);
  }
</code>```

using this, then I get

Uncaught TypeError: Cannot read property 'loadArticle' of null

How should I deal with this? I know it is a matter of context but, being new to ReactJS, I really don't know how to proceed.

EDIT

This is not a duplicate of this question, as it was marked. The reason is simple. In the mentioned question the function to bind is a event handler and in my problem a function being called by another. In fact, my event handler (similar to the other question) was working fine without the bind, then we are not talking about the same thing.

答:
You must bind your custom functions in the constructor.
Modify your constructor like this.

```<code>constructor(props) {
  super(props);
  this.state = {
    articles: null
  }
 this.handleClick = this.handleClick.bind(this);
 this.loadArticle = this.loadArticle.bind(this);
}
</code>```

Now everywhere you should call this function as this.handleClick & this.loadMore.

You can read about other binding patterns here. The one I've mentioned is number 4.

That is the preferred way in facebook docs as well.

Body:
I have the following ReactJS component:

articles_list.jsx

import React from 'react';
import marked from 'marked';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  handleClick(e) {
    e.preventDefault();
    var elem = e.target;
    var file = elem.getAttribute('data-file').split('.')[0];
    fetch('/article/'+file, {
      headers: {
        'Accept': 'text/markdown'
      }
    })
    .then(res => res.text())
    .then(txt => marked(txt))
    .then(html => document.getElementById('article-text').innerHTML = html)
  }

  render() {

    var teste = []

    if (this.state.articles === null) {
      teste.push(
No articles
)
    } else {
      {this.state.articles.forEach( function(element, index) {
        teste.push(
{element.title}
);
      }.bind(this))}
    }

    return(

          ARTICLES

{teste}

    );
  }
}

As you may see, it fetches as list of articles and creates links. When these links are clicked the corresponding article is load in a certain area of the page.

The code is working perfectly, but now I need to load a certain article before any of the links to be clicked. Then I decided to break the code inside handleClick like this:

   loadArticle(file) {
     fetch('/article/'+file, {
       headers: {
         'Accept': 'text/markdown'
       }
     })
     .then(res => res.text())
     .then(txt => marked(txt))
     .then(html => document.getElementById('article-text').innerHTML = html)
   }

   handleClick(e) {
    e.preventDefault();
    var elem = e.target;
    var file = elem.getAttribute('data-file').split('.')[0];
    loadArticle(file);
  }

My idea with this is to invoke loadArticle inside render to load an specific article when the component loads, like this:

return(

      ARTICLES

{teste}{this.loadArticle('my_specific_article')}

);

It works and now my_specific_article loads correctly when I navigate to the page. But...

But now when I click the links, that were working fine before, I got an error

Uncaught ReferenceError: loadArticle is not defined

And if I do

   handleClick(e) {
    e.preventDefault();
    var elem = e.target;
    var file = elem.getAttribute('data-file').split('.')[0];
    this.loadArticle(file);
  }

using this, then I get

Uncaught TypeError: Cannot read property 'loadArticle' of null

How should I deal with this? I know it is a matter of context but, being new to ReactJS, I really don't know how to proceed.

EDIT

This is not a duplicate of this question, as it was marked. The reason is simple. In the mentioned question the function to bind is a event handler and in my problem a function being called by another. In fact, my event handler (similar to the other question) was working fine without the bind, then we are not talking about the same thing.

Body:
You must bind your custom functions in the constructor.
Modify your constructor like this.

constructor(props) {
  super(props);
  this.state = {
    articles: null
  }
 this.handleClick = this.handleClick.bind(this);
 this.loadArticle = this.loadArticle.bind(this);
}

Now everywhere you should call this function as this.handleClick & this.loadMore.

You can read about other binding patterns here. The one I've mentioned is number 4.

That is the preferred way in facebook docs as well.


问:
Implementing Navigation-bar and an Extension view attached to the bottom of nav-bar
What's the right way to implement a hides-on-scroll navigation bar along with an extension view attached to the navigation bar's bottom. And on scroll the navigation bar gets hidden and the extension view sticks to the status bar.</p>

答:
You can use TLYShyNavBar library to implement this feature if you want extension view to stick to status bar. If you just want navigationBar to hide along with extension then use hidesBarsOnSwipe property </p>

```<code>navigationController?.hidesBarsOnSwipe = true
</code>```

<p>refer this thread to read more about this behaviour. </p>

Body:
You can use TLYShyNavBar library to implement this feature if you want extension view to stick to status bar. If you just want navigationBar to hide along with extension then use hidesBarsOnSwipe property

navigationController?.hidesBarsOnSwipe = true

refer this thread to read more about this behaviour.


问:
GetPixels and SetPixels for only alpha channel
I want to change alpha-channel of RenderedTexture, that is target of camera. I know, I can GetPixels from Texture2d and SetPixels to another Texture2d. But how can I copy pixels from my own .psd texture (I need only alpha-channel pixels) and pass it into RenderTexture?

UPD: I can ReadPixels to temp texture from RenderTexture, but how can I GetPixels and SetPixels for only one channel?

答:
Have a look here...

http://answers.unity3d.com/questions/902538/change-alpha-channel-of-a-texture-in-code.html

To quote: "A texture doesn't have one value for alpha that spans the entire texture, instead, the alpha channel is per pixel.

To copy the alpha channel from one texture to another, you have to pass through the texture in its entirety, pixel by pixel, and copy each pixel's alpha channel over."


问:
Use environment variable in NuGet config?
Is there a way to use an environment variable in NuGet.Config file?

Currently I am constrained to using relative path, as follows:

<configuration>
  <config>
    <add key="repositoryPath" value="..\..\teampackages" />
  </config>
</configuration>
```

But would be really handy to have an environment variable with absolute path instead.

答:
This works using standard %foo% environment variable references as of nuget 3.4 and higher:
https://github.com/NuGet/Home/issues/1852</p>

Body:
Is there a way to use an environment variable in NuGet.Config file?

Currently I am constrained to using relative path, as follows:

<configuration>
  <config>
    <add key="repositoryPath" value="..\..\teampackages" />
  </config>
</configuration>

But would be really handy to have an environment variable with absolute path instead.


问:
How can i return value from one method to another & swapping
I have this

```<code>public class Mapper implements ScramblerIF
{
 private static String map = "drsjckpwrypwsftylmzxopqtdo";

public static String charAt(String str)
{
 //char[] chars = str.toCharArray();
int length = str.length();

 for(int i=0; i<length; i++)
{
 char aChar = str.charAt(i);
 char upper = Character.toUpperCase(aChar);
 int num = (upper - 'A');
char mChar = map.charAt(num);
 //String chard = Character.toString(mChar);

 StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );
 }
   return str;
 }

public String scramble(String str) {
return charAt(str);
 }
}
</code>```

I am trying to get it to where the method

```<code> public String scramble(String str) {
return charAt(str);
 }
</code>```

returns the computed value from the

```<code> public static String charAt(String str)
</code>```

method. Don't know where i went wrong.

Also instead of using

```<code>StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );
</code>```

how would i be able to use the swap function?
When I try

```<code> char temp = chars[i];
chars[i] = chars[mChar];
chars[mChar] = temp;
</code>```

I am given an ArrayIndexOutOfBoundsException.
Summary of what i am trying to do is "For each character in the original string, use its position in the alphabet to look up its replacement in the map string. For example, the string “dog” would be translated to “jtp”."

答:
This scrables with the replacement-map you have provided. It also handles upper and lower case letters:

```<code>public class Mapper {
    //                           abcdefghijklmnopqrstuvwxyz
    private static String map = "drsjckpwrypwsftylmzxopqtdo";

    public static String scramble(String str) {

        if (!str.matches("[A-Za-z]*"))
            throw new RuntimeException(str + " contains weird characters");

        String out = "";
        for (char c : str.toCharArray()) {
            if (Character.isUpperCase(c)) {
                out += Character.toUpperCase(map.charAt(c - 'A'));
            } else {
                out += map.charAt(c - 'a');
            }
        }

        return out;

    }

    public static void main(String[] args) {
        System.out.println(scramble("David"));
    }
}
</code>```

Body:
I have this

public class Mapper implements ScramblerIF
{
 private static String map = "drsjckpwrypwsftylmzxopqtdo";

public static String charAt(String str)
{
 //char[] chars = str.toCharArray();
int length = str.length();

 for(int i=0; i<length; i++)
{
 char aChar = str.charAt(i);
 char upper = Character.toUpperCase(aChar);
 int num = (upper - 'A');
char mChar = map.charAt(num);
 //String chard = Character.toString(mChar);

 StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );
 }
   return str;
 }

public String scramble(String str) {
return charAt(str);
 }
}

I am trying to get it to where the method

 public String scramble(String str) {
return charAt(str);
 }

returns the computed value from the

 public static String charAt(String str)

method. Don't know where i went wrong.

Also instead of using

StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );

how would i be able to use the swap function?
When I try

 char temp = chars[i];
chars[i] = chars[mChar];
chars[mChar] = temp;

I am given an ArrayIndexOutOfBoundsException.
Summary of what i am trying to do is "For each character in the original string, use its position in the alphabet to look up its replacement in the map string. For example, the string “dog” would be translated to “jtp”."

Body:
This scrables with the replacement-map you have provided. It also handles upper and lower case letters:

public class Mapper {
    //                           abcdefghijklmnopqrstuvwxyz
    private static String map = "drsjckpwrypwsftylmzxopqtdo";

    public static String scramble(String str) {

        if (!str.matches("[A-Za-z]*"))
            throw new RuntimeException(str + " contains weird characters");

        String out = "";
        for (char c : str.toCharArray()) {
            if (Character.isUpperCase(c)) {
                out += Character.toUpperCase(map.charAt(c - 'A'));
            } else {
                out += map.charAt(c - 'a');
            }
        }

        return out;

    }

    public static void main(String[] args) {
        System.out.println(scramble("David"));
    }
}