问:
How to set and capture unchecked and checked checkboxes in Angular 2?
In the above code i want to display initial state of checkboxes as mentioned in initialstatus array in UI and then I may change randomly any checkbox in initialStatus .. which should be reflected in initialstatus array.

```<code> <div class="container" [hidden]="submitted">
       <form   ng-app="app" (submit)="onSubmit()">
      <div *ngFor="let initial of initialState,let j = index" >
    <div *ngIf="initial.checked==true">
     <button class="button" type="button">Device{{j}} </button>

       <label class="switch">
         <input type="checkbox" name= "checked" id="checkbox_category" checked    />
        <div class="slider round"></div>
      </label>
       <br/>
    </div>

    <div *ngIf="initial.checked==false">
       <button class="button" type="button">Device{{j}}</button>

       <label class="switch">
         <input type="checkbox"  id="checkbox_category" name= "checked"   />
        <div class="slider round"></div>
      </label>
       <br/>
       </div>
    </div>
    <button class="buttons" type="submit">Submit</button>

    <button (click)="resetAll()">Reset</button>
    <button (click)="selectAll()">selectALL</button>
    </form>

    </div>
</code>```

Component :

```<code>export class DashboardComponent{

submitted:boolean;
 model= new SendDetails();

  initialState:any = [{checked:true},{checked:false},{checked:true},{checked:false},{checked:true},{checked:false}];

  intendedDeviceStatus: any = this.initialState;

   constructor(
    ) {
        this.submitted=false;
        }

  onSubmit(){
      this.submitted=true;
      this.model.initSession();

  }

resetAll() {
  this.initialState.forEach((initial:any) => {
   initial.checked = false;
  }
)}
selectAll() {
  this.initialState.forEach((initial:any) => {
   initial.checked = true;
  }
)}
}
}
</code>```

But its not happening ....I'm able to show initial status separately and any changes made in UI are reflected back in Array.
        To achieve  InitialStatus display my input tag is mentioned as above  and to achieve two way binding i need to add ngModel into my input tag

    in my input tag.But I'm unable to achieve both at same time. How to achieve two way binding and displaying some check boxes as checked and few as unchecked.

答:
You can get this all by just one loop

Template :

```<code><form (submit)="register()">
            <div *ngFor="let initial of initialState,let j = index" >
                <button class="button" type="button">Device{{j}} </button>

                <label class="switch">
                    <input type="checkbox" name= "checked[{{j}}]" [(ngModel)]='initialState[j].checked'/>
                <div class="slider round"></div>
                </label>
                <br/>
            </div>
            <button class="buttons" type="submit">Submit</button>
        </form>
</code>```

Component :

```<code>initialState:any = [{'checked':true},{'checked':false},{'checked':true},{'checked':false},{'checked':true},{'checked':false}];

register()
{
  console.log(this.initialState);
}
</code>```

Changed initialState:any a little bit.

For your plunker just change this line:

```<code><input type="checkbox" name="checked" [checked]='initialState[j].checked' (change)='initialState[j].checked = $event.target.checked' />
</code>```

You can also check it here : Plunker

Body:
In the above code i want to display initial state of checkboxes as mentioned in initialstatus array in UI and then I may change randomly any checkbox in initialStatus .. which should be reflected in initialstatus array.

       <form   ng-app="app" (submit)="onSubmit()">

     <button class="button" type="button">Device{{j}} </button>

         <input type="checkbox" name= "checked" id="checkbox_category" checked    />

       <button class="button" type="button">Device{{j}}</button>

         <input type="checkbox"  id="checkbox_category" name= "checked"   />

    <button class="buttons" type="submit">Submit</button>

    <button (click)="resetAll()">Reset</button>
    <button (click)="selectAll()">selectALL</button>
    </form>

Component :

export class DashboardComponent{

submitted:boolean;
 model= new SendDetails();

  initialState:any = [{checked:true},{checked:false},{checked:true},{checked:false},{checked:true},{checked:false}];

  intendedDeviceStatus: any = this.initialState;

   constructor(
    ) {
        this.submitted=false;
        }

  onSubmit(){
      this.submitted=true;
      this.model.initSession();

  }

resetAll() {
  this.initialState.forEach((initial:any) => {
   initial.checked = false;
  }
)}
selectAll() {
  this.initialState.forEach((initial:any) => {
   initial.checked = true;
  }
)}
}
}

But its not happening ....I'm able to show initial status separately and any changes made in UI are reflected back in Array.
        To achieve  InitialStatus display my input tag is mentioned as above  and to achieve two way binding i need to add ngModel into my input tag

    in my input tag.But I'm unable to achieve both at same time. How to achieve two way binding and displaying some check boxes as checked and few as unchecked.

Body:
You can get this all by just one loop

Template :

<form (submit)="register()">
            <div *ngFor="let initial of initialState,let j = index" >
                <button class="button" type="button">Device{{j}} </button>
                &nbsp;
                <label class="switch">
                    <input type="checkbox" name= "checked[{{j}}]" [(ngModel)]='initialState[j].checked'/>
                <div class="slider round"></div>
                </label>
                <br/>
            </div>
            <button class="buttons" type="submit">Submit</button>
        </form>

Component :

initialState:any = [{'checked':true},{'checked':false},{'checked':true},{'checked':false},{'checked':true},{'checked':false}];

register()
{
  console.log(this.initialState);
}

Changed initialState:any a little bit.

For your plunker just change this line:

<input type="checkbox" name="checked" [checked]='initialState[j].checked' (change)='initialState[j].checked = $event.target.checked' />

You can also check it here : Plunker


来源: stackexchange

问:
Query to update the content of a cell using
I have a table with the following format:

```<code>column1   column2
   40       blue
   20       red
</code>```

I have I would like to update the contain of my column based on a value entered a TextBox and a comboBox, for example if I select red from my comboBox and enter the value 30 in my TextBox , I would like my table to be updated as follow

```<code>column1   column2
   40       blue
   50       red
</code>```

I thought of something like this:

```<code>update tablename set column1=....+TextBox.Text where column2=ComboBox.Text
</code>```

My question how do I get the current content of that row? do I need a query to do that?

答:
directly pass the column name as shown below</p>

```<code>update tablename set column1=column1+TextBox.Text where column2=ComboBox.Text
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table with the following format:

column1   column2
   40       blue
   20       red

I have I would like to update the contain of my column based on a value entered a TextBox and a comboBox, for example if I select red from my comboBox and enter the value 30 in my TextBox , I would like my table to be updated as follow

column1   column2
   40       blue
   50       red

I thought of something like this:

update tablename set column1=....+TextBox.Text where column2=ComboBox.Text

My question how do I get the current content of that row? do I need a query to do that?

Body:
directly pass the column name as shown below

update tablename set column1=column1+TextBox.Text where column2=ComboBox.Text


答: input type="checkbox" checked={{initial.checked}} . This will set the initial checked state as true or false depending on what you have in your array. When user changes that will also be reflected in the array that you are repeating.</p>

Title: How to set and capture unchecked and checked checkboxes in Angular 2?


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答: You can have a Dictionary having the words you would like to ignore, split the sentence in phrases (.split(' ')) and for each phrase, check if the phrase exists in the dictionary, if it does not, capitalize the first character and then, add the string to a string buffer. If the phrase you are currently processing is in the dictionary, simply add it to the string buffer.</p>

ContentLicense: CC BY-SA 4.0

Title: Capitalizing words in a string using C#

ContentLicense: CC BY-SA 2.5


问:
Best way to store/retrieve service properties
What is the best way to store/retrieve configurations related to the microservice?
How to get for instance, the IP and port serving the endpoint?</p>

答:
This depends on your service orchestration tool. The IP/port of your service instance may change during its lifetime, as instances can be added, removed, moved etc.
Other services communicating with yours would retrieve the necessary information through a service lookup mechanism.</p>


问:
Running through complex json and match text
I want to run through reddit comments and match the json with a specific text:

I tried the following

```<code>$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'));
foreach ($str as $comments) {
    //dd($comments->data->children);
    foreach ($comments->data->children as $comment) {
        if ($comment->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
    }
}
</code>```

However,  I  get the following error message:

```<code>  [ErrorException]
  Trying to get property of non-object

Exception trace:
 () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 App\Console\Commands\reddit->handle() at n/a:n/a
 call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
 Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
 Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
 Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
 Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
 Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
 Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
 Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
 Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36
</code>```

I expected to use $comments->data->children to access the body_html tag, but it does not work. Any suggestions why?

答:
In your case, str is not an array but an object. That's how it works :    </p>

```<code>$str = file_get_contents('https://www.reddit.com/r/all/comments.json');
$comments = json_decode($str);
foreach ($comments->data->children as $comment) {
        if ($comment->data->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
}
</code>```

Body:
I want to run through reddit comments and match the json with a specific text:

I tried the following

$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'));
foreach ($str as $comments) {
    //dd($comments->data->children);
    foreach ($comments->data->children as $comment) {
        if ($comment->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
    }
}

However,  I  get the following error message:

  [ErrorException]
  Trying to get property of non-object

Exception trace:
 () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 App\Console\Commands\reddit->handle() at n/a:n/a
 call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
 Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
 Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
 Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
 Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
 Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
 Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
 Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
 Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36

I expected to use $comments->data->children to access the body_html tag, but it does not work. Any suggestions why?

Body:
In your case, str is not an array but an object. That's how it works :

$str = file_get_contents('https://www.reddit.com/r/all/comments.json');
$comments = json_decode($str);
foreach ($comments->data->children as $comment) {
        if ($comment->data->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
}


问:
When do I need to call setNeedsDisplay in iOS?
When creating an iOS app, I'm confused as to when exactly I need to call setNeedsDisplay?  I know that it has something to do with updating/redrawing the UI; however, do I need to call this every time I change any of my views?

For example, do I need to call it:

After programatically changing the text in a text field

When changing the background of a view?

When I make changes in viewDidLoad?

How about in viewDidAppear?

Could someone give me some general guidelines regarding when to use this method?

答: You will call setNeedDisplay when you are changing the property on which your view custom drawing depends. It will explicitly call drawRect: method forcefully.</p>


问:
Run exe from within program
I have been trying to run a small executable from my code with pretty much 0 success. If I place the .exe in the main directory (and the files it needs) it does fine. But that is very messy, as there are several files in there already.

This is the directory I want it in:

```<code>C:\\Users\\Alex\\Desktop\\GSP381 iLab\\GSP381 iLab\\Models\\ModelLoader.exe
</code>```

I have tried using ShellExecute and system("") as well as CreateProcess(). Each time I try to put in the exact file path in, it fails. Same goes for things like ./ModelLoader.exe, ModelLoader.exe, or even ./Models/ModelLoader.exe.

It is getting to be quite annoying. My research has told me that system() is not the way to go, but I am 100% unconcerned with security or runtime, because this is just a learning experience for me. I just want to get something that works right now.

Edit:
Currently I've just commented everything out. It is running only this. As for failing, the program runs, but the executable does not. The executable 100% works. Verified it many times. So that is not the issue.

```<code>    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
    {
        system("ModelLoader.exe");
    }
</code>```

答: Try SetCurrentDirectory. If the executable depends on local files, then it will be looking for them in the current working directory, where your host program is executing from. Changing the working directory allows the new running program to search for its local files there.

Title: Run exe from within program

Body:
I have been trying to run a small executable from my code with pretty much 0 success. If I place the .exe in the main directory (and the files it needs) it does fine. But that is very messy, as there are several files in there already.

This is the directory I want it in:

C:\\Users\\Alex\\Desktop\\GSP381 iLab\\GSP381 iLab\\Models\\ModelLoader.exe

I have tried using ShellExecute and system("") as well as CreateProcess(). Each time I try to put in the exact file path in, it fails. Same goes for things like ./ModelLoader.exe, ModelLoader.exe, or even ./Models/ModelLoader.exe.

It is getting to be quite annoying. My research has told me that system() is not the way to go, but I am 100% unconcerned with security or runtime, because this is just a learning experience for me. I just want to get something that works right now.

Edit:
Currently I've just commented everything out. It is running only this. As for failing, the program runs, but the executable does not. The executable 100% works. Verified it many times. So that is not the issue.

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
    {
        system("ModelLoader.exe");
    }


问:
c# - Opening chosen file with associated App
I have successfully prompted user to select a file in  C# using

the openFileDialog control.

I now have the filename, lets call it foo.docx

I want to open the file with the asssoicated app.

i.e., if it is a docx file, launch with word.

Is there a best way to just pass the filename and it do the launch ?

I used System.Diagnostics.Process.Start(openFileDialog1.FileName.ToString());

TIA.

Ralph

答:
Just call Process.Start with the file name - the OS will select the associated application.

```<code>Process.Start(@"path to\foo.exe");
</code>```

Body:
Just call Process.Start with the file name - the OS will select the associated application.

Process.Start(@"path to\foo.exe");


问:
Can I use OneLogin API to generate SAML assertions in a standalone app?
I want to use OneLogin to write a command-line program that takes a username/password and generates a SAML assertion that can be used to authenticate to other sites.

The problem is that calling the "Generate SAML Assertion" API itself requires an access token generated from API credentials. So to distribute my app to users would require me to bake in API credentials to make that call. That would be fine, but the only authorization profile that allows callers to POST to the SAML resource is "Manage All", which is way more permission than is safe to give.

Has anyone done something like this?

OneLogin people, can you add an API credential type for calling only the SAML Assertion APIs? Or you could just make the API open. (Note that AWS's "AssumeRoleWithSAML" API doesn't require user credentials -- the whole point of the API is that you have credentials you want to convert to another credential type.)

答:
There is now an Authentication Only API scope, which can be baked into your application.

The endpoints available in this scope include:

Verify Factor (SAML Assertion)

Generate SAML Assertion

Verify Factor (Login)

Create Session Login Token

Log User Out

Writing a web app to get the SAML assertation would be the best solution and let the CLI interact with it. Especially if you consider the "Log User Out", which can log out any given user as long as you can guess the ID (easy).
If you trust your employees you could embed an Authentication Only scoped client ID/secret in your CLI. This is exactly what we will do at the first step with our OneLogin AWS-STS CLI tool. Of course we could have a rogue employee abusing this, but it's an edge case and really easy to revoke the client ID/secret and rollout a new version with a new client ID/secret.


问:
Getting "argument is not defined" error while running the javascript from Selenium
TestCase class is where I initailize the driver and invoke the url (url "http://www.amazon.in/")

```<code>public class TestCase {
    InitializeDriver id = new InitializeDriver();
    WebDriver driver = null;

    @BeforeTest
    public void setup()
    {
        id.invokeApplicationUrl();
        driver = id.getDriver();

    }

}
</code>```

TC1 is my test to go to Amazon sign in page

```<code>public class TC1 extends TestCase {
    @Test
    public void runTC1 ()
    {
        GoToSignInPage gts = new GoToSignInPage(driver);
        gts.clickElement();
    }
}
</code>```

Logic to go to the sign in page is written in GoToSignPage is written

```<code>public class GoToSignInPage {

    WebDriver driver;

    public GoToSignInPage(WebDriver driver)
    {
        this.driver=driver;
    }

    InitialPage ip = new InitialPage(driver);
    InitializeDriver id = new InitializeDriver();

    public void clickElement()
    {
        Actions action = new Actions(driver);
        //driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        //ip.yourOrders(driver).click();
        jse.executeScript("argument[0].style.border='3px dotted blue'", ip.yourOrders(driver));
action.moveToElement(ip.yourOrders(driver)).moveToElement(ip.signInBt(driver)).click().build().perform();
}
</code>```

InitialPage class has all the required page objects

```<code>public class InitialPage {

    WebDriver driver;

    public InitialPage(WebDriver driver)
    {
        this.driver = driver;
    }

    WebElement element ;

    public WebElement yourOrders(WebDriver driver)
    {
        element = driver.findElement(By.id("nav-link-yourAccount"));
        return(element);

    }
    public WebElement signInBt(WebDriver driver)
    {
        element = driver.findElement(By.xpath(".//*[@id='nav-flyout-ya-signin']/a/span"));
        return(element);

    }

}
</code>```

Error is as below

org.openqa.selenium.WebDriverException: unknown error: argument is not defined
        (Session info: chrome=56.0.2924.87)
        (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
      Command duration or timeout: 22 milliseconds
      Build info: version: '3.0.0-beta1', revision: '8e4315c', time: '2016-07-28 18:04:05 -0700'
      System info: host: 'VAIO', ip: '192.168.0.6', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
      Driver info: org.openqa.selenium.chrome.ChromeDriver
      Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\Akash\AppData\Local\Temp\scoped_dir6352_11834}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=56.0.2924.87, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
      Session ID: f74e69d9f66bab833287a8fd6f9d3021
          at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

答:
Your error comes from executing this JavaScript code jse.executeScript("argument[0].style.border='3px dotted blue'", try loading the website in your browser (i.e. Chrome), open developer tools (F12), navigate to console, input the same command, and you will get the same error:

According to Selenium documentation,

The arguments will be made available to the JavaScript via the "arguments" variable.

In your code, you use argument[0] instead of arguments[0]

Body:
TestCase class is where I initailize the driver and invoke the url (url "http://www.amazon.in/")

public class TestCase {
    InitializeDriver id = new InitializeDriver();
    WebDriver driver = null;

    @BeforeTest
    public void setup()
    {
        id.invokeApplicationUrl();
        driver = id.getDriver();

    }

}

TC1 is my test to go to Amazon sign in page

public class TC1 extends TestCase {
    @Test
    public void runTC1 ()
    {
        GoToSignInPage gts = new GoToSignInPage(driver);
        gts.clickElement();
    }
}

Logic to go to the sign in page is written in GoToSignPage is written

public class GoToSignInPage {

    WebDriver driver;

    public GoToSignInPage(WebDriver driver)
    {
        this.driver=driver;
    }

    InitialPage ip = new InitialPage(driver);
    InitializeDriver id = new InitializeDriver();

    public void clickElement()
    {
        Actions action = new Actions(driver);
        //driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        //ip.yourOrders(driver).click();
        jse.executeScript("argument[0].style.border='3px dotted blue'", ip.yourOrders(driver));
action.moveToElement(ip.yourOrders(driver)).moveToElement(ip.signInBt(driver)).click().build().perform();
}

InitialPage class has all the required page objects

public class InitialPage {

    WebDriver driver;

    public InitialPage(WebDriver driver)
    {
        this.driver = driver;
    }

    WebElement element ;

    public WebElement yourOrders(WebDriver driver)
    {
        element = driver.findElement(By.id("nav-link-yourAccount"));
        return(element);

    }
    public WebElement signInBt(WebDriver driver)
    {
        element = driver.findElement(By.xpath(".//*[@id='nav-flyout-ya-signin']/a/span"));
        return(element);

    }

}

Error is as below

org.openqa.selenium.WebDriverException: unknown error: argument is not defined
        (Session info: chrome=56.0.2924.87)
        (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
      Command duration or timeout: 22 milliseconds
      Build info: version: '3.0.0-beta1', revision: '8e4315c', time: '2016-07-28 18:04:05 -0700'
      System info: host: 'VAIO', ip: '192.168.0.6', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
      Driver info: org.openqa.selenium.chrome.ChromeDriver
      Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\Akash\AppData\Local\Temp\scoped_dir6352_11834}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=56.0.2924.87, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
      Session ID: f74e69d9f66bab833287a8fd6f9d3021
          at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)


问:
Apply button javascript to an a href
My friend gave me this code that will allow a smooth scroll effect to the page once the user pushes an anchor button:

```<code><form id = "button_design" action="#page2">
     <input type="submit" class="anchor-button" value="Page 2" />
</form>
</code>```

And the javascript:

```<code>$(function() {
$('input.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});
</code>```

It works for input type = "submit" only and I want to try to use this code to my href ="#page3"... which is only a link and not a button. Can anyone help me to convert the code to make it apply to a href too? I tried messing around with it but I get nowhere.

答:
If you change the tag to a (both in jQuery and HTML) the code functions basically the same. Example:

$(function() {
$('a.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = "button_design" action="#page2">
      Page 2
</form>

<div style="height:800px; background-color:blue;"> </div>
<div name="page2">test</div></code>```

Title: Apply button javascript to an a href

Body:
My friend gave me this code that will allow a smooth scroll effect to the page once the user pushes an anchor button:

<form id = "button_design" action="#page2">
     <input type="submit" class="anchor-button" value="Page 2" />
</form>

And the javascript:

$(function() {
$('input.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});

It works for input type = "submit" only and I want to try to use this code to my <a href ="#page3"... which is only a link and not a button. Can anyone help me to convert the code to make it apply to a href too? I tried messing around with it but I get nowhere.

Body:
If you change the tag to a (both in jQuery and HTML) the code functions basically the same. Example:

$(function() {
$('a.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = "button_design" action="#page2">
     <a class="anchor-button" href="javascript:void(0)"> Page 2 </a>
</form>

<div style="height:800px; background-color:blue;">&nbsp;</div>
<div name="page2">test</div>


问:
How to add a default sound in MS PowerPoint to a shape in a slide using c#
Here is my code:

```<code>Microsoft.Office.Interop.PowerPoint.Shape rectangle = curSlide.Shapes.AddShape(Microsoft.Office.Core.MsoAutoShapeType.msoShapeRoundedRectangle, slideWidth - 110, slideHeight - 60, 100, 50);
Sequence objSequence = curSlide.TimeLine.InteractiveSequences.Add(1);
Effect pEffect_start = objSequence.AddEffect(rectangle, MsoAnimEffect.msoAnimEffectTransparency, MsoAnimateByLevel.msoAnimateLevelNone, MsoAnimTriggerType.msoAnimTriggerOnShapeClick, 1);
</code>```

I can add an animation to shape, but with a sound I can not.

I do not want to add file in a location:

```<code>rectangle.AnimationSettings.SoundEffect.ImportFromFile(fileLocation);
</code>```

I want to add default sounds in Powerpoint:

How can I do that?

答:
let you try to add this line of code after yours

```<code>pEffect_start.EffectInformation.PlaySettings.PlayOnEntry = Office.MsoTriState.msoCTrue;
</code>```

The PlayOnEntry means the media is played/ not played on load event. This property is supported even before MS Powerpoint 2007

Body:
Here is my code:

Microsoft.Office.Interop.PowerPoint.Shape rectangle = curSlide.Shapes.AddShape(Microsoft.Office.Core.MsoAutoShapeType.msoShapeRoundedRectangle, slideWidth - 110, slideHeight - 60, 100, 50);
Sequence objSequence = curSlide.TimeLine.InteractiveSequences.Add(1);
Effect pEffect_start = objSequence.AddEffect(rectangle, MsoAnimEffect.msoAnimEffectTransparency, MsoAnimateByLevel.msoAnimateLevelNone, MsoAnimTriggerType.msoAnimTriggerOnShapeClick, 1);

I can add an animation to shape, but with a sound I can not.

I do not want to add file in a location:

rectangle.AnimationSettings.SoundEffect.ImportFromFile(fileLocation);

I want to add default sounds in Powerpoint:

How can I do that?

Body:
let you try to add this line of code after yours

pEffect_start.EffectInformation.PlaySettings.PlayOnEntry = Office.MsoTriState.msoCTrue;

The PlayOnEntry means the media is played/ not played on load event. This property is supported even before MS Powerpoint 2007


问:
QThread pass result data to MainThread
I'm thinking about how to pass result data from some worker thread back to client without copying. Worker lives in other thread and BigData inherits QObject. My idea is to change ownership of data:

```<code>class Worker: public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0): QObject(parent);
signals:
    void resultReady(BigData *data);
public slots:
    void doWork() {
        BigData *data = new BigData(this); // alloc new Data
        while (!dataReady) {
            ... // appending data
        }
        // Data ready
        // clearing ownership
        data->setParent(NULL); // data can't be moved to another thread with parent
        data->moveToThread(NULL);
        emit resultReady(data);
    }
};

void MainWindow::handleResult(BigData *data)
{
    if (currentData_) {
        delete currentData_;
    }
    data->setParent(this); // set new ownership

    // works only if data's thread is NULL
    data->moveToThread(QApplication::instance()->thread());
    currentData_ = data;
}
</code>```

Does it look good? Or there is more proper way to do it?

答:
Usually you use moveToThread() to push an object from one thread to another. This means that instead of doing data->moveToThread(NULL); in your doWork() slot, You can write data->moveToThread(QApplication::instance()->thread()); to avoid setting the thread affinity to NULL and then changing that from the main thread. But after moving the BigData instance to the main thread, Be aware of touching that QObject from the worker thread. Another thing to note about is that, moving a QObject back and forth between threads might cause some side effects, from the docs:

Note that all active timers for the object will be reset. The timers are first stopped in the current thread and restarted (with the same interval) in the targetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.

Inherting QObject just for the purpose of memory management is an overkill. QObject provides much more stuff (Introspection capabilities, dynamic properties, signals/slots, thread affinity, event processing, internationalization ...) that you don't really need here.

If you are interested only in memory management, Qt and the C++ standard library have smart pointers that can implement object lifetime management by unique ownership or shared ownership semantics.

Have a look at this answer for an example of a model that offloads data loading to the global thread pool and displays these data in the view as soon as they are ready. Notice that the model inherits QObject (because QAbstractItemModel inherits QObject, since it uses signals/slots to inform the view of data changes) but there is no reason for the data structure that actually holds data to inherit QObject. . .

Title: QThread pass result data to MainThread

Body:
I'm thinking about how to pass result data from some worker thread back to client without copying. Worker lives in other thread and BigData inherits QObject. My idea is to change ownership of data:

class Worker: public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0): QObject(parent);
signals:
    void resultReady(BigData *data);
public slots:
    void doWork() {
        BigData *data = new BigData(this); // alloc new Data
        while (!dataReady) {
            ... // appending data
        }
        // Data ready
        // clearing ownership
        data->setParent(NULL); // data can't be moved to another thread with parent
        data->moveToThread(NULL);
        emit resultReady(data);
    }
};

void MainWindow::handleResult(BigData *data)
{
    if (currentData_) {
        delete currentData_;
    }
    data->setParent(this); // set new ownership

    // works only if data's thread is NULL
    data->moveToThread(QApplication::instance()->thread());
    currentData_ = data;
}

Does it look good? Or there is more proper way to do it?


问:
Text Categorization datasets for MATLAB
I am looking for a reliable  dataset for Text categorization tasks in MATLAB format.
I want to run some experiments and don't want to spend too much time in preprocessing the text and creating feature vectors. I need something to be ready so I can plug it in my algorithm. I found a MATLAB files for reuters dataset here: link text

Everything is ready in here, but I want to use a subset of this. In this "fea" contains the feature vectors for each document. However, it seems that it is not a normal matrix. I want for example to select the top 1000 documents in this "fea". If you just download it and load it into MATLAB you will see what I mean.
So, If it is possible I need a solution for the above-mentioned dataset or any alternative datasets.
Thanks in advance.

答:
It is stored as sparse matrix. Extract the first 1000 documents (rows), and if you have enough space, you can convert it to full dense matrix:

```<code>load Reuters21578.mat
TF = full( fea(1:1000,:) );
</code>```

Lets check the variables we have:

```<code>>> whos
  Name             Size                   Bytes  Class     Attributes

  TF            1000x18933            151464000  double
  fea           8293x18933              4749196  double    sparse
  gnd           8293x1                    66344  double
  testIdx       2347x1                    18776  double
  trainIdx      5946x1                    47568  double
</code>```

so you can see TF is now about 150MB.

Other than that, the rest is self-explanatory:

fea: term-frequency matrix, rows are documents, columns are terms

gnd: category of each document, where numel(unique(gnd)) == 65

trainIdx/testIdx: split of instances (documents) for classification purposes, contains indices of rows, used as: tr = fea(trainIdx,:); tt = fea(testIdx,:);

Title: Text Categorization datasets for MATLAB

Body:
It is stored as sparse matrix. Extract the first 1000 documents (rows), and if you have enough space, you can convert it to full dense matrix:

load Reuters21578.mat
TF = full( fea(1:1000,:) );

Lets check the variables we have:

>> whos
  Name             Size                   Bytes  Class     Attributes

  TF            1000x18933            151464000  double
  fea           8293x18933              4749196  double    sparse
  gnd           8293x1                    66344  double
  testIdx       2347x1                    18776  double
  trainIdx      5946x1                    47568  double

so you can see TF is now about 150MB.

Other than that, the rest is self-explanatory:

fea: term-frequency matrix, rows are documents, columns are terms

gnd: category of each document, where numel(unique(gnd)) == 65

trainIdx/testIdx: split of instances (documents) for classification purposes, contains indices of rows, used as: tr = fea(trainIdx,:); tt = fea(testIdx,:);


问:
Avoiding duplicates, SQLITE, android
I have a button, when user clicks it it passes some value and im adding this value with cv.put("name", name), how can i avoid adding duplicates?</p>

答:
I you have a table t and you do not want duplicate values of name, then the best method is to have the database maintain the integrity of the data.

SQL offers unique indexes/constraints just for this purpose.  For instance, you can create a unique index on the data:

```<code>create unique index unq_t_name on t(name);
</code>```

Any attempt to create a duplicate name value in t (whether by insert or update) will generate an error.

Title: Avoiding duplicates, SQLITE, android

Body:
I you have a table t and you do not want duplicate values of name, then the best method is to have the database maintain the integrity of the data.

SQL offers unique indexes/constraints just for this purpose.  For instance, you can create a unique index on the data:

create unique index unq_t_name on t(name);

Any attempt to create a duplicate name value in t (whether by insert or update) will generate an error.


问:
Mix 2 mp3 files with FFmpeg for Android
I am developing something similar to a karaoke app. I have a sound file(beat) and a recorded file(voice) from android mediarecorder. I am trying to mix the two files to become one file that plays the same time. I have set up ffmpeg provided by writingminds and everything is working fine. I am not familiar with ffmpeg commands so searched for and got few commands that can achieve the task for me. This is the code i got:

```<code>  String files = "-i " + currentFile + " -i " + someFile.getAbsolutePath();
            String output = mFileName + "/recorded/test.mp3";
            String cmd = "ffmpeg "+files+
                    " -filter_complex \"aevalsrc=0:d=10[s1];[s1][1:a]concat=n=2:v=0:a=1[ac1];[0:a][ac1]amix[aout]\" -map [aout] -c:a libmp3lame " + output;
</code>```

But it not working. this is the error i got:

```<code>04-01 12:09:26.598 21300-21300/com.shixels.thankgodrichard.mixer I/fpeg: ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
                                                                           built with gcc 4.8 (GCC)
                                                                           configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
                                                                           libavutil      55. 17.103 / 55. 17.103
                                                                           libavcodec     57. 24.102 / 57. 24.102
                                                                           libavformat    57. 25.100 / 57. 25.100
                                                                           libavdevice    57.  0.101 / 57.  0.101
                                                                           libavfilter     6. 31.100 /  6. 31.100
                                                                           libswscale      4.  0.100 /  4.  0.100
                                                                           libswresample   2.  0.101 /  2.  0.101
                                                                           libpostproc    54.  0.100 / 54.  0.100
                                                                         Output #0, mp3, to 'ffmpeg -i /storage/emulated/0/MyStudio/temps/1491044929409.mp3 -i /storage/emulated/0/temp.mp3 -filter_complex "aevalsrc=0:d=10[s1];[s1][1:a]concat=n=2:v=0:a=1[ac1];[0:a][ac1]amix[aout]" -map [aout] -c:a libmp3lame /storage/emulated/0/recorded/test.mp3':
                                                                         Output file #0 does not contain any stream
04-01 12:09:26.599 21300-21300/com.shixels.thankgodrichard.mixer I/fpeg: finished
</code>```

I read some answers here saying it depends on the version of the ffmpeg your using. I am using the latest ffmpeg for android by writingminds.

答:
I dont know for android, but in unix, you could use this command, maybe it helps you:

ffmpeg -filter_complex "amovie=file1.mp3 [a0]; amovie=file2.mp3 [a1]; [a0][a1] amix=inputs=2:duration=shortest [aout]" -map [aout] -acodec mp3 file_merged.mp3

Title: Mix 2 mp3 files with FFmpeg for Android

Body:
I am developing something similar to a karaoke app. I have a sound file(beat) and a recorded file(voice) from android mediarecorder. I am trying to mix the two files to become one file that plays the same time. I have set up ffmpeg provided by writingminds and everything is working fine. I am not familiar with ffmpeg commands so searched for and got few commands that can achieve the task for me. This is the code i got:

  String files = "-i " + currentFile + " -i " + someFile.getAbsolutePath();
            String output = mFileName + "/recorded/test.mp3";
            String cmd = "ffmpeg "+files+
                    " -filter_complex \"aevalsrc=0:d=10[s1];[s1][1:a]concat=n=2:v=0:a=1[ac1];[0:a][ac1]amix[aout]\" -map [aout] -c:a libmp3lame " + output;

But it not working. this is the error i got:

04-01 12:09:26.598 21300-21300/com.shixels.thankgodrichard.mixer I/fpeg: ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
                                                                           built with gcc 4.8 (GCC)
                                                                           configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
                                                                           libavutil      55. 17.103 / 55. 17.103
                                                                           libavcodec     57. 24.102 / 57. 24.102
                                                                           libavformat    57. 25.100 / 57. 25.100
                                                                           libavdevice    57.  0.101 / 57.  0.101
                                                                           libavfilter     6. 31.100 /  6. 31.100
                                                                           libswscale      4.  0.100 /  4.  0.100
                                                                           libswresample   2.  0.101 /  2.  0.101
                                                                           libpostproc    54.  0.100 / 54.  0.100
                                                                         Output #0, mp3, to 'ffmpeg -i /storage/emulated/0/MyStudio/temps/1491044929409.mp3 -i /storage/emulated/0/temp.mp3 -filter_complex "aevalsrc=0:d=10[s1];[s1][1:a]concat=n=2:v=0:a=1[ac1];[0:a][ac1]amix[aout]" -map [aout] -c:a libmp3lame /storage/emulated/0/recorded/test.mp3':
                                                                         Output file #0 does not contain any stream
04-01 12:09:26.599 21300-21300/com.shixels.thankgodrichard.mixer I/fpeg: finished

I read some answers here saying it depends on the version of the ffmpeg your using. I am using the latest ffmpeg for android by writingminds.


问:
Splitting timespan and creating new fields in csv
The following csv structure and data is given:

```<code>timespan,someOtherField, ...
27.03.2017 - 31.03.2017,someOtherValue, ...
31.03.2017,someOtherValue, ...
</code>```

I would like to split up the timespan into begin and end. As you can see a timespan can be several days (first record) or only one day (second record). Splitting up the first record is pretty easy by replacing the delimiter but i don't know how to process the second record. There must be some logic to identify it as single day (begin and end should be same value).

All is done in SSIS but i would like to realize it in C#.

Result:

```<code>begin,end,someOtherField, ...
27.03.2017,31.03.2017,someOtherValue, ...
31.03.2017,31.03.2017,someOtherValue, ...
</code>```

答:
First add a Derived Column Transformation. Inside of the Derived Column Editor, add the begin and end columns with a default value of the timespan.

Now add a Script Component Transformation (SCT), and add the Input Columns of timespan, begin, end and mark begin, end as ReadWrite.

Still inside the SCT, click on Script in the left hand pane, then click Edit Script at the bottom of the dialog.  This will launch a Visual Studio instance to edit your C# script.

Scroll down to the Input0_ProcessInputRow function and make it look like the following:

```<code> public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    var times = Row.timespan.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
    if (times.Length > 1)
    {
        Row.begin = times[0];
        Row.end = times[1];
    }
}
</code>```

Save the file, exit that instance of VS (It will be title VstaProjects), then click OK to exit the Script Transformation Editor.

Your dataflow should now look like this.

Now if you add a data viewer at the bottom of that pipeline, you will see the results you are looking for.

Body:
The following csv structure and data is given:

timespan,someOtherField, ...
27.03.2017 - 31.03.2017,someOtherValue, ...
31.03.2017,someOtherValue, ...

I would like to split up the timespan into begin and end. As you can see a timespan can be several days (first record) or only one day (second record). Splitting up the first record is pretty easy by replacing the delimiter but i don't know how to process the second record. There must be some logic to identify it as single day (begin and end should be same value).

All is done in SSIS but i would like to realize it in C#.

Result:

begin,end,someOtherField, ...
27.03.2017,31.03.2017,someOtherValue, ...
31.03.2017,31.03.2017,someOtherValue, ...

Body:
First add a Derived Column Transformation. Inside of the Derived Column Editor, add the begin and end columns with a default value of the timespan.

Now add a Script Component Transformation (SCT), and add the Input Columns of timespan, begin, end and mark begin, end as ReadWrite.

Still inside the SCT, click on Script in the left hand pane, then click Edit Script at the bottom of the dialog.  This will launch a Visual Studio instance to edit your C# script.

Scroll down to the Input0_ProcessInputRow function and make it look like the following:

 public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    var times = Row.timespan.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
    if (times.Length > 1)
    {
        Row.begin = times[0];
        Row.end = times[1];
    }
}

Save the file, exit that instance of VS (It will be title VstaProjects), then click OK to exit the Script Transformation Editor.

Your dataflow should now look like this.

Now if you add a data viewer at the bottom of that pipeline, you will see the results you are looking for.


问:
How to stop "if(isset($_POST['form-submit']))" from redirecting after clicking Submit?
I have a serious problem about Password Recovery Program these days.  While I was programing an if(isset($_POST['pass-submit'])) on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. When someone clicks Submit button of the form, it should stay at the same page for processing, i.e. on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. But instead it takes us to reset.php where no code would work because the variable recoverykey is empty. Even after using header("Location: reset.php?recoverykey=$recovery_code");, nothing worked.
I want it to stay where it was even after clicking the Submit button so that PHP can check whether the Password and Confirm Password fields where same or incorrect according to the program.

Here's all my code in reset.php:

<?php
    ob_start();
    session_start();
?>
<!DOCTYPE html>

                <meta name="robots" content="noindex" />
                <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
                <title>Reset Password</title>

<?php
    include('db-config.php');
    function show_change_pass_form(){
        ?>
                <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Change your Password

                    <?php echo $passError ?><input type="password" placeholder="New Password" name="new-pass" required />
                    <?php echo $Con_passError; ?><input type="password" placeholder="Confirm Password" name="confirm-new-pass" required />
                    <input type="submit" value="Change Password" name="pass-submit" />
                </form>
        <?php
    }
    $recovery_code = $_GET['recoverykey'];
    if(empty($recovery_code)){
        echo 'Looks like you landed elsewhere.';
    }
    $sql = "SELECT * FROM RegisteredMembers WHERE RecoveryCode='$recovery_code'";
    $result = mysql_query($sql);
    if($result){
        $count = mysql_num_rows($result);
        if($count==1){

            if( isset($_POST['pass-submit']) ){

               header("Location: reset.php?recoverykey=$recovery_code");

                $pass = $_POST['new-pass'];
                $Con_pass = $_POST['confirm-new-pass'];

                    // Confirmation
                        if($pass==$Con_pass){
                            $sql1 = "UPDATE RegisteredMembers SET password = '$pass' WHERE RecoveryCode = '$recovery_code'";
                            $output = mysql_query($sql1);
                            echo $output;
                            $error = false;
                            $passError = "Password successfully changed. Feel free to Log In.";
                        } else if(!($pass==$Con_pass)){
                            $error = true;
                            $Con_passError = "The Password isn't matching. Be sure you remember the New Password.";
                        } else if(empty($pass)){
                            $error = true;
                            $passError = "Please do not keep the password empty.";
                        } else if(empty($Con_pass)){
                            $error = true;
                            $Con_passError = "Please do not keep this field empty.";
                        }
            }
            show_change_pass_form();

        } else if($count==0) {
            echo "No such recovery code, please don't try Spamming around!";
        }
    }
?>
<?php ob_end_flush(); ?>```
</div>
</div>
</p>

<p>Here's my code in <code>forget.php</code> (I added it though its not much necessary):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php

    ob_start();
    session_start();
    include('db-config.php');

    if(isset($_POST['forgot-submit'])){
        $recovery_user = $_POST['forgot-email'];
        $query = "SELECT * FROM RegisteredMembers WHERE userEmail='$recovery_user'";
        $output = mysql_query($query);
        $count = mysql_num_rows($output);
        $row = mysql_fetch_array($output);
        if($count==1){
            $error = false;

            // Mail the Recovery link
            $recovery_code = md5(uniqid(rand()));
            $mTo = $recovery_user;
            $mFrom = 'From: '.$website_details['name'].' Team '.'<'.$website_details['email'].'>';
            $mSubject = $website_details['name']." Account recovery Mail";
                // Message
                $mMsg[0] = "Hi ".$row['fname'].", \r\n";
                $mMsg[1] = "This is the password recovery email which you have requested just few minutes before. <b>(If you havn't requested, you may kindly ingnore this Email)</b>";
                $mMsg[2] = "Here's your Password Recovery Link. Clicking it would allow you to change your existing password into a new one.";
                $mFinMsg = $mMsg[0].$mMsg[1].$mMsg[2];
            $sendRecMail = mail( $mTo , $mSubject , $mFinMsg , $mFrom );

            // Add recovery code to Database
            $mysql = "UPDATE RegisteredMembers SET RecoveryCode='$recovery_code' WHERE userEmail='$recovery_user'";
            $result = mysql_query($mysql);
            if($result){
                $error = false;
                $forgotEmailMsg = "Thanks, Check your Email for recovering your password.";
            } else{
                echo "Looks like there's a Disturbance and Load on server. Try again later.";
            }
        } else if(strlen($recovery_user)==0){
            $error = true;
            $forgotEmailMsg = "Please do not leave this field empty.";
        } else{
            $error = true;
            $forgotEmailMsg = "No such Email found in Database.";
        }
    }

?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="robots" content="noindex" />
        <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
        <title>Password Recovery</title>
    </head>
    <body>
        <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
            <h3>Password Recovery</h3>
            <label><span class="text-danger"><?php echo $forgotEmailMsg; ?></span><input type="email" placeholder="Your registered Email" name="forgot-email" required /></label>
            <input type="submit" value="Next" name="forgot-submit" />
        </form>
    </body>
</html>
<?php ob_end_flush(); ?></code>```

Forget.php is all okay but may be you can refer something from it.

答:
```<code>   if(isset($_POST['submit'])){
        header("Location:https://www.example.com/subname/");
        exit; // Exit should always be called after a redirection to
              // cease further PHP code execution.
    }
</code>```

use this code for rediect after submit.

Body:
I have a serious problem about Password Recovery Program these days.  While I was programing an if(isset($_POST['pass-submit'])) on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. When someone clicks Submit button of the form, it should stay at the same page for processing, i.e. on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. But instead it takes us to reset.php where no code would work because the variable recoverykey is empty. Even after using header("Location: reset.php?recoverykey=$recovery_code");, nothing worked.
I want it to stay where it was even after clicking the Submit button so that PHP can check whether the Password and Confirm Password fields where same or incorrect according to the program.

Here's all my code in reset.php:

<?php
    ob_start();
    session_start();
?>
<!DOCTYPE html>

                <meta name="robots" content="noindex" />
                <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
                <title>Reset Password</title>

<?php
    include('db-config.php');
    function show_change_pass_form(){
        ?>
                <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Change your Password

                    <?php echo $passError ?><input type="password" placeholder="New Password" name="new-pass" required />
                    <?php echo $Con_passError; ?><input type="password" placeholder="Confirm Password" name="confirm-new-pass" required />
                    <input type="submit" value="Change Password" name="pass-submit" />
                </form>
        <?php
    }
    $recovery_code = $_GET['recoverykey'];
    if(empty($recovery_code)){
        echo 'Looks like you landed elsewhere.';
    }
    $sql = "SELECT * FROM RegisteredMembers WHERE RecoveryCode='$recovery_code'";
    $result = mysql_query($sql);
    if($result){
        $count = mysql_num_rows($result);
        if($count==1){

            if( isset($_POST['pass-submit']) ){

               header("Location: reset.php?recoverykey=$recovery_code");

                $pass = $_POST['new-pass'];
                $Con_pass = $_POST['confirm-new-pass'];

                    // Confirmation
                        if($pass==$Con_pass){
                            $sql1 = "UPDATE RegisteredMembers SET password = '$pass' WHERE RecoveryCode = '$recovery_code'";
                            $output = mysql_query($sql1);
                            echo $output;
                            $error = false;
                            $passError = "Password successfully changed. Feel free to Log In.";
                        } else if(!($pass==$Con_pass)){
                            $error = true;
                            $Con_passError = "The Password isn't matching. Be sure you remember the New Password.";
                        } else if(empty($pass)){
                            $error = true;
                            $passError = "Please do not keep the password empty.";
                        } else if(empty($Con_pass)){
                            $error = true;
                            $Con_passError = "Please do not keep this field empty.";
                        }
            }
            show_change_pass_form();

        } else if($count==0) {
            echo "No such recovery code, please don't try Spamming around!";
        }
    }
?>
<?php ob_end_flush(); ?>

Here's my code in forget.php (I added it though its not much necessary):

<?php

    ob_start();
    session_start();
    include('db-config.php');

    if(isset($_POST['forgot-submit'])){
        $recovery_user = $_POST['forgot-email'];
        $query = "SELECT * FROM RegisteredMembers WHERE userEmail='$recovery_user'";
        $output = mysql_query($query);
        $count = mysql_num_rows($output);
        $row = mysql_fetch_array($output);
        if($count==1){
            $error = false;

            // Mail the Recovery link
            $recovery_code = md5(uniqid(rand()));
            $mTo = $recovery_user;
            $mFrom = 'From: '.$website_details['name'].' Team '.'<'.$website_details['email'].'>';
            $mSubject = $website_details['name']." Account recovery Mail";
                // Message
                $mMsg[0] = "Hi ".$row['fname'].", \r\n";
                $mMsg[1] = "This is the password recovery email which you have requested just few minutes before. (If you havn't requested, you may kindly ingnore this Email)";
                $mMsg[2] = "Here's your Password Recovery Link. Clicking it would allow you to change your existing password into a new one.";
                $mFinMsg = $mMsg[0].$mMsg[1].$mMsg[2];
            $sendRecMail = mail( $mTo , $mSubject , $mFinMsg , $mFrom );

            // Add recovery code to Database
            $mysql = "UPDATE RegisteredMembers SET RecoveryCode='$recovery_code' WHERE userEmail='$recovery_user'";
            $result = mysql_query($mysql);
            if($result){
                $error = false;
                $forgotEmailMsg = "Thanks, Check your Email for recovering your password.";
            } else{
                echo "Looks like there's a Disturbance and Load on server. Try again later.";
            }
        } else if(strlen($recovery_user)==0){
            $error = true;
            $forgotEmailMsg = "Please do not leave this field empty.";
        } else{
            $error = true;
            $forgotEmailMsg = "No such Email found in Database.";
        }
    }

?>
<!DOCTYPE html>

        <meta name="robots" content="noindex" />
        <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
        <title>Password Recovery</title>

        <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Password Recovery

            <?php echo $forgotEmailMsg; ?><input type="email" placeholder="Your registered Email" name="forgot-email" required />
            <input type="submit" value="Next" name="forgot-submit" />
        </form>

<?php ob_end_flush(); ?>

Forget.php is all okay but may be you can refer something from it.

Body:
   if(isset($_POST['submit'])){
        header("Location:https://www.example.com/subname/");
        exit; // Exit should always be called after a redirection to
              // cease further PHP code execution.
    }

use this code for rediect after submit.


问:
Complexity of the python code
I am trying to find the runtime complexity of this Python program. Will the complexity be still n or will it be more than n as I am creating a new list for each recursive call</p>

```<code>def RecLinearSearch(lyst,number):
    found = False
    index = len(lyst)-1
    if lyst[index] == number:
        found = True
        return found
    elif index<len(lyst)-1:
        index +=1
        return RecLinearSearch(lyst[index:],number)
    return found
print(RecLinearSearch([1,4,5,65,44],55))
</code>```

答:
Your original code was broken. It only required 1 step and checked if the last element is the desired number. It was O(1) but didn't do what the function name implies it should do. The recursive call never happened, and the lyst was never sliced.

Your updated code runs in O(n**2) : the worst case would be n slices at the n/2th index on average. It's slower than necessary, and due to the recursive calls, it's not possible to say at which index the number has been found.

If you passed the last index as argument and would leave the lyst untouched, it could run in O(n). But then, you also wouldn't need recursive call, just a simple loop.

With a sorted lyst, it could run in O(log n) with a binary search.

Title: Complexity of the python code

Body:
I am trying to find the runtime complexity of this Python program. Will the complexity be still n or will it be more than n as I am creating a new list for each recursive call

def RecLinearSearch(lyst,number):
    found = False
    index = len(lyst)-1
    if lyst[index] == number:
        found = True
        return found
    elif index<len(lyst)-1:
        index +=1
        return RecLinearSearch(lyst[index:],number)
    return found
print(RecLinearSearch([1,4,5,65,44],55))


问:
Conversion of if condition to ternary operator
```<code>status = (Hcill_state == HCILL_STATE_AWAKE)?GPIO_Request(GPIO_5,13):API_FAIL;
</code>```

Is the above code equivalent to the code below?

```<code> if (Hcill_state == HCILL_STATE_AWAKE)
 {
     status = GPIO_Request (GPIO_5,13);
 }
</code>```

答:
Since, Ternary operator define as :

```<code>Condition ? if true : if false
</code>```

In your second case you have an operation for true but not for false.

So, these code are not equal because in second one you do not have else statement.
It will be equal if you wrote second one like this.

```<code>if (Hcill_state == HCILL_STATE_AWAKE)
{
 status = GPIO_Request (GPIO_5,13);
}
else
{
 status = API_FAIL;
}
</code>```

Body:
status = (Hcill_state == HCILL_STATE_AWAKE)?GPIO_Request(GPIO_5,13):API_FAIL;

Is the above code equivalent to the code below?

 if (Hcill_state == HCILL_STATE_AWAKE)
 {
     status = GPIO_Request (GPIO_5,13);
 }

Body:
Since, Ternary operator define as :

Condition ? if true : if false

In your second case you have an operation for true but not for false.

So, these code are not equal because in second one you do not have else statement.
It will be equal if you wrote second one like this.

if (Hcill_state == HCILL_STATE_AWAKE)
{
 status = GPIO_Request (GPIO_5,13);
}
else
{
 status = API_FAIL;
}


问:
How to skip empty keyword arguments
Is there a better way to avoid redundant code? As in this case, if storage is 0 then I don't want to pass it to the function and keep code neat, but I had to do a if-else.

```<code>if storage == 0:
    response_lc = asg_client.create_launch_configuration(
        ImageId=ami,
        InstanceType=instance_type,
        KeyName=keypair
    )
else:
    response_lc = asg_client.create_launch_configuration(
        VolumeSize=storage,
        ImageId=ami,
        InstanceType=instance_type,
        KeyName=keypair
    )
</code>```

答:
If there is no way out, you can do this:

```<code>kwargs = {
  "ImageId": ami,
  "InstanceType": instance_type,
  "KeyName": keypair
}
if storage:
    kwargs["VolumeSize"] = storage

response_lc = asg_client.create_launch_configuration(**kwargs)
</code>```

But I will advise you to dig into the asg_client.create_launch_configuration method and see if all the four parameters can be passed in all the cases.

Title: How to skip empty keyword arguments

Body:
Is there a better way to avoid redundant code? As in this case, if storage is 0 then I don't want to pass it to the function and keep code neat, but I had to do a if-else.

if storage == 0:
    response_lc = asg_client.create_launch_configuration(
        ImageId=ami,
        InstanceType=instance_type,
        KeyName=keypair
    )
else:
    response_lc = asg_client.create_launch_configuration(
        VolumeSize=storage,
        ImageId=ami,
        InstanceType=instance_type,
        KeyName=keypair
    )

Body:
If there is no way out, you can do this:

kwargs = {
  "ImageId": ami,
  "InstanceType": instance_type,
  "KeyName": keypair
}
if storage:
    kwargs["VolumeSize"] = storage

response_lc = asg_client.create_launch_configuration(**kwargs)

But I will advise you to dig into the asg_client.create_launch_configuration method and see if all the four parameters can be passed in all the cases.


答:
1- Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.

2-When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.

```<code>ContentValues Val = new ContentValues();
Val.put("IDD", id);
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null,  Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
db.close();
Log.d(TAG,""+ rows);
</code>```

Gordon Linoff answer shows you how to make some columns UNIQUE

Title: Avoiding duplicates, SQLITE, android

Body: I have a button, when user clicks it it passes some value and im adding this value with cv.put("name", name), how can i avoid adding duplicates?

Body:
1- Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.

2-When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.

ContentValues Val = new ContentValues();
Val.put("IDD", id);
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null,  Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
db.close();
Log.d(TAG,""+ rows);

Gordon Linoff answer shows you how to make some columns UNIQUE


问:
Join query in Hanami-model
Is it possible to create join query in subclass of Hanami::Repository?

I found that this pull request implements this feature but I can't find it in current codebase.

答:
Hanami model based on rom, that's why you can use Relation#join method with a needful relation.

For this you need to call join method for one relation and set other relation as an attribute:

```<code>class PostRepository < Hanami::Repository
  associations do
    has_many :comments
  end

  # ...

  def join_example(date_range)
    posts    # => posts relation
    comments # => comments relation

    posts
      .join(comments) # set relation object here
      .where(comments[:created_at].qualified => date_range)
      .as(Post).to_a
  end
end
</code>```

And that's all.

Some helpful links:

rom-sql tests for left_join

A real example

Title: Join query in Hanami-model

Body:
Hanami model based on rom, that's why you can use Relation#join method with a needful relation.

For this you need to call join method for one relation and set other relation as an attribute:

class PostRepository < Hanami::Repository
  associations do
    has_many :comments
  end

  # ...

  def join_example(date_range)
    posts    # => posts relation
    comments # => comments relation

    posts
      .join(comments) # set relation object here
      .where(comments[:created_at].qualified => date_range)
      .as(Post).to_a
  end
end

And that's all.

Some helpful links:

rom-sql tests for left_join

A real example


问:
attribute change does not work
I'm working on the prettyphoto image gallery. I need to make a gallery with both "all images" category (containing all image categories) and separate categories of images (containing only images of specific category). To achieve this I'm trying to use jquery to change data-rel attribute of links. The code does not work and I am not able to find out what I'm doing wrong.
Please help, thank you in advance.

javascript:

```<code>var data_filter = 'category';// value inserted from php
//$('.test').html(data_filter);
(function($){
$(document).ready(function(){
   $('.cms-isotope-grid-post').each(function(){
      $this = $(this);
      $filter = $this.parent().find('.cms-grid-filter');
      $this.imagesLoaded(function(){
        $this.isotope({
           itemSelector:'.cms-grid-item',
           layoutMode: 'fitRows',
           filter: data_filter
       });
      });
      $filter.find('a').click(function(e){
          e.preventDefault();
          $filter.find("a").removeClass('active');
          $(this).addClass('active');
          var data_filter = $(this).data('filter');
          // my code
          $('.prettyphoto').data('rel', 'all');
          // end of my code
          $this.isotope({
              filter: data_filter
          });
      });
   });
});
})(jQuery);
</code>```

php:

```<code>                                        echo '
                                        <div class="cms-grid-item col-xs-12 col-sm-12 col-md-4 col-lg-4 portfolio-'.$image['category'].'">
                                            <div class="portfolio-wrapper muliples">
                                                <div class="entry-content">
                                                    <div class="entry-media cms-blog-media cms-media overlay-wrap">
                                                        <img width="770" height="520" src="photo/'.$image['file'].'" alt="" />
                                                        <div class="overlay">
                                                            <div class="overlay-content">
                                                                <a class="icon circle prettyphoto" data-rel="prettyPhoto['.$image['category'].']" href="photo/'.$image['file'].'">
                                                                    <i class="fa fa-search"></i>
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="entry-header">
                                                    <h4 class="entry-title"><a href="portfolio-detail.php">'.$image['name'].'</a></h4>
                                                    <div class="entry-meta cms-meta">
                                                        <ul class="list-unstyled list-inline">
                                                            <li class="detail-terms">
                                                                <a href="#">'.$image['name'].'</a>, <a href="#">'.$image['subtitle'].'</a>
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        ';
</code>```

http://visand.pl/monaco/demo1/portfolio.php

答:
Try using:</p>

```<code>$('.prettyphoto').data('rel', 'newvalue')
</code>```

Title: attribute change does not work

Body:
I'm working on the prettyphoto image gallery. I need to make a gallery with both "all images" category (containing all image categories) and separate categories of images (containing only images of specific category). To achieve this I'm trying to use jquery to change data-rel attribute of links. The code does not work and I am not able to find out what I'm doing wrong.
Please help, thank you in advance.

javascript:

var data_filter = 'category';// value inserted from php
//$('.test').html(data_filter);
(function($){
$(document).ready(function(){
   $('.cms-isotope-grid-post').each(function(){
      $this = $(this);
      $filter = $this.parent().find('.cms-grid-filter');
      $this.imagesLoaded(function(){
        $this.isotope({
           itemSelector:'.cms-grid-item',
           layoutMode: 'fitRows',
           filter: data_filter
       });
      });
      $filter.find('a').click(function(e){
          e.preventDefault();
          $filter.find("a").removeClass('active');
          $(this).addClass('active');
          var data_filter = $(this).data('filter');
          // my code
          $('.prettyphoto').data('rel', 'all');
          // end of my code
          $this.isotope({
              filter: data_filter
          });
      });
   });
});
})(jQuery);

php:

                                        echo '

'.$image['name'].'

                                                                '.$image['name'].', '.$image['subtitle'].'

                                        ';

http://visand.pl/monaco/demo1/portfolio.php

Body:
Try using:

$('.prettyphoto').data('rel', 'newvalue')


问:
Request Not Authorized Youtube Live streaming Android
In Youtube live streaming in OAuthClient Credential. I got "Request not Authorized". I create new credentials in google api console. but i got this error Thanks Advance for Help. </p>

```<code>     GoogleJsonResponseException code: 403 : Request is not authorized
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err: {
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   "code": 403,
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   "errors": [
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     {
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "domain": "youtube.liveBroadcast",
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "message": "Request is not authorized",
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "reason": "insufficientLivePermissions",
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "extendedHelp": "https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert#auth_required"
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     }
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   ],
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   "message": "Request is not authorized"
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err: }
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.android.apps.watchme.util.YouTubeApi.createLiveEvent(YouTubeApi.java:95)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.android.apps.watchme.StartActivity$CreateLiveEventTask.doInBackground(StartActivity.java:326)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.android.apps.watchme.StartActivity$CreateLiveEventTask.doInBackground(StartActivity.java:309)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-31 19:28:48.536 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-31 19:28:48.536 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-31 19:28:48.536 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.lang.Thread.run(Thread.java:841)
</code>```

答:
First, make sure that you enabled the YouTube Data API in your Developer Console.

The error 403 or "Request is not authorized" is a problem regarding your authorization in the YouTube API based from this documentation. So make sure that you properly follow the guide here in implementing the OAuth 2.0 Authentication. Also make sure that you use all the necessary scope.

I suggest you to try first to run your request through this try it part to verify if the issue in in the authorization part.

Hope this information helps you.

Body:
In Youtube live streaming in OAuthClient Credential. I got "Request not Authorized". I create new credentials in google api console. but i got this error Thanks Advance for Help.

     GoogleJsonResponseException code: 403 : Request is not authorized
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err: {
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   "code": 403,
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   "errors": [
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     {
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "domain": "youtube.liveBroadcast",
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "message": "Request is not authorized",
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "reason": "insufficientLivePermissions",
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:       "extendedHelp": "https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert#auth_required"
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     }
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   ],
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:   "message": "Request is not authorized"
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err: }
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.android.apps.watchme.util.YouTubeApi.createLiveEvent(YouTubeApi.java:95)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.android.apps.watchme.StartActivity$CreateLiveEventTask.doInBackground(StartActivity.java:326)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at com.google.android.apps.watchme.StartActivity$CreateLiveEventTask.doInBackground(StartActivity.java:309)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-31 19:28:48.531 19284-19810/com.ephron.mobilizerapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-31 19:28:48.536 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-31 19:28:48.536 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-31 19:28:48.536 19284-19810/com.ephron.mobilizerapp W/System.err:     at java.lang.Thread.run(Thread.java:841)