问:
Rails: Stripe appears to work but no charge is created
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

```<code>No route matches [POST] "/charges/new"
</code>```

Even though my routes are like this:

```<code>resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'
</code>```

My charges_controller reads like this:

```<code>class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end
</code>```

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?

答:
Try to restart your server to reload the routes. Run rake routes | grep charges to verify that you see POST /charges/new.

Wait, I know why. You are supposed to GET /charges/new and POST to /charges. Show us your view code, specifically the form submission URL address.

See http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

Body:
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

No route matches [POST] "/charges/new"

Even though my routes are like this:

resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'

My charges_controller reads like this:

class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?


来源: stackexchange

问:
Do two installations of Oracle SQL Developer on the same machine conflict?
I already have oracle SQL developer installed in my machine. I want to install another oracle SQL developer in my computer that I want to use for my personal web application. Of course I can work with one SQL developer, but in order to ease my maintenance I am planing to have two.

So, do they conflict? Can I run my applications smoothly?

答:
Yes, you can have 2 instance of sql developer on same machine without conflicting each other. They both can share same TNS file if you want to or keep them separately. </p>

<p>I have used 2 instances of it and never faced any issue. In my case they were or different version, but that doesn't matter. </p>

ContentLicense: CC BY-SA 3.0

Body:
Yes, you can have 2 instance of sql developer on same machine without conflicting each other. They both can share same TNS file if you want to or keep them separately.

I have used 2 instances of it and never faced any issue. In my case they were or different version, but that doesn't matter.


问:
How do you call a function once a day at a certain time in c++?
Well i need to figure out how to call a function at a certain time if my application is running.

it will probably be in a while loop and check the time but i don't want it to check the time every minute but i don't want it to miss the exact time, say 18:00.

is there any way do to this?

答:
You could install a scheduled task in your system that will notify your application.
If your system is Linux you can use cron for example.</p>

ContentLicense: CC BY-SA 2.5


问:
Using insert() on empty std::vector when sorting
I know ideally to add to a std::vector without worry I should use push_back(). However my problem set is that I need a clean code to check if the value I am entering is already in the std::vector and if not, I have to put in sequential, ascending order. To do that I am doing:

```<code>vector<Book>::iterator it;
it = std::find(books.begin(), books.end(), b);
if (it != books.end()) {
    *it = b; // if b exists in books, overwrite the iterator
}
else {
    vector<Book>::iterator _it;
    _it = lower_bound(books.begin(), books.end(), b);
    books.insert(_it, b); // here on an empty vector, _it has no values
}
</code>```

The else will only run if the value b doesnt already exist in the std::vector. If this is the first value being checked against it, the else runs (since its empty) and the std::iterator is at books[0](?).

What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to. Now the program functions and yields anticipated results, but is it erroneously?

答:
What you are doing works fine. However it is not the most efficient way. Using std::find doesn't take advantage of the fact that the data in the vector is sorted, it visits every element until if finds the correct one.

Instead of std::find you can use std::lower_bound from the beginning because that will find your element if it exists and if not, it will find the correct place to insert a new one.

Also it will use a binary search so it will be leaps and bounds faster than std::find. Also you don't end up finding the insertion/replacemt point twice.

Something like this should do:

```<code>void insert_or_replace(std::vector<Book>& books, Book const& b)
{
    std::vector<Book>::iterator it;

    it = std::lower_bound(books.begin(), books.end(), b);

    if(it != books.end() && *it == b)
        *it = b;
    else
        books.insert(it, b);
}
</code>```

Body:
I know ideally to add to a std::vector without worry I should use push_back(). However my problem set is that I need a clean code to check if the value I am entering is already in the std::vector and if not, I have to put in sequential, ascending order. To do that I am doing:

vector<Book>::iterator it;
it = std::find(books.begin(), books.end(), b);
if (it != books.end()) {
    *it = b; // if b exists in books, overwrite the iterator
}
else {
    vector<Book>::iterator _it;
    _it = lower_bound(books.begin(), books.end(), b);
    books.insert(_it, b); // here on an empty vector, _it has no values
}

The else will only run if the value b doesnt already exist in the std::vector. If this is the first value being checked against it, the else runs (since its empty) and the std::iterator is at books[0](?).

What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to. Now the program functions and yields anticipated results, but is it erroneously?

Body:
What you are doing works fine. However it is not the most efficient way. Using std::find doesn't take advantage of the fact that the data in the vector is sorted, it visits every element until if finds the correct one.

Instead of std::find you can use std::lower_bound from the beginning because that will find your element if it exists and if not, it will find the correct place to insert a new one.

Also it will use a binary search so it will be leaps and bounds faster than std::find. Also you don't end up finding the insertion/replacemt point twice.

Something like this should do:

void insert_or_replace(std::vector<Book>& books, Book const& b)
{
    std::vector<Book>::iterator it;

    it = std::lower_bound(books.begin(), books.end(), b);

    if(it != books.end() && *it == b)
        *it = b;
    else
        books.insert(it, b);
}


问:
Swift 4 Codable decoding json
I'm trying to implement the new Codable protocol, so I added Codable to my struct, but am stuck on decoding the JSON.

Here's what I had before:

Struct -

```<code>struct Question {
    var title: String
    var answer: Int
    var question: Int
}
</code>```

Client -

...

```<code>guard let data = data else {
    return
}

do {
    self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
    let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]

    questionItems.forEach {
        let item = Question(title: $0["title"] as! String,
                            answer: $0["answer"] as! Int,
                            question: $0["question"] as! Int)
        questionData.append(item)
    }

} catch {
    print("error")
}
</code>```

Here's what I have now, except I can't figure out the decoder part:

Struct -

```<code>struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}
</code>```

Client -

...

```<code>let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
    // Can't get past this part
} else {
    print("Not working")
}
</code>```

It prints "Not working" because I can't get past the decoder.decode part. Any ideas? Will post any extra code as needed, thanks!

EDIT:

Sample of API JSON:

```<code>{
  "themes": [
    {
      "answer": 1,
      "question": 44438222,
      "title": "How many letters are in the alphabet?"
    },
    {
      "answer": 0,
      "question": 44438489,
      "title": "This is a random question"
    }
  ]
 }
</code>```

If I print self.jsonResponse I get this:

```<code>Optional(["themes": <__NSArrayI 0x6180002478f0>(
{
    "answer" = 7;
    "question" = 7674790;
    title = "This is the title of the question";
},
{
    "answer_" = 2;
    "question" = 23915741;
    title = "This is the title of the question";
}
</code>```

My new code:

```<code>struct Theme: Codable {
    var themes : [Question]
}

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}
</code>```

...

```<code>if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}
</code>```

答:
If your JSON has a structure

```<code>{"themes" : [{"title": "Foo", "answer": 1, "question": 2},
             {"title": "Bar", "answer": 3, "question": 4}]}
</code>```

you need an equivalent for the themes object. Add this struct

```<code>struct Theme : Codable {
    var themes : [Question]
}
</code>```

Now you can decode the JSON:

```<code>if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}
</code>```

The containing Question objects are decoded implicitly.

Title: Swift 4 Codable decoding json

Body:
I'm trying to implement the new Codable protocol, so I added Codable to my struct, but am stuck on decoding the JSON.

Here's what I had before:

Struct -

struct Question {
    var title: String
    var answer: Int
    var question: Int
}

Client -

...

guard let data = data else {
    return
}

do {
    self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
    let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]

    questionItems.forEach {
        let item = Question(title: $0["title"] as! String,
                            answer: $0["answer"] as! Int,
                            question: $0["question"] as! Int)
        questionData.append(item)
    }

} catch {
    print("error")
}

Here's what I have now, except I can't figure out the decoder part:

Struct -

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}

Client -

...

let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
    // Can't get past this part
} else {
    print("Not working")
}

It prints "Not working" because I can't get past the decoder.decode part. Any ideas? Will post any extra code as needed, thanks!

EDIT:

Sample of API JSON:

{
  "themes": [
    {
      "answer": 1,
      "question": 44438222,
      "title": "How many letters are in the alphabet?"
    },
    {
      "answer": 0,
      "question": 44438489,
      "title": "This is a random question"
    }
  ]
 }

If I print self.jsonResponse I get this:

Optional(["themes": <__NSArrayI 0x6180002478f0>(
{
    "answer" = 7;
    "question" = 7674790;
    title = "This is the title of the question";
},
{
    "answer_" = 2;
    "question" = 23915741;
    title = "This is the title of the question";
}

My new code:

struct Theme: Codable {
    var themes : [Question]
}

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}

...

if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}

Body:
If your JSON has a structure

{"themes" : [{"title": "Foo", "answer": 1, "question": 2},
             {"title": "Bar", "answer": 3, "question": 4}]}

you need an equivalent for the themes object. Add this struct

struct Theme : Codable {
    var themes : [Question]
}

Now you can decode the JSON:

if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}

The containing Question objects are decoded implicitly.


问:
Remove explicit zero values from sparse matrix in Julia
Is it possible to remove explicit zero value from sparse matrix in Julia?

Namely, I want to convert a=sparse([1],[1],[0]) into b=spzeros(1,1)

答:
Yes: see dropzeros:

```<code>julia> a=sparse([1],[1],[0])
1×1 SparseMatrixCSC{Int64,Int64} with 1 stored entry:
  [1, 1]  =  0

julia> dropzeros(a)
1×1 SparseMatrixCSC{Int64,Int64} with 0 stored entries
</code>```

Or you can do it in place (modifying a) with dropzeros!.

Body:
Yes: see dropzeros:

julia> a=sparse([1],[1],[0])
1×1 SparseMatrixCSC{Int64,Int64} with 1 stored entry:
  [1, 1]  =  0

julia> dropzeros(a)
1×1 SparseMatrixCSC{Int64,Int64} with 0 stored entries

Or you can do it in place (modifying a) with dropzeros!.


问:
Search predecessor of a key in a sorted array using binary search
For a sorted int array, the BS algorithm returns the predecessor of the key.

For example, given array {3, 5, 7, 9, 11}, BS(15) = 11, BS(9) = 7. You can define the behavior of the algorithm when predecessor does not exist in the array (e.g. BS(3)). I think the solution is a variation of the binary search algorithm, but I cannot get the correct one. This is what I have so far, it is incorrect:

```<code>int BinarySearch5(vector<int> &data, int left, int right, int key) {
  // if pred does not exist in the array, then return the smallest element in the array
  if (left >= right) {
    return left;
  }
  int mid = left + (right - left) / 2;
  if (data[mid] >= key) {  // search left
    return BinarySearch5(data, left, mid - 1, key);
  } else {  // data[mid] < key, search right but including mid
    return BinarySearch5(data, mid, right, key);
  }
}
</code>```

答:
Your code would give a segmentation fault if the key value was greater than the largest value in you vector. If a key 20 was given for your vector {3, 5, 7, 9, 11}, BS(0,4) would call BS(2,4), then BS(3,4), then again BS(3,4) and on and on. So once data[mid] > key we know that mid is a possible answer. But if there is an element less than data[mid] and located to the right of mid, that element's position should be the answer.

One possible way to avoid that problem is below: store mid as an answer. If BS(mid+1,r) gives a value ind such that data[ind] > key, we return ind instead of mid. Else return mid.

```<code>int BinarySearch5(vector<int> &data, int left, int right, int key) {
  if (left >= right) {
    return left;
  }

  int mid = left + (right - left) / 2;
  if (data[mid] >= key) {
    return BinarySearch5(data, left, mid - 1, key);
  } else {
    int t = BinarySearch5(data, mid+1, right, key); // See the change here
    return data[t]<key? t:mid;
  }
}
</code>```

Body:
For a sorted int array, the BS algorithm returns the predecessor of the key.

For example, given array {3, 5, 7, 9, 11}, BS(15) = 11, BS(9) = 7. You can define the behavior of the algorithm when predecessor does not exist in the array (e.g. BS(3)). I think the solution is a variation of the binary search algorithm, but I cannot get the correct one. This is what I have so far, it is incorrect:

int BinarySearch5(vector<int> &data, int left, int right, int key) {
  // if pred does not exist in the array, then return the smallest element in the array
  if (left >= right) {
    return left;
  }
  int mid = left + (right - left) / 2;
  if (data[mid] >= key) {  // search left
    return BinarySearch5(data, left, mid - 1, key);
  } else {  // data[mid] < key, search right but including mid
    return BinarySearch5(data, mid, right, key);
  }
}

Body:
Your code would give a segmentation fault if the key value was greater than the largest value in you vector. If a key 20 was given for your vector {3, 5, 7, 9, 11}, BS(0,4) would call BS(2,4), then BS(3,4), then again BS(3,4) and on and on. So once data[mid] > key we know that mid is a possible answer. But if there is an element less than data[mid] and located to the right of mid, that element's position should be the answer.

One possible way to avoid that problem is below: store mid as an answer. If BS(mid+1,r) gives a value ind such that data[ind] > key, we return ind instead of mid. Else return mid.

int BinarySearch5(vector<int> &data, int left, int right, int key) {
  if (left >= right) {
    return left;
  }

  int mid = left + (right - left) / 2;
  if (data[mid] >= key) {
    return BinarySearch5(data, left, mid - 1, key);
  } else {
    int t = BinarySearch5(data, mid+1, right, key); // See the change here
    return data[t]<key? t:mid;
  }
}


问:
Laravel update multiple database rows with Eloquent
I want to update the products leased count when a product is rented to a customer.
The owner of the website can rent multiple things. I do this by cloning with Ajax.

Now, when someone has rented like 2 chairs and 1 table, i want to update the products_leased row for both products. How would i do that?

The error i get:

```<code>`SQLSTATE[01000]: Warning: 1265 Data truncated for column 'product_leased' at row 1 (SQL: update `products` set `product_leased` = 3 5, `updated_at` = 2017-06-07 19:57:03 where `id` = 1)`
</code>```

My controller:

```<code>public function create_order($id) {

    $customer = Customer::find($id);
    $pr = Product::get();

    $rent_from = Request::input('rent_from');
    $rent_till = Request::input('rent_till');
    $productArray = Request::get('product_name');
    $productCountArray = Request::get('product_count');

    $rentProduct = new cRent;
    $rentProduct->customer_id = $customer->id;
    $rentProduct->rent_from = $rent_from;
    $rentProduct->rent_till = $rent_till;
    $rentProduct->rented_products = implode(', ', $productArray);
    $rentProduct->rented_products_count = implode(', ', $productCountArray);

    $rentProduct->save();

    $pru = Product::find($id);

    $pru->product_leased = implode(' ', $productCountArray);
    $pru->update();

    return back();

}
</code>```

The code above works only when one product has been rented. Not when i rent 2 products.

Thanks in advance.

答:
Why are you passing in the same $id to

```<code> $customer = Customer::find($id);
</code>```

and

```<code>$pru = Product::find($id);
</code>```

?

Instead of imploding the product names and counts and storing them together, why not create separate rent records for each product and relate them as a one-to-many? Assuming product name and product count line in the arrays, something to the effect of:

```<code>foreach(array_combine($productArray, $productCountArray) as $product_name => $count){
    $product = Product::where('name', $product_name)->first();
    $rentProduct = new cRent;
    $rentProduct->customer_id = $customer->id;
    $rentProduct->rent_from = $rent_from;
    $rentProduct->rent_till = $rent_till;
    $rentProduct->product_id = $product->id
    $rentProduct->count = $count;
    $rentProduct->save();
}
</code>```

Better yet, don't pass in the product names, instead pass the product ids in from the form.

Body:
I want to update the products leased count when a product is rented to a customer.
The owner of the website can rent multiple things. I do this by cloning with Ajax.

Now, when someone has rented like 2 chairs and 1 table, i want to update the products_leased row for both products. How would i do that?

The error i get:

`SQLSTATE[01000]: Warning: 1265 Data truncated for column 'product_leased' at row 1 (SQL: update `products` set `product_leased` = 3 5, `updated_at` = 2017-06-07 19:57:03 where `id` = 1)`

My controller:

public function create_order($id) {

    $customer = Customer::find($id);
    $pr = Product::get();

    $rent_from = Request::input('rent_from');
    $rent_till = Request::input('rent_till');
    $productArray = Request::get('product_name');
    $productCountArray = Request::get('product_count');

    $rentProduct = new cRent;
    $rentProduct->customer_id = $customer->id;
    $rentProduct->rent_from = $rent_from;
    $rentProduct->rent_till = $rent_till;
    $rentProduct->rented_products = implode(', ', $productArray);
    $rentProduct->rented_products_count = implode(', ', $productCountArray);

    $rentProduct->save();

    $pru = Product::find($id);

    $pru->product_leased = implode(' ', $productCountArray);
    $pru->update();

    return back();

}

The code above works only when one product has been rented. Not when i rent 2 products.

Thanks in advance.

Body:
Why are you passing in the same $id to

 $customer = Customer::find($id);

and

$pru = Product::find($id);

?

Instead of imploding the product names and counts and storing them together, why not create separate rent records for each product and relate them as a one-to-many? Assuming product name and product count line in the arrays, something to the effect of:

foreach(array_combine($productArray, $productCountArray) as $product_name => $count){
    $product = Product::where('name', $product_name)->first();
    $rentProduct = new cRent;
    $rentProduct->customer_id = $customer->id;
    $rentProduct->rent_from = $rent_from;
    $rentProduct->rent_till = $rent_till;
    $rentProduct->product_id = $product->id
    $rentProduct->count = $count;
    $rentProduct->save();
}

Better yet, don't pass in the product names, instead pass the product ids in from the form.


问:
Easy way to get date from UTC to PST in python 2.7.x
I have this:

```<code>>>> import datetime
>>> today = str(datetime.date.today())
>>> print today
2017-06-07
</code>```

The machine is in UTC time. I would like to know if there is easy/simple way to get same kind of output for PST (without changing machine time zone).

答:
```<code>import datetime
import pytz

def tz2ntz(date_obj, tz, ntz):

    # date_obj: datetime object
    # tz: old timezone
    # ntz: new timezone

    if isinstance(date_obj, datetime.date) and tz and ntz:
       date_obj = date_obj.replace(tzinfo=pytz.timezone(tz))
       return date_obj.astimezone(pytz.timezone(ntz))
    return False

print tz2ntz(datetime.datetime.utcnow(), 'UTC', 'US/Pacific')
</code>```

Body:
I have this:

>>> import datetime
>>> today = str(datetime.date.today())
>>> print today
2017-06-07

The machine is in UTC time. I would like to know if there is easy/simple way to get same kind of output for PST (without changing machine time zone).


问:
Which Array To Use?
I am designing a new cinema booking system, where there will be 4 screens holding various number of seats on each.

I need to know what ARRAY or what data structure is best for ADDING and REMOVING people onto or off seats ANYWHERE they want on the screen.

I believe that I will need a 2 dimentional array structure, but any help will be much appreciated!... thank you

答:
I'd vote personally for a plain and simple Seat[][] array of the class structure suggested above. There's simply no reason to use another array as the array size probably isn't ever going to change, if it is that can be done at initialisation. Then just show them or don't on the screen by either data in a certain position or null for unreserved seats.

Depending on your need (do you need to remember where the guest booked?) you could even use boolean[][] as the bare minimum.

No matter what, just create and name four different such Seat 2D arrays. Preferably stick them in a separate class and have setters and getters.

Title: Which Array To Use?


问:
I do not get native selenium error such as 'Element not Found' or 'Element is not clickable'.Instead i get timeout error in protractor
I'm working in Protractor cucumber framework.I do not get native selenium errors such as 'Element not Found' or 'No Such Element Found' or 'Element is not clickable' if the element is not found in page or not clickable.Instead i get "TimeoutError: Wait timed out after 10002ms"

Only if i get these errors I will come to know i have made some mistake in my element xpath or I have tried to click a disabled button etc.

Generic error like time out does not help me fix the failed test cases easily.

Below is my code.contactPage.js is the implementation.util.js is some helper methods in my framework

File contactPage.js

```<code>  var contact = element(by.xpath("//p[contains(text(),'Contact Me')]"));

   function clickUserGuide() {
   return util.isDisplayed(contact, 10000).then(() => {
    return util.clickElement(contact, 10000);
});
</code>```

File util.js

```<code>function isDisplayed(element, milliseconds) {
return browser.wait(EC.visibilityOf(element), milliseconds).then(() => {
    return element.isDisplayed();
  });
};
function clickElement(element, milliseconds) {
 return browser.wait(EC.visibilityOf(element), milliseconds).then(() => {
    element.click();
    return true;
 });
};
}
</code>```

答:
The reason why you are getting TimeoutError: Wait timed out after 10002ms is because of the method browser.wait(EC.visibilityOf(element), milliseconds) you are using.

The method doesn't have a fail "hard" like the No Such Element Found, it just keeps waiting for the element to match the expected condition, in your case you are waiting for:

the element is be displayed

AND the height and width to be greater than 0

If this doesn't happen in the given amount of seconds the condition fails with a message that the element couldn't match the condition within the given time.

What happens is you use browser.wait(EC.presenceOf(element), milliseconds), is the element really present in the DOM?

Body:
I'm working in Protractor cucumber framework.I do not get native selenium errors such as 'Element not Found' or 'No Such Element Found' or 'Element is not clickable' if the element is not found in page or not clickable.Instead i get "TimeoutError: Wait timed out after 10002ms"

Only if i get these errors I will come to know i have made some mistake in my element xpath or I have tried to click a disabled button etc.

Generic error like time out does not help me fix the failed test cases easily.

Below is my code.contactPage.js is the implementation.util.js is some helper methods in my framework

File contactPage.js

  var contact = element(by.xpath("//p[contains(text(),'Contact Me')]"));

   function clickUserGuide() {
   return util.isDisplayed(contact, 10000).then(() => {
    return util.clickElement(contact, 10000);
});

File util.js

function isDisplayed(element, milliseconds) {
return browser.wait(EC.visibilityOf(element), milliseconds).then(() => {
    return element.isDisplayed();
  });
};
function clickElement(element, milliseconds) {
 return browser.wait(EC.visibilityOf(element), milliseconds).then(() => {
    element.click();
    return true;
 });
};
}


问:
SQL: parse the first, middle and last name from a fullname field
How do I parse the first, middle, and last name out of a fullname field with SQL?

I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name.

The data does not include any prefixes or suffixes. The middle name is optional. The data is formatted 'First Middle Last'.

I'm interested in some practical solutions to get me 90% of the way there.  As it has been stated, this is a complex problem, so I'll handle special cases individually.

答:
The work by @JosephStyons and @Digs is great! I used parts of their work to create a new function for SQL Server 2016 and newer. This one also handles suffixes, as well as prefixes.</p>

```<code>CREATE FUNCTION [dbo].[NameParser]
(
    @name nvarchar(100)
)
RETURNS TABLE
AS
RETURN (

WITH prep AS (
    SELECT
        original = @name,
        cleanName = REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(@name)),'  ',' '),'  ',' '), '.', ''), ',', '')
)
SELECT
    prep.original,
    aux.prefix,
    firstName.firstName,
    middleName.middleName,
    lastName.lastName,
    aux.suffix
FROM
    prep
    CROSS APPLY (
        SELECT
            prefix =
                CASE
                    WHEN LEFT(prep.cleanName, 3) IN ('MR ', 'MS ', 'DR ', 'FR ')
                        THEN LEFT(prep.cleanName, 2)
                    WHEN LEFT(prep.cleanName, 4) IN ('MRS ', 'LRD ', 'SIR ')
                        THEN LEFT(prep.cleanName, 3)
                    WHEN LEFT(prep.cleanName, 5) IN ('LORD ', 'LADY ', 'MISS ', 'PROF ')
                        THEN LEFT(prep.cleanName, 4)
                    ELSE ''
                END,
            suffix =
                CASE
                    WHEN RIGHT(prep.cleanName, 3) IN (' JR', ' SR', ' II', ' IV')
                        THEN RIGHT(prep.cleanName, 2)
                    WHEN RIGHT(prep.cleanName, 4) IN (' III', ' ESQ')
                        THEN RIGHT(prep.cleanName, 3)
                    ELSE ''
                END
    ) aux
    CROSS APPLY (
        SELECT
            baseName = LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))),
            numParts = (SELECT COUNT(1) FROM STRING_SPLIT(LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))), ' '))
    ) core
    CROSS APPLY (
        SELECT
            firstName =
                CASE
                    WHEN core.numParts <= 1 THEN core.baseName
                    ELSE LEFT(core.baseName, CHARINDEX(' ', core.baseName, 1) - 1)
                END

    ) firstName
    CROSS APPLY (
        SELECT
            remainder =
                CASE
                    WHEN core.numParts <= 1 THEN ''
                    ELSE LTRIM(SUBSTRING(core.baseName, LEN(firstName.firstName) + 1, 999999))
                END
    ) work1
    CROSS APPLY (
        SELECT
            middleName =
                CASE
                    WHEN core.numParts <= 2 THEN ''
                    ELSE LEFT(work1.remainder, CHARINDEX(' ', work1.remainder, 1) - 1)
                END
    ) middleName
    CROSS APPLY (
        SELECT
            lastName =
                CASE
                    WHEN core.numParts <= 1 THEN ''
                    ELSE LTRIM(SUBSTRING(work1.remainder, LEN(middleName.middleName) + 1, 999999))
                END
    ) lastName
)

GO

SELECT * FROM dbo.NameParser('Madonna')
SELECT * FROM dbo.NameParser('Will Smith')
SELECT * FROM dbo.NameParser('Neil Degrasse Tyson')
SELECT * FROM dbo.NameParser('Dr. Neil Degrasse Tyson')
SELECT * FROM dbo.NameParser('Mr. Hyde')
SELECT * FROM dbo.NameParser('Mrs. Thurston Howell, III')
</code>```

OwnerDisplayName: TheOtherScott

LastEditorDisplayName: Andy Lester

Body:
The work by @JosephStyons and @Digs is great! I used parts of their work to create a new function for SQL Server 2016 and newer. This one also handles suffixes, as well as prefixes.

CREATE FUNCTION [dbo].[NameParser]
(
    @name nvarchar(100)
)
RETURNS TABLE
AS
RETURN (

WITH prep AS (
    SELECT
        original = @name,
        cleanName = REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(@name)),'  ',' '),'  ',' '), '.', ''), ',', '')
)
SELECT
    prep.original,
    aux.prefix,
    firstName.firstName,
    middleName.middleName,
    lastName.lastName,
    aux.suffix
FROM
    prep
    CROSS APPLY (
        SELECT
            prefix =
                CASE
                    WHEN LEFT(prep.cleanName, 3) IN ('MR ', 'MS ', 'DR ', 'FR ')
                        THEN LEFT(prep.cleanName, 2)
                    WHEN LEFT(prep.cleanName, 4) IN ('MRS ', 'LRD ', 'SIR ')
                        THEN LEFT(prep.cleanName, 3)
                    WHEN LEFT(prep.cleanName, 5) IN ('LORD ', 'LADY ', 'MISS ', 'PROF ')
                        THEN LEFT(prep.cleanName, 4)
                    ELSE ''
                END,
            suffix =
                CASE
                    WHEN RIGHT(prep.cleanName, 3) IN (' JR', ' SR', ' II', ' IV')
                        THEN RIGHT(prep.cleanName, 2)
                    WHEN RIGHT(prep.cleanName, 4) IN (' III', ' ESQ')
                        THEN RIGHT(prep.cleanName, 3)
                    ELSE ''
                END
    ) aux
    CROSS APPLY (
        SELECT
            baseName = LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))),
            numParts = (SELECT COUNT(1) FROM STRING_SPLIT(LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))), ' '))
    ) core
    CROSS APPLY (
        SELECT
            firstName =
                CASE
                    WHEN core.numParts <= 1 THEN core.baseName
                    ELSE LEFT(core.baseName, CHARINDEX(' ', core.baseName, 1) - 1)
                END

    ) firstName
    CROSS APPLY (
        SELECT
            remainder =
                CASE
                    WHEN core.numParts <= 1 THEN ''
                    ELSE LTRIM(SUBSTRING(core.baseName, LEN(firstName.firstName) + 1, 999999))
                END
    ) work1
    CROSS APPLY (
        SELECT
            middleName =
                CASE
                    WHEN core.numParts <= 2 THEN ''
                    ELSE LEFT(work1.remainder, CHARINDEX(' ', work1.remainder, 1) - 1)
                END
    ) middleName
    CROSS APPLY (
        SELECT
            lastName =
                CASE
                    WHEN core.numParts <= 1 THEN ''
                    ELSE LTRIM(SUBSTRING(work1.remainder, LEN(middleName.middleName) + 1, 999999))
                END
    ) lastName
)

GO

SELECT * FROM dbo.NameParser('Madonna')
SELECT * FROM dbo.NameParser('Will Smith')
SELECT * FROM dbo.NameParser('Neil Degrasse Tyson')
SELECT * FROM dbo.NameParser('Dr. Neil Degrasse Tyson')
SELECT * FROM dbo.NameParser('Mr. Hyde')
SELECT * FROM dbo.NameParser('Mrs. Thurston Howell, III')


问:
Not receiving Google OAuth refresh token
I want to get the access token from Google.  The Google API says that to get the access token, send the code and other parameters to token generating page, and the response will be a JSON Object like :

```<code>{
"access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74"
}
</code>```

However, I'm not receiving the refresh token.  The response in my case is:

```<code>{
 "access_token" : "ya29.sddsdsdsdsds_h9v_nF0IR7XcwDK8XFB2EbvtxmgvB-4oZ8oU",
"token_type" : "Bearer",
"expires_in" : 3600
}
</code>```

答:
now google had refused those parameters in my request (access_type, prompt)... :( and there is no "Revoke Access" button at all. I'm frustrating because of getting back my refresh_token lol

UPDATE:
I found the answer in here :D you can get back the refresh token by a request
https://developers.google.com/identity/protocols/OAuth2WebServer

curl -H "Content-type:application/x-www-form-urlencoded" \
          https://accounts.google.com/o/oauth2/revoke?token={token}

The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.

Body:
I want to get the access token from Google.  The Google API says that to get the access token, send the code and other parameters to token generating page, and the response will be a JSON Object like :

{
"access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74"
}

However, I'm not receiving the refresh token.  The response in my case is:

{
 "access_token" : "ya29.sddsdsdsdsds_h9v_nF0IR7XcwDK8XFB2EbvtxmgvB-4oZ8oU",
"token_type" : "Bearer",
"expires_in" : 3600
}


问:
How to provide an alternate i18n language link in Angular with aot compiling?
I am currently working on i18n of my Angular app. I use AOT compiling with xlf files to create pre-compiled apps as described here. In the build, I provide a language specific base href (using the --base-href parm). For example, this means, I end up with two language specific apps using the following url paths:

/app_path/en/...

/app_path/de/...

Now I want to provide a link to the respective alternate language within my app by replacing for example en by de in the active url. I used the Router injection, so I can access its url property, but this property does not give me the full url including the base-href.

How can I find out the base url from within an Angular app?

Alternatively, is there a way to I find out language the app was built for? Can I access the target-language property from the xliff files somehow?

答:
When you compile your app for the various languages you set the locale in the ng build process:

```<code>./node_modules/.bin/ngc --i18nFile=./locale/messages.es.xlf --locale=es --i18nFormat=xlf
</code>```

You can get access to this locale by injecting it to your component:

```<code>import { Inject, LOCALE_ID } from '@angular/core';
...
constructor(@Inject(LOCALE_ID) locale: string, ...
</code>```

Then you can use the locale string to determine the current language. In the example above the locale was set to "es"

Hope this helps

Body:
When you compile your app for the various languages you set the locale in the ng build process:

./node_modules/.bin/ngc --i18nFile=./locale/messages.es.xlf --locale=es --i18nFormat=xlf

You can get access to this locale by injecting it to your component:

import { Inject, LOCALE_ID } from '@angular/core';
...
constructor(@Inject(LOCALE_ID) locale: string, ...

Then you can use the locale string to determine the current language. In the example above the locale was set to "es"

Hope this helps


问:
How can i get the value on the same name param/key on the url format with flask?
url that I send to flask webservice :

http://localhost:5000/bendauji?do_nomor=DOCKET/ICN/05-2017/5538&[{"nourutbenda": "0 "}, {"nourutbenda": "3 "}]

flask error respond :
code 400, message Bad request syntax ('GET /bendauji?do_nomor=DOCKET/ICN/05-2017/5538&[{"nourutbenda": "0 "}, {"nourutbenda": "3 "}] HTTP/1.1')

code below in flask :

do_nomor = request.args.get('do_nomor')

nourutbenda = reguest.args ???????

I need value do_nomor and list of nourutbenda. What should I do ?

答:
If you sending your value in this format

```<code>http://localhost:8000/bendauji?nourutbenda=2&nourutbenda=5
</code>```

then you can use getlist to get the nourutbenda

```<code>request.args.getlist('nourutbenda')
</code>```

Body:
If you sending your value in this format

http://localhost:8000/bendauji?nourutbenda=2&nourutbenda=5

then you can use getlist to get the nourutbenda

request.args.getlist('nourutbenda')


问:
Looping through all possible ways of having x out of n correct guesses
I have 10 objects. Each object can be in 3 states, 1, 2, or 3. Let's take the outcome 1111111111. For that one outcome (or any other), I am trying to loop through all the ways one can get 8 out of 10 guesses correct for it. For example, 2111211111 would be one of them. I've managed to get this to work with 9/10 with the loop below, but I need help for getting it to work with 8/10 and 7/10 as well.

For simplicity, let's assume the only combination we're ever checking is 1111111111.

```<code>    Dim incorrectcombos As New Text.StringBuilder
    For i = 2 To 3
        For j = 0 To 9
            Dim combo As New Text.StringBuilder
            For k = 0 To 9
                If k = j Then
                    combo.Append(i)
                Else
                    combo.Append(1)
                End If
            Next
            incorrectcombos.AppendLine(combo.ToString)
        Next
    Next
    MessageBox.Show(incorrectcombos.ToString)
</code>```

答:
Recursive approach is very simple. Delphi code (note that Delphi string is 1-based)

```<code>  procedure GenerateCombs(s: string; MaxLen, Position, ErrCount: Integer);
  begin
    if Position = MaxLen + 1 then
      Memo1.Lines.Add(s)   //output string
    else begin
      if ErrCount <= MaxLen - Position then
        GenerateCombs(s + '1', MaxLen, Position + 1, ErrCount);
      if ErrCount > 0 then begin
        GenerateCombs(s + '2', MaxLen, Position + 1, ErrCount - 1);
        GenerateCombs(s + '3', MaxLen, Position + 1, ErrCount - 1);
      end;
    end;
  end;

begin
  GenerateCombs('', 4, 1, 2);
</code>```

generates

```<code>1122
1123
1132
1133
1212
1213
1221
1231
1312
1313
1321
1331
2112
2113
2121
2131
2211
2311
3112
3113
3121
3131
3211
3311
</code>```

C# (ideone):

```<code>using System;

public class Test
{
        static public void GenerateCombs(string s, int MaxLen, int Position, int ErrCount)
        {
          if (Position == MaxLen + 1)
            {
                Console.WriteLine(s);
                return;
            }

         if (ErrCount <= MaxLen - Position)
         {
              GenerateCombs(s + "1", MaxLen, Position + 1, ErrCount);
         }

          if (ErrCount > 0)
           {
              GenerateCombs(s + "2", MaxLen, Position + 1, ErrCount - 1);
              GenerateCombs(s + "3", MaxLen, Position + 1, ErrCount - 1);
           }
        }

    public static void Main()
    {
        GenerateCombs("", 4, 1, 2);
    }
}
</code>```

Body:
I have 10 objects. Each object can be in 3 states, 1, 2, or 3. Let's take the outcome 1111111111. For that one outcome (or any other), I am trying to loop through all the ways one can get 8 out of 10 guesses correct for it. For example, 2111211111 would be one of them. I've managed to get this to work with 9/10 with the loop below, but I need help for getting it to work with 8/10 and 7/10 as well.

For simplicity, let's assume the only combination we're ever checking is 1111111111.

    Dim incorrectcombos As New Text.StringBuilder
    For i = 2 To 3
        For j = 0 To 9
            Dim combo As New Text.StringBuilder
            For k = 0 To 9
                If k = j Then
                    combo.Append(i)
                Else
                    combo.Append(1)
                End If
            Next
            incorrectcombos.AppendLine(combo.ToString)
        Next
    Next
    MessageBox.Show(incorrectcombos.ToString)

Body:
Recursive approach is very simple. Delphi code (note that Delphi string is 1-based)

  procedure GenerateCombs(s: string; MaxLen, Position, ErrCount: Integer);
  begin
    if Position = MaxLen + 1 then
      Memo1.Lines.Add(s)   //output string
    else begin
      if ErrCount <= MaxLen - Position then
        GenerateCombs(s + '1', MaxLen, Position + 1, ErrCount);
      if ErrCount > 0 then begin
        GenerateCombs(s + '2', MaxLen, Position + 1, ErrCount - 1);
        GenerateCombs(s + '3', MaxLen, Position + 1, ErrCount - 1);
      end;
    end;
  end;

begin
  GenerateCombs('', 4, 1, 2);

generates

1122
1123
1132
1133
1212
1213
1221
1231
1312
1313
1321
1331
2112
2113
2121
2131
2211
2311
3112
3113
3121
3131
3211
3311

C# (ideone):

using System;

public class Test
{
        static public void GenerateCombs(string s, int MaxLen, int Position, int ErrCount)
        {
          if (Position == MaxLen + 1)
            {
                Console.WriteLine(s);
                return;
            }

         if (ErrCount <= MaxLen - Position)
         {
              GenerateCombs(s + "1", MaxLen, Position + 1, ErrCount);
         }

          if (ErrCount > 0)
           {
              GenerateCombs(s + "2", MaxLen, Position + 1, ErrCount - 1);
              GenerateCombs(s + "3", MaxLen, Position + 1, ErrCount - 1);
           }
        }

    public static void Main()
    {
        GenerateCombs("", 4, 1, 2);
    }
}


问:
AS3 TextField.textWidth ignore whitespace at end
I'm trying to calculate the textWidth, but it seems to ignore the white spaces at the end. The text

"Hello"
"Hello "

returns the same text width. A string with " " returns 0. How do I calculate the width with the space?

答:
Choose a terminator character, for Example "|".

Calculate Width(Text+Termainator)-Width(Terminator).


问:
How to extract all words from tweet using single regex in python?
I tried below code but this expression finds just one word
please suggest some way to get expected output.

```<code>import re
tweet = 'RT @marcobonzanini: just an example! :D http://example.com #NLP'
re.findall('(^[a-zA-z]+)\s',tweet)
</code>```

output : ['RT']

expected output =['RT','just','an','example']

so basically remove websites @ mentions,# hash-tags,emotions

答:
I could match all the cases in your input data by using

```<code>((RT)|(@[a-z:]*)|(http:\/\/[a-z.]*)|(#[a-zA-Z]*)|( )|(!))|(:D)
</code>```

Here's the live preview: https://regex101.com/r/xKeFOa/1

Let me know if it helps you.

Body:
I tried below code but this expression finds just one word
please suggest some way to get expected output.

import re
tweet = 'RT @marcobonzanini: just an example! :D http://example.com #NLP'
re.findall('(^[a-zA-z]+)\s',tweet)

output : ['RT']

expected output =['RT','just','an','example']

so basically remove websites @ mentions,# hash-tags,emotions

Body:
I could match all the cases in your input data by using

((RT)|(@[a-z:]*)|(http:\/\/[a-z.]*)|(#[a-zA-Z]*)|( )|(!))|(:D)

Here's the live preview: https://regex101.com/r/xKeFOa/1

Let me know if it helps you.


问:
Trying to make the navbar width 100% to fit nav items on one line
For some reason my navbar is not becoming 100% width. I tried to make .main-header 100% width but still not sure what the problem. The reason to make the navbar 100% is for all the nav items fit on one line. Any ideas what I am doing wrong?

Here is what the navbar looks like on the machine
http://imgur.com/a/za9LH

HTML

**Css**

/* Navigation */
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: purple;
  width: 100%;
}
.logo-name {
  margin-left: 1%;
  background-color: red;
}
.main-nav {
  display: flex;
  background-color: yellow;
}

.main-nav li {
  padding: 0.3em;
  align-items: flex-end;
  background-color: transparent;
  font-size: 17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="main-header">
<!--<h1 class="logo-name"><li>R.J Roofer</li></h1>-->
  <h1 class="logo-name">R.J Roofer</h1>

  <nav class="main-nav">
    <li class="nav-item-1">home</li>
    <li>services</li>
    <li>gallery</li>
    <li>about us</li>
    <li>contact</li>
<!--<li>FREE QUOTE</li>-->
  </nav>
</header></code>```

答:
Probably all you need is the padding and margin for html and body to be set to zero. You may want to consider using a generic reset like this or this.

/* Navigation */
html, body {
padding: 0;
margin: 0;
}
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: purple;
  width: 100vw;
}

.logo-name {
  margin-left: 1%;
  background-color: red;
}

.main-nav {
  display: flex;
  background-color: yellow;
}

.main-nav li {
  padding: 0.3em;
  align-items: flex-end;
  background-color: transparent;
  font-size: 17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="main-header">
  <!--        <h1 class="logo-name"><li>R.J Roofer</li></h1>
         -->
  <h1 class="logo-name">R.J Roofer</h1>

  <nav class="main-nav">
    <li class="nav-item-1">home</li>
    <li>services</li>
    <li>gallery</li>
    <li>about us</li>
    <li>contact</li>
    <!--                    <li>FREE QUOTE</li>
 -->
  </nav>
</header></code>```

Body:
For some reason my navbar is not becoming 100% width. I tried to make .main-header 100% width but still not sure what the problem. The reason to make the navbar 100% is for all the nav items fit on one line. Any ideas what I am doing wrong?

Here is what the navbar looks like on the machine
http://imgur.com/a/za9LH

HTML

**Css**

/* Navigation */
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: purple;
  width: 100%;
}
.logo-name {
  margin-left: 1%;
  background-color: red;
}
.main-nav {
  display: flex;
  background-color: yellow;
}

.main-nav li {
  padding: 0.3em;
  align-items: flex-end;
  background-color: transparent;
  font-size: 17px;
}

R.J Roofer

home

services

gallery

about us

contact

Body:
Probably all you need is the padding and margin for html and body to be set to zero. You may want to consider using a generic reset like this or this.

/* Navigation */
html, body {
padding: 0;
margin: 0;
}
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: purple;
  width: 100vw;
}

.logo-name {
  margin-left: 1%;
  background-color: red;
}

.main-nav {
  display: flex;
  background-color: yellow;
}

.main-nav li {
  padding: 0.3em;
  align-items: flex-end;
  background-color: transparent;
  font-size: 17px;
}

<header class="main-header">
  <!--        <h1 class="logo-name"><li><a href="index.html">R.J Roofer</a></li></h1>
         -->
  <h1 class="logo-name"><a href="index.html">R.J Roofer</a></h1>

  <nav class="main-nav">
    <li class="nav-item-1"><a href="#">home</a></li>
    <li><a href="#">services</a></li>
    <li><a href="#">gallery</a></li>
    <li><a href="#">about us</a></li>
    <li><a href="#">contact</a></li>
    <!--                    <li><a href="#">FREE QUOTE</a></li>
 -->
  </nav>
</header>


问:
Angular 2 and Firebase throwing ThenableReference exception on form submit
Can you please help me to solve this issue:

```<code>ERROR in /src/app/services/firebase.service.ts (33,12): Type 'ThenableReference' is not assignable to type 'Promise<any>'.
  Property '[Symbol.toStringTag]' is missing in type 'ThenableReference'.)

webpack: Failed to compile.
</code>```

My code in service:

```<code>addBusiness(newBusiness): Promise<any>{
    return this.businesses.push(newBusiness);
  }
</code>```

and codes in component:

```<code>  addBusiness(
    company:string,
    category:string,
    years_in_business:number,
    description:string,
    phone:string,
    email:string,
    street_address:string,
    city:string,
    state:string,
    zipcode:string
  ){
    var created_at = new Date().toString();

    var newBusiness = {
      company: company,
      category: category,
      years_in_business:years_in_business,
      description:description,
      phone:phone,
      email:email,
      street_address:street_address,
      city:city,
      state:state,
      zipcode:zipcode,
      created_at:created_at
    }
    this._firebaseService.addBusiness(newBusiness);
    this.changeState('default');
  }
</code>```

答:
make your addBusiness method return firebase.Thenable instead of Promise

Create a Promise object

```<code>addBusiness(newBusiness): Promise<any>{
   return new Promise(function(resolve, reject){
       this.businesses.push(newBusiness)
          .then(x=>resolve(x), x=>reject(x));
   });
}
</code>```

Body:
Can you please help me to solve this issue:

ERROR in /src/app/services/firebase.service.ts (33,12): Type 'ThenableReference' is not assignable to type 'Promise<any>'.
  Property '[Symbol.toStringTag]' is missing in type 'ThenableReference'.)

webpack: Failed to compile.

My code in service:

addBusiness(newBusiness): Promise<any>{
    return this.businesses.push(newBusiness);
  }

and codes in component:

  addBusiness(
    company:string,
    category:string,
    years_in_business:number,
    description:string,
    phone:string,
    email:string,
    street_address:string,
    city:string,
    state:string,
    zipcode:string
  ){
    var created_at = new Date().toString();

    var newBusiness = {
      company: company,
      category: category,
      years_in_business:years_in_business,
      description:description,
      phone:phone,
      email:email,
      street_address:street_address,
      city:city,
      state:state,
      zipcode:zipcode,
      created_at:created_at
    }
    this._firebaseService.addBusiness(newBusiness);
    this.changeState('default');
  }

Body:
make your addBusiness method return firebase.Thenable instead of Promise

Create a Promise object

addBusiness(newBusiness): Promise<any>{
   return new Promise(function(resolve, reject){
       this.businesses.push(newBusiness)
          .then(x=>resolve(x), x=>reject(x));
   });
}


问:
Is KMP Algorithm's jumps error-prone?
Let's consider an example:
text = "AABCAABDCAAB",
pattern = "AABCAAB"

In this example, the pattern will match at index = 0

AABCAABDCAAB

AABCAAB

According to the KMP algorithm, when j = pattern length, we found a match and reset j = lps[pattern length - 1] = 3, this means pattern[j] = 'C'

The algorithm made a jump:

AABCAABDCAAB

_____AABCAAB

without consider the cases between the jump, for example:

AABCAABDCAAB

_AABCAAB

AABCAABDCAAB

__AABCAAB

...

Is it possible to overlook some matches in this case?

答:
The KMP algorithm is proved to work correctly in all cases. The main idea behind it is that if you have matched the first k characters of the pattern, you know k characters of text, because they match those k characters exactly. The shift table is calculated so that the shift to be used when you have matched k characters is as far as you can safely go, given the knowledge of those k characters.

In your example you have just matched AABCAAB, so you know the text is AABCAAB. There is only one C in the pattern, which you have just matched, so you must move the pattern on far enough that the C that used to match doesn't overlap any part of the pattern at the next attempted match, which in this case gives you the next attempted match position.

(I note that the KMP algorithm is usually described and proved not as making irregular shifts of the pattern but of stepping regularly along the text to be searched and working out how many characters of the pattern have been matched so far. Because there is a proof using that view of the algorithm we know that it works in all cases).

Title: Is KMP Algorithm's jumps error-prone?


问:
How do I read a string > 255 chars in php/adodb?
I'm maintaining a web application written in PHP that connects to a MSSQL database.

The original developer used http://adodb.sourceforge.net/ as his database library.

The problem is, when reading data using the GetAll method, all the strings are truncated to 255 chars.

Has anyone a solution to my problem?

edit: The column I am having a problem with is a varchar(800)

答:
Can you get the last column seperately using:

```<code>SELECT SUBSTRING (longfield,1,200) as Part1, SUBSTRING (longfield,201,200) as Part2, SUBSTRING (longfield,401,200) as Part3, SUBSTRING (longfield,601,200) as Part4
</code>```

?

You can then glue the columns back together. You might need some special cases for when then string isn't actualy that long.

Body:
Can you get the last column seperately using:

SELECT SUBSTRING (longfield,1,200) as Part1, SUBSTRING (longfield,201,200) as Part2, SUBSTRING (longfield,401,200) as Part3, SUBSTRING (longfield,601,200) as Part4

?

You can then glue the columns back together. You might need some special cases for when then string isn't actualy that long.


问:
Folder importing in SCSS
Say for example. Need to import a folder where all your scss partials in there. My query is how will I import the entire directory.

@import'layout/.'; Is this a right way or Correct me if i am wrong.

答:
You can't import a folder SCSS you have to import each file

```<code>// Modules and Variables
@import "/base";

// Partials
@import "/reset";
@import "/typography";
@import "/buttons";
@import "/figures";
@import "/grids";
// ...

// Third-party
@import "vendor/colorpicker";
@import "vendor/jquery.ui.core";
</code>```

Also you can import one file that has already imported everything in the folder. This way you can choose not to import some files.

Title: Folder importing in SCSS

Body:
You can't import a folder SCSS you have to import each file

// Modules and Variables
@import "/base";

// Partials
@import "/reset";
@import "/typography";
@import "/buttons";
@import "/figures";
@import "/grids";
// ...

// Third-party
@import "vendor/colorpicker";
@import "vendor/jquery.ui.core";

Also you can import one file that has already imported everything in the folder. This way you can choose not to import some files.


答:
If I follow your question correctly I think you are after a where clause such as this:

```<code>select
*
from YourTable
where (
       oDate > '20170602'
      OR
       (oDate = '20170602' AND oTime >= '21:00:00')
      )
</code>```

This would give you all dates after 2017-06-02 as well as times on that date at and after 21:00

To make best use of indexes that may exist on those columns I suggest you do not try to combine the date with time such as this dateadd(day,datediff(day,0,oDate),oTime) and then try to filter >= '20170602 21:00:00' as that would produce table scanning.

perhaps this will help

```<code>select
*
from YourTable
where (
       oDate > @dateparameterhere
      OR
       (oDate = @dateparemterhere AND oTime >= '21:00:00')
      )
</code>```

Title: Select Date with Specific Time SQL

Body:
I have the following table:

oDate          oTime          oAct
--------------------------------------
2017-06-01     00:00:00       A
2017-06-01     01:00:00       B
2017-06-01     02:00:00       C
ff.
2017-06-02     00:00:00       B
ff.

I want to select a day before (only after 21:00:00) and after.

Let say, If I Select '2017-06-02' then the result should be:

oDate          oTime          oAct
--------------------------------------
2017-06-01     22:00:00       A
2017-06-02     00:00:00       B
2017-06-02     01:00:00       C
ff.
2017-06-03     00:00:00       C
ff.

Also, for the query. I only have one parameter, which is @oDate date.

Please advise.

Thank you.

Body:
If I follow your question correctly I think you are after a where clause such as this:

select
*
from YourTable
where (
       oDate > '20170602'
      OR
       (oDate = '20170602' AND oTime >= '21:00:00')
      )

This would give you all dates after 2017-06-02 as well as times on that date at and after 21:00

To make best use of indexes that may exist on those columns I suggest you do not try to combine the date with time such as this dateadd(day,datediff(day,0,oDate),oTime) and then try to filter >= '20170602 21:00:00' as that would produce table scanning.

perhaps this will help

select
*
from YourTable
where (
       oDate > @dateparameterhere
      OR
       (oDate = @dateparemterhere AND oTime >= '21:00:00')
      )


问:
How to save a numeric value in a specified location of a CSV file inside for loops in MATLAB?
I want to do this because otherwise I run out of memory to save the values in a matrix, as the dimensions of the matrix increases.

For example,

```<code>for a=1:10000
   for b=1:10000
      M(a,b)=rand;
   end
end
</code>```

Here, the system runs out of memory as it can't store a 10000x10000 matrix.

So, I want to keep writing the (a,b)'th value inside the for loops into the (a,b)'th cell of a csv file (or an xls file, whatever). How do I do that?

I want something like this:

```<code>for a=1:10000
   for b=1:10000
      xlswrite1('file.xls',a,b,rand); % better if I can get a solution with csvwrite, as I prefer CSVs to work with
   end
end
</code>```

But this obviously doesn't work. The error it gives is:

```<code>Error using evalin
Undefined function or variable 'Excel'.

Error in xlswrite1 (line 2)
Excel=evalin('caller','Excel');
</code>```

Then when I add the following lines according to this article,

```<code>Excel = actxserver ('Excel.Application');
File='datafile.xls';
if ~exist(File,'file')
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);
</code>```

it gives this error:

```<code>Error using xlswrite1 (line 82)
Range argument must a string of Excel A1 notation.
</code>```

Can anyone please suggest a simple solution? I can't find any from my online search so far.

答:
You can do this using dlmwrite. But I suggest you to write row by row instead of element by element.

```<code>  N = 100 ;
  M = zeros(N,N) ;
  filename = 'test.csv';
  for a=1:N
     for b=1:N
        M(a,b)=rand;
     end
     dlmwrite(filename,M(a,:),'-append')
  end
</code>```

If you don't want to make a matrix M, then make rows and write them to your file:

```<code>N = 100 ;
M = zeros(1,N) ;
filename = 'test.csv';
for a=1:N
   for b=1:N
      M(1,b)=rand;
   end
   dlmwrite(filename,M(1,:),'-append')
end
</code>```

Body:
I want to do this because otherwise I run out of memory to save the values in a matrix, as the dimensions of the matrix increases.

For example,

for a=1:10000
   for b=1:10000
      M(a,b)=rand;
   end
end

Here, the system runs out of memory as it can't store a 10000x10000 matrix.

So, I want to keep writing the (a,b)'th value inside the for loops into the (a,b)'th cell of a csv file (or an xls file, whatever). How do I do that?

I want something like this:

for a=1:10000
   for b=1:10000
      xlswrite1('file.xls',a,b,rand); % better if I can get a solution with csvwrite, as I prefer CSVs to work with
   end
end

But this obviously doesn't work. The error it gives is:

Error using evalin
Undefined function or variable 'Excel'.

Error in xlswrite1 (line 2)
Excel=evalin('caller','Excel');

Then when I add the following lines according to this article,

Excel = actxserver ('Excel.Application');
File='datafile.xls';
if ~exist(File,'file')
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);

it gives this error:

Error using xlswrite1 (line 82)
Range argument must a string of Excel A1 notation.

Can anyone please suggest a simple solution? I can't find any from my online search so far.

Body:
You can do this using dlmwrite. But I suggest you to write row by row instead of element by element.

  N = 100 ;
  M = zeros(N,N) ;
  filename = 'test.csv';
  for a=1:N
     for b=1:N
        M(a,b)=rand;
     end
     dlmwrite(filename,M(a,:),'-append')
  end

If you don't want to make a matrix M, then make rows and write them to your file:

N = 100 ;
M = zeros(1,N) ;
filename = 'test.csv';
for a=1:N
   for b=1:N
      M(1,b)=rand;
   end
   dlmwrite(filename,M(1,:),'-append')
end


问:
Python open() requires full path
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

```<code>with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)
</code>```

If I give the full path to the file, it will work. Why open() requires full path of the file ?

答:
From the documentation:

open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None)

file is a path-like object giving the pathname (absolute or relative
to the current working directory) of the file to be opened or an
integer file descriptor of the file to be wrapped.

So, if the file that you want open isn't in the current folder of the running script, you can use an absolute path, or getting the working directory or/and absolute path by using:

```<code>import os
# Look to the path of your current working directory
working_directory = os.getcwd()
# Or: file_path = os.path.join(working_directory, 'my_file.py')
file_path = working_directory + 'my_file.py'
</code>```

Or, you can retrieve your absolute path while running your script, using:

```<code>import os
# Look for your absolute directory path
absolute_path = os.path.dirname(os.path.abspath(__file__))
# Or: file_path = os.path.join(absolute_path, 'folder', 'my_file.py')
file_path = absolute_path + '/folder/my_file.py'
</code>```

If you want to be operating system agnostic, then you can use:

```<code>file_path = os.path.join(absolute_path, folder, my_file.py)
</code>```

Title: Python open() requires full path

Body:
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)

If I give the full path to the file, it will work. Why open() requires full path of the file ?

Body:
From the documentation:

open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None)

file is a path-like object giving the pathname (absolute or relative
to the current working directory) of the file to be opened or an
integer file descriptor of the file to be wrapped.

So, if the file that you want open isn't in the current folder of the running script, you can use an absolute path, or getting the working directory or/and absolute path by using:

import os
# Look to the path of your current working directory
working_directory = os.getcwd()
# Or: file_path = os.path.join(working_directory, 'my_file.py')
file_path = working_directory + 'my_file.py'

Or, you can retrieve your absolute path while running your script, using:

import os
# Look for your absolute directory path
absolute_path = os.path.dirname(os.path.abspath(__file__))
# Or: file_path = os.path.join(absolute_path, 'folder', 'my_file.py')
file_path = absolute_path + '/folder/my_file.py'

If you want to be operating system agnostic, then you can use:

file_path = os.path.join(absolute_path, folder, my_file.py)

ContentLicense: CC BY-SA 4.0


问:
How to duplicate rows of existing table and change value of one column based on a simple condition
I am a beginner in R, and I would appreciate help from experts for this problem.
I have Products table like this:

Table1 : Existing Products

```<code>ProductId Width  Thickness
CM72      4.2     12
CM73      1.2     76
CM84      3.5     32
CM93      2.1     31
</code>```

Table2 : New Products

```<code>ProductId
CG72
CG93
</code>```

I want to append the ProductId of the NewProducts table to the existing Products table. And I want to copy the Width and Thickness and Length from the similar numbered existing product. CM72 -> is the match for CG72. CM93 -> match for CG93.

Final table should look like this:

```<code>ProductId Width  Thickness
CM72      4.2     12
CM73      1.2     76
CM84      3.5     32
CM93      2.1     31
CG72      4.2     12
CG93      2.1     31
</code>```

Is there an effective way to do this in R? Many thanks!

答:
We replace the 'G' with 'M' in the 'ProductId' of second dataset ('df2') using sub, get the index of row in 'df1' by matching with 'ProductId', subset the 2nd and 3rd column with only the rows based on the match ids, cbind with the second dataset 'df2' and then rbind with the 'df1'

```<code>dfN <- rbind(df1,  cbind(df2, df1[match(sub("G", "M", df2$ProductId), df1$ProductId), 2:3]))
row.names(dfN) <- NULL
dfN
#  ProductId Width Thickness
#1      CM72   4.2        12
#2      CM73   1.2        76
#3      CM84   3.5        32
#4      CM93   2.1        31
#5      CG72   4.2        12
#6      CG93   2.1        31
</code>```

Or another option is with data.table, We get the datasets in a list, rbind, grouped by the substring of 'ProductId', loop through the other columns, get the non-NA elements and assign (:=) it to the columns

```<code>rbindlist(list(df1, df2), fill = TRUE)[, (2:3) :=
 lapply(.SD, function(x) x[!is.na(x)]), .(grp = sub("G", "M", ProductId))][]
#    ProductId Width Thickness
#1:      CM72   4.2        12
#2:      CM73   1.2        76
#3:      CM84   3.5        32
#4:      CM93   2.1        31
#5:      CG72   4.2        12
#6:      CG93   2.1        31
</code>```

A corresponding tidyverse approach would be

```<code>library(tidyverse)
bind_rows(df1, df2) %>%
     group_by(grp =  sub("G", "M", ProductId)) %>%
     mutate_at(vars(Width:Thickness), funs(.[!is.na(.)])) %>%
     ungroup() %>%
     select(-grp)
</code>```

data

```<code>df1 <- structure(list(ProductId = c("CM72", "CM73", "CM84", "CM93"),
Width = c(4.2, 1.2, 3.5, 2.1), Thickness = c(12L, 76L, 32L,
31L)), .Names = c("ProductId", "Width", "Thickness"),
 class =  "data.frame", row.names = c(NA, -4L))

df2 <- structure(list(ProductId = c("CG72", "CG93")),
.Names = "ProductId", class = "data.frame", row.names = c(NA,
 -2L))
</code>```

Body:
I am a beginner in R, and I would appreciate help from experts for this problem.
I have Products table like this:

Table1 : Existing Products

ProductId Width  Thickness
CM72      4.2     12
CM73      1.2     76
CM84      3.5     32
CM93      2.1     31

Table2 : New Products

ProductId
CG72
CG93

I want to append the ProductId of the NewProducts table to the existing Products table. And I want to copy the Width and Thickness and Length from the similar numbered existing product. CM72 -> is the match for CG72. CM93 -> match for CG93.

Final table should look like this:

ProductId Width  Thickness
CM72      4.2     12
CM73      1.2     76
CM84      3.5     32
CM93      2.1     31
CG72      4.2     12
CG93      2.1     31

Is there an effective way to do this in R? Many thanks!

Body:
We replace the 'G' with 'M' in the 'ProductId' of second dataset ('df2') using sub, get the index of row in 'df1' by matching with 'ProductId', subset the 2nd and 3rd column with only the rows based on the match ids, cbind with the second dataset 'df2' and then rbind with the 'df1'

dfN <- rbind(df1,  cbind(df2, df1[match(sub("G", "M", df2$ProductId), df1$ProductId), 2:3]))
row.names(dfN) <- NULL
dfN
#  ProductId Width Thickness
#1      CM72   4.2        12
#2      CM73   1.2        76
#3      CM84   3.5        32
#4      CM93   2.1        31
#5      CG72   4.2        12
#6      CG93   2.1        31

Or another option is with data.table, We get the datasets in a list, rbind, grouped by the substring of 'ProductId', loop through the other columns, get the non-NA elements and assign (:=) it to the columns

rbindlist(list(df1, df2), fill = TRUE)[, (2:3) :=
 lapply(.SD, function(x) x[!is.na(x)]), .(grp = sub("G", "M", ProductId))][]
#    ProductId Width Thickness
#1:      CM72   4.2        12
#2:      CM73   1.2        76
#3:      CM84   3.5        32
#4:      CM93   2.1        31
#5:      CG72   4.2        12
#6:      CG93   2.1        31

A corresponding tidyverse approach would be

library(tidyverse)
bind_rows(df1, df2) %>%
     group_by(grp =  sub("G", "M", ProductId)) %>%
     mutate_at(vars(Width:Thickness), funs(.[!is.na(.)])) %>%
     ungroup() %>%
     select(-grp)

data

df1 <- structure(list(ProductId = c("CM72", "CM73", "CM84", "CM93"),
Width = c(4.2, 1.2, 3.5, 2.1), Thickness = c(12L, 76L, 32L,
31L)), .Names = c("ProductId", "Width", "Thickness"),
 class =  "data.frame", row.names = c(NA, -4L))

df2 <- structure(list(ProductId = c("CG72", "CG93")),
.Names = "ProductId", class = "data.frame", row.names = c(NA,
 -2L))


答:
Try this
concatenating fields to make a datetime field</p>

```<code>select
* from table
where
cast (cast(odate as varchar(max)) + ' ' + cast(otime as varchar(max))  as datetime) < cast('2017-06-02 21:00:00' as datetime)
</code>```

Title: Select Date with Specific Time SQL

Body:
Try this
concatenating fields to make a datetime field

select
* from table
where
cast (cast(odate as varchar(max)) + ' ' + cast(otime as varchar(max))  as datetime) < cast('2017-06-02 21:00:00' as datetime)


问:
what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array
I have an String Array and Integer Array,

```<code>String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
</code>```

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

答:
In Java, String and Integer both are inherited from Object. So you can use Object type to define a general array. </p>

```<code>    String[] strArray = { "a", "b", "c" };
    Integer[] intArray = { 1, 2, 3 };
    Object[] arr = new Object[strArray.length + intArray.length];
    int j = 0;
    for (int i = 0; i < strArray.length; i++) {
        arr[j++] = strArray[i];
    }
    for (int i = 0; i < intArray.length; i++) {
        arr[j++] = intArray[i];
    }
</code>```

Body:
I have an String Array and Integer Array,

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

Body:
In Java, String and Integer both are inherited from Object. So you can use Object type to define a general array.

    String[] strArray = { "a", "b", "c" };
    Integer[] intArray = { 1, 2, 3 };
    Object[] arr = new Object[strArray.length + intArray.length];
    int j = 0;
    for (int i = 0; i < strArray.length; i++) {
        arr[j++] = strArray[i];
    }
    for (int i = 0; i < intArray.length; i++) {
        arr[j++] = intArray[i];
    }


问:
How to put delay inside a arraylist in android
Hey guys i want to put 2 second delay in each code inside of the arraylist. How can i do this? Sorry newbie in android developing. Thanks for any help.

Here is my code.

```<code>  private ArrayList<double[]> points = new ArrayList<>();
{
    points.add( new double[] {-2885, 4537} );
    points.add( new double[] {-2903, 3916} );
    points.add( new double[] {-3236, 3883} );
    points.add( new double[] {-3233, 3657} );
    points.add( new double[] {-3552, 3638} );
    points.add( new double[] {-3570, 2661} );
    points.add( new double[] {-2735, 2651} );
    points.add( new double[] {-2720, 2613} );
    points.add( new double[] {-2634, 2613} );
}
</code>```

答:
You can use Thread class to make delay during the execution.

```<code>try{
Thread.sleep(seconds to delay*1000)
}
catch(Exception e)
{
e.printStackTrace();
}
</code>```

or you can use the Asynchronous Task to delay

```<code>public void callAsynchronousTask() {
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                          Log.e("data","5 sconds");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 5 s
    }
</code>```

Body:
Hey guys i want to put 2 second delay in each code inside of the arraylist. How can i do this? Sorry newbie in android developing. Thanks for any help.

Here is my code.

  private ArrayList<double[]> points = new ArrayList<>();
{
    points.add( new double[] {-2885, 4537} );
    points.add( new double[] {-2903, 3916} );
    points.add( new double[] {-3236, 3883} );
    points.add( new double[] {-3233, 3657} );
    points.add( new double[] {-3552, 3638} );
    points.add( new double[] {-3570, 2661} );
    points.add( new double[] {-2735, 2651} );
    points.add( new double[] {-2720, 2613} );
    points.add( new double[] {-2634, 2613} );
}

Body:
You can use Thread class to make delay during the execution.

try{
Thread.sleep(seconds to delay*1000)
}
catch(Exception e)
{
e.printStackTrace();
}

or you can use the Asynchronous Task to delay

public void callAsynchronousTask() {
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                          Log.e("data","5 sconds");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 5 s
    }


问:
javascript canvas: draw moving average line with curves
So basically, I want to draw a curved average line over a certain amount of points of a time-series line chart. Like this:

I want it to span the entire length of the chart but I can't figure out how to calculate the start and end points because the average would (I think) be a point in the middle of each section. Looking at a stock chart with moving average you can see what I want to acheive:

I calculate the averages first by splitting the data array up into chunks based on a period of time. So if I start with:

```<code>[
    { time: 1, value: 2 },
    { time: 2, value: 4 },
    { time: 3, value: 5 },
    { time: 4, value: 7 },
]
</code>```

I get to:

```<code>var averages = [
   {
      x: 1.5,
      y: 3,
   },
   {
       x: 3.5  (the average time)
       y: 6    (the average value)
   },
]
</code>```

This is what I've tried where I end up with an incomplete line, one that doesnt start at the beginning of the chart and doesnt stop at the end, but stars and ends inside the chart at the first average time:

```<code>            ctx.moveTo((averages[0].x), averages[0].y);

            for(var i = 0; i < averages.length-1; i ++)
            {

              var x_mid = (averages[i].x + averages[i+1].x) / 2;
              var y_mid = (averages[i].y + averages[i+1].y) / 2;
              var cp_x1 = (x_mid + averages[i].x) / 2;
              var cp_x2 = (x_mid + averages[i+1].x) / 2;
              ctx.quadraticCurveTo(cp_x1, averages[i].y ,x_mid, y_mid);
              ctx.quadraticCurveTo(cp_x2, averages[i+1].y ,averages[i+1].x, averages[i+1].y);
            }

            ctx.stroke();
</code>```

How would you do this?

答:
To get a moving mean you need to just get the mean of n points either side of the current sample.

For example

```<code>// array of data points
const movingMean = []; // the resulting means
const data = [12,345,123,53,134,...,219]; // data with index representing x axis
const sampleSize = 5;
for(var i = sampleSize; i < data.length - sampleSize; i++){
    var total = 0;
    for(var j = i- sampleSize; j < i + sampleSize;  j++){
         total += data[j];
    }
    movingMean[i] = total / (sampleSize * 2);
}
</code>```

This method does not pull the mean forward giving the most accurate mean for each data point.

The problem with this method is that you do not get a mean for the first n and last n samples, where n is the number of samples either side of the mean.

You can do an alternative that will pull the mean forward a little but by applying a weighted mean you can reduce the bias a little

```<code>for(var i = sampleSize; i < data.length + Math.floor(sampleSize / 4); i++){
    var total = 0;
    var count = 0;
    for(var j = sampleSize; j > 0; j --){
        var index = i - (sampleSize - j);
        if(index < data.length){
             total += data[index] * j; // linear weighting
            count += j;
        }
    }
    movingMean[i-Math.floor(sampleSize / 4)] = total / count;
}
</code>```

This method keeps that mean closer to the current sample end.

The example show a random data set and the two types of means plotted over it. Click to get a new plot. The red line is the moving mean and the blue is the weighted mean. Note how the blue line tends to follow the data a little slow.
The green line is a weighted mean that has a sample range 4 times greater than the other two.

// helper functions
const doFor = (count, callback) => {var i = 0; while (i < count) { callback(i ++) } };
const setOf = (count, callback) => {var a = [],i = 0; while (i < count) { a.push(callback(i ++)) } return a };
const rand  = (min, max = min + (min = 0)) => Math.random() * (max - min) + min;
const randG = (dis, min, max) => {var r = 0; doFor(dis,()=>r+=rand(min,max)); return r / dis};
function getMinMax(data){
    var min = data[0];
    var max = data[0];
    doFor(data.length - 1, i => {
        min = Math.min(min,data[i+1]);
        max = Math.max(max,data[i+1]);
    });
    var range = max-min;
    return {min,max,range};
}
function plotData(data,minMax){
   ctx.beginPath();
   for(var i = 0; i < data.length; i++){
      if(data[i] !== undefined){
          var y = (data[i] - minMax.min) / minMax.range;
          y = y *(ctx.canvas.height - 2) + 1;
          ctx.lineTo(i/2,y);
      }
   }
   ctx.stroke();
}
function getMovingMean(data,sampleSize){
    const movingMean = []; // the resulting means
    for(var i = sampleSize; i < data.length - sampleSize; i++){
        var total = 0;
        for(var j = i- sampleSize; j < i + sampleSize;  j++){
             total += data[j];
        }
        movingMean[i] = total / (sampleSize * 2);
    }
    return movingMean[i];
}

function getMovingMean(data,sampleSize){
    const movingMean = []; // the resulting means
    for(var i = sampleSize; i < data.length - sampleSize; i++){
        var total = 0;
        for(var j = i- sampleSize; j < i + sampleSize;  j++){
             total += data[j];
        }
        movingMean[i] = total / (sampleSize * 2);
    }
    return movingMean;
}

function getWeightedMean(data,sampleSize){
    const weightedMean = [];
    for(var i = sampleSize; i < data.length+Math.floor(sampleSize/4); i++){
        var total = 0;
        var count = 0;
        for(var j = sampleSize; j > 0; j --){
            var index = i - (sampleSize - j);
            if(index < data.length){
                total += data[index] * j; // linear weighting
                count += j;
            }

        }
        weightedMean[i-Math.floor(sampleSize/4)] = total / count;
    }
    return weightedMean;
}
const dataSize = 1000;
const sampleSize = 50;
canvas.width = dataSize/2;
canvas.height = 200;
const ctx = canvas.getContext("2d");
function displayData(){
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
    var dataPoint = 100;
    var distribution = Math.floor(rand(1,8));
    var movement = rand(2,20);
    const data = setOf(dataSize,i => dataPoint += randG(distribution, -movement, movement));
    const movingMean = getMovingMean(data, sampleSize);
    const weightedMean = getWeightedMean(data, sampleSize*2);
    const weightedMean1 = getWeightedMean(data, sampleSize*8);
    var minMax = getMinMax(data);
    ctx.strokeStyle = "#ccc";
    plotData(data,minMax);
    ctx.strokeStyle = "#F50";
    plotData(movingMean,minMax);
    ctx.strokeStyle = "#08F";
    plotData(weightedMean,minMax);
    ctx.strokeStyle = "#4C0";
    plotData(weightedMean1,minMax);
}
displayData();
document.onclick = displayData;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family : arial; }
.red { color : #F50; }
.blue { color : #0AF; }
.green { color : #4C0; }
canvas { position : absolute; top : 0px; left :130px; }</code>```

<canvas id="canvas"></canvas>

Moving mean

Weighted mean

Wide weighted mean

Click for another sample
```

Body:
So basically, I want to draw a curved average line over a certain amount of points of a time-series line chart. Like this:

I want it to span the entire length of the chart but I can't figure out how to calculate the start and end points because the average would (I think) be a point in the middle of each section. Looking at a stock chart with moving average you can see what I want to acheive:

I calculate the averages first by splitting the data array up into chunks based on a period of time. So if I start with:

[
    { time: 1, value: 2 },
    { time: 2, value: 4 },
    { time: 3, value: 5 },
    { time: 4, value: 7 },
]

I get to:

var averages = [
   {
      x: 1.5,
      y: 3,
   },
   {
       x: 3.5  (the average time)
       y: 6    (the average value)
   },
]

This is what I've tried where I end up with an incomplete line, one that doesnt start at the beginning of the chart and doesnt stop at the end, but stars and ends inside the chart at the first average time:

            ctx.moveTo((averages[0].x), averages[0].y);

            for(var i = 0; i < averages.length-1; i ++)
            {

              var x_mid = (averages[i].x + averages[i+1].x) / 2;
              var y_mid = (averages[i].y + averages[i+1].y) / 2;
              var cp_x1 = (x_mid + averages[i].x) / 2;
              var cp_x2 = (x_mid + averages[i+1].x) / 2;
              ctx.quadraticCurveTo(cp_x1, averages[i].y ,x_mid, y_mid);
              ctx.quadraticCurveTo(cp_x2, averages[i+1].y ,averages[i+1].x, averages[i+1].y);
            }

            ctx.stroke();

How would you do this?

Body:
To get a moving mean you need to just get the mean of n points either side of the current sample.

For example

// array of data points
const movingMean = []; // the resulting means
const data = [12,345,123,53,134,...,219]; // data with index representing x axis
const sampleSize = 5;
for(var i = sampleSize; i < data.length - sampleSize; i++){
    var total = 0;
    for(var j = i- sampleSize; j < i + sampleSize;  j++){
         total += data[j];
    }
    movingMean[i] = total / (sampleSize * 2);
}

This method does not pull the mean forward giving the most accurate mean for each data point.

The problem with this method is that you do not get a mean for the first n and last n samples, where n is the number of samples either side of the mean.

You can do an alternative that will pull the mean forward a little but by applying a weighted mean you can reduce the bias a little

for(var i = sampleSize; i < data.length + Math.floor(sampleSize / 4); i++){
    var total = 0;
    var count = 0;
    for(var j = sampleSize; j > 0; j --){
        var index = i - (sampleSize - j);
        if(index < data.length){
             total += data[index] * j; // linear weighting
            count += j;
        }
    }
    movingMean[i-Math.floor(sampleSize / 4)] = total / count;
}

This method keeps that mean closer to the current sample end.

The example show a random data set and the two types of means plotted over it. Click to get a new plot. The red line is the moving mean and the blue is the weighted mean. Note how the blue line tends to follow the data a little slow.
The green line is a weighted mean that has a sample range 4 times greater than the other two.

// helper functions
const doFor = (count, callback) => {var i = 0; while (i < count) { callback(i ++) } };
const setOf = (count, callback) => {var a = [],i = 0; while (i < count) { a.push(callback(i ++)) } return a };
const rand  = (min, max = min + (min = 0)) => Math.random() * (max - min) + min;
const randG = (dis, min, max) => {var r = 0; doFor(dis,()=>r+=rand(min,max)); return r / dis};
function getMinMax(data){
    var min = data[0];
    var max = data[0];
    doFor(data.length - 1, i => {
        min = Math.min(min,data[i+1]);
        max = Math.max(max,data[i+1]);
    });
    var range = max-min;
    return {min,max,range};
}
function plotData(data,minMax){
   ctx.beginPath();
   for(var i = 0; i < data.length; i++){
      if(data[i] !== undefined){
          var y = (data[i] - minMax.min) / minMax.range;
          y = y *(ctx.canvas.height - 2) + 1;
          ctx.lineTo(i/2,y);
      }
   }
   ctx.stroke();
}
function getMovingMean(data,sampleSize){
    const movingMean = []; // the resulting means
    for(var i = sampleSize; i < data.length - sampleSize; i++){
        var total = 0;
        for(var j = i- sampleSize; j < i + sampleSize;  j++){
             total += data[j];
        }
        movingMean[i] = total / (sampleSize * 2);
    }
    return movingMean[i];
}

function getMovingMean(data,sampleSize){
    const movingMean = []; // the resulting means
    for(var i = sampleSize; i < data.length - sampleSize; i++){
        var total = 0;
        for(var j = i- sampleSize; j < i + sampleSize;  j++){
             total += data[j];
        }
        movingMean[i] = total / (sampleSize * 2);
    }
    return movingMean;
}

function getWeightedMean(data,sampleSize){
    const weightedMean = [];
    for(var i = sampleSize; i < data.length+Math.floor(sampleSize/4); i++){
        var total = 0;
        var count = 0;
        for(var j = sampleSize; j > 0; j --){
            var index = i - (sampleSize - j);
            if(index < data.length){
                total += data[index] * j; // linear weighting
                count += j;
            }

        }
        weightedMean[i-Math.floor(sampleSize/4)] = total / count;
    }
    return weightedMean;
}
const dataSize = 1000;
const sampleSize = 50;
canvas.width = dataSize/2;
canvas.height = 200;
const ctx = canvas.getContext("2d");
function displayData(){
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
    var dataPoint = 100;
    var distribution = Math.floor(rand(1,8));
    var movement = rand(2,20);
    const data = setOf(dataSize,i => dataPoint += randG(distribution, -movement, movement));
    const movingMean = getMovingMean(data, sampleSize);
    const weightedMean = getWeightedMean(data, sampleSize*2);
    const weightedMean1 = getWeightedMean(data, sampleSize*8);
    var minMax = getMinMax(data);
    ctx.strokeStyle = "#ccc";
    plotData(data,minMax);
    ctx.strokeStyle = "#F50";
    plotData(movingMean,minMax);
    ctx.strokeStyle = "#08F";
    plotData(weightedMean,minMax);
    ctx.strokeStyle = "#4C0";
    plotData(weightedMean1,minMax);
}
displayData();
document.onclick = displayData;

body { font-family : arial; }
.red { color : #F50; }
.blue { color : #0AF; }
.green { color : #4C0; }
canvas { position : absolute; top : 0px; left :130px; }

<canvas id="canvas"></canvas>
<div class="red">Moving mean</div>
<div class="blue">Weighted mean</div>
<div class="green">Wide weighted mean</div>
<div>Click for another sample</div>


问:
O_NONBLOCK SOCK_STREAM limited to 8192
I'm writing from c program into a SOCK_STREAM of a Unix Domain Socket that is being listened from a go program, using net.Listen("unix", sockname). When I set the socket to O_NONBLOCK using fcntl(), I see that the C program writes only 8192 bytes in the first write. After it fails, I monitor and write back the remaining data, but the read data on my server is not valid in this case.

When I do not use O_NONBLOCK, then the whole of 8762 bytes are written in a single write and everything works as expected.

C Client Socket Connection

```<code>    if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        return;
    }
   int flags = fcntl(fd, F_GETFL, 0);
   flags = flags|O_NONBLOCK;
   fcntl(fd, F_SETFL, flags);
   ...
    if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        return;
    }
</code>```

C Client Writing

```<code>        while (written < to_write) {
            int result;
            if ((result = write(fd, &buffer[written], to_write - written)) < 0) {
                if (errno == EINTR) {
                    continue;
                }
                if (errno == EAGAIN) {
                    struct pollfd pfd = { .fd = fd, .events = POLLOUT };
                    poll_count++;
                    if (poll_count > 3) {
                        goto end;
                    }
                    if ((poll(&pfd, 1, -1) <= 0) && (errno != EAGAIN)) {
                        goto end;
                    }
                    continue;
                }
end:
                return written ? written : result;
            }
            written += result;
            buffer += result;
        }
</code>```

Go Server Reading

```<code>buf := make([]byte, 0, count)
var tmpsize int32
for {
    if count <= 0 {
        break
    }

    if count > 100 {
        tmpsize = 100
    } else {
        tmpsize = count
    }

    tmp := make([]byte, tmpsize)
    nr, err = conn.Read(tmp)
    if err != nil {
        return
    }

    buf = append(buf, tmp[:nr]...)
    count = count - int32(nr)
}
</code>```

What am I missing here. I'm running it on OSX. I also tried setting the SO_SNDBUF in the Go Server to 10000, but it does not help

```<code>err = syscall.SetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF, 10000)
if err != nil {
    return
}
</code>```

答:
What I would do is read the data straight into a bytes.Buffer similar to the answer listed here:

https://stackoverflow.com/a/24343240/8092543

https://golang.org/pkg/io/#Copy

The beauty of the io.Copy is that it consumes a Writer + Reader interface, which are satisfied nicely but your bytes.Buffer (io.Writer) and your conn.Read (io.Reader). Replace your entire block with something like...

```<code>var buf bytes.Buffer
count, err := io.Copy(buf, conn)
if err != nil {
    return nil, fmt.Errorf("error during conn read: %v", err)
}

return buf.Bytes(), nil
</code>```

Title: O_NONBLOCK SOCK_STREAM limited to 8192

Body:
I'm writing from c program into a SOCK_STREAM of a Unix Domain Socket that is being listened from a go program, using net.Listen("unix", sockname). When I set the socket to O_NONBLOCK using fcntl(), I see that the C program writes only 8192 bytes in the first write. After it fails, I monitor and write back the remaining data, but the read data on my server is not valid in this case.

When I do not use O_NONBLOCK, then the whole of 8762 bytes are written in a single write and everything works as expected.

C Client Socket Connection

    if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        return;
    }
   int flags = fcntl(fd, F_GETFL, 0);
   flags = flags|O_NONBLOCK;
   fcntl(fd, F_SETFL, flags);
   ...
    if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        return;
    }

C Client Writing

        while (written < to_write) {
            int result;
            if ((result = write(fd, &buffer[written], to_write - written)) < 0) {
                if (errno == EINTR) {
                    continue;
                }
                if (errno == EAGAIN) {
                    struct pollfd pfd = { .fd = fd, .events = POLLOUT };
                    poll_count++;
                    if (poll_count > 3) {
                        goto end;
                    }
                    if ((poll(&pfd, 1, -1) <= 0) && (errno != EAGAIN)) {
                        goto end;
                    }
                    continue;
                }
end:
                return written ? written : result;
            }
            written += result;
            buffer += result;
        }

Go Server Reading

buf := make([]byte, 0, count)
var tmpsize int32
for {
    if count <= 0 {
        break
    }

    if count > 100 {
        tmpsize = 100
    } else {
        tmpsize = count
    }

    tmp := make([]byte, tmpsize)
    nr, err = conn.Read(tmp)
    if err != nil {
        return
    }

    buf = append(buf, tmp[:nr]...)
    count = count - int32(nr)
}

What am I missing here. I'm running it on OSX. I also tried setting the SO_SNDBUF in the Go Server to 10000, but it does not help

err = syscall.SetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF, 10000)
if err != nil {
    return
}

Body:
What I would do is read the data straight into a bytes.Buffer similar to the answer listed here:

https://stackoverflow.com/a/24343240/8092543

https://golang.org/pkg/io/#Copy

The beauty of the io.Copy is that it consumes a Writer + Reader interface, which are satisfied nicely but your bytes.Buffer (io.Writer) and your conn.Read (io.Reader). Replace your entire block with something like...

var buf bytes.Buffer
count, err := io.Copy(buf, conn)
if err != nil {
    return nil, fmt.Errorf("error during conn read: %v", err)
}

return buf.Bytes(), nil