问:
Dynamic SQL output of a query to a variable
I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

```<code>declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab

exec(@SQl)

select @Count
</code>```

thank you

答:
Here's another way to do it that also safely addresses the SQL Injection isuues:</p>

```<code>/* Counts the number of rows from any non-system Table, *SAFELY* */

-- The table name passed
DECLARE @PassedTableName as NVarchar(255) = 'Person.Person';

-- Make sure this isn't a SQL Injection attempt
DECLARE @ActualTableName AS NVarchar(255)

SELECT  @ActualTableName = TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME   = PARSENAME(@PassedTableName,1)
  AND TABLE_SCHEMA = PARSENAME(@PassedTableName,2)

-- make a temp table to hold the results
CREATE TABLE #tmp( cnt INT );

-- create the dynamic SQL
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';'

-- execute it and store the output into the temp table
INSERT INTO #tmp( cnt )
EXEC(@SQL);

-- Now, finally, we can get it into a local variable
DECLARE @result AS INT;
SELECT @result = cnt FROM #tmp;
</code>```

Body:
I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab

exec(@SQl)

select @Count

thank you

Body:
Here's another way to do it that also safely addresses the SQL Injection isuues:

/* Counts the number of rows from any non-system Table, *SAFELY* */

-- The table name passed
DECLARE @PassedTableName as NVarchar(255) = 'Person.Person';

-- Make sure this isn't a SQL Injection attempt
DECLARE @ActualTableName AS NVarchar(255)

SELECT  @ActualTableName = TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME   = PARSENAME(@PassedTableName,1)
  AND TABLE_SCHEMA = PARSENAME(@PassedTableName,2)

-- make a temp table to hold the results
CREATE TABLE #tmp( cnt INT );

-- create the dynamic SQL
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';'

-- execute it and store the output into the temp table
INSERT INTO #tmp( cnt )
EXEC(@SQL);

-- Now, finally, we can get it into a local variable
DECLARE @result AS INT;
SELECT @result = cnt FROM #tmp;


来源: stackexchange

问:
How can I position the last element at the end of the column using flexbox?
I'm trying to use flexbox to position the last item at the bottom of the vertical navbar. Is there a way to do this using flexbox?

Here is the code example:

```<code><!doctype html>
<html>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
 ul {
    list-style: none;
    background: red;
    width: 100px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
 }

 li {
    border: 1px solid blue;
 }

 li:last-child {
    background: blue;
    align-self: end;
 }

</style>
<body>
<ul>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
</ul>
</body>
</html>
</code>```

答:
margin-top: auto will push it to the bottom. You can read more about auto margin's and flexbox here - https://hackernoon.com/flexbox-s-best-kept-secret-bd3d892826b6

<!doctype html>

foo

foo

foo

foo

foo

foo

```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use flexbox to position the last item at the bottom of the vertical navbar. Is there a way to do this using flexbox?

Here is the code example:

<!doctype html>

foo

foo

foo

foo

foo

foo

Body:
margin-top: auto will push it to the bottom. You can read more about auto margin's and flexbox here - https://hackernoon.com/flexbox-s-best-kept-secret-bd3d892826b6

<!doctype html>
<html>
<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  ul {
    list-style: none;
    background: red;
    width: 100px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  li {
    border: 1px solid blue;
  }

  li:last-child {
    background: blue;
    margin-top: auto;
  }
</style>

<body>
  <ul>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
  </ul>
</body>

</html>


问:
Speck Cipher - Decryption Issue in C
I'm trying to extend the following implementation of the Speck cipher (https://github.com/inmcm/Simon_Speck_Ciphers) by adding the decryption module. I implemented the decryption algorithm by following the instructions from the original paper from NSA about Speck and Simon (https://eprint.iacr.org/2013/404).

At the moment I'm kinda stuck because I can't decipher correctly the cipher text generated from the encryption routine. I already had a look at other similar questions posted here on SO to no avail.

By checking my code and the stdout, I've noticed that the value stored in x_word in the decryption phase is not correct, starting with the first iteration. Therefore, there is probably an issue with the following instruction:

```<code>x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);
</code>```

I'm posting the relevant part of my code here:

```<code>#define rotate_left(x,n) (x >> (word_size - n)) | (x << n)
#define rotate_right(x,n) (x << (word_size - n)) | (x >> n)

void Speck_Encrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    uint16_t y_word = *(uint16_t *)plaintext;
    uint16_t x_word = *(((uint16_t *)plaintext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)ciphertext;

    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        x_word = ((rotate_right(x_word, 7)) + y_word) ^ *(round_key_ptr + i);
        y_word = (rotate_left(y_word, 2)) ^ x_word;

        printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
    }
    // Assemble Ciphertext Output Array
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}

static inline uint16_t sub_mod(uint16_t a, uint16_t b, uint16_t m)
{
  if ( a>=b )
    return a - b;
  else
    return m - b + a;
}

void Speck_Decrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    // Swapping cipher text words
    uint16_t y_word = *(uint16_t *)ciphertext;
    uint16_t x_word = *(((uint16_t *)ciphertext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)plaintext;

    for(int i=0; i < 4; i++) {
        printf("Ciphertext Byte %02d: %02x \n",i,ciphertext[i]);
        printf("Plaintext Byte %02d: %02x \n",i,plaintext[i]);
    }

    // Reading round keys in reverse order
    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        //printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        //printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
        // Inverting rotations and using custom modular subtraction
        y_word = rotate_right((x_word ^ y_word), 2);
        x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);

    }
    // Assemble Plaintext - Swapping plaintext words
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}
</code>```

I haven't been coding in C in awhile, there might be a few mistakes.

答:
Given that the repo's author didn't get around the writing the C decryption routine, I'd have some concerns as to the validity of the C setup or encryption routine first.

Rather than starting there, why not look over one of the working C implementations:

https://github.com/tomasaazevedo/Speck_8-bit_C

https://github.com/yuehann/Simon_Speck

https://github.com/mysummergit/myssl/blob/master/demos/mycipher/speck.c

Title: Speck Cipher - Decryption Issue in C

Body:
I'm trying to extend the following implementation of the Speck cipher (https://github.com/inmcm/Simon_Speck_Ciphers) by adding the decryption module. I implemented the decryption algorithm by following the instructions from the original paper from NSA about Speck and Simon (https://eprint.iacr.org/2013/404).

At the moment I'm kinda stuck because I can't decipher correctly the cipher text generated from the encryption routine. I already had a look at other similar questions posted here on SO to no avail.

By checking my code and the stdout, I've noticed that the value stored in x_word in the decryption phase is not correct, starting with the first iteration. Therefore, there is probably an issue with the following instruction:

x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);

I'm posting the relevant part of my code here:

#define rotate_left(x,n) (x >> (word_size - n)) | (x << n)
#define rotate_right(x,n) (x << (word_size - n)) | (x >> n)

void Speck_Encrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    uint16_t y_word = *(uint16_t *)plaintext;
    uint16_t x_word = *(((uint16_t *)plaintext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)ciphertext;

    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        x_word = ((rotate_right(x_word, 7)) + y_word) ^ *(round_key_ptr + i);
        y_word = (rotate_left(y_word, 2)) ^ x_word;

        printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
    }
    // Assemble Ciphertext Output Array
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}

static inline uint16_t sub_mod(uint16_t a, uint16_t b, uint16_t m)
{
  if ( a>=b )
    return a - b;
  else
    return m - b + a;
}

void Speck_Decrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    // Swapping cipher text words
    uint16_t y_word = *(uint16_t *)ciphertext;
    uint16_t x_word = *(((uint16_t *)ciphertext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)plaintext;

    for(int i=0; i < 4; i++) {
        printf("Ciphertext Byte %02d: %02x \n",i,ciphertext[i]);
        printf("Plaintext Byte %02d: %02x \n",i,plaintext[i]);
    }

    // Reading round keys in reverse order
    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        //printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        //printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
        // Inverting rotations and using custom modular subtraction
        y_word = rotate_right((x_word ^ y_word), 2);
        x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);

    }
    // Assemble Plaintext - Swapping plaintext words
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}

I haven't been coding in C in awhile, there might be a few mistakes.


问:
How to find a duplicate element in an array of shuffled consecutive integers?
I recently came across a question somewhere:

Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?

What I am interested in to know is the second part, i.e., without using auxiliary storage.  Do you have any idea?

答:
```<code>n = 1000
s = sum(GivenList)
r = str(n/2)
duplicate = int( r + r ) - s
</code>```

ContentLicense: CC BY-SA 2.5


问:
Debugging Step Into, Over, Out within VB6 IDE closes the class window
I am experiencing very strange behavior within VB6 IDE whenever the break point hits(Step Into, Out, Over), the class is closed and makes it impossible to debug. Then within window-Cascade i can re-open the class but again when break point hits, the class is closed. Can anyone help please.</p>

答:
I finally resolved this issue and problem was within Display settings within windows 10. Basically if I apply vertical settings by placing both screen vertically 2nd on top of first then this issue happens,if i apply horizontal settings then this issue does not happen.

problematic settings with vb

settings that does solves debugging issue. VB is so weird and old cannot cope with display settings


问:
Deselect a selected object in Fabric.js
I have multiple type objects on my canvas.
I can do scaling, rotation, etc. everything on a particular object.

But when I select a particular object, I want to change its stroke color.

```<code>canvas.observe('mouse:down', function(e) {

    activeInstance = canvas.getActiveObject();
    activeGroupInstance = canvas.getActiveGroup();
    if (activeInstance!=null){
        activeInstance.set("stroke","#FF0000");
    }
}
</code>```

The code works well. But the issue is that the stroke color or any other valid property doesn't reflect directly which means I have to deselect a currently selected object to see the change in its properties. So my question is what's going wrong? If this is the usual behavior that we have to deselect/click the selected object, then, how to deselect the selected object using code i.e without using mouse clicks simply using a code-snippet.

答:
We can use below mentioned solutions.

To discard all active groups you can use below function.Discards currently active group and fire events If the function is called by fabric as a consequence of a mouse event, the event is passed as a parmater and sent to the fire function for the custom events. When used as a method the e param does not have any application.

```<code>canvas.discardActiveGroup();
</code>```

To discard sigle object you can use like this. Discards currently active object and fire events. If the function is called by fabric as a consequence of a mouse event, the event is passed as a parmater and sent to the fire function for the custom events. When used as a method the e param does not have any application.

```<code>canvas.discardActiveObject();
</code>```

And i the last finally renders both the top canvas and the secondary container canvas like this.

```<code>canvas.renderAll();
</code>```

Title: Deselect a selected object in Fabric.js

Body:
I have multiple type objects on my canvas.
I can do scaling, rotation, etc. everything on a particular object.

But when I select a particular object, I want to change its stroke color.

canvas.observe('mouse:down', function(e) {

    activeInstance = canvas.getActiveObject();
    activeGroupInstance = canvas.getActiveGroup();
    if (activeInstance!=null){
        activeInstance.set("stroke","#FF0000");
    }
}

The code works well. But the issue is that the stroke color or any other valid property doesn't reflect directly which means I have to deselect a currently selected object to see the change in its properties. So my question is what's going wrong? If this is the usual behavior that we have to deselect/click the selected object, then, how to deselect the selected object using code i.e without using mouse clicks simply using a code-snippet.

Body:
We can use below mentioned solutions.

To discard all active groups you can use below function.Discards currently active group and fire events If the function is called by fabric as a consequence of a mouse event, the event is passed as a parmater and sent to the fire function for the custom events. When used as a method the e param does not have any application.

canvas.discardActiveGroup();

To discard sigle object you can use like this. Discards currently active object and fire events. If the function is called by fabric as a consequence of a mouse event, the event is passed as a parmater and sent to the fire function for the custom events. When used as a method the e param does not have any application.

canvas.discardActiveObject();

And i the last finally renders both the top canvas and the secondary container canvas like this.

canvas.renderAll();


问:
have button call a specfic excel filename?

Private Sub Excel_File_Click()
Dim stAppName As String
Dim Nozero As String
Nozero = VAL(strFFF)
stAppName = "excel.exe C:\Users\excel\xxx " & Nozero & ".xlsx"
Call Shell(stAppName, 1)
End Sub```
</div>
</div>
</p>

<p>have an ms access form by case number and need to add a button to pull up the excel file with the case number, but the case number has (leading)zero's, strip the zero's and pull the file with correct characters in xxx(space)111.xlsx.
excel file: xxx 111.xlsx
case number(7 characters): xxxxxxx<br>
table: tblCase
column: fff
please help
thank you</p>

<p>Fixed it and posting for others to use
</p>

```Private Sub Excel_File_Click()
Dim Nozero As String
Nozero = Nz(strFFF)
//test variable to ensure correct path and file name
MsgBox "C:\Users\excel\xxx " & Nozero & ".xlsx"
Dim objXLApp As Object
    Dim objXLBook As Object
    Set objXLApp = CreateObject("Excel.Application")
    Set objXLBook = objXLApp.Workbooks.Open("C:\Users\excel\xxx " & Nozero & ".xlsx")
objXLApp.Application.Visible = True
End Sub
```

答:
Fixed it and posting for others to use, just add that to a button in a form or report and call it by setting it in the button properties. Changed the characters to integers in the DB. enjoy
</p>

```<code>Private Sub Excel_File_Click()
Dim Nozero As String
Nozero = Nz(strFFF)
//test variable to ensure correct path and file name
MsgBox "C:\Users\excel\xxx " & Nozero & ".xlsx"
Dim objXLApp As Object
    Dim objXLBook As Object
    Set objXLApp = CreateObject("Excel.Application")
    Set objXLBook = objXLApp.Workbooks.Open("C:\Users\excel\xxx " & Nozero & ".xlsx")
objXLApp.Application.Visible = True
End Sub
</code>```

Body:
Private Sub Excel_File_Click()
Dim stAppName As String
Dim Nozero As String
Nozero = VAL(strFFF)
stAppName = "excel.exe C:\Users\excel\xxx " & Nozero & ".xlsx"
Call Shell(stAppName, 1)
End Sub

have an ms access form by case number and need to add a button to pull up the excel file with the case number, but the case number has (leading)zero's, strip the zero's and pull the file with correct characters in xxx(space)111.xlsx.
excel file: xxx 111.xlsx
case number(7 characters): xxxxxxx

table: tblCase
column: fff
please help
thank you

Fixed it and posting for others to use

Private Sub Excel_File_Click()
Dim Nozero As String
Nozero = Nz(strFFF)
//test variable to ensure correct path and file name
MsgBox "C:\Users\excel\xxx " & Nozero & ".xlsx"
Dim objXLApp As Object
    Dim objXLBook As Object
    Set objXLApp = CreateObject("Excel.Application")
    Set objXLBook = objXLApp.Workbooks.Open("C:\Users\excel\xxx " & Nozero & ".xlsx")
objXLApp.Application.Visible = True
End Sub

Body:
Fixed it and posting for others to use, just add that to a button in a form or report and call it by setting it in the button properties. Changed the characters to integers in the DB. enjoy

Private Sub Excel_File_Click()
Dim Nozero As String
Nozero = Nz(strFFF)
//test variable to ensure correct path and file name
MsgBox "C:\Users\excel\xxx " & Nozero & ".xlsx"
Dim objXLApp As Object
    Dim objXLBook As Object
    Set objXLApp = CreateObject("Excel.Application")
    Set objXLBook = objXLApp.Workbooks.Open("C:\Users\excel\xxx " & Nozero & ".xlsx")
objXLApp.Application.Visible = True
End Sub


问:
Angular - Prevent to trigger onClick on "parent" element
I have this (excerpt of a) template:

```<code><custom-panel [summary]="summary.activity" routerLink="/activities">
  <a *ngIf="(user$ | async)?.verification.isOK" (click)="openQuestionModal()">Verify</a>
</custom-panel>
</code>```

...and this "component" class:

```<code>// imports here

@Component({
  selector: 'custom-panel',
  templateUrl: './custom-panel.component.html',
  styleUrls: ['./custom-panel.component.scss']
})
export class CustomPanelComponent implements OnInit {
  public summary$: Observable<Summary>;
  public user$: Observable<User>;

  constructor(private service: UserService, private dialog: MdDialog) {
    // ...
  }

  public ngOnInit() {
    // Populate this.user$
    // Populate this.summary$
  }

  public openQuestionModal(): void {
    console.log('openQuestionModal() ...');
  }
}
</code>```

The issue is: whenever I click on the link to open up the "Questions Modal" it also takes me to the /activities route (and eventually the modal dialog is opened there).

Is there any way to prevent this?

The only way I've found so far is to have a boolean "flag" and updating the [routeLink] directive to: [routerLink]="isActive() ? '/activities' : null". I would like to get rid of that "flag".

答:
Have you tried using stopPropagation ?

```<code>(click)="openQuestionModal($event)"

  public openQuestionModal(event): void {
    event.stopPropagation();
    console.log('openQuestionModal() ...');
  }
</code>```

Body:
I have this (excerpt of a) template:

<custom-panel [summary]="summary.activity" routerLink="/activities">
  Verify
</custom-panel>

...and this "component" class:

// imports here

@Component({
  selector: 'custom-panel',
  templateUrl: './custom-panel.component.html',
  styleUrls: ['./custom-panel.component.scss']
})
export class CustomPanelComponent implements OnInit {
  public summary$: Observable;
  public user$: Observable<User>;

  constructor(private service: UserService, private dialog: MdDialog) {
    // ...
  }

  public ngOnInit() {
    // Populate this.user$
    // Populate this.summary$
  }

  public openQuestionModal(): void {
    console.log('openQuestionModal() ...');
  }
}

The issue is: whenever I click on the link to open up the "Questions Modal" it also takes me to the /activities route (and eventually the modal dialog is opened there).

Is there any way to prevent this?

The only way I've found so far is to have a boolean "flag" and updating the [routeLink] directive to: [routerLink]="isActive() ? '/activities' : null". I would like to get rid of that "flag".

Body:
Have you tried using stopPropagation ?

(click)="openQuestionModal($event)"

  public openQuestionModal(event): void {
    event.stopPropagation();
    console.log('openQuestionModal() ...');
  }


问:
Problem with the camera
I am currently developing an app which is using the UIImagePickerController for taking pictures with the build in camera.

What I no want to do, is to provide the user a switch on bottom bar of the UIImagePickerController to be able to switch between the front and the rear camera (if available of course). I know how it's possible to determine if there's a front camera, but how can I show such a switch on the bottom bar?

Thanx for all your help!

答:
.h file
@property(nonatomic) UIImagePickerControllerCameraDevice cameraDevice;

cameraButtonPressed method opens the rear camera. changeCam method toggles between rear and front camera.

.m file

```

-(void) cameraButtonPressed

{
 overLay=[[UIView alloc]initWithFrame:CGRectMake(0,0, 320, 480)];

 UIImage *CameraClickImg=[UIImage imageNamed:@"capture.png"];
 UIButton *captureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
 [captureBtn setFrame:CGRectMake(35,440, 240,40)];
 [captureBtn addTarget:self action:@selector(captureImage) forControlEvents:UIControlEventTouchUpInside];
 [captureBtn setImage:CameraClickImg forState:UIControlStateNormal];

 UIButton *changeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
 [changeBtn setFrame:CGRectMake(250,30, 40,40)];
 [changeBtn addTarget:self action:@selector(changeCam) forControlEvents:UIControlEventTouchUpInside];
 [changeBtn setImage:CameraClickImg forState:UIControlStateNormal];

 picker = [[UIImagePickerController alloc] init];
 picker.delegate = self;
 picker.allowsEditing = NO;
 picker.sourceType = UIImagePickerControllerSourceTypeCamera;
 picker.showsCameraControls=NO;
 picker.cameraFlashMode =  UIImagePickerControllerCameraFlashModeOff;
 picker.cameraOverlayView=overLay;
 [self presentModalViewController: picker animated:YES];
 [overLay addSubview:captureBtn];
 [overLay addSubview:changeBtn];

 [picker release];

 [self.view addSubview:activityIndicator];

}

-(void)captureImage
{

 [picker takePicture];

}

-(void)changeCam
{
 if (picker.cameraDevice==UIImagePickerControllerCameraDeviceRear)
  picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;
 else
  picker.cameraDevice=UIImagePickerControllerCameraDeviceRear;

}
```

Title: Problem with the camera

Body:
.h file
@property(nonatomic) UIImagePickerControllerCameraDevice cameraDevice;

cameraButtonPressed method opens the rear camera. changeCam method toggles between rear and front camera.

.m file

-(void) cameraButtonPressed

{
 overLay=[[UIView alloc]initWithFrame:CGRectMake(0,0, 320, 480)];

 UIImage *CameraClickImg=[UIImage imageNamed:@"capture.png"];
 UIButton *captureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
 [captureBtn setFrame:CGRectMake(35,440, 240,40)];
 [captureBtn addTarget:self action:@selector(captureImage) forControlEvents:UIControlEventTouchUpInside];
 [captureBtn setImage:CameraClickImg forState:UIControlStateNormal];

 UIButton *changeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
 [changeBtn setFrame:CGRectMake(250,30, 40,40)];
 [changeBtn addTarget:self action:@selector(changeCam) forControlEvents:UIControlEventTouchUpInside];
 [changeBtn setImage:CameraClickImg forState:UIControlStateNormal];

 picker = [[UIImagePickerController alloc] init];
 picker.delegate = self;
 picker.allowsEditing = NO;
 picker.sourceType = UIImagePickerControllerSourceTypeCamera;
 picker.showsCameraControls=NO;
 picker.cameraFlashMode =  UIImagePickerControllerCameraFlashModeOff;
 picker.cameraOverlayView=overLay;
 [self presentModalViewController: picker animated:YES];
 [overLay addSubview:captureBtn];
 [overLay addSubview:changeBtn];

 [picker release];

 [self.view addSubview:activityIndicator];

}

-(void)captureImage
{

 [picker takePicture];

}

-(void)changeCam
{
 if (picker.cameraDevice==UIImagePickerControllerCameraDeviceRear)
  picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;
 else
  picker.cameraDevice=UIImagePickerControllerCameraDeviceRear;

}


问:
Google KMS on AppEngine Dev Server - logging clutter

This is a known issue: https://issuetracker.google.com/issues/63253097

Further to my question about getting Google KMS working with App Engine, I'm opening a new question about a related but problematic side effect.

Namely, the Google Cloud API discovery appears to want to walk a number of paths outside the AppEngine sandbox.  This itself is not a problem, but it makes testing and debugging very problematic because each attempt is logged, producing hundreds of lines like the following:

INFO  03 Jul 2017 14:44:51  Sandbox prevented access to file "/Users"

INFO  03 Jul 2017 14:44:51  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat9/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat8/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

Is there a way to disable or silence these requests or logs?

EDIT* One of the many results printed by adding traceback.print_stack() to log_access_check_fail in stub.py (sorry it's not very legible here):

Test #1: Sentry.io's Raven imports pkg_resources

```<code>  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app, sentry
  File "/Users/bmh/testapp/nassau/application.py", line 28, in <module>
    from raven.contrib.flask import Sentry
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/raven/__init__.py", line 16, in <module>
    VERSION = __import__('pkg_resources') \
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3037, in <module>
    @_call_aside
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3021, in _call_aside
    f(*args, **kwargs)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3050, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 646, in _build_master
    ws = cls()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 639, in __init__
    self.add_entry(entry)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 695, in add_entry
    for dist in find_distributions(entry, True):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2006, in find_on_path
    path_item = _normalize_cached(path_item)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2217, in _normalize_cached
    _cache[filename] = result = normalize_path(filename)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2210, in normalize_path
    return os.path.normcase(os.path.realpath(filename))
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()
</code>```

I removed the dependency on Sentry / Raven, but the stack traces continue, via:

Test #2: Flask imports pkgutil

```<code>  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app
  File "/Users/bmh/testapp/nassau/application.py", line 72, in <module>
    app = Flask('nassau')
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 331, in __init__
    instance_path = self.auto_find_instance_path()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 622, in auto_find_instance_path
    prefix, package_path = find_package(self.import_name)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/helpers.py", line 661, in find_package
    loader = pkgutil.get_loader(root_mod_name)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 464, in get_loader
    return find_loader(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 475, in find_loader
    loader = importer.find_module(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 184, in find_module
    path = [os.path.realpath(self.path)]
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()
</code>```

There must be a better way to represent a stack trace on stack overflow :)

答:
I am a fulltime engineer working on dev_appserver.
This log message is reported from /google/appengine/tools/devappserver2/python/stubs.py, in the method log_access_check_fail

We added this log message to remind users of dev_appserver's behavior of blocking file access.

Recommended workaround:
 dev_appserver.py   --log_level warning

--log_level sets the log level in local python runtime process. The log_access_check_fail() is set to INFO and would not be logged. NOTE, this flag will also prevent other INFO level logging in your application.

Meanwhile, we are working on a fix to this log_access_check_fail method. It could be lowering log_access_check_fail() logging level to DEBUG.

Body:
This is a known issue: https://issuetracker.google.com/issues/63253097

Further to my question about getting Google KMS working with App Engine, I'm opening a new question about a related but problematic side effect.

Namely, the Google Cloud API discovery appears to want to walk a number of paths outside the AppEngine sandbox.  This itself is not a problem, but it makes testing and debugging very problematic because each attempt is logged, producing hundreds of lines like the following:

INFO  03 Jul 2017 14:44:51  Sandbox prevented access to file "/Users"

INFO  03 Jul 2017 14:44:51  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat9/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat8/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

Is there a way to disable or silence these requests or logs?

EDIT* One of the many results printed by adding traceback.print_stack() to log_access_check_fail in stub.py (sorry it's not very legible here):

Test #1: Sentry.io's Raven imports pkg_resources

  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app, sentry
  File "/Users/bmh/testapp/nassau/application.py", line 28, in <module>
    from raven.contrib.flask import Sentry
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/raven/__init__.py", line 16, in <module>
    VERSION = __import__('pkg_resources') \
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3037, in <module>
    @_call_aside
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3021, in _call_aside
    f(*args, **kwargs)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3050, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 646, in _build_master
    ws = cls()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 639, in __init__
    self.add_entry(entry)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 695, in add_entry
    for dist in find_distributions(entry, True):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2006, in find_on_path
    path_item = _normalize_cached(path_item)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2217, in _normalize_cached
    _cache[filename] = result = normalize_path(filename)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2210, in normalize_path
    return os.path.normcase(os.path.realpath(filename))
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()

I removed the dependency on Sentry / Raven, but the stack traces continue, via:

Test #2: Flask imports pkgutil

  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app
  File "/Users/bmh/testapp/nassau/application.py", line 72, in <module>
    app = Flask('nassau')
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 331, in __init__
    instance_path = self.auto_find_instance_path()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 622, in auto_find_instance_path
    prefix, package_path = find_package(self.import_name)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/helpers.py", line 661, in find_package
    loader = pkgutil.get_loader(root_mod_name)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 464, in get_loader
    return find_loader(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 475, in find_loader
    loader = importer.find_module(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 184, in find_module
    path = [os.path.realpath(self.path)]
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()

There must be a better way to represent a stack trace on stack overflow :)


问:
Regular expression to extract file name?
I want to remove last three character of filenames.  To rename any files, i'm using:

```<code>String str = ""; // Here set File name, i.e. listFile.getName();
String[] tempFile = str.split("[$^txt]");
</code>```

This regex remove last three character it's OK, but when passing any file name containing "t OR x" the regex remove it. For example:

```<code>1) fileName.txt   -> result after split -> fileName -> OK.
2) textfile.txt   -> result after split -> efile. -> remove any t OR x in file name.
</code>```

My Q is : How i can remove only last three char.

Thank you

答:
If you want to remove the file's extension a regex is much too complicated for the task. You can work with String.lastIndexOf(int) instead to determine the position of the file extension:</p>

```<code>public static String extractFileName(final String fileName)
{
    final int dotIndex = fileName.lastIndexOf('.');
    return dotIndex < 0 ? fileName : fileName.substring(0,dotIndex);
}
</code>```

Body:
I want to remove last three character of filenames.  To rename any files, i'm using:

String str = ""; // Here set File name, i.e. listFile.getName();
String[] tempFile = str.split("[$^txt]");

This regex remove last three character it's OK, but when passing any file name containing "t OR x" the regex remove it. For example:

1) fileName.txt   -> result after split -> fileName -> OK.
2) textfile.txt   -> result after split -> efile. -> remove any t OR x in file name.

My Q is : How i can remove only last three char.

Thank you

Body:
If you want to remove the file's extension a regex is much too complicated for the task. You can work with String.lastIndexOf(int) instead to determine the position of the file extension:

public static String extractFileName(final String fileName)
{
    final int dotIndex = fileName.lastIndexOf('.');
    return dotIndex < 0 ? fileName : fileName.substring(0,dotIndex);
}


问:
Threads and access to a shared list
I'm encountering (I hope) a deadlocking issue with a WCF service I'm trying to write.

I have the following lock on a function that "locates" a particular item im the list:

```<code> CIPRecipe FindRecipe_ByUniqueID(string uniqueID)
    {
        lock (_locks[LOCK_RECIPES])
        {
            foreach (var r in _recipes.Keys)
            {
                if (_recipes[r].UniqueID == uniqueID)
                {
                    return _recipes[r];
                }
            }
        }
        return null;
    }
</code>```

However, various functions reiterate through this list and always apply the same LOCK for example ....

```<code> lock (_locks[LOCK_RECIPES_NO_ADD_OR_REMOVE])
            {
                foreach (var r in _recipes)
                {
                    r.Value.UpdateSummary();
                    summaries.Add((RecipeSummary)r.Value.Summary);
                }
            }
</code>```

What I suspect is,  an item in _recipes in the above example has suddenly called a function which ultimately calls the first function - "CIPRecipe FindRecipe_ByUniqueID(string uniqueID)" and this is causing a deadlock when it is reached in the iteration.

I need to stop this list changing whilst I'm iterating through it. Can someone advise me the best practice?

Thanks

答: Perhaps a ConcurrentDictionary is called for here?</p>

Title: Threads and access to a shared list

Body:
I'm encountering (I hope) a deadlocking issue with a WCF service I'm trying to write.

I have the following lock on a function that "locates" a particular item im the list:

 CIPRecipe FindRecipe_ByUniqueID(string uniqueID)
    {
        lock (_locks[LOCK_RECIPES])
        {
            foreach (var r in _recipes.Keys)
            {
                if (_recipes[r].UniqueID == uniqueID)
                {
                    return _recipes[r];
                }
            }
        }
        return null;
    }

However, various functions reiterate through this list and always apply the same LOCK for example ....

 lock (_locks[LOCK_RECIPES_NO_ADD_OR_REMOVE])
            {
                foreach (var r in _recipes)
                {
                    r.Value.UpdateSummary();
                    summaries.Add((RecipeSummary)r.Value.Summary);
                }
            }

What I suspect is,  an item in _recipes in the above example has suddenly called a function which ultimately calls the first function - "CIPRecipe FindRecipe_ByUniqueID(string uniqueID)" and this is causing a deadlock when it is reached in the iteration.

I need to stop this list changing whilst I'm iterating through it. Can someone advise me the best practice?

Thanks


问:
Formatting in percent by Intl.NumberFormat in JavaScript
```<code>var discount = 25.1;

var option = {
   style: 'percent',
   maximumFractionDigits: 2
};
var formatter = new Intl.NumberFormat(locale, option);
var discountFormat = formatter.format(discount );
// discountFormat return -> 2.510%
</code>```

<p>While I want you to come back like this: 25.10% </p>

答:
Because 25.1 is 2510%. Percentages are fractions of 100. If you had 100% it would be 100/100 which is equal to 1. So 25.1% is 25/100 or 0.251 not 25.1

var discount = 0.251;

var option = {
   style: 'percent',
   minimumFractionDigits: 2,
   maximumFractionDigits: 2
};
var formatter = new Intl.NumberFormat("en-US",option);
var discountFormat = formatter.format(discount );
console.log(discountFormat);```

Also if you wanted to keep the trailing zero you would need to set minimumFractionDigits as the default for percentages is 0.

If your value is the actual percentage to be displayed, you would just put the % symbol on the end, eg value = 25.1+"0%";.

Body:
var discount = 25.1;

var option = {
   style: 'percent',
   maximumFractionDigits: 2
};
var formatter = new Intl.NumberFormat(locale, option);
var discountFormat = formatter.format(discount );
// discountFormat return -> 2.510%

While I want you to come back like this: 25.10%

Body:
Because 25.1 is 2510%. Percentages are fractions of 100. If you had 100% it would be 100/100 which is equal to 1. So 25.1% is 25/100 or 0.251 not 25.1

var discount = 0.251;

var option = {
   style: 'percent',
   minimumFractionDigits: 2,
   maximumFractionDigits: 2
};
var formatter = new Intl.NumberFormat("en-US",option);
var discountFormat = formatter.format(discount );
console.log(discountFormat);

Also if you wanted to keep the trailing zero you would need to set minimumFractionDigits as the default for percentages is 0.

If your value is the actual percentage to be displayed, you would just put the % symbol on the end, eg value = 25.1+"0%";.


问:
Error with a bash loop for sqlite insert
I'm trying to insert stuff in db whith a while loop, but after 2 inserts my loop break ...
here the code:

```<code>x=0
while [[ "$x" < 10 ]];do
    ((x++))
    sqlite my_db.db "insert into (col) values ('$x...')
done
</code>```

So I tried to do that  but unsuccess too.

```<code>y=0
x=0
while [[ "$y" < 5 ]];do
    while [[ "$x" < 10 ]];do
        ((x++))
        sqlite my_db.db "insert into (col) values ('$x...')"
    done
    ((y++))
done
</code>```

But once again its only insert 2 times ...
So why did i have this error and how to fixe that ? thx.

答:
< and > are string comparison operators.

For integers you must use -lt (less than) and -gt (greater than) respectively.

Also close the query string.

```<code>x=0
while [[ "$x" -lt 10 ]];do
    ((x++))
    sqlite my_db.db "insert into (col) values ('$x...')"
done
</code>```

Body:
I'm trying to insert stuff in db whith a while loop, but after 2 inserts my loop break ...
here the code:

x=0
while [[ "$x" < 10 ]];do
    ((x++))
    sqlite my_db.db "insert into (col) values ('$x...')
done

So I tried to do that  but unsuccess too.

y=0
x=0
while [[ "$y" < 5 ]];do
    while [[ "$x" < 10 ]];do
        ((x++))
        sqlite my_db.db "insert into (col) values ('$x...')"
    done
    ((y++))
done

But once again its only insert 2 times ...
So why did i have this error and how to fixe that ? thx.

Body:
< and > are string comparison operators.

For integers you must use -lt (less than) and -gt (greater than) respectively.

Also close the query string.

x=0
while [[ "$x" -lt 10 ]];do
    ((x++))
    sqlite my_db.db "insert into (col) values ('$x...')"
done


问:
Get ID using the name and folder of a spreadsheet
I'm copying some spreadsheets and those copies need to be edited (transform formulas into raw data) and I CAN'T edit the source spreadsheet.

I'm creating a simple copy of the source spreadsheet:

```<code> DriveApp.getFileById("ID HERE").makeCopy(name, folder);
</code>```

So, at this point I have the name and folder of the new spreadsheet but I need to how to access and edit it. Maybe getting it's ID or URL.

Thanks in advance.

答:
Likely what you are looking for is

```<code>var id = DriveApp.getFileById("ID HERE").makeCopy(name, folder).getId();
</code>```

or alternatively a general case

```<code>var files = DriveApp.getFilesByName(name);
while (files.hasNext()) {
   var file = files.next();
   var id = file.getId();
}

// do something with id here
</code>```

If there are multiple files with the same name, you may encounter the issue of making a copy of the wrong file.

Body:
I'm copying some spreadsheets and those copies need to be edited (transform formulas into raw data) and I CAN'T edit the source spreadsheet.

I'm creating a simple copy of the source spreadsheet:

 DriveApp.getFileById("ID HERE").makeCopy(name, folder);

So, at this point I have the name and folder of the new spreadsheet but I need to how to access and edit it. Maybe getting it's ID or URL.

Thanks in advance.

Body:
Likely what you are looking for is

var id = DriveApp.getFileById("ID HERE").makeCopy(name, folder).getId();

or alternatively a general case

var files = DriveApp.getFilesByName(name);
while (files.hasNext()) {
   var file = files.next();
   var id = file.getId();
}

// do something with id here

If there are multiple files with the same name, you may encounter the issue of making a copy of the wrong file.


问:
How to assign a method to a button when pressed or released with ActionListener in Java?
I am new to coding GUIs in Java and I am trying to just print a message on the terminal when a button is pressed and another one when it is released.

This is what I have for a regular button pressing.

```<code> leftButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Pressed");
        }
    });
</code>```

I did this with the help of IntelliJ IDEA. I want to make the button send a message when pressed and a different thing when released.

答:
You can use a MouseListener instead:

```<code>leftButton.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
        // The mouse button was pressed and released
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // The mouse button was pressed
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // The mouse button was released
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // The cursor entered the bounds of the button (i.e. hovering)
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // The cursor exited the bounds of the button
    }
});
</code>```

Body:
I am new to coding GUIs in Java and I am trying to just print a message on the terminal when a button is pressed and another one when it is released.

This is what I have for a regular button pressing.

 leftButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Pressed");
        }
    });

I did this with the help of IntelliJ IDEA. I want to make the button send a message when pressed and a different thing when released.

Body:
You can use a MouseListener instead:

leftButton.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
        // The mouse button was pressed and released
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // The mouse button was pressed
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // The mouse button was released
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // The cursor entered the bounds of the button (i.e. hovering)
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // The cursor exited the bounds of the button
    }
});


问:
couldn't find samples in android-sdk directory
When I go to the directory C:/programfiles/android/android-sdk/platform/<version>/
I couldn't find the samples directory.

I installed all the versions of the sdk with samples from the sdk manager opening from eclipse but I couldn't install the same when I open it from

start--> all programs--> android--> sdk

when I open sdk from eclipse it shows installed which when opened from start menu shows as not installed.

Can anyone help me to find the samples directory?
I create the project from samples in eclipse.

答: You can currently view them online at https://android.googlesource.com/platform/development/+/05523fb0b48280a5364908b00768ec71edb847a2/samples</p>


问:
posting a value and retrieve it in php
I have two fields in a form category name and id. The id is an auto increment. After posting the category name, I want that posted category id pass to next page.

I think i am doing some mistake in select statement.

http://pastebin.com/3Tu2Hr6g

答:
Fetch your last inserted id using   mysql_insert_id()

Sample...

```<code>$res = mysql_query( "SELECT LAST_INSERT_ID()" );

or

$res - mysql_insert_id();
</code>```

OwnerDisplayName: Please delete me

LastEditorDisplayName: Please delete me

Title: posting a value and retrieve it in php

Body:
Fetch your last inserted id using   mysql_insert_id()

Sample...

$res = mysql_query( "SELECT LAST_INSERT_ID()" );

or

$res - mysql_insert_id();


Title: Regular expression to extract file name?

Body:
Try this RegEx instead:

 ^\\(.+\\)*(.+)\.(.+)$


问:
Execute JavaScript in a modal window
I have the following JS code:

```<code><script type="text/javascript">
    $(document).ready(function () {
        var items = "<option value='0'>Select</option>";
        $('#DistrictID').html(items);
    });
</script>
</code>```

This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.

But since it is mark as

```<code>$(document).ready
</code>```

This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?

Thanks in advance!

Regards,

答:
You can easily achieve this using bootstrap modal events. You can use following code snippet to achieve your objective:

```<code>$(document).ready(function () {
     $('#myModal').on('shown.bs.modal', function (e) {
            var items = "<option value='0'>Select</option>";
            $('#DistrictID').html(items);
      });
});
</code>```

For reference Please check bootstrap modal events.

Title: Execute JavaScript in a modal window

Body:
I have the following JS code:

This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.

But since it is mark as

$(document).ready

This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?

Thanks in advance!

Regards,

Body:
You can easily achieve this using bootstrap modal events. You can use following code snippet to achieve your objective:

$(document).ready(function () {
     $('#myModal').on('shown.bs.modal', function (e) {
            var items = "<option value='0'>Select</option>";
            $('#DistrictID').html(items);
      });
});

For reference Please check bootstrap modal events.


问:
How can I link Trac with Git?
I am trying to set up Trac 1.0.1 with git on CentOS 7.

Trac is running fine but I am not able to link a Git repository with Trac.

Here is what I've done so far:

```<code>yum install git
adduser git
mkdir -p /srv/git/myrepo
cd /srv/git/myrepo
git --bare --shared=true init
chown -R git:git -R /srv/git/myrepo
</code>```

At this point I am able to clone and checkin changes from a client.

Now I want to browse the source files via trac. Here I've changed the Trac.ini like this:

```<code>repository_type = git
[components]
tracopt.versioncontrol.git.* = enabled
</code>```

If I understand correctly, I now have two options to add the repository.

Directly in the Trac.ini file

```<code>repository_dir = /srv/git/myrepo
</code>```

or via the admin panel in the menu 'repositories'

If I add the repo directly in the trac.ini config-file I get the following error:

Warning: Can't synchronize with repository "(default)"
  (/srv/git/myrepo does not appear to be a Git repository.). Look in the
  Trac log for more information.

The problem here is, that there is no log file, although it's set in the trac.ini to debug and to trac.log. If I add the repo via the admin panel, I get no errors but there is also no browse tab.

What am I doing wrong?

答:
I had some trouble with this. There's no [components] section in the initial Trac.ini, and several different methods for enabling and adding repositories to your Trac environment are presented, leading one to believe that any one of them will suffice. I believe this not to be the case.

The successful actions for me were to:

Specify the following in the TracIni [versioncontrol] section:

default_repository_type = 'git'

Add the missing [components] section to trac.ini:

```<code>[components]
tracopt.versioncontrol.git.* = enabled
</code>```

Use the 'database' method and trac-admin to add the repository. Please note: 'git' is not yet "a valid type". Omit this final argument to the command:

repository add <repo> <dir> [type]

Title: How can I link Trac with Git?

Body:
I am trying to set up Trac 1.0.1 with git on CentOS 7.

Trac is running fine but I am not able to link a Git repository with Trac.

Here is what I've done so far:

yum install git
adduser git
mkdir -p /srv/git/myrepo
cd /srv/git/myrepo
git --bare --shared=true init
chown -R git:git -R /srv/git/myrepo

At this point I am able to clone and checkin changes from a client.

Now I want to browse the source files via trac. Here I've changed the Trac.ini like this:

repository_type = git
[components]
tracopt.versioncontrol.git.* = enabled

If I understand correctly, I now have two options to add the repository.

Directly in the Trac.ini file

repository_dir = /srv/git/myrepo

or via the admin panel in the menu 'repositories'

If I add the repo directly in the trac.ini config-file I get the following error:

Warning: Can't synchronize with repository "(default)"
  (/srv/git/myrepo does not appear to be a Git repository.). Look in the
  Trac log for more information.

The problem here is, that there is no log file, although it's set in the trac.ini to debug and to trac.log. If I add the repo via the admin panel, I get no errors but there is also no browse tab.

What am I doing wrong?

Body:
I had some trouble with this. There's no [components] section in the initial Trac.ini, and several different methods for enabling and adding repositories to your Trac environment are presented, leading one to believe that any one of them will suffice. I believe this not to be the case.

The successful actions for me were to:

Specify the following in the TracIni [versioncontrol] section:

default_repository_type = 'git'

Add the missing [components] section to trac.ini:

[components]
tracopt.versioncontrol.git.* = enabled

Use the 'database' method and trac-admin to add the repository. Please note: 'git' is not yet "a valid type". Omit this final argument to the command:

repository add <repo> <dir> [type]


问:
ChromeDriver hangs on a page with many images randomly for 20-30 minutes
I used ChromeDriver for automation web page interaction for a while, however, there is a random issue I'm not able to resolve. I hope to search help in this community.

ChromeDriver: I've tried 2.12 - 2.16, all of them has this issue

Chrome: Version 43.0.2357.134 m

Selenium: 2.44

JAVA: 1.7.79 X86

Symptom: When program run to the last page, it hangs there, sometimes it will cost 20-30 minutes for webdriver get back, within this time, WebDriver is out of control, program can do nothing about WebDriver. And in status bar of chrome there are some words saying "waiting for pda-ads.amazon.com"...

I don't know whether there is a solution to resolve this issue. I've tried below ways:

Submit a callable task with timeout of 10 seconds, in case it still hangs on, throw exception and continue, however, at this time WebDriver still hangs, I cannot get necessary information in the last page, only manually enter anther web site address will make WebDriver come back to normal

Maybe it's due to the first time load page will consume very long time, so I'm not sure whether a profile setting so that it might use local cache would be better

I even thought of to call external auto keyboard tools to get information in last page, however I don't practice yet.

Would you please give me some thoughts or tips to resolve this issue or a workaround?

PS: I've already set timeout values like this:

```<code>driver.manage().timeouts()
.implicitlyWait(timeOut, TimeUnit.MILLISECONDS)
.pageLoadTimeout(timeOut * 3, TimeUnit.SECONDS)
.setScriptTimeout(timeOut * 3, TimeUnit.SECONDS)
</code>```

implicitlWait timeout is 10 seconds, thus pageload timeout and script timeout are both 30 seconds, I've always set these timeout values, but still not works.

答:
We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.</p>

```<code>        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }
</code>```

Body:
I used ChromeDriver for automation web page interaction for a while, however, there is a random issue I'm not able to resolve. I hope to search help in this community.

ChromeDriver: I've tried 2.12 - 2.16, all of them has this issue

Chrome: Version 43.0.2357.134 m

Selenium: 2.44

JAVA: 1.7.79 X86

Symptom: When program run to the last page, it hangs there, sometimes it will cost 20-30 minutes for webdriver get back, within this time, WebDriver is out of control, program can do nothing about WebDriver. And in status bar of chrome there are some words saying "waiting for pda-ads.amazon.com"...

I don't know whether there is a solution to resolve this issue. I've tried below ways:

Submit a callable task with timeout of 10 seconds, in case it still hangs on, throw exception and continue, however, at this time WebDriver still hangs, I cannot get necessary information in the last page, only manually enter anther web site address will make WebDriver come back to normal

Maybe it's due to the first time load page will consume very long time, so I'm not sure whether a profile setting so that it might use local cache would be better

I even thought of to call external auto keyboard tools to get information in last page, however I don't practice yet.

Would you please give me some thoughts or tips to resolve this issue or a workaround?

PS: I've already set timeout values like this:

driver.manage().timeouts()
.implicitlyWait(timeOut, TimeUnit.MILLISECONDS)
.pageLoadTimeout(timeOut * 3, TimeUnit.SECONDS)
.setScriptTimeout(timeOut * 3, TimeUnit.SECONDS)

implicitlWait timeout is 10 seconds, thus pageload timeout and script timeout are both 30 seconds, I've always set these timeout values, but still not works.

Body:
We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.

        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }


问:
C# webservice unable to use HTTP POST to send bytes to it
I have the followind webservice defined.

```<code>       [WebMethod]
        public String sendBytes(byte[] a)
        {
            return "good";
        }
</code>```

I am able to call it successfully using the Webservice proxy class.

However I am unable to send a HTTP POST with binaries to this web method.
I tried this:

```<code>      try
           {
               HttpWebRequest request = HttpWebRequest.Create(address) as
               HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //request.ContentLength = 0;

            var postData = "xxx";

            var data = Encoding.UTF8.GetBytes(postData);

            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            String x = Console.ReadLine();
</code>```

and I got this

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

The thing is I can send Strings using this method, but not binary data. The definition in the webservice POST Example is also wierd.

http://localhost:50178/WebService1.asmx?op=sendBytes

I am grateful for ANY help or suggestions on this topic. Thx for reading :)

Edit:
Thank you for your quick response.

I think I have solved the null exception, I think the cause of it is because it cant find the param for the value that I am sending. But I have another problem now:

System.ArgumentException: Cannot convert ef to System.Byte.
Parameter name: type ---> System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at System.String.System.IConvertible.ToByte(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type)
   --- End of inner exception stack trace ---
   at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type)
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Here is the code:

```<code>          try
        {
            HttpWebRequest request = HttpWebRequest.Create(address) as
           HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //request.ContentLength = 0;

            var postData = "a=";

            var data = Encoding.UTF8.GetBytes(postData);
            byte[] bytedata = new byte[] { 0x65,0x66};
            request.ContentLength = data.Length + bytedata.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Write(bytedata, 0, bytedata.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
</code>```

Edit 2:
I have tried Aaron's suggestion but it did not work.

Here is the edited code:

```<code>        try
        {
            HttpWebRequest request = HttpWebRequest.Create(address) as
          HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/octet-stream";

            //request.ContentLength = 0;

            var postData = "a=";

            var data = Encoding.UTF8.GetBytes(postData);
            byte[] bytedata = new byte[] { 0x65,0x66};
            request.ContentLength = data.Length + bytedata.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Write(bytedata, 0, bytedata.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
</code>```

Gave the following error:

System.InvalidOperationException: Request format is invalid:
   application/octet-stream.
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Reference :How can I make a local file as body of an HttpWebRequest?.

The thing is i tried changing the url, because if the problem was the packet not being formed well I would get the same error, but it dint. Could it be my webservice being wrong somewhere?

答:
Try setting the request.ContentType to application/octet-stream.  This content type is used to signal that the request body contains arbitrary binary data.

Remember that HTTP is a text based protocol that uses ASCII encoding in it's messages. In your test data 0x65 and 0x66 are 'e' and 'f' in which is why the exception you get says "Cannot convert ef to System.Byte". The bytes you are trying to send are getting encoded to ASCII, therefore becoming a string, where your endpoint is expecting bytes.

Edit:

You could also try using a multipart/form-data request.  Example of how to do it with C# is here:

https://gist.github.com/bgrins/1789787

References:

Why Http Protocol is designed in a plain text way

Which Mime Type to use for a binary file

Body:
I have the followind webservice defined.

       [WebMethod]
        public String sendBytes(byte[] a)
        {
            return "good";
        }

I am able to call it successfully using the Webservice proxy class.

However I am unable to send a HTTP POST with binaries to this web method.
I tried this:

      try
           {
               HttpWebRequest request = HttpWebRequest.Create(address) as
               HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //request.ContentLength = 0;

            var postData = "xxx";

            var data = Encoding.UTF8.GetBytes(postData);

            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            String x = Console.ReadLine();

and I got this

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

The thing is I can send Strings using this method, but not binary data. The definition in the webservice POST Example is also wierd.

http://localhost:50178/WebService1.asmx?op=sendBytes

I am grateful for ANY help or suggestions on this topic. Thx for reading :)

Edit:
Thank you for your quick response.

I think I have solved the null exception, I think the cause of it is because it cant find the param for the value that I am sending. But I have another problem now:

System.ArgumentException: Cannot convert ef to System.Byte.
Parameter name: type ---> System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at System.String.System.IConvertible.ToByte(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type)
   --- End of inner exception stack trace ---
   at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type)
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Here is the code:

          try
        {
            HttpWebRequest request = HttpWebRequest.Create(address) as
           HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //request.ContentLength = 0;

            var postData = "a=";

            var data = Encoding.UTF8.GetBytes(postData);
            byte[] bytedata = new byte[] { 0x65,0x66};
            request.ContentLength = data.Length + bytedata.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Write(bytedata, 0, bytedata.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Edit 2:
I have tried Aaron's suggestion but it did not work.

Here is the edited code:

        try
        {
            HttpWebRequest request = HttpWebRequest.Create(address) as
          HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/octet-stream";

            //request.ContentLength = 0;

            var postData = "a=";

            var data = Encoding.UTF8.GetBytes(postData);
            byte[] bytedata = new byte[] { 0x65,0x66};
            request.ContentLength = data.Length + bytedata.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Write(bytedata, 0, bytedata.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Gave the following error:

System.InvalidOperationException: Request format is invalid:
   application/octet-stream.
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Reference :How can I make a local file as body of an HttpWebRequest?.

The thing is i tried changing the url, because if the problem was the packet not being formed well I would get the same error, but it dint. Could it be my webservice being wrong somewhere?


问:
Flow of my spark streaming program
Small question about the flow of my spark streaming program.

I have this function :

```<code>def parse(msg: String): Seq[String]
</code>```

Which actually split a "good" message into multiple strings, and, if the string is "bad", returns an empty Seq.

I'm reading the messages from a kafka topic, and I want to send the results of the parsing into two different topics:
If the message is "good", send the result of the parsing to the topic "good_msg_topic"
If the message is "bad", send the "bad" message to the topic "bad_msg_topic"

To achieve that, I did this :

```<code>stream.foreachRDD(rdd => {
  val res = rdd.map(msg => msg.value() -> parse(msg.value()))

  res.foreach(pair => {
    if (pair._2.isEmpty) {
      producer.send(junkTopic, pair._1)
    } else {
      pair._2.foreach(m => producer.send(splitTopic, m))
    }
  })
})
</code>```

However, I feel like this is not optimal. Using a Map Object to associate the original message to the result may slow down the process...

I'm beginning with Spark and Scala, so I think one could do better.

Any idea on how I could improve that ? Changing the signature of the parse function if also possible if you think it's better.

Thank you

答:
I wouldn't be too concerned regarding performance if you haven't already measured this and found a bottleneck.

One thing I can think of which might make this code clearer is to use an ADT to describe the result type:

```<code>sealed trait Result
case class GoodResult(seq: Seq[String]) extends Result
case class BadResult(original: String) extends Result
</code>```

Have parse return Result

```<code>def parse(s: String): Result
</code>```

And then use map on DStream instead of RDD:

```<code>stream
.map(msg => parse(msg.value())
.foreachRDD { rdd =>
   rdd.foreach { result =>
     result match {
       case GoodResult(seq) => seq.foreach(value => producer.send(splitTopic, value))
       case BadResult(original) => producer.send(junkTopic, original)
     }
   }
}
</code>```

Title: Flow of my spark streaming program

Body:
Small question about the flow of my spark streaming program.

I have this function :

def parse(msg: String): Seq[String]

Which actually split a "good" message into multiple strings, and, if the string is "bad", returns an empty Seq.

I'm reading the messages from a kafka topic, and I want to send the results of the parsing into two different topics:
If the message is "good", send the result of the parsing to the topic "good_msg_topic"
If the message is "bad", send the "bad" message to the topic "bad_msg_topic"

To achieve that, I did this :

stream.foreachRDD(rdd => {
  val res = rdd.map(msg => msg.value() -> parse(msg.value()))

  res.foreach(pair => {
    if (pair._2.isEmpty) {
      producer.send(junkTopic, pair._1)
    } else {
      pair._2.foreach(m => producer.send(splitTopic, m))
    }
  })
})

However, I feel like this is not optimal. Using a Map Object to associate the original message to the result may slow down the process...

I'm beginning with Spark and Scala, so I think one could do better.

Any idea on how I could improve that ? Changing the signature of the parse function if also possible if you think it's better.

Thank you

Body:
I wouldn't be too concerned regarding performance if you haven't already measured this and found a bottleneck.

One thing I can think of which might make this code clearer is to use an ADT to describe the result type:

sealed trait Result
case class GoodResult(seq: Seq[String]) extends Result
case class BadResult(original: String) extends Result

Have parse return Result

def parse(s: String): Result

And then use map on DStream instead of RDD:

stream
.map(msg => parse(msg.value())
.foreachRDD { rdd =>
   rdd.foreach { result =>
     result match {
       case GoodResult(seq) => seq.foreach(value => producer.send(splitTopic, value))
       case BadResult(original) => producer.send(junkTopic, original)
     }
   }
}


问:
Generating Fibonacci Sequence
```<code>var x = 0;
var y = 1;
var z;

fib[0] = 0;
fib[1] = 1;

for (i = 2; i <= 10; i++) {
  alert(x + y);
  fib[i] = x + y;
  x = y;
  z = y;
}
</code>```

I'm trying to get to generate a simple Fibonacci Sequence but there no output.

Can anybody let me know what's wrong?

答:
```<code>function getFibonacciNumbers(n) {
    var sequence = [0, 1];
    if (n === 0 || n === 1) {
        return sequence[n];
    }
    else {
        for (var i = 2; i < n; i++ ) {
            var sum = sequence[i - 1] + sequence[i - 2];
            sequence.push(sum);
        }
    return sequence;
    }
}
console.log(getFibonacciNumbers(0));
console.log(getFibonacciNumbers(1));
console.log(getFibonacciNumbers(9));
</code>```

ContentLicense: CC BY-SA 4.0

Title: Generating Fibonacci Sequence

Body:
var x = 0;
var y = 1;
var z;

fib[0] = 0;
fib[1] = 1;

for (i = 2; i <= 10; i++) {
  alert(x + y);
  fib[i] = x + y;
  x = y;
  z = y;
}

I'm trying to get to generate a simple Fibonacci Sequence but there no output.

Can anybody let me know what's wrong?


问:
Github public site with Jekyll does not update anymore
Excuse me again for seeking help for my site at meredithhu.github.io.

All the codes are here: https://github.com/meredithhu/meredithhu.github.io.

As you can see the updated codes never get updated any more, for instance,
the About page here https://github.com/meredithhu/meredithhu.github.io/About
never gets updated according to my most recent changes in codes:
https://github.com/meredithhu/meredithhu.github.io/blob/master/About/index.html

The same goes for my Reseach/Misc/Memo pages...

Could anyone give me some hints how to fix the problem?

答:
This is the error you should address: Liquid Exception: Invalid Date: 'nil' is not a valid datetime. in /_layouts/blog.html.

You should use {{ page.date | date_to_string }} only if page.date is a valid date, so you can check if it is not nil updating _layouts/blog.html:

```<code>{%if page.date%}
 <p class="meta">{{ page.date | date_to_string }}</p>
{%endif%}
</code>```

Body:
This is the error you should address: Liquid Exception: Invalid Date: 'nil' is not a valid datetime. in /_layouts/blog.html.

You should use {{ page.date | date_to_string }} only if page.date is a valid date, so you can check if it is not nil updating _layouts/blog.html:

{%if page.date%}
 <p class="meta">{{ page.date | date_to_string }}</p>
{%endif%}


问:
Spree Allow admin login with different roles added in user
In my Spree Application i have created new role having name sales_rep and i want to give admin access to users having this role.

Here you can find my cancan ability file:

```<code>module Spree
  class SalesRepAbility
  include CanCan::Ability

  def initialize(user)
    if user.respond_to?(:has_spree_role?) && user.has_spree_role?('sales_rep')
      can :manage, :all
    end
  end
 end
end
</code>```

but when i try to login via admin with admin/login URL it is not authenticating user other than admin.

Actually i want to override Spree::Admin::UserSessionsController's create method in which authenticate_spree_user! is failing.

Is there any way to override Spree::Admin::UserSessionsController's authenticate_spree_user! method so that having role of sales_rep can access this Admin panel.

Here is my method of controller:

```<code> def create
   authenticate_spree_user!

  if spree_user_signed_in?
    respond_to do |format|
      format.html {
        flash[:success] = Spree.t(:logged_in_succesfully)

redirect_back_or_default(after_sign_in_path_for(spree_current_user))
    }
      format.js {
        user = resource.record
        render :json => {:ship_address => user.ship_address, :bill_address => user.bill_address}.to_json
    }
    end
  end
</code>```

I just want to allow user having sales_rep role to login same as Admin do in Spree and for that i want to override Spree::Admin::UserSessionsController's create method.

Is there any way to achieve this? How i can allow user having different role than admin to access panel.

Any help appreciated!!

答:
You have to register your ability also.
Add Spree::Ability.register_ability(Spree:: SalesRepAbility) in spree.rb and restart you server

Body:
In my Spree Application i have created new role having name sales_rep and i want to give admin access to users having this role.

Here you can find my cancan ability file:

module Spree
  class SalesRepAbility
  include CanCan::Ability

  def initialize(user)
    if user.respond_to?(:has_spree_role?) && user.has_spree_role?('sales_rep')
      can :manage, :all
    end
  end
 end
end

but when i try to login via admin with admin/login URL it is not authenticating user other than admin.

Actually i want to override Spree::Admin::UserSessionsController's create method in which authenticate_spree_user! is failing.

Is there any way to override Spree::Admin::UserSessionsController's authenticate_spree_user! method so that having role of sales_rep can access this Admin panel.

Here is my method of controller:

 def create
   authenticate_spree_user!

  if spree_user_signed_in?
    respond_to do |format|
      format.html {
        flash[:success] = Spree.t(:logged_in_succesfully)

redirect_back_or_default(after_sign_in_path_for(spree_current_user))
    }
      format.js {
        user = resource.record
        render :json => {:ship_address => user.ship_address, :bill_address => user.bill_address}.to_json
    }
    end
  end

I just want to allow user having sales_rep role to login same as Admin do in Spree and for that i want to override Spree::Admin::UserSessionsController's create method.

Is there any way to achieve this? How i can allow user having different role than admin to access panel.

Any help appreciated!!


问:
Permission Denied while trying to connect to Docker Daemon while running Jenkins pipeline in Macbook
I am trying to run Jenkins pipeline job in my macbook. I also have docker instance running locally. Initially I got the "docker command not found" error while running the Jenkins Job. I fixed the error by adding a symlink "ln -f -s /Applications/Docker.app/Contents/Resources/bin/* /usr/local/bin"

I also applied these two changes so that jenkins user has the access to the docker directory

chmod -R 777 /Users/myUserName/Library/Containers/com.docker.docker/

chmod -R 777 /Users/myUserName/Library/Containers/com.docker.helper/

I am getting below errors:

Got permission denied while trying to connect to the Docker daemon
  socket at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.27/containers/openjdk:8/json:
  dial unix /var/run/docker.sock: connect: permission denied
      [Pipeline] sh
      [test] Running shell script
      + docker pull openjdk:8
      Warning: failed to get default registry endpoint from daemon (Got permission denied while trying to connect to the Docker daemon socket
  at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.27/info: dial unix
  /var/run/docker.sock: connect: permission denied). Using system
  default: https://index.docker.io/v1/
      Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post
  http://%2Fvar%2Frun%2Fdocker.sock/v1.27/images/create?fromImage=openjdk&tag=8:
  dial unix /var/run/docker.sock: connect: permission denied
      [Pipeline] }
      [Pipeline] // node
      [Pipeline] End of Pipeline
      ERROR: script returned exit code 1
      Finished: FAILURE

答:
This is a docker permission issue. Add the jenkins user to docker group as follow:

usermod -aG docker ${USER}


问:
Configure routing in GAE java standard environment
I have a GAE application in java standard environment for the backend and angular 4.0 for the frontend.

The app works fine locally, but when deployed, I get a 404 error when refreshing or when trying to type the url of the desired page.

I understand that I have got to define a routing fallback as described in the angular documentation in order to redirect every unknown request to my index.html.

As I understand it from many stackoverflow GAE appengine python questions, the solution consists of configuring the app.yaml file.

Ok, but how? In the app engine standard environment, the app.yaml file is auto-generated in the staging folder as follow, but everything happens under the hood when I deploy with the google plugin for eclipse and I have no access to it.

```<code>runtime: java7
inbound_services:
- warmup
derived_file_type:
- java_precompiled
threadsafe: True
auto_id_policy: default
api_version: '1.0'
handlers:
- url: (/.*/)
static_files: __static__\1index.html
upload: __NOT_USED__
require_matching_file: True
login: optional
secure: optional
- url: (/)
static_files: __static__\1index.html
upload: __NOT_USED__
require_matching_file: True
login: optional
secure: optional
- url: (/.*)
static_files: __static__\1
upload: __NOT_USED__
require_matching_file: True
login: optional
secure: optional
- url: /.*
script: unused
login: optional
secure: optional
</code>```

Can someone tell me if there is a way to edit the app.yaml file before deploying in the appengine java standard environment.
A similar question has been posted recently but there is no response for the moment.

答:
I think you're confusing angular routing, which happens on the browser side, from the server-side URL routing, which is described by a web.xml.

My guess is that your web.xml is missing a welcome file to load the index.html.  For example, here's a simple web.xml that should do the trick:

```<code><?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
 <welcome-file-list>
   <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>
</code>```

Body:
I have a GAE application in java standard environment for the backend and angular 4.0 for the frontend.

The app works fine locally, but when deployed, I get a 404 error when refreshing or when trying to type the url of the desired page.

I understand that I have got to define a routing fallback as described in the angular documentation in order to redirect every unknown request to my index.html.

As I understand it from many stackoverflow GAE appengine python questions, the solution consists of configuring the app.yaml file.

Ok, but how? In the app engine standard environment, the app.yaml file is auto-generated in the staging folder as follow, but everything happens under the hood when I deploy with the google plugin for eclipse and I have no access to it.

runtime: java7
inbound_services:
- warmup
derived_file_type:
- java_precompiled
threadsafe: True
auto_id_policy: default
api_version: '1.0'
handlers:
- url: (/.*/)
static_files: __static__\1index.html
upload: __NOT_USED__
require_matching_file: True
login: optional
secure: optional
- url: (/)
static_files: __static__\1index.html
upload: __NOT_USED__
require_matching_file: True
login: optional
secure: optional
- url: (/.*)
static_files: __static__\1
upload: __NOT_USED__
require_matching_file: True
login: optional
secure: optional
- url: /.*
script: unused
login: optional
secure: optional

Can someone tell me if there is a way to edit the app.yaml file before deploying in the appengine java standard environment.
A similar question has been posted recently but there is no response for the moment.

Body:
I think you're confusing angular routing, which happens on the browser side, from the server-side URL routing, which is described by a web.xml.

My guess is that your web.xml is missing a welcome file to load the index.html.  For example, here's a simple web.xml that should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
 <welcome-file-list>
   <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>


问:
Missing python kernel in jupyter notebook
I am new to jupyter/ipython. I usually start the notebook on a remote machine and create a ssh tunnel. Details of how the tunnel is set up can be found here: http://www.hydro.washington.edu/~jhamman/hydro-logic/blog/2013/10/04/pybook-remote/

However, many times when I start a notebook, it reports back with 0 active kernels (not all the times). Following is the screenshot of that:

```<code>-bash-4.1$ jupyter notebook --no-browser --port=7777
[NotebookApp] Serving notebooks from local directory: /x/y/z
[NotebookApp] 0 active kernels
[NotebookApp] The Jupyter Notebook is running at: http://localhost:7777/
[NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
</code>```

I obviously have python.

```<code>python --version
Python 2.7.11 :: Anaconda 2.0.1 (64-bit)
</code>```

Can someone explain to me this erratic behavior? and how it can be fixed?

Any help would be appreciated.

Thank you

Attached is the error I get:

答:
I also use jupyter using a ssh tunnel and was getting 0 active kernels message and I could not run any notebook. My error snapshot is here.  The ipython kernel was not installed properly in the direct install of jupyter using sudo -H pip install jupyter. I resolved it by updating the ipython kernel using:

sudo apt-get -y install ipython ipython-notebook

sudo -H pip install jupyter

If it doesn't work, try uninstalling jupyter and then install packages in sequence as explained in this link.

Body:
I am new to jupyter/ipython. I usually start the notebook on a remote machine and create a ssh tunnel. Details of how the tunnel is set up can be found here: http://www.hydro.washington.edu/~jhamman/hydro-logic/blog/2013/10/04/pybook-remote/

However, many times when I start a notebook, it reports back with 0 active kernels (not all the times). Following is the screenshot of that:

-bash-4.1$ jupyter notebook --no-browser --port=7777
[NotebookApp] Serving notebooks from local directory: /x/y/z
[NotebookApp] 0 active kernels
[NotebookApp] The Jupyter Notebook is running at: http://localhost:7777/
[NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

I obviously have python.

python --version
Python 2.7.11 :: Anaconda 2.0.1 (64-bit)

Can someone explain to me this erratic behavior? and how it can be fixed?

Any help would be appreciated.

Thank you

Attached is the error I get:


问:
How to inject service into class (not component)
I'd like to inject a service into a class that is not a component.

For example:

Myservice

```<code>import {Injectable} from '@angular/core';
@Injectable()
export class myService {
  dosomething() {
    // implementation
  }
}
</code>```

MyClass

```<code>import { myService } from './myService'
export class MyClass {
  constructor(private myservice:myService) {

  }
  test() {
     this.myservice.dosomething();
  }
}
</code>```

I tried and it doesn't work. It seems like service need to be used in only component or service.

Is there a way to use a service in a normal class? or it's a bad practice to use a service in a normal class.

Thank you.

答:
Not a direct answer to the question, but if you're reading this SO for the reason I am this may help...

Let's say you're using ng2-translate and you really want your User.ts class to have it. You're immediate thought is to use DI to put it in, you are doing Angular after all. But that's kind of overthinking it, you can just pass it in your constructor, or make it a public variable you set from the component (where you presumably did DI it in).

e.g.:

```<code>import { TranslateService } from "ng2-translate";

export class User {
  public translateService: TranslateService; // will set from components.

  // a bunch of awesome User methods
}
</code>```

then from some user-related component that injected TranslateService

```<code>addEmptyUser() {
  let emptyUser = new User("", "");
  emptyUser.translateService = this.translateService;
  this.users.push(emptyUser);
}
</code>```

Hopefully this helps those out there like me who were about to write a lot of harder to maintain code because we're too clever sometimes =]

(NOTE: the reason you may want to set a variable instead of making it part of your constructor method is you could have cases where you don't need to use the service, so always being required to pass it in would mean introducing extra imports/code that are never really used)

Body:
I'd like to inject a service into a class that is not a component.

For example:

Myservice

import {Injectable} from '@angular/core';
@Injectable()
export class myService {
  dosomething() {
    // implementation
  }
}

MyClass

import { myService } from './myService'
export class MyClass {
  constructor(private myservice:myService) {

  }
  test() {
     this.myservice.dosomething();
  }
}

I tried and it doesn't work. It seems like service need to be used in only component or service.

Is there a way to use a service in a normal class? or it's a bad practice to use a service in a normal class.

Thank you.

Body:
Not a direct answer to the question, but if you're reading this SO for the reason I am this may help...

Let's say you're using ng2-translate and you really want your User.ts class to have it. You're immediate thought is to use DI to put it in, you are doing Angular after all. But that's kind of overthinking it, you can just pass it in your constructor, or make it a public variable you set from the component (where you presumably did DI it in).

e.g.:

import { TranslateService } from "ng2-translate";

export class User {
  public translateService: TranslateService; // will set from components.

  // a bunch of awesome User methods
}

then from some user-related component that injected TranslateService

addEmptyUser() {
  let emptyUser = new User("", "");
  emptyUser.translateService = this.translateService;
  this.users.push(emptyUser);
}

Hopefully this helps those out there like me who were about to write a lot of harder to maintain code because we're too clever sometimes =]

(NOTE: the reason you may want to set a variable instead of making it part of your constructor method is you could have cases where you don't need to use the service, so always being required to pass it in would mean introducing extra imports/code that are never really used)