问:
PHP - Users links
I have created a registration & login system, it is working properly.
But, I only knew how to make a register & login system, I don't know how to make a link for every registered user

like :
example.com/marwan

example.com/user/marwan

Here is my Register PHP Code :

<?php
error_reporting(0);
session_start();

if( isset($_SESSION['user_id']) ){
 header("Location: /");
}

require 'includes/database.php';

$message = '';

if(!empty($_POST['email']) && !empty($_POST['password'])):

 // Enter the new user in the database
 $sql = "INSERT INTO users (full_name, email, password, phone, country) VALUES (:full_name, :email, :password, :phone, :country)";
 $stmt = $conn->prepare($sql);

 $stmt->bindParam(':full_name', $_POST['full_name']);
 $stmt->bindParam(':email', $_POST['email']);
 $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
 $stmt->bindParam(':phone', $_POST['phone']);
 $stmt->bindParam(':country', $_POST['country']);

 if( $stmt->execute() ):
   header("Location: account-created.php");
 else:
  header("Location: failed.php");
 endif;

endif;

?>```
</div>
</div>
</p>

<p>And my Login code is :</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

session_start();

if( isset($_SESSION['user_id']) ){
 header("Location: /tregolapp/home");
}

require 'includes/database.php';

if(!empty($_POST['email']) && !empty($_POST['password'])):

 $records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
 $records->bindParam(':email', $_POST['email']);
 $records->execute();
 $results = $records->fetch(PDO::FETCH_ASSOC);

 $message = '';

 if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){

  $_SESSION['user_id'] = $results['id'];
  header("Location: /tregolapp/index.php");

 } else {
  header("Location: /tregolapp/failed");
 }

endif;

?></code>```

Can someone help me please?

答:
What is your purpose in giving each user their "own URL"?

If you want each user to see their "own information" upon login, then after login go to a common "home page" while holding a session id. Use that id to pull "user specific" data from your database and display it on the "home page".

Title: PHP - Users links

Body:
I have created a registration & login system, it is working properly.
But, I only knew how to make a register & login system, I don't know how to make a link for every registered user

like :
example.com/marwan

example.com/user/marwan

Here is my Register PHP Code :

<?php
error_reporting(0);
session_start();

if( isset($_SESSION['user_id']) ){
 header("Location: /");
}

require 'includes/database.php';

$message = '';

if(!empty($_POST['email']) && !empty($_POST['password'])):

 // Enter the new user in the database
 $sql = "INSERT INTO users (full_name, email, password, phone, country) VALUES (:full_name, :email, :password, :phone, :country)";
 $stmt = $conn->prepare($sql);

 $stmt->bindParam(':full_name', $_POST['full_name']);
 $stmt->bindParam(':email', $_POST['email']);
 $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
 $stmt->bindParam(':phone', $_POST['phone']);
 $stmt->bindParam(':country', $_POST['country']);

 if( $stmt->execute() ):
   header("Location: account-created.php");
 else:
  header("Location: failed.php");
 endif;

endif;

?>

And my Login code is :

<?php

session_start();

if( isset($_SESSION['user_id']) ){
 header("Location: /tregolapp/home");
}

require 'includes/database.php';

if(!empty($_POST['email']) && !empty($_POST['password'])):

 $records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
 $records->bindParam(':email', $_POST['email']);
 $records->execute();
 $results = $records->fetch(PDO::FETCH_ASSOC);

 $message = '';

 if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){

  $_SESSION['user_id'] = $results['id'];
  header("Location: /tregolapp/index.php");

 } else {
  header("Location: /tregolapp/failed");
 }

endif;

?>

Can someone help me please?


来源: stackexchange

问:
GameMaker: How to freeze enemies temporarily?
I tried to set the Enemy.path_speed=0 and then set an alarm[0]=5, when it gets to alarm[0] it simply set Enemy.path_speed=100(the default value) again. But it does not work. enemies are frozen forever. How else can I freeze the enemies temporarily when I hit the space?

答: You just set alarm. You never decrease it. so your statement is never true and hence the objects do not move. </p>

ContentLicense: CC BY-SA 3.0


问:
Always Show Tooltip ( Angular Material2)
I have somebuttons

```<code>            <button mdTooltip="bye" mdTooltipPosition="left" md-mini-fab>
                BYE
            </button>
            <button mdTooltip="hi" mdTooltipPosition="left" md-mini-fab>
                HI
            </button>
</code>```

The tooltips show on "hover" by default. Is there a way to make it always show? (Show on page load and stay)

答:
First add imports:

```<code>import {MdTooltip} from '@angular/material';
</code>```

then add reference names to tooltips:

```<code><div>
  <button #tooltipBye="mdTooltip"
          mdTooltip="bye"
          mdTooltipPosition="below"
          md-mini-fab>
          BYE
  </button>
  <button #tooltipHi="mdTooltip"
          mdTooltip="hi"
          mdTooltipPosition="below"
          mdTooltipHideDelay="1000"
          md-mini-fab>
          HI
    </button>
</div>
</code>```

Pass references of these elements in the component. Then use AfterViewChecked lifecycle hook to call the show() method.

component.ts:

```<code>@ViewChild('tooltipHi') tooltipHi: MdTooltip;
@ViewChild('tooltipBye') tooltipBye: MdTooltip;

ngAfterViewChecked(){

  if(this.tooltipHi._isTooltipVisible() == false){
    this.tooltipHi.show();
  }
  if(this.tooltipBye._isTooltipVisible() == false){
    this.tooltipBye.show();
  }

}
</code>```

Here's the demo

Body:
I have somebuttons

            <button mdTooltip="bye" mdTooltipPosition="left" md-mini-fab>
                BYE
            </button>
            <button mdTooltip="hi" mdTooltipPosition="left" md-mini-fab>
                HI
            </button>

The tooltips show on "hover" by default. Is there a way to make it always show? (Show on page load and stay)

Body:
First add imports:

import {MdTooltip} from '@angular/material';

then add reference names to tooltips:

<div>
  <button #tooltipBye="mdTooltip"
          mdTooltip="bye"
          mdTooltipPosition="below"
          md-mini-fab>
          BYE
  </button>
  <button #tooltipHi="mdTooltip"
          mdTooltip="hi"
          mdTooltipPosition="below"
          mdTooltipHideDelay="1000"
          md-mini-fab>
          HI
    </button>
</div>

Pass references of these elements in the component. Then use AfterViewChecked lifecycle hook to call the show() method.

component.ts:

@ViewChild('tooltipHi') tooltipHi: MdTooltip;
@ViewChild('tooltipBye') tooltipBye: MdTooltip;

ngAfterViewChecked(){

  if(this.tooltipHi._isTooltipVisible() == false){
    this.tooltipHi.show();
  }
  if(this.tooltipBye._isTooltipVisible() == false){
    this.tooltipBye.show();
  }

}

Here's the demo


问:
How to put sign_up form on the home page without Devise?
I came with How to display a custom sign_in form anywhere in your app, that uses Devise to place any form anywhere.

But we don't want to use Devise.

I have tried using:

```<code><%= render 'sessions/new',  :locals => {:session => Session.new} %>
</code>```

And in the form:

```<code><%= simple_form_for(session, url: sessions_path) do |f| %>
</code>```

But it didn't work.

I've also tried load the session, it did not work too.

Does someone have any hint?

```<code>before_filter :load_categories
  protected

  def load_categories
    @sessions = Session.new
  end
</code>```

答:
inside routes.rb

```<code>  resources :sessions, only: [:new, :create]
</code>```

inside app/controllers/session_controller.rb

```<code>class SessionsController < ApplicationController
  def new
    # just put empty here
    # rails will automatically render views/sessions/new.html.erb
    # makesure you have this file
  end

  # I put create and delete session in case you need it later
  def create
    user = User.find_by_username(params[:session][:username])
    if user && user.authenticate(params[:session][:password])
        login user
        flash[:success] = "Anda berhasil login"
        redirect_to yours_path
    else
        flash.now[:error] = 'sorry cannot login'
        render 'new'
    end
  end

  def destroy
    session[:user_id] = nil
    flash[:success] = "Log out"
    redirect_to root_url
  end
end
</code>```

inside views/sessions/new.html.erb (I put sample for login page so you can check)

```<code><%= form_for(:session, url: sessions_path) do |f| %>
<h2>Please sign in</h2>
  <p>
    <%= f.label :username, "User name", class: "sr-only" %><br>
    <%= f.text_field :username, class: "form-control", placeholder: "User name" %>
  </p>
  <p>
    <%= f.label :password, class: "sr-only" %><br>
    <%= f.password_field :password, class: "form-control", placeholder: "Password" %>
  </p>
  <div class="checkbox">
    <label>
      <input type="checkbox" value="remember-me"> Remember me
    </label>
  </div>
  <%= f.submit "Log in", class: "btn btn-lg btn-primary btn-block" %>
  <h4>
    <%= link_to "Reset Password?", new_password_reset_path %>
  </h4>
<% end %>
</code>```

Body:
I came with How to display a custom sign_in form anywhere in your app, that uses Devise to place any form anywhere.

But we don't want to use Devise.

I have tried using:

<%= render 'sessions/new',  :locals => {:session => Session.new} %>

And in the form:

<%= simple_form_for(session, url: sessions_path) do |f| %>

But it didn't work.

I've also tried load the session, it did not work too.

Does someone have any hint?

before_filter :load_categories
  protected

  def load_categories
    @sessions = Session.new
  end

Body:
inside routes.rb

  resources :sessions, only: [:new, :create]

inside app/controllers/session_controller.rb

class SessionsController < ApplicationController
  def new
    # just put empty here
    # rails will automatically render views/sessions/new.html.erb
    # makesure you have this file
  end

  # I put create and delete session in case you need it later
  def create
    user = User.find_by_username(params[:session][:username])
    if user && user.authenticate(params[:session][:password])
        login user
        flash[:success] = "Anda berhasil login"
        redirect_to yours_path
    else
        flash.now[:error] = 'sorry cannot login'
        render 'new'
    end
  end

  def destroy
    session[:user_id] = nil
    flash[:success] = "Log out"
    redirect_to root_url
  end
end

inside views/sessions/new.html.erb (I put sample for login page so you can check)

<%= form_for(:session, url: sessions_path) do |f| %>
<h2>Please sign in</h2>
  <p>
    <%= f.label :username, "User name", class: "sr-only" %><br>
    <%= f.text_field :username, class: "form-control", placeholder: "User name" %>
  </p>
  <p>
    <%= f.label :password, class: "sr-only" %><br>
    <%= f.password_field :password, class: "form-control", placeholder: "Password" %>
  </p>
  <div class="checkbox">
    <label>
      <input type="checkbox" value="remember-me"> Remember me
    </label>
  </div>
  <%= f.submit "Log in", class: "btn btn-lg btn-primary btn-block" %>
  <h4>
    <%= link_to "Reset Password?", new_password_reset_path %>
  </h4>
<% end %>


问:
ASP.NET C# How to hide and display particular field inside Repeater? (if statement)
Needed some help here,
So I am using repeater and retrieve some data from DB then put into the repeater, the thing is that for certain data value I would like to display it differently in the HTML, basically do IF checking inside Repeater to determine which HTML code to use, can someone help me with that?

I have two different codes

```<code><div class="message-data">
  <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
</div>
<div class="message you-message">
A new client?!?! I would love to help them, but where are we going to find the time?
</code>```

and

```<code> <li class="clearfix">
    <div class="message-data align-right">
      <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
    </div>
    <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
  </li>
</code>```

As you can see, how do I put IF statement, for the first one like if (username == "You") and second one if (Username != "You"). Assume that the DB I retrieve has attribute named "Username"

Thanks

答:
Maybe you can put them in

like

```<code><asp:Panel ID="Panel1" runat="server">
<div class="message-data">
    <span class="message-data-name"><i class="fa fa-circle you"></i>You</span>
</div>
<div class="message you-message">
    A new client?!?! I would love to help them, but where are we going to find the time?
</div>
</asp:Panel>

<asp:Panel ID="Panel2" runat="server">
<li class="clearfix">
    <div class="message-data align-right">
        <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
    </div>
    <div class="message me-message float-right">We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
</li>
</asp:Panel>
</code>```

then

you can use IF statement in code behind (C#)

```<code>if (username == "You") {
    Panel1.Visible = true;
}
</code>```

Body:
Needed some help here,
So I am using repeater and retrieve some data from DB then put into the repeater, the thing is that for certain data value I would like to display it differently in the HTML, basically do IF checking inside Repeater to determine which HTML code to use, can someone help me with that?

I have two different codes

   You

A new client?!?! I would love to help them, but where are we going to find the time?

and

      Ada, your OperationsAlly

 We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.

As you can see, how do I put IF statement, for the first one like if (username == "You") and second one if (Username != "You"). Assume that the DB I retrieve has attribute named "Username"

Thanks

Body:
Maybe you can put them in

like

<asp:Panel ID="Panel1" runat="server">
<div class="message-data">
    <span class="message-data-name"><i class="fa fa-circle you"></i>You</span>
</div>
<div class="message you-message">
    A new client?!?! I would love to help them, but where are we going to find the time?
</div>
</asp:Panel>

<asp:Panel ID="Panel2" runat="server">
<li class="clearfix">
    <div class="message-data align-right">
        <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
    </div>
    <div class="message me-message float-right">We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
</li>
</asp:Panel>

then

you can use IF statement in code behind (C#)

if (username == "You") {
    Panel1.Visible = true;
}


问:
how do I convert csv file output from vertical to horizontal?
I have a function that retrieves csv file content

```<code>var reader = new FileReader();

reader.onload = function () {
    console.log("This is the file Output Format \n" + reader.result);
    reader.readAsBinaryString(fileInput.files[0]);
};
</code>```

My csv file function output file data in this format:

456789

454356

098569

856995

I want it to be in this format:

456789, 454356, 098569, 856995

how do I generate an horizontal file output like below?

答:
Since your desired output does not contain ID, I've left the numbers only:

```<code>console.log(
   "This is the wanted Output Format \n" +
   reader.result.split(/\s+/).splice(1).join(', ')
);
</code>```

Body:
I have a function that retrieves csv file content

var reader = new FileReader();

reader.onload = function () {
    console.log("This is the file Output Format \n" + reader.result);
    reader.readAsBinaryString(fileInput.files[0]);
};

My csv file function output file data in this format:

456789

454356

098569

856995

I want it to be in this format:

456789, 454356, 098569, 856995

how do I generate an horizontal file output like below?

Body:
Since your desired output does not contain ID, I've left the numbers only:

console.log(
   "This is the wanted Output Format \n" +
   reader.result.split(/\s+/).splice(1).join(', ')
);


问:
When I try to use the string parameter for ComSourceInterfaces instead of typeof I cannot register the assembly as a COM object
When I try to use the string parameter for ComSourceInterfaces instead of typeof I cannot register the assembly as a COM object.  I'm implementing multiple interfaces because that is what is required by the SDK.

When I use

```<code>[ComVisible(true),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces("IAccessControl"),
Guid("738CFFEF-37DC-4C61-957E-C5A78FE20223")]
public class EventGeneratorV2  : IAccessControl
</code>```

I get the error

error MSB3217: Cannot register assembly "...\Event Generator v2.dll". Could not load type 'IAccessControl' from assembly 'Event
  Generator v2, Version=1.1.0.0, Culture=neutral,
  PublicKeyToken=bffdb712704a75b7'.

However if I change my code to use

```<code>[ComVisible(true),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(IAccessControl)),
Guid("738CFFEF-37DC-4C61-957E-C5A78FE20223")]
public class EventGeneratorV2  : IAccessControl
</code>```

It does work correctly.  I also tried the full qualified name for the IAccessControl interface, Lib.Interfaces.IAcccessControl as the string but it still fails.  The best resolution would be to use multiple ComSourceInterfaces but you can only use that once and it takes at most 4 interfaces using typeof.  I have 9 interfaces I need to implement in order for it to be compatible with this other software.  Is there a way to get the string to work?

答:
Okay I figured it out.  The string is actually "Lib.Interfaces.IAcccessControl, Lib" for each Interface.  Where the first part is the fully qualified name for the interface and the lib is the Reference that that the Interface is coming from.

Then when I add the other interfaces I have to add the \0 between each.  So my final ComSourceInterfaces is the rather lengthy

```<code>ComSourceInterfaces("Lib.Interfaces.IAccessControl, Lib\0Lib.Interfaces.IAccessControl2, Lib\0Lib.Interfaces.ITranslate, Lib\0Lib.Interfaces.ITranslate2, Lib\0Lib.Interfaces.IComConfig, Lib\0Lib.Interfaces.IComConfig2, Lib\0Lib.Interfaces.IInput, Lib\0Lib.Interfaces.IInput2, Lib\0Lib.Interfaces.IAsset, Lib\0Lib.Interfaces.IAsset2, Lib\0Lib.Interfaces.IFakeName, Lib\0Lib.Interfaces.IComManager, Lib\0Lib.Interfaces.IDistributeEvent, Lib")
</code>```

After that the DLL compiles and registers correctly.

Body:
When I try to use the string parameter for ComSourceInterfaces instead of typeof I cannot register the assembly as a COM object.  I'm implementing multiple interfaces because that is what is required by the SDK.

When I use

[ComVisible(true),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces("IAccessControl"),
Guid("738CFFEF-37DC-4C61-957E-C5A78FE20223")]
public class EventGeneratorV2  : IAccessControl

I get the error

error MSB3217: Cannot register assembly "...\Event Generator v2.dll". Could not load type 'IAccessControl' from assembly 'Event
  Generator v2, Version=1.1.0.0, Culture=neutral,
  PublicKeyToken=bffdb712704a75b7'.

However if I change my code to use

[ComVisible(true),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(IAccessControl)),
Guid("738CFFEF-37DC-4C61-957E-C5A78FE20223")]
public class EventGeneratorV2  : IAccessControl

It does work correctly.  I also tried the full qualified name for the IAccessControl interface, Lib.Interfaces.IAcccessControl as the string but it still fails.  The best resolution would be to use multiple ComSourceInterfaces but you can only use that once and it takes at most 4 interfaces using typeof.  I have 9 interfaces I need to implement in order for it to be compatible with this other software.  Is there a way to get the string to work?

Body:
Okay I figured it out.  The string is actually "Lib.Interfaces.IAcccessControl, Lib" for each Interface.  Where the first part is the fully qualified name for the interface and the lib is the Reference that that the Interface is coming from.

Then when I add the other interfaces I have to add the \0 between each.  So my final ComSourceInterfaces is the rather lengthy

ComSourceInterfaces("Lib.Interfaces.IAccessControl, Lib\0Lib.Interfaces.IAccessControl2, Lib\0Lib.Interfaces.ITranslate, Lib\0Lib.Interfaces.ITranslate2, Lib\0Lib.Interfaces.IComConfig, Lib\0Lib.Interfaces.IComConfig2, Lib\0Lib.Interfaces.IInput, Lib\0Lib.Interfaces.IInput2, Lib\0Lib.Interfaces.IAsset, Lib\0Lib.Interfaces.IAsset2, Lib\0Lib.Interfaces.IFakeName, Lib\0Lib.Interfaces.IComManager, Lib\0Lib.Interfaces.IDistributeEvent, Lib")

After that the DLL compiles and registers correctly.


问:
implict declaration of function - vlc android
i want to compile the android version of vlc player but in progress i have two error as follow :

```<code>../../src/misc/block.c:315:5: error: implicit declaration of function 'shmdt' is invalid in C99 [-Werror,-Wimplicit-function-declaration]

../../src/posix/filesystem.c:258:16: error: implicit declaration of function 'sigtimedwait' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
</code>```

i searched many posts here or in another forums for implicit problem and they say it's because not importing lib / header file.

shmdt want shm.h and it is in block.c file correctly. and sigtimedwait have its own header.

i have this problem about two days and change many lines of code.

how can i fix this ? any idea ?

答:
The compiler wants to know the function before it can use it
just declare the function before you call it
You can add definition of method sigtimedwait in file filesystem.c.

That means add following:

int sigtimedwait(const sigset_t *set, siginfo_t *info,
                 const struct timespec *timeout);

See https://linux.die.net/man/2/sigtimedwait

Body:
i want to compile the android version of vlc player but in progress i have two error as follow :

../../src/misc/block.c:315:5: error: implicit declaration of function 'shmdt' is invalid in C99 [-Werror,-Wimplicit-function-declaration]

../../src/posix/filesystem.c:258:16: error: implicit declaration of function 'sigtimedwait' is invalid in C99 [-Werror,-Wimplicit-function-declaration]

i searched many posts here or in another forums for implicit problem and they say it's because not importing lib / header file.

shmdt want shm.h and it is in block.c file correctly. and sigtimedwait have its own header.

i have this problem about two days and change many lines of code.

how can i fix this ? any idea ?


问:
For web scraping through python, when should I use an html parser instead of lxml? Which is better and why?
While I was trying to read Amazon's data, I noticed little difference in the outputs when I used an lxml parser instead of html. Which one should I prefer and why?</p>

答:
Are you using BeautifulSoup for parsing? If so then read the documentation.

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#differences-between-parsers


问:
TestCafe issue, onChange event not triggred for input box in a modal dialog box
I am trying to update a number on the screen. I click on the update menu that lets me update a number. When I click on the update button it will open a modal dialog box with an empty text box for the new number and a save button. The save button is initially disabled. If the user manually types in a number in the text box, the onChange event will trigger and the save button is enabled. However, if I let the testcafe script to put a number in the number text box, the save button remains disabled. My guess is that when I use the testcafe .typeText(inputbox,'123') it does not fire the onChange event on the text box. Any help on this is greatly appreciated.

答:
Have you tried to put "alert" or "print" to see if onChange method is triggered?
Furthermore, can you post your code?</p>


问:
Should the hover event be disabled once a link is clicked?
As I was working on the link styling for this page component-header I noticed that the hover event was not triggering.  I then opened the page up in incognito mode, and the link :hover styling renders.

So the browser (Both Chrome and Firefox) remember that you have visited a certain link (Regardless of whether it's a new tab), and after that the browser does not trigger the hover event.

I was expecting that event to be triggered regardless of whether the link has been visited or not.  I do expect the :visited style to be displayed once the link is visited, but if the mouse hovers, I would just naturally expect that the :hover style be triggered.

I filed a bug report with Chrome for this I'm just wondering whether I should follow up on it or whether the current behavior is there for a good reason?

It seems like we should not have to remember the right order for Pseudo selectors, although the clever tip offered by @kapreski makes it very easy.

答:
After visited the :visited rule overwrites the :hover rule, if the :hover is before the ":visited".

The :hover works in any case if it comes after the :visited rule in the css file, or if the :hover has the !important clause.


问:
getPlacePredictions vs getPredictions, google maps autocomplete service clarification
What is the difference between autocompleteService.getPlacePredictions and autocompleteService.getPredictions in the Google Maps Autocomplete Service? I've created tests for these here, but they seem to be returning the same things:

https://github.com/QuantumInformation/google-places-tests

答:
It's the same thing.

```<code>kx.prototype.getPlacePredictions = function(a, b) { _.G("places_impl", (0, _.p)(function() { this.b.getPlacePredictions(a, b) }, this)) };
kx.prototype.getPredictions = kx.prototype.getPlacePredictions;
</code>```

'getPrediction' method is directly assigned to 'getPlacePrediction' in the JavaScript code from Google API

ContentLicense: CC BY-SA 4.0

Body:
It's the same thing.

kx.prototype.getPlacePredictions = function(a, b) { _.G("places_impl", (0, _.p)(function() { this.b.getPlacePredictions(a, b) }, this)) };
kx.prototype.getPredictions = kx.prototype.getPlacePredictions;

'getPrediction' method is directly assigned to 'getPlacePrediction' in the JavaScript code from Google API


问:
Python regex pull first capitalized word or first and second words if both are capitalized
The current regex formula I have implemented is only able to extract the first two capitalized words for a given string. I want to be able to extract just the first word in a string if the second word is not capitalized.

Here are some examples:

```<code>s = 'Smith John went to ss for Jones.'
s = 'Jones, Greg went to 2b for Smith.'
s = 'Doe went to ss for Jones.'
</code>```

Essentially, I just want regex to output the following:

```<code>'Smith John'
'Jones, Greg'
'Doe'
</code>```

The current regex formula I have is as follows, except it will not capture the Doe example:

```<code>new = re.findall(r'([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', s)
</code>```

Body:
The current regex formula I have implemented is only able to extract the first two capitalized words for a given string. I want to be able to extract just the first word in a string if the second word is not capitalized.

Here are some examples:

s = 'Smith John went to ss for Jones.'
s = 'Jones, Greg went to 2b for Smith.'
s = 'Doe went to ss for Jones.'

Essentially, I just want regex to output the following:

'Smith John'
'Jones, Greg'
'Doe'

The current regex formula I have is as follows, except it will not capture the Doe example:

new = re.findall(r'([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', s)

Body:
import re
print re.match(r'([A-Z].*?(?:[, ]+)){1,}',s).group()


问:
calculating time difference between days
I have 4 columns:start date,end date, start time and end time. I need to find the difference i.e. endtime-start time. However the start date and end date need to be taken into account. Example: If I have start date = 7/6/2017 and start time =1:00 and end date -7/7/2017 end time = 2:00 then it is 25 hours..

I need to do this for all start and end dates within the past 1 week. Can someone help me with this. It would be really helpful.

答:
Use UNIX_TIMESTAMP() and STR_TO_DATE() to convert your date and time to a Unix timestamp in seconds. Eg: UNIX_TIMESTAMP(STR_TO_DATE("7/6/2017 1:00", '%d/%m/%Y %H:%i'))

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date

Then perform a basic substraction on both timestamps to get the time gap in seconds.

Also, as a general recommandation, it is best to convert your dates into the proper MySQL Datetime column type (better SQL support), or as a unix int timestamp (faster diffs), or as an ISO formatted string including the GMT data (better human readability, terrible lookups).


问:
What is the equivalent of IE's removeNode
IE's removeNode
http://msdn.microsoft.com/en-us/library/ms536708(VS.85).aspx

helps me to decide whether I would like to remove childNodes or not.

I would like to know whether the same exists for Firefox, Opera, Chrome and Safari. If not, how can I achieve it?

答:
No, .removeNode() is not a standard method and it does not exist outside IE.

If you are looking for removeNode's functionality of promoting element's children up a level (an optional boolean argument), you have to do it manually.

However, with jQuery it is easy:

```<code>$(elToRemove).replaceWith($(elToRemove).children());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
No, .removeNode() is not a standard method and it does not exist outside IE.

If you are looking for removeNode's functionality of promoting element's children up a level (an optional boolean argument), you have to do it manually.

However, with jQuery it is easy:

$(elToRemove).replaceWith($(elToRemove).children());


问:
Why does Code::Blocks keep crashing when I try to run this code?
Code::Blocks keeps crashing when I enter the first score in this simple code. It is a perfectly type code to my understanding now I'm confused.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    float grade = 0;
    float scoreEntered = 0;
    float numtest = 0;
    float average = 0;

    printf("Press 0 when complete. \n\n");
    do {
        printf("Test: %.0f   Average: %.2f \n", numtest, average);
        printf("\nEnter test score ");
        scanf("%f", scoreEntered);
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
    } while (scoreEntered != 0);

    return 0;
}
</code>```

答:
```<code>scanf("%f", scoreEntered);
</code>```

should be

```<code>scanf("%f", &scoreEntered);
</code>```

scanf expects address of variable, when you pass variable rather than address of variable, it will end up accessing invalid memory leading to segment fault

Body:
Code::Blocks keeps crashing when I enter the first score in this simple code. It is a perfectly type code to my understanding now I'm confused.

#include <stdio.h>
#include <stdlib.h>

int main() {
    float grade = 0;
    float scoreEntered = 0;
    float numtest = 0;
    float average = 0;

    printf("Press 0 when complete. \n\n");
    do {
        printf("Test: %.0f   Average: %.2f \n", numtest, average);
        printf("\nEnter test score ");
        scanf("%f", scoreEntered);
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
    } while (scoreEntered != 0);

    return 0;
}

Body:
scanf("%f", scoreEntered);

should be

scanf("%f", &scoreEntered);

scanf expects address of variable, when you pass variable rather than address of variable, it will end up accessing invalid memory leading to segment fault


问:
Adding a new channel to an image
I am trying to add a 4th "channel" to an image. Specifically, I have a RGB image and would like append that image matrix with an edge detection layer as found by a Canny filter, which I will then use as an input for a neural network.

I have edge detection working, and I can even append the images, but for some reason, the data 'reverts' after looping. The changes that I make in the size of the image do not stick.

Code

I have three sets of 32x32x3 color images: X_train, X_valid, and X_test. For each one, I am normalizing the image and then appending the gradient. Appending appears to take affect while looping, but the changes do not exist after looping.

Code snippet

```<code>import cv2 as cv
example_record = 2

print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_valid.shape))
print('X_test is shape {}'.format(X_test.shape))

# Show before
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} Before Normalization'.format(example_record))

# Normalize
canny_low = 50
canny_high = 100
for dataset in [X_train, X_valid, X_test]:
    for i, img in enumerate(dataset):
        cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
        edges = cv.Canny(img, canny_low, canny_high)
        edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
        img = np.concatenate((img, edges),axis=2)
        if i == 0:
            print('img shape after concatenation {}'.format(img.shape))

# Show after
plt.figure()
print('Updated image shape: {}'.format(X_valid[example_record].shape))
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} After Normalization'.format(example_record))
</code>```

Output

```<code>X_train is shape (34799, 32, 32, 3)
X_valid is shape (4410, 32, 32, 3)
X_test is shape (12630, 32, 32, 3)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
Updated image shape: (32, 32, 3)
</code>```

Other Attempts

If I replace img = np.concatenate((img, edges),axis=2) with dataset[i] = np.concatenate((img, edges),axis=2), I get the error:

```<code>     21         edges = cv.Canny(img, canny_low, canny_high)
     22         edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
---> 23         dataset[i] = np.concatenate((img, edges),axis=2)
     24         if i == 0:
     25             print('img shape after concatenation {}'.format(img.shape))

ValueError: could not broadcast input array from shape (32,32,4) into shape (32,32,3)
</code>```

答:
You inner loop

```<code>for i, img in enumerate(dataset):
</code>```

is overwriting the value of concatenated img

Your

```<code>print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_train.shape))
print('X_test is shape {}'.format(X_train.shape))
</code>```

is printing the value of the shape of X_train.shape!

After the line

img = np.concatenate(...)

inside the loop, what do you do with the concatenated image img? Don't you think you have to store the result somehow for the program to "remember" it?

Your second attempt is promising, just do not store new img in the dataset. Define a dataset_new outside the loop (make an empty list or numpy array of the correct shape) and then in the loop do dataset_new[i] = np.concatenate....

Title: Adding a new channel to an image

Body:
I am trying to add a 4th "channel" to an image. Specifically, I have a RGB image and would like append that image matrix with an edge detection layer as found by a Canny filter, which I will then use as an input for a neural network.

I have edge detection working, and I can even append the images, but for some reason, the data 'reverts' after looping. The changes that I make in the size of the image do not stick.

Code

I have three sets of 32x32x3 color images: X_train, X_valid, and X_test. For each one, I am normalizing the image and then appending the gradient. Appending appears to take affect while looping, but the changes do not exist after looping.

Code snippet

import cv2 as cv
example_record = 2

print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_valid.shape))
print('X_test is shape {}'.format(X_test.shape))

# Show before
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} Before Normalization'.format(example_record))

# Normalize
canny_low = 50
canny_high = 100
for dataset in [X_train, X_valid, X_test]:
    for i, img in enumerate(dataset):
        cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
        edges = cv.Canny(img, canny_low, canny_high)
        edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
        img = np.concatenate((img, edges),axis=2)
        if i == 0:
            print('img shape after concatenation {}'.format(img.shape))

# Show after
plt.figure()
print('Updated image shape: {}'.format(X_valid[example_record].shape))
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} After Normalization'.format(example_record))

Output

X_train is shape (34799, 32, 32, 3)
X_valid is shape (4410, 32, 32, 3)
X_test is shape (12630, 32, 32, 3)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
Updated image shape: (32, 32, 3)

Other Attempts

If I replace img = np.concatenate((img, edges),axis=2) with dataset[i] = np.concatenate((img, edges),axis=2), I get the error:

     21         edges = cv.Canny(img, canny_low, canny_high)
     22         edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
---> 23         dataset[i] = np.concatenate((img, edges),axis=2)
     24         if i == 0:
     25             print('img shape after concatenation {}'.format(img.shape))

ValueError: could not broadcast input array from shape (32,32,4) into shape (32,32,3)

Body:
You inner loop

for i, img in enumerate(dataset):

is overwriting the value of concatenated img

Your

print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_train.shape))
print('X_test is shape {}'.format(X_train.shape))

is printing the value of the shape of X_train.shape!

After the line

img = np.concatenate(...)

inside the loop, what do you do with the concatenated image img? Don't you think you have to store the result somehow for the program to "remember" it?

Your second attempt is promising, just do not store new img in the dataset. Define a dataset_new outside the loop (make an empty list or numpy array of the correct shape) and then in the loop do dataset_new[i] = np.concatenate....


问:
Swift and Firebase - Adding multiple nodes at a time with same Id
I'm trying to add multiple nodes at the same time the company is created. I can only add one node at a time. I will like the result in this image. I need to get the childByAutoId at the time of creation to use it as a ref to add the second node.
Then I just add the value like this.

```<code>"isActive": self.isActiveSwitch.isOn
</code>```

Image1

```<code>Database.database().reference().child(“Company”).childByAutoId.child("Profile").setValue([
 "Name": cName.text!,
 "Address": cAddress.text!,
 "City": cCity.text!,
 "State": cState.text!,
 "Zip": cZip.text!
])
</code>```

Image2

This is what I'm doing at this moment

答:
You can get childByAutoId key this way and then use that latter to add STATUS node.

```<code>let ref = Database.database().reference().child("Company").childByAutoId
let key = ref.key
//Now set profile node
ref.child("Profile").setValue([
    "Name": cName.text!,
    "Address": cAddress.text!,
    "City": cCity.text!,
    "State": cState.text!,
    "Zip": cZip.text!
])
//later use this key to set Status node
Database.database().reference().child("Company").child(key).child("Status").setValue([
    "isActive": self.isActiveSwitch.isOn
])
</code>```

Note: This is unnecessary if your requirement is to set both Profile and Status at same time then you can make it like this.

```<code>Database.database().reference().child("Company").childByAutoId.setValue([
    "Profile": [
        "Name": cName.text!,
        "Address": cAddress.text!,
        "City": cCity.text!,
        "State": cState.text!,
        "Zip": cZip.text!
    ],
    "Status":[
        "isActive": self.isActiveSwitch.isOn
    ]
])
</code>```

Body:
I'm trying to add multiple nodes at the same time the company is created. I can only add one node at a time. I will like the result in this image. I need to get the childByAutoId at the time of creation to use it as a ref to add the second node.
Then I just add the value like this.

"isActive": self.isActiveSwitch.isOn

Image1

Database.database().reference().child(“Company”).childByAutoId.child("Profile").setValue([
 "Name": cName.text!,
 "Address": cAddress.text!,
 "City": cCity.text!,
 "State": cState.text!,
 "Zip": cZip.text!
])

Image2

This is what I'm doing at this moment

Body:
You can get childByAutoId key this way and then use that latter to add STATUS node.

let ref = Database.database().reference().child("Company").childByAutoId
let key = ref.key
//Now set profile node
ref.child("Profile").setValue([
    "Name": cName.text!,
    "Address": cAddress.text!,
    "City": cCity.text!,
    "State": cState.text!,
    "Zip": cZip.text!
])
//later use this key to set Status node
Database.database().reference().child("Company").child(key).child("Status").setValue([
    "isActive": self.isActiveSwitch.isOn
])

Note: This is unnecessary if your requirement is to set both Profile and Status at same time then you can make it like this.

Database.database().reference().child("Company").childByAutoId.setValue([
    "Profile": [
        "Name": cName.text!,
        "Address": cAddress.text!,
        "City": cCity.text!,
        "State": cState.text!,
        "Zip": cZip.text!
    ],
    "Status":[
        "isActive": self.isActiveSwitch.isOn
    ]
])


问:
How to get text of next td in jQuery?
I need Test 2 text when I clicked on "Click". I have tried like this ...

```<code>$("#clicked").click(function(){
  alert( $('this').closest('td').next('td').next('td').text());
})
</code>```

But In alert there is empty. How I can get Test 2 ?

```<code><tr>
  <td> </td>
  <td><a id = 'clicked'>Click</a></td>
  <td>Test 1</td>
  <td><a id = 'clicked2' /> Test 2</a></td>
</tr>
</code>```

From comment below:

this means $('#clicked'). That means when I clicked on the Click link.

答:
```<code>$('#clicked').click(function(){
  console.log($(this).closest('td').next().text());
});
</code>```

Title: How to get text of next td in jQuery?

Body:
I need Test 2 text when I clicked on "Click". I have tried like this ...

$("#clicked").click(function(){
  alert( $('this').closest('td').next('td').next('td').text());
})

But In alert there is empty. How I can get Test 2 ?

  Click
  Test 1
   Test 2

From comment below:

this means $('#clicked'). That means when I clicked on the Click link.


问:
Custom http client when using google's java adwords client library?
I'm using google's java client library to create adwords campaigns. This works fine during development, but when I deploy my service to production, all our outgoing requests need to pass through our own proxy. Our proxy examines some of our custom http headers and forwards the request to the Internet. My questions are:
 1. is it possible to use my own custom http client instead of the one that ships with the library to make the http request ?
 2. in case 1. is not possible, is it possible to add custom http headers to the requests made by the client?

(I have looked at the source code and have determined that there is no obvious way to plug in my own http client, and would be pleased to be proven wrong. :) )

答:
The sdk doesn't support it at the moment, the workaround is to use the proxySelector and add custom logic there.
  docs here


问:
Parsing HTML Response - iPhone App
I'm creating an app. I'm sending the login info using HTTP POST method and the replyI'm getting from server is in HTML format. How can I parse that HTML and add different methods for succession or failure? What I'm trying to achieve is, upon login failure it should show the message using UIAlerView and upon successful login, the app should change the view with animation. :)

The code I'm using right now:

```<code>- (IBAction) loginButton: (id) sender {
indicator.hidden = NO;
[indicator startAnimating];
loginbutton.enabled = NO;

// Create the username and password string.
// username and password are the username and password to login with
NSString *postString = [[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, password];
// Package the string in an NSData object
NSData *requestData = [postString dataUsingEncoding:NSASCIIStringEncoding];

// Create the URL request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"http://localhost/dologin.php"]];  // create the URL request
[request setHTTPMethod: @"POST"];   // you're sending POST data
[request setHTTPBody: requestData];  // apply the post data to be sent

// Call the URL
NSURLResponse *response;  // holds the response from the server
NSError *error;   // holds any errors
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];  // call the URL

/* If the response from the server is a web page, dataReturned will hold the string of the HTML returned. */
NSString *dataReturned = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];

alertWithOkButton = [[UIAlertView alloc] initWithTitle:@"Status..." message:[NSString stringWithFormat:@"%@",dataReturned] delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[alertWithOkButton show];
[alertWithOkButton release];
}
</code>```

答: What I did exactly is I used HTMLparser class. This class is very useful if you're getting response in HTML format. </p>

Title: Parsing HTML Response - iPhone App

Body:
I'm creating an app. I'm sending the login info using HTTP POST method and the replyI'm getting from server is in HTML format. How can I parse that HTML and add different methods for succession or failure? What I'm trying to achieve is, upon login failure it should show the message using UIAlerView and upon successful login, the app should change the view with animation. :)

The code I'm using right now:

- (IBAction) loginButton: (id) sender {
indicator.hidden = NO;
[indicator startAnimating];
loginbutton.enabled = NO;

// Create the username and password string.
// username and password are the username and password to login with
NSString *postString = [[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, password];
// Package the string in an NSData object
NSData *requestData = [postString dataUsingEncoding:NSASCIIStringEncoding];

// Create the URL request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"http://localhost/dologin.php"]];  // create the URL request
[request setHTTPMethod: @"POST"];   // you're sending POST data
[request setHTTPBody: requestData];  // apply the post data to be sent

// Call the URL
NSURLResponse *response;  // holds the response from the server
NSError *error;   // holds any errors
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];  // call the URL

/* If the response from the server is a web page, dataReturned will hold the string of the HTML returned. */
NSString *dataReturned = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];

alertWithOkButton = [[UIAlertView alloc] initWithTitle:@"Status..." message:[NSString stringWithFormat:@"%@",dataReturned] delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[alertWithOkButton show];
[alertWithOkButton release];
}


问:
failed to resolve com.android.support.constraint:constraint-layout:2.0.0-alpha4
I imported a project from my work-space. After this some errors were shown which I can't solve.

The message

Install Repository and sync project

was shown as a link, but clicking on it didn't solve my problem.

答:
Add ConstraintLayout to your project.

To use ConstraintLayout in your project, proceed as follows:

Ensure you have the "maven.google.com" repository declared in your
module-level build.gradle file:

```<code>repositories {
    maven {
        url 'https://maven.google.com'
    }
}
</code>```

Add the library as a dependency in the same build.gradle file:

```<code>dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
</code>```

In the toolbar or sync notification, click Sync Project with Gradle Files.

Body:
Add ConstraintLayout to your project.

To use ConstraintLayout in your project, proceed as follows:

Ensure you have the "maven.google.com" repository declared in your
module-level build.gradle file:

repositories {
    maven {
        url 'https://maven.google.com'
    }
}

Add the library as a dependency in the same build.gradle file:

dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}

In the toolbar or sync notification, click Sync Project with Gradle Files.


问:
R - Count number of rows based on specific matching criteria
I have a data.frame that I wish to, upon matching a set criteria (match variable), in a separate column count 1,2,3,4,5,6,7 etc.... After the condition is met, it shall continue to count until the next match appears.

if i set:

match <- <-1.0

The below data.frame is an example of the output:

```<code>    roll.z.score.n3 sig.count
1           NA          0
2           NA          0
3   -1.135974424        1
4   0.193311168         2
5   0.714285714         3
6   -1.148753543        4
7   -0.942160394        5
8   0.695763683         6
9   1.140646864         7
10  0.985196899         8
11  -0.768766574        1
12  -1.011293858        2
13  -0.516703612        3
14  -1.120897077        4
15  1.091089451         5
16  0.968364052         6
17  0.872871561         7
18  1.099524999         8
19  0.918397948         9
</code>```

on row 3 we have a match below -1.0. So the count beings, and it continues until the next match below -1.0 on line 11. The count then begins... and it would continue to do so until the next match below -1.0.

Any assistance is appreciated!

EDIT: In response to baptise

```<code>set.seed(123)
new.df$sig_long <- runif(13787,2,1)
cbind(new.df$sig_long, n = do.call(c, lapply(rle(new.df$sig_long < -1)[["lengths"]], seq_len)))
</code>```

cbind(new.df$sig_long, n = do.call(c, lapply(rle(new.df$sig_long < -1)[["lengths"]], seq_len)))
  Error in do.call(c, lapply(rle(new.df$sig_long < -1)[["lengths"]], seq_len)) :
    'what' must be a function or character string

答:
something like this perhaps,</p>

```<code>set.seed(123)
x <- runif(20,-2,1)
cbind(x, n = do.call(c, lapply(rle(x < -1)[["lengths"]], seq_len)))
</code>```

Body:
I have a data.frame that I wish to, upon matching a set criteria (match variable), in a separate column count 1,2,3,4,5,6,7 etc.... After the condition is met, it shall continue to count until the next match appears.

if i set:

match <- <-1.0

The below data.frame is an example of the output:

    roll.z.score.n3 sig.count
1           NA          0
2           NA          0
3   -1.135974424        1
4   0.193311168         2
5   0.714285714         3
6   -1.148753543        4
7   -0.942160394        5
8   0.695763683         6
9   1.140646864         7
10  0.985196899         8
11  -0.768766574        1
12  -1.011293858        2
13  -0.516703612        3
14  -1.120897077        4
15  1.091089451         5
16  0.968364052         6
17  0.872871561         7
18  1.099524999         8
19  0.918397948         9

on row 3 we have a match below -1.0. So the count beings, and it continues until the next match below -1.0 on line 11. The count then begins... and it would continue to do so until the next match below -1.0.

Any assistance is appreciated!

EDIT: In response to baptise

set.seed(123)
new.df$sig_long <- runif(13787,2,1)
cbind(new.df$sig_long, n = do.call(c, lapply(rle(new.df$sig_long < -1)[["lengths"]], seq_len)))

cbind(new.df$sig_long, n = do.call(c, lapply(rle(new.df$sig_long < -1)[["lengths"]], seq_len)))
  Error in do.call(c, lapply(rle(new.df$sig_long < -1)[["lengths"]], seq_len)) :
    'what' must be a function or character string

Body:
something like this perhaps,

set.seed(123)
x <- runif(20,-2,1)
cbind(x, n = do.call(c, lapply(rle(x < -1)[["lengths"]], seq_len)))


问:
Approaches to services and components in Angular modules provided by libraries
I thought I understood Angular modules, but am having trouble figuring out the best approach for structuring modules involving services and components to be provided by a library.

The library implements a NotificationsComponent, which depends on a NotificationsService, which needs to be a singleton since it persists notification information. The consumer wants to use the NotificationsComponent in various pages, some of which are inside an AdminPagesModules, and others are inside an BookPagesModule.

Let's say in the library I define a NotificationsModule, which "declares" and
"exports" NotificationsComponent, and "provides" NotificationsService. Now if I import this module into both AdminPagesModule and BookPagesModules so pages in those modules can use NotificationComponent, I get separate instances of the NotificationsService, which won't work. On the other hand, if I import NotificationsModule in my AppModule, I succeed in making sure NotificationsService is a singleton used throughout the app, but I cannot see NotificationsComponent inside the components inside the individual feature modules such as AdminPagesModule.

I have seen a pattern where one module imports another module, then re-exports it. In this case, we would import NotificationsModule in AppModule, and then re-export it, then import NotificationsModule again in AdminPagesModule. In this case, will NotificationsService be a singleton across the app, as I want, yet NotificationsComponent still be available to components inside AdminPagesModule?

Or is there an approach to this problem involving the SharedModule pattern?

答:
Best to put singleton Services in a separate ts file and import/provide once and only once either in AppModule or SharedModule, not the component module (e.g. library).  Components declared in modules that are imported into AppModule will be available in templates throughout the app, and do not need to be re-declared or exported.

Also see https://stackoverflow.com/a/39665993/3103979

Example of services provided in a SharedModule:

```<code>export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        ...
        ApiService,
        Auth,
        ...
      ]
    };
  }
}
</code>```

Body:
Best to put singleton Services in a separate ts file and import/provide once and only once either in AppModule or SharedModule, not the component module (e.g. library).  Components declared in modules that are imported into AppModule will be available in templates throughout the app, and do not need to be re-declared or exported.

Also see https://stackoverflow.com/a/39665993/3103979

Example of services provided in a SharedModule:

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        ...
        ApiService,
        Auth,
        ...
      ]
    };
  }
}


问:
How to plot data over time
I have some calcium imaging data (measuring the intensity of a fluorescence molecule that responds to cellular calcium levels) in Excel that I can use for practicing Python. I imported the data into Python as csv, then tried to plot calcium concentration versus time. The trouble I have is, Python expect time to be expressed as Year-Month-Day-Hour-Minute-Second. But I only have Hour-Minute-Second. So want to ask, is Python always expecting time as Year-Month-Day-Hour-Minute-Second and therefore I just need to make up a day, or, can I use some command to tell Python to only use Day-Hour-Minute?</p>

答:
Python doesn't expect anything, except that you give it a date. Or something date like. (To be perfectly fair, Python doesn't even expect that. You just need to give Python something date like if you want to to behave the way you expect.).

Probably the easiest way is to read the csv into a Dataframe, and then use plot. Once you've got that down, you can start looking at using Matplotlib, or Seaborn, etc.

So, assuming that when you say "I only have hour-minute-second" what you mean is that the date was the same for each point, you could do something like this.

```<code>import datetime

import pandas as pd

date = "20170707 "
times = ["09-00-00", "10-00-00", "11-00-00"]
timestamps = [datetime.datetime.strptime(date + time, "%Y%m%d %H-%M-%S") for time in times]
df = pd.DataFrame(data={"Ca": [2, 1, 3]}, index=timestamps)
df.plot()
</code>```

Title: How to plot data over time

Body:
Python doesn't expect anything, except that you give it a date. Or something date like. (To be perfectly fair, Python doesn't even expect that. You just need to give Python something date like if you want to to behave the way you expect.).

Probably the easiest way is to read the csv into a Dataframe, and then use plot. Once you've got that down, you can start looking at using Matplotlib, or Seaborn, etc.

So, assuming that when you say "I only have hour-minute-second" what you mean is that the date was the same for each point, you could do something like this.

import datetime

import pandas as pd

date = "20170707 "
times = ["09-00-00", "10-00-00", "11-00-00"]
timestamps = [datetime.datetime.strptime(date + time, "%Y%m%d %H-%M-%S") for time in times]
df = pd.DataFrame(data={"Ca": [2, 1, 3]}, index=timestamps)
df.plot()


问:
Convert observable to list
I am using RxJava.

I have an Observable<T>. How do I convert it to List<T>?

Seems to be a simple operation, but I couldn't find it anywhere on the net.

答:
You can't convert observable to list in any idiomatic way, because a list isn't really a type that fits in with Rx.

If you want to populate a list with the events from a observable stream you need to basically create a list and add the items within a Subscribe method like so (C#):

```<code>IObservable<EventType> myObservable = ...;
var list = new List<EventType>();
myObservable.Subscribe(evt => list.Add(evt));
</code>```

The ToList-style operators only provide a list once the stream completes (as an IObservable<List<T>>), so that isnt useful in scenarios where you have a long-lived stream or you want to see values before the stream completes.

Title: Convert observable to list

Body:
You can't convert observable to list in any idiomatic way, because a list isn't really a type that fits in with Rx.

If you want to populate a list with the events from a observable stream you need to basically create a list and add the items within a Subscribe method like so (C#):

IObservable<EventType> myObservable = ...;
var list = new List<EventType>();
myObservable.Subscribe(evt => list.Add(evt));

The ToList-style operators only provide a list once the stream completes (as an IObservable<List<T>>), so that isnt useful in scenarios where you have a long-lived stream or you want to see values before the stream completes.


问:
MVC data annotaion for validating data type
How do you customize data annotation validation for this scenario.

I am receiving this error:

The value 'Select Province' is not
  valid for Province.

I want it like this

Please select a country

My ViewModel looks like this:

```<code>    [DisplayName("Province")]
    [UIHint("ProvinceDropDown")]
    public long? ProvinceId { get; set; }
</code>```

My View is a select list :

```<code><select name="ProvinceId" id="ProvinceId" class="input-validation-error">
    <option value="">Select Province</option>
    <option value="613">Allen </option>
    <option value="614">Anderson</option>
   // data truncated ....
</select>
</code>```

答:
To customize the validators you can inherit from ValidationAttribute:

```<code>public class SomeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
    public override bool IsValid(object value)
    {
    }
}
</code>```

I think you won't need to do this but instead should try making your nullable long a string, and having the validators on this property.

```<code>public string ProvinceId { get; set; }
</code>```

Then converting your View Model to some domain model which has the nullable long once the validation has passed.

Body:
How do you customize data annotation validation for this scenario.

I am receiving this error:

The value 'Select Province' is not
  valid for Province.

I want it like this

Please select a country

My ViewModel looks like this:

    [DisplayName("Province")]
    [UIHint("ProvinceDropDown")]
    public long? ProvinceId { get; set; }

My View is a select list :

<select name="ProvinceId" id="ProvinceId" class="input-validation-error">
    <option value="">Select Province</option>
    <option value="613">Allen </option>
    <option value="614">Anderson</option>
   // data truncated ....
</select>

Body:
To customize the validators you can inherit from ValidationAttribute:

public class SomeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
    public override bool IsValid(object value)
    {
    }
}

I think you won't need to do this but instead should try making your nullable long a string, and having the validators on this property.

public string ProvinceId { get; set; }

Then converting your View Model to some domain model which has the nullable long once the validation has passed.


问:
Angular4 - How to detect if a response is JSON or plain text with observable
I'm wondering if there is a way to detect the format of a response in an observable, when using a generic api service to call a variety of endpoints. Some send back JSON, others plain text.</p>

```<code>this.http.get(endpoint).map(response => {
    // if JSON
    return response.json();
    // else if plain text
    return response.text();
})...
</code>```

答:
I was never able to find a built in way with Angular to verify JSON, so I just check the content type in the response header.

Here's the function I use:

```<code>/**
 * True of the response content type is JSON.
 */
private static isJson(value: Response): boolean {
    return /\bapplication\/json\b/.test(value.headers.get('Content-Type'));
}
</code>```

Content-Type can have extra stuff in the string so I use a regex to be safe.

I would recommend failing if it's not JSON.

```<code> this.http.get().map((value:Response)=>{
      if(this.isJson(value)) {
         return value;
      }
      throw value;
 });
</code>```

You can then catch the known JSON responses later in the subscriber. Now you know all responses in the subscriber are getting JSON.

Body:
I'm wondering if there is a way to detect the format of a response in an observable, when using a generic api service to call a variety of endpoints. Some send back JSON, others plain text.

this.http.get(endpoint).map(response => {
    // if JSON
    return response.json();
    // else if plain text
    return response.text();
})...

Body:
I was never able to find a built in way with Angular to verify JSON, so I just check the content type in the response header.

Here's the function I use:

/**
 * True of the response content type is JSON.
 */
private static isJson(value: Response): boolean {
    return /\bapplication\/json\b/.test(value.headers.get('Content-Type'));
}

Content-Type can have extra stuff in the string so I use a regex to be safe.

I would recommend failing if it's not JSON.

 this.http.get().map((value:Response)=>{
      if(this.isJson(value)) {
         return value;
      }
      throw value;
 });

You can then catch the known JSON responses later in the subscriber. Now you know all responses in the subscriber are getting JSON.


问:
SQL Server - Values multiplied by join
having a bit of trouble with this one...

The summed, grouped column TotalStoreVisitTime is being multiplied due to the left join further down. I have attempted sub-queries but cannot successfully implement. Someone else I have spoken with has attempted this using cursors etc. but it seems over complicated.

```<code>SELECT t1.StaffName                 AS "Staff Name"
       ,MIN(t1.ManagerName)         AS "Manager"
       ,t1.Name                     AS "Store"
       ,t1.StartDate                AS "Date"
       ,SUM(t1.TotalStoreVisitTime) AS "Total Store Time" -- this value gets multiplied by the LEFT JOIN further down.
       ,SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM   t1
       LEFT JOIN t2
              ON t1.StaffName =
                 t2.StaffName
                 AND t1.Name = t2.Store
                 AND t1.StartDate =
                     t2.StartDate
WHERE  t1.StartDate >= DATEADD(DAY, -7, GETDATE())
GROUP  BY t1.StaffName
          ,t1.Name
          ,t1.StartDate
ORDER  BY t1.StartDate DESC;
</code>```

The output is as follows:

```<code>| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |        25.899996 |          4.033332 |
</code>```

The desired output is this (i.e. with Total Store Time just summing the rows from t1 and not being multiplied by the number of rows in t2):

```<code>| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |         4.316666 |          4.033332 |
</code>```

答:
Sub-query is good to go:</p>

```<code>SELECT t1.StaffName     AS "Staff Name"
   ,MIN(t1.ManagerName) AS "Manager"
   ,t1.Name             AS "Store"
   ,t1.StartDate        AS "Date"
   ,(SELECT SUM(t3.TotalStoreVisitTime)
     FROM TableA t3
     WHERE t1.StaffName = t3.StaffName
       AND t1.Name = t3.Name
       AND t1.StartDate = t3.StartDate) AS "Total Store Time" -- compare with primary key
   ,SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM TableA  t1
LEFT JOIN TableB t2
ON t1.StaffName =t2.StaffName
AND t1.Name = t2.Store
AND t1.StartDate = t2.StartDate
WHERE t1.StartDate >= DATEADD(DAY, -7, GETDATE())
GROUP BY t1.StaffName, t1.Name, t1.StartDate
ORDER BY t1.StartDate DESC;
</code>```

Title: SQL Server - Values multiplied by join

Body:
having a bit of trouble with this one...

The summed, grouped column TotalStoreVisitTime is being multiplied due to the left join further down. I have attempted sub-queries but cannot successfully implement. Someone else I have spoken with has attempted this using cursors etc. but it seems over complicated.

SELECT t1.StaffName                 AS "Staff Name"
       ,MIN(t1.ManagerName)         AS "Manager"
       ,t1.Name                     AS "Store"
       ,t1.StartDate                AS "Date"
       ,SUM(t1.TotalStoreVisitTime) AS "Total Store Time" -- this value gets multiplied by the LEFT JOIN further down.
       ,SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM   t1
       LEFT JOIN t2
              ON t1.StaffName =
                 t2.StaffName
                 AND t1.Name = t2.Store
                 AND t1.StartDate =
                     t2.StartDate
WHERE  t1.StartDate >= DATEADD(DAY, -7, GETDATE())
GROUP  BY t1.StaffName
          ,t1.Name
          ,t1.StartDate
ORDER  BY t1.StartDate DESC;

The output is as follows:

| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |        25.899996 |          4.033332 |

The desired output is this (i.e. with Total Store Time just summing the rows from t1 and not being multiplied by the number of rows in t2):

| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |         4.316666 |          4.033332 |

Body:
Sub-query is good to go:

SELECT t1.StaffName     AS "Staff Name"
   ,MIN(t1.ManagerName) AS "Manager"
   ,t1.Name             AS "Store"
   ,t1.StartDate        AS "Date"
   ,(SELECT SUM(t3.TotalStoreVisitTime)
     FROM TableA t3
     WHERE t1.StaffName = t3.StaffName
       AND t1.Name = t3.Name
       AND t1.StartDate = t3.StartDate) AS "Total Store Time" -- compare with primary key
   ,SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM TableA  t1
LEFT JOIN TableB t2
ON t1.StaffName =t2.StaffName
AND t1.Name = t2.Store
AND t1.StartDate = t2.StartDate
WHERE t1.StartDate >= DATEADD(DAY, -7, GETDATE())
GROUP BY t1.StaffName, t1.Name, t1.StartDate
ORDER BY t1.StartDate DESC;


问:
Converting fat arrow to standard notation
How do I convert this piece of code to not use the fat arrow?

```<code>propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}
</code>```

I changed the first line to

```<code>propertyOf = function (object) {
</code>```

and the code still worked. When I changed also the second line to

```<code>return propName = function () {
</code>```

I got an error saying "undefined" when I tried to call the function. I also got an error beside the second line saying 'Did you mean to run a conditional instead of an assignment?'

The full code is this:

```<code>let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));
</code>```

答:
I'd like to point out that the snippet you've tried to use

```<code>return propName = function () {
</code>```

is  valid JavaScript. You get undefined because propName variable is undefined inside your inner function. Hence the if condition in the for..in loop pretty much translates to

```<code>if (key === undefined) // This never passes, hence undefined is returned
</code>```

Your code will work if you change it to

```<code>return propName = function(propName) {
</code>```

Full working example:

let bob = {
    name: 'Bob',
    age: 87
  },
  searchBob;

propertyOf = function(object) {
  return propName = function(/* This is the only change */ propName) {
    for (let key in object) {
      if (key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));```

That being said, I don't see any reason why you should be doing it. This answer is the most simple one.

Body:
How do I convert this piece of code to not use the fat arrow?

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

I changed the first line to

propertyOf = function (object) {

and the code still worked. When I changed also the second line to

return propName = function () {

I got an error saying "undefined" when I tried to call the function. I also got an error beside the second line saying 'Did you mean to run a conditional instead of an assignment?'

The full code is this:

let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));

Body:
I'd like to point out that the snippet you've tried to use

return propName = function () {

is  valid JavaScript. You get undefined because propName variable is undefined inside your inner function. Hence the if condition in the for..in loop pretty much translates to

if (key === undefined) // This never passes, hence undefined is returned

Your code will work if you change it to

return propName = function(propName) {

Full working example:

let bob = {
    name: 'Bob',
    age: 87
  },
  searchBob;

propertyOf = function(object) {
  return propName = function(/* This is the only change */ propName) {
    for (let key in object) {
      if (key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));

That being said, I don't see any reason why you should be doing it. This answer is the most simple one.


问:
conflicting ruby gems
I need to use two gems in my project that both claim the PDF namespace:  pdf-reader and htmldoc.

Is there any way to get them to play nice together?  The only way I can think of is to rewrite my own version of htmldoc to give it a different namespace.

答:
Basically, there's nothing you can do. It is good practice in Ruby, to use distinctive names in the top-level namespace precisely for this reason, and you just happened to stumble upon two libraries that violate that practice.

One thing you could do is to use Kernel#load instead of Kernel#require. Kernel#load takes an optional boolean argument, which will tell it to evaluate the file within an anonymous module. Note, however, that this is in no way safe: it is perfectly possible to explicitly put stuff in the top-level namespace (using something like module ::PDF) and thus break out of the anonymous module.

Note also that the API is really crappy: load simply returns true or false, just like require does. (Actually, since load always loads, it always returns true.) There is no way to actually get at the anonymous module. You basically have to grab it out of the ObjectSpace by hand. Oh, and of course, since nothing actually references the anonymous module, it will be garbage-collected, so not only do you have to rummage around in the bowels of ObjectSpace to find the module, you also have to race the garbage collector.

Sometimes, I wish Ruby had a proper module system like Newspeak, Standard ML or Racket.

Title: conflicting ruby gems


问:
Why is TFS not updating my project?
We have an ASP.Net MVC Core project solution in TFS.

And there is an error icon at the top of the solution explorer that says "Package restore failed".
And if I open up the project.json I see the red sqigglies:
"The dependency ... could not be resolved" for several dependencies.

The developer who created this error has since fixed it.  And all the other developers on the team get latest and the error goes away.
But it won't go away for me.
I get latest and the error icon at the top of the solution explorer and the errors within the project.json are still there.

I blew away the folder, got latest from Team Explorer, and the errors are still there while gone for the other errors.

Anyone know why this is happening?
I'm stumped.  I don't understand what is happening.

答:
First, you could try to do a force update for the specific error fixed changeset.

To force a update, use the "Get Specific Version" command with the
  "Overwrite all... " option checked.

You could also clear TFS and VS cache, delete old workspace(back up changes first), create a new one, then do a fresh getting latest files from TFS source control. Which should do the trick.

If the issue still exist, you will have to check your local environment if you are missing some thing. Do a simply compare of the environment with other developers on the team.

Title: Why is TFS not updating my project?