问:
Rails Controller Spec. Wrong number of arguments
I'm trying to test my controller using RSpec but I'm getting the error below.

error

```<code>  1) Api::V1::UsersController GET #show responds with 200 status code
     Failure/Error: request.headers.merge!(auth_headers)

     ArgumentError:
       wrong number of arguments (given 0, expected 1..2)
     # ./spec/controllers/api/v1/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  2) Api::V1::UsersController GET #show returns the serialized user attributes
     Failure/Error: request.headers.merge!(auth_headers)

     ArgumentError:
       wrong number of arguments (given 0, expected 1..2)
     # ./spec/controllers/api/v1/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
</code>```

spec

```<code>require 'spec_helper'

describe Api::V1::UsersController, type: :api do

  describe 'GET #show' do
    before(:each) do
      @user = FactoryBot.create :user
      auth_headers = @user.create_new_auth_token
      request.headers.merge!(auth_headers)
      get :show, id: @user.id
    end

    it 'responds with 200 status code' do
      expect(response.code).to eq('200')
    end

    it 'returns the serialized user attributes' do
      expect(json['data']['attributes']).to eq({'name'=>'John Doe', 'email'=>'test@test.com'})
    end
  end

end
</code>```

spec_helper

```<code>require File.expand_path("../../config/environment", __FILE__)
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.include ApiHelper, type: :api
  config.include Requests::JsonHelpers, type: :api

  config.include FactoryBot::Syntax::Methods
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
end
</code>```

api_helper.rb

```<code>module ApiHelper
  include Rack::Test::Methods

  def app
    Rails.application
  end
end
</code>```

request_helper.rb

```<code>module Requests
  module JsonHelpers
    def json
      JSON.parse(last_response.body)
    end
  end
end
</code>```

答:
describe Api::V1::UsersController, type: :api

must be

describe Api::V1::UsersController, type: :controller

OR (and it will be more suitable for api test)

you can rewrite this

```<code>auth_headers = @user.create_new_auth_token
request.headers.merge!(auth_headers)
get :show, id: @user.id
</code>```

to this

```<code>auth_headers = { 'AUTHORIZATION' => "Token #{@user.create_new_auth_token}" }
get :show, { id: @user.id }, auth_headers
</code>```

Body:
I'm trying to test my controller using RSpec but I'm getting the error below.

error

  1) Api::V1::UsersController GET #show responds with 200 status code
     Failure/Error: request.headers.merge!(auth_headers)

     ArgumentError:
       wrong number of arguments (given 0, expected 1..2)
     # ./spec/controllers/api/v1/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  2) Api::V1::UsersController GET #show returns the serialized user attributes
     Failure/Error: request.headers.merge!(auth_headers)

     ArgumentError:
       wrong number of arguments (given 0, expected 1..2)
     # ./spec/controllers/api/v1/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

spec

require 'spec_helper'

describe Api::V1::UsersController, type: :api do

  describe 'GET #show' do
    before(:each) do
      @user = FactoryBot.create :user
      auth_headers = @user.create_new_auth_token
      request.headers.merge!(auth_headers)
      get :show, id: @user.id
    end

    it 'responds with 200 status code' do
      expect(response.code).to eq('200')
    end

    it 'returns the serialized user attributes' do
      expect(json['data']['attributes']).to eq({'name'=>'John Doe', 'email'=>'test@test.com'})
    end
  end

end

spec_helper

require File.expand_path("../../config/environment", __FILE__)
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.include ApiHelper, type: :api
  config.include Requests::JsonHelpers, type: :api

  config.include FactoryBot::Syntax::Methods
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
end

api_helper.rb

module ApiHelper
  include Rack::Test::Methods

  def app
    Rails.application
  end
end

request_helper.rb

module Requests
  module JsonHelpers
    def json
      JSON.parse(last_response.body)
    end
  end
end

Body:
describe Api::V1::UsersController, type: :api

must be

describe Api::V1::UsersController, type: :controller

OR (and it will be more suitable for api test)

you can rewrite this

auth_headers = @user.create_new_auth_token
request.headers.merge!(auth_headers)
get :show, id: @user.id

to this

auth_headers = { 'AUTHORIZATION' => "Token #{@user.create_new_auth_token}" }
get :show, { id: @user.id }, auth_headers


来源: stackexchange

问:
Google BigQuery: creating a view via Python google-cloud-bigquery version 0.27.0 vs. 0.28.0
All,

I'm having trouble creating a Google BigQuery view in python with the version 0.28 of the bq library that has come out about two weeks ago.  I'm quite certain the problem is on my side, something I'm missing, but I cannot find the issue.

Please be gentle, I don't ask lots of questions online but I'm quite stumped.
 I'm also not completely incompetent, here are some details:

I have my GOOGLE_APPLICATION_CREDENTIALS set correctly

All the other commands I've run against bq via python are fine

I've reviewed the
https://cloud.google.com/bigquery/docs/python-client-migration

I think the issue is around the "fix"
https://github.com/GoogleCloudPlatform/google-cloud-python/pull/4038
BigQuery: replaces table.create() with client.create_table() #4038

I've tried legacy vs. standard sql

I'm on python 2.7.12 (can't upgrade anytime soon, corporate version thing)

The issue?  The code in the second block below creates a TABLE, with no schema and no records.  It clearly should create a VIEW instead, right?

sudo pip install -Iv google-cloud-bigquery==0.27.0

```<code>from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data20'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(view_name)
table.view_query = sqlQuery

table.create()
</code>```

the above works fine, view created, great!

the below, only a table is created, no rows, no schema, yuck!

sudo pip uninstall google-cloud-bigquery

sudo pip install -Iv google-cloud-bigquery==0.28.0

```<code>from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data21'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_name)
table_ref = dataset_ref.table(view_name)
table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True

table = bigquery.Table(table_ref)
bigquery_client.create_table(table)
</code>```

Other links:

How can I create a new view in bigquery using the python API?

https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html

Any useful thoughts would be very much appreciated.

Thanks and best regards...Rich

答:
You were so close!

The issue is with the lines

```<code>table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True
</code>```

a TableReference class does not contain these properties. Instead, you must populate them on the Table class, as in

```<code>table = bigquery.Table(table_ref)
table.view_query = sqlQuery
table.view_use_legacy_sql = True

bigquery_client.create_table(table)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
All,

I'm having trouble creating a Google BigQuery view in python with the version 0.28 of the bq library that has come out about two weeks ago.  I'm quite certain the problem is on my side, something I'm missing, but I cannot find the issue.

Please be gentle, I don't ask lots of questions online but I'm quite stumped.
 I'm also not completely incompetent, here are some details:

I have my GOOGLE_APPLICATION_CREDENTIALS set correctly

All the other commands I've run against bq via python are fine

I've reviewed the
https://cloud.google.com/bigquery/docs/python-client-migration

I think the issue is around the "fix"
https://github.com/GoogleCloudPlatform/google-cloud-python/pull/4038
BigQuery: replaces table.create() with client.create_table() #4038

I've tried legacy vs. standard sql

I'm on python 2.7.12 (can't upgrade anytime soon, corporate version thing)

The issue?  The code in the second block below creates a TABLE, with no schema and no records.  It clearly should create a VIEW instead, right?

sudo pip install -Iv google-cloud-bigquery==0.27.0

from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data20'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(view_name)
table.view_query = sqlQuery

table.create()

the above works fine, view created, great!

the below, only a table is created, no rows, no schema, yuck!

sudo pip uninstall google-cloud-bigquery

sudo pip install -Iv google-cloud-bigquery==0.28.0

from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data21'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_name)
table_ref = dataset_ref.table(view_name)
table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True

table = bigquery.Table(table_ref)
bigquery_client.create_table(table)

Other links:

How can I create a new view in bigquery using the python API?

https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html

Any useful thoughts would be very much appreciated.

Thanks and best regards...Rich

Body:
You were so close!

The issue is with the lines

table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True

a TableReference class does not contain these properties. Instead, you must populate them on the Table class, as in

table = bigquery.Table(table_ref)
table.view_query = sqlQuery
table.view_use_legacy_sql = True

bigquery_client.create_table(table)


问:
Align swf to bottom of div, even if div is smaller than swf?
I had the idea to contain a swf of 270px in height inside a div that is 29px in height at the start. This div is going to be absolute positioned along the bottom of the page and the swf file in it's normal state will only take up 29px in height. It isn't until the user hovers over some pieces of the swf that it will take up a height of 270px. I was going to incorporate some java script to change the height of the div for when that happens. However the problem I am running into is that the swf file won't align to the bottom of the div. It always seems to align to the top despite the fact that I am putting in <param name="salign" value="lb" />, aka align left bottom. Is it not possible to fit a swf into a smaller div and have that swf align to the bottom vs being pushed down from the top?

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title>egnewsTicker</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style type="text/css" media="screen">
        html, body { height:100%; background-color: #ffffff;}
        body { margin:0; padding:0; overflow:hidden; }
        #flashContent { width:100%; height:29px; vertical-align:bottom; display:inline-block;}
        </style>
    </head>
    <body>
        <div id="flashContent">
            <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="100%" height="100%" id="egnewsTicker" align="bottom" vertical-align="bottom">
                <param name="movie" value="egnewsTicker.swf" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffffff" />
                <param name="play" value="true" />
                <param name="loop" value="true" />
                <param name="wmode" value="transparent" />
                <param name="scale" value="noscale" />
                <param name="menu" value="false" />
                <param name="devicefont" value="false" />
                <param name="salign" value="lb" />
                <param name="allowScriptAccess" value="sameDomain" />
                <!--[if !IE]>-->
                <object type="application/x-shockwave-flash" data="egnewsTicker.swf" width="100%" height="100%">
                    <param name="movie" value="egnewsTicker.swf" />
                    <param name="quality" value="high" />
                    <param name="bgcolor" value="#ffffff" />
                    <param name="play" value="true" />
                    <param name="loop" value="true" />
                    <param name="wmode" value="transparent" />
                    <param name="scale" value="noscale" />
                    <param name="menu" value="false" />
                    <param name="devicefont" value="false" />
                    <param name="salign" value="lb" />
                    <param name="allowScriptAccess" value="sameDomain" />
                <!--<![endif]-->
                    <a href="http://www.adobe.com/go/getflash">
                        <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
                    </a>
                <!--[if !IE]>-->
                </object>
                <!--<![endif]-->
            </object>
        </div>
    </body>
</html>
</code>```

答:
```<code><div id="wrapperDiv" style="text-align:bottom;border:1px solid black;display:inline-block">
<!-- text goes here -->
</div>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had the idea to contain a swf of 270px in height inside a div that is 29px in height at the start. This div is going to be absolute positioned along the bottom of the page and the swf file in it's normal state will only take up 29px in height. It isn't until the user hovers over some pieces of the swf that it will take up a height of 270px. I was going to incorporate some java script to change the height of the div for when that happens. However the problem I am running into is that the swf file won't align to the bottom of the div. It always seems to align to the top despite the fact that I am putting in <param name="salign" value="lb" />, aka align left bottom. Is it not possible to fit a swf into a smaller div and have that swf align to the bottom vs being pushed down from the top?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>egnewsTicker</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

            <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="100%" height="100%" id="egnewsTicker" align="bottom" vertical-align="bottom">
                <param name="movie" value="egnewsTicker.swf" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffffff" />
                <param name="play" value="true" />
                <param name="loop" value="true" />
                <param name="wmode" value="transparent" />
                <param name="scale" value="noscale" />
                <param name="menu" value="false" />
                <param name="devicefont" value="false" />
                <param name="salign" value="lb" />
                <param name="allowScriptAccess" value="sameDomain" />

                <object type="application/x-shockwave-flash" data="egnewsTicker.swf" width="100%" height="100%">
                    <param name="movie" value="egnewsTicker.swf" />
                    <param name="quality" value="high" />
                    <param name="bgcolor" value="#ffffff" />
                    <param name="play" value="true" />
                    <param name="loop" value="true" />
                    <param name="wmode" value="transparent" />
                    <param name="scale" value="noscale" />
                    <param name="menu" value="false" />
                    <param name="devicefont" value="false" />
                    <param name="salign" value="lb" />
                    <param name="allowScriptAccess" value="sameDomain" />

                </object>

            </object>


问:
How to populate values into a VBA array using the evaluate method and return them back to an Excel sheet?
I am trying to populate an array with the values from the VBA EVALUATE method.  Once the array is populated, then I want to populate a range of cells in an Excel worksheet with the values from the array.

I wrote a SUB to do what I want, however when I run this function, I get the following error:

Run-time error 9: Subscript out of range

So my question is: How do I correct my script to get max_min_date2 to run correctly? A screenshot of my data is upload here

```<code>Sub max_min_date2():

  'Define an array
  Dim values As Variant

  'Define the size of the array
  values = Range("L2:L1000").Value

    'Set up for loop'
    For i = 2 To 1000

     'Populate values in the array.
     values(i - 1) = Evaluate("=MAX(IF(A:A=" & Cells(i, 11).Address & ",B:B))")

     Next i

  'Populate Excel sheet with values in the array.
  Range("L2:L1000").Value = values

End Sub
</code>```

答:
It is my understanding that you want to display each ticker's maximum and minimum dates. I do not believe the formula you've been working on will work as expected. Here's an alternate route, via a Pivot Table; you'll get your results real quick.

Paste this code into a code module:

```<code>Option Explicit

Public Sub CreateMaxDateByTickerPivotTable(ByVal prngTopLeftDataCell As Excel.Range, ByVal prngPivotTableTopLeft As Excel.Range, ByVal psPivotTableName As String)
    Dim pt As Excel.PivotTable

    Set pt = Nothing
    On Error Resume Next
    Set pt = prngPivotTableTopLeft.Worksheet.PivotTables(psPivotTableName)
    On Error GoTo 0

    If Not pt Is Nothing Then
        pt.TableRange2.Clear
    End If

    With ThisWorkbook.PivotCaches.Create(xlDatabase, prngTopLeftDataCell.CurrentRegion)
        With .CreatePivotTable(prngPivotTableTopLeft, psPivotTableName)
            .ShowValuesRow = False
            .CompactLayoutRowHeader = "Ticker"

            .ColumnGrand = False
            .RowGrand = False

            With .PivotFields("<ticker>")
                .Orientation = xlRowField
                .Position = 1
            End With

            .AddDataField .PivotFields("<date>"), "Max Date", xlMax
            .AddDataField .PivotFields("<date>"), "Min Date", xlMin
        End With
    End With

    Set pt = Nothing
End Sub
</code>```

You can then call the sub above with a few parameters:

```<code>CreateMaxDateByTickerPivotTable Sheet1.Range("A1"), Sheet1.Range("K1"), "MaxDateByTicker"
</code>```

The sub simply builds a pivot table (deleting it if it already exists), lists the tickers down and finds the maximum and minimum dates available in the data set for each ticker.

Body:
I am trying to populate an array with the values from the VBA EVALUATE method.  Once the array is populated, then I want to populate a range of cells in an Excel worksheet with the values from the array.

I wrote a SUB to do what I want, however when I run this function, I get the following error:

Run-time error 9: Subscript out of range

So my question is: How do I correct my script to get max_min_date2 to run correctly? A screenshot of my data is upload here

Sub max_min_date2():

  'Define an array
  Dim values As Variant

  'Define the size of the array
  values = Range("L2:L1000").Value

    'Set up for loop'
    For i = 2 To 1000

     'Populate values in the array.
     values(i - 1) = Evaluate("=MAX(IF(A:A=" & Cells(i, 11).Address & ",B:B))")

     Next i

  'Populate Excel sheet with values in the array.
  Range("L2:L1000").Value = values

End Sub

Body:
It is my understanding that you want to display each ticker's maximum and minimum dates. I do not believe the formula you've been working on will work as expected. Here's an alternate route, via a Pivot Table; you'll get your results real quick.

Paste this code into a code module:

Option Explicit

Public Sub CreateMaxDateByTickerPivotTable(ByVal prngTopLeftDataCell As Excel.Range, ByVal prngPivotTableTopLeft As Excel.Range, ByVal psPivotTableName As String)
    Dim pt As Excel.PivotTable

    Set pt = Nothing
    On Error Resume Next
    Set pt = prngPivotTableTopLeft.Worksheet.PivotTables(psPivotTableName)
    On Error GoTo 0

    If Not pt Is Nothing Then
        pt.TableRange2.Clear
    End If

    With ThisWorkbook.PivotCaches.Create(xlDatabase, prngTopLeftDataCell.CurrentRegion)
        With .CreatePivotTable(prngPivotTableTopLeft, psPivotTableName)
            .ShowValuesRow = False
            .CompactLayoutRowHeader = "Ticker"

            .ColumnGrand = False
            .RowGrand = False

            With .PivotFields("<ticker>")
                .Orientation = xlRowField
                .Position = 1
            End With

            .AddDataField .PivotFields("<date>"), "Max Date", xlMax
            .AddDataField .PivotFields("<date>"), "Min Date", xlMin
        End With
    End With

    Set pt = Nothing
End Sub

You can then call the sub above with a few parameters:

CreateMaxDateByTickerPivotTable Sheet1.Range("A1"), Sheet1.Range("K1"), "MaxDateByTicker"

The sub simply builds a pivot table (deleting it if it already exists), lists the tickers down and finds the maximum and minimum dates available in the data set for each ticker.


问:
Instagram API Likes on Media does not have pagination
I am trying to return all the users who have liked a specific post in Instagram, but it seems to be only returning 120 of the users who have liked the image.

https://instagram.com/p/73rVHrnFqS/

There is no pagination object being returned by the query.  I don't see any limits mentioned in the documentation:

https://instagram.com/developer/endpoints/likes/

I was able to reproduce it using the Instagram API Console here:

Link to Instagram Query

Is it a permissions issue with users hiding their likes from the API, or does the API limit the number of likes returned.

答:
You can you Unofficial Instagram API to get a max of 1000 likers list via calling to instagram.com/media_id/likers by attaching proper headers in post-call.

You would be able to achieve top 1000 likers of media.


问:
Arduino Nano with ESP8266 problems
this is my first post here because I'm a bit lost at the moment.
I currently have my ESP8266-01 hocked up to the Nano like this:

The issue I'm having is that it won't even turn on, only when I'm using the 3.3V pin the red led on the ESP8266 turns on. If connected to 3.3V and I connect the CH_PD pin to 3.3V aswell, the blue led flashes 2-3 times and then the ESP8266 turns off.

I hope someone is able to help me

答:
Your fritzing diagram isn't the clearest. But from what I can interpret you need to do this for the ESP8266-

VCC should be connected to 3.3V
CH_PD should be connected or pulled to 3.3V
REST should be pulled to 3.3V. I see no mention of the REST pin so this is most likely the issue.

Title: Arduino Nano with ESP8266 problems


问:
Mongoose query for "hot" posts
I want to show a list of posts from the database based on likes and date, think of the basic "trending" items page.

I want to use a formula like score = likes / daysSinceCreation and then get the first 10 posts based on this score.

How can I add that sort function with mongoDB/Mongoose?

Posts.find().sort(???).limit(10).then(posts => console.log(posts));

Currently I can get top posts in last week (find if creation date larger than last week and order by score), but how can I implement a more complex sorting function without getting all the items from the DB?

eg:
Today is Friday

```<code>ID  CREATION_DAY    LIKES
 1  Monday          4     // score is 5/5 = 0
 2  Tuesday         10    // score is 10/4 = 2
 3  Wednesday       3     // score is 3/3 = 1
 4  Thursday        20    // score is 20/2 = 10
 5  Friday          5     // score is 5/1 = 5
</code>```

Sorted list of IDs is: [4 (Th), 5 (Fr), 2 (Tu), 3 (We), 1(Mo)]

答:
This will create a new document in a "trendingposts" table:

```<code>const fiveDaysAgo = new Date(Date.now() - (5 * 24 * 60 * 60 * 1000));
const oid = new ObjectId();
const now = new Date();

Posts.aggregate([
    {
        $match: {
            createdAt: {
                $gte: fiveDaysAgo
            },
            score: {
                $gt: 0
            }
        }
    },
    {
        $project: {
            _id: true,
            createdAt: true,
            updatedAt: true,
            title: true,
            description: true,
            score: true,
            trendScore: {
                $divide: [ "$score", {$subtract: [new Date(), "$createdAt"]} ]
            }
        }
    },
    {
        $sort: {
            trendScore: -1
        }
    },
    {
        $limit: 10
    },
    {
        $group: {
            _id: { $min: oid },
            evaluatedAt: { $min: now },
            posts: { $push: "$$ROOT"}
        }
    },
    {
        $out: "trendingposts"
    }
])
    .then(...)
</code>```

A few things to note:

If using Mongo 3.4+ the $project stage can also be written as:

```<code>{
    $addFields: {
        trendScore: {
            $divide: [ "$score", {$subtract: [new Date(), "$createdAt"]} ]
        }
    }
},
</code>```

{ $min: now } is just a hack to grab the minimum value of now on each document, even though it's the same value for all of them.

"$$ROOT" is the entire current document. This means your end result will be a single object with the form:

```<code>{
    "_id" : ObjectId("5a0a2fe912a325eb331f2759"),
    "evaluatedAt" : ISODate("2017-11-13T23:51:56.051Z"),
    "posts" : [/*10 `post` documents, sorted by trendScore */]
}
</code>```

You can then query with:

```<code>TrendingPosts.findOne({})
    .sort({_id: -1})
    .then(trendingPost => console.log(trendingPost));
</code>```

If your description/title are changing frequently, instead of $pushing the entire document in, you could just push the ids and use them for an $in query on your posts in order to guarantee the latest data.

Title: Mongoose query for "hot" posts

Body:
I want to show a list of posts from the database based on likes and date, think of the basic "trending" items page.

I want to use a formula like score = likes / daysSinceCreation and then get the first 10 posts based on this score.

How can I add that sort function with mongoDB/Mongoose?

Posts.find().sort(???).limit(10).then(posts => console.log(posts));

Currently I can get top posts in last week (find if creation date larger than last week and order by score), but how can I implement a more complex sorting function without getting all the items from the DB?

eg:
Today is Friday

ID  CREATION_DAY    LIKES
 1  Monday          4     // score is 5/5 = 0
 2  Tuesday         10    // score is 10/4 = 2
 3  Wednesday       3     // score is 3/3 = 1
 4  Thursday        20    // score is 20/2 = 10
 5  Friday          5     // score is 5/1 = 5

Sorted list of IDs is: [4 (Th), 5 (Fr), 2 (Tu), 3 (We), 1(Mo)]

Body:
This will create a new document in a "trendingposts" table:

const fiveDaysAgo = new Date(Date.now() - (5 * 24 * 60 * 60 * 1000));
const oid = new ObjectId();
const now = new Date();

Posts.aggregate([
    {
        $match: {
            createdAt: {
                $gte: fiveDaysAgo
            },
            score: {
                $gt: 0
            }
        }
    },
    {
        $project: {
            _id: true,
            createdAt: true,
            updatedAt: true,
            title: true,
            description: true,
            score: true,
            trendScore: {
                $divide: [ "$score", {$subtract: [new Date(), "$createdAt"]} ]
            }
        }
    },
    {
        $sort: {
            trendScore: -1
        }
    },
    {
        $limit: 10
    },
    {
        $group: {
            _id: { $min: oid },
            evaluatedAt: { $min: now },
            posts: { $push: "$$ROOT"}
        }
    },
    {
        $out: "trendingposts"
    }
])
    .then(...)

A few things to note:

If using Mongo 3.4+ the $project stage can also be written as:

{
    $addFields: {
        trendScore: {
            $divide: [ "$score", {$subtract: [new Date(), "$createdAt"]} ]
        }
    }
},

{ $min: now } is just a hack to grab the minimum value of now on each document, even though it's the same value for all of them.

"$$ROOT" is the entire current document. This means your end result will be a single object with the form:

{
    "_id" : ObjectId("5a0a2fe912a325eb331f2759"),
    "evaluatedAt" : ISODate("2017-11-13T23:51:56.051Z"),
    "posts" : [/*10 `post` documents, sorted by trendScore */]
}

You can then query with:

TrendingPosts.findOne({})
    .sort({_id: -1})
    .then(trendingPost => console.log(trendingPost));

If your description/title are changing frequently, instead of $pushing the entire document in, you could just push the ids and use them for an $in query on your posts in order to guarantee the latest data.


问:
How to use SUMIF if criteria contains a ">" symbol?
So I tried using the SUMIF formula as follows:

```<code>=SUMIF(A1:A10, ">30D", B1:B10)
</code>```

Within my criteria range, there are instances of '>30D' occurring as a value. For instance, my data would look like this:

```<code>A        B
>30D     200
0-7D     100
8-14D    200
15D-29D  300
>30D     400
</code>```

And I would like the formula to return 600. However, in the above formula, I'm getting the wrong values (double checked with a pivot table). I think this is because Excel is is interpreting ">30D" as an expression instead of a value. I've also tried referencing the cell itself with:

```<code>=SUMIF(A1:A10, $A$1, B1:B10)
</code>```

This doesn't work either. Help would be much appreciated!

Body:
So I tried using the SUMIF formula as follows:

=SUMIF(A1:A10, ">30D", B1:B10)

Within my criteria range, there are instances of '>30D' occurring as a value. For instance, my data would look like this:

A        B
>30D     200
0-7D     100
8-14D    200
15D-29D  300
>30D     400

And I would like the formula to return 600. However, in the above formula, I'm getting the wrong values (double checked with a pivot table). I think this is because Excel is is interpreting ">30D" as an expression instead of a value. I've also tried referencing the cell itself with:

=SUMIF(A1:A10, $A$1, B1:B10)

This doesn't work either. Help would be much appreciated!

Body:
Consider:

=SUMPRODUCT(--(LEFT(A1:A5,1)=">")*(B1:B5))


问:
Use the same makefile for make (Linux) and nmake (Windows)
I have a simple C program (one source file) which I want to compile on Linux and on Windows via make and nmake, respectively. Is there a possibility to accomplish this with a single makefile?

I thought about something like

```<code>ifeq($(MAKE), nmake)
    // nmake code here
else
    // make code here
endif
</code>```

Unfortunately nmake seems not to understand ifeq, so I cannot use that. I have a working makefile, but that produces very ugly results:

```<code>hello: hello.c
    $(CC) hello.c
</code>```

That works on both systems. The problem is that the outcome depends on the default behaviors of the respective compilers. Under Linux I get an executeable named 'a.out' rather than 'hello'. Under Windows I get 'hello.exe' but there is also 'hello.obj' which I do not want to have.

Is there an alternative way? Or is what I'm trying absolutely impossible?

答:
I am not able to find a way to use a common makefile to work for both GNU Make and Microsoft NMAKE, mainly because they have an incompatible syntax for "include" and/or "if" directives. Microsoft NMAKE requires to use ! prefix for directives. For example, !if, !include, etc...

If it is allowed to have separate macros, however, it could be tricked around. Here I presents the best way I found so far for making a makefile compatible for both GNU Make and Microsoft NMAKE by observing the followings:

Microsoft NMAKE reads TOOLS.ini file for default macros.

The Microsoft suite uses .obj as the object file extension.

GNU Make reads files defined in a MAKEFILES environment variable.

The GNU suite use .o as the object file extension.

GNU make need not give an executable extension .exe for a target.

Note: The following has been tested using Microsoft Visual Studio 2015 and MINGW32.

Step 1: create a following DOS batch file and let it run whenever the CMD prompt is invoked.

```<code>set MAKEFILES=TOOLS.gcc
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
</code>```

Step 2: Create a TOOLS.ini file under your working directory as below: (this file is independent of your project dependencies except the libraries possibly)

```<code>[NMAKE]
LDLIBS  =
CDEBUG  = /Zi
LDEBUG  = /debug:full
WDFLAGS = /wd4996 /wd4774 /wd4018 /wd4710 /wd4820
CFLAGS  = /nologo $(CDEBUG) /EHsc /Wall $(WDFLAGS)
LDFLAGS = /nologo $(LDEBUG)
RM      = del /F /Q
LINK     = "$(VCINSTALLDIR)bin\link" $(LDFLAGS)
CP    = copy
CC    = cl
CPP = $(CC) /P
X    = .exe
O    = .obj

.obj.exe:
    $(LINK) $** $(LOADLIBES) $(LDLIBS) /Out:$@
</code>```

Step 3: Create a TOOLS.gcc under your working directory as below: (this file is independent of your project dependencies except the libraries possibly)

```<code>LD_LIBS =
LDLIBS  =
CDEBUG  = -g
LDEBUG  = -g
CFLAGS  = $(CDEBUG)
LDFLAGS = $(LDEBUG)
RM      = rm -f
LINK     = gcc $(LDFLAGS)
CP        = cp
CC        = gcc
CPP     = $(CC) -E
X        =
O        = .o

%: %.o
    $(LINK) $^ $(LOADLIBES) $(LDLIBS) -o $@
</code>```

Step 4: Edit your makefile as below (note $(X) and $(O)) where only dependencies are specified.

```<code>SHELL    = /usr/bin/sh
app: app1$(X) app2$(X)
app1$(X): app1$(O)
app2$(X): app2$(O)

clean:
    $(RM) *.exe *.o *.obj *.ilk *.pdb *.tmp *.i *~
</code>```

Step 5: Enjoy GNU Make and Microsoft NMAKE with the same makefile

```<code>$ nmake
$ make clean
$ nmake clean
$ make
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple C program (one source file) which I want to compile on Linux and on Windows via make and nmake, respectively. Is there a possibility to accomplish this with a single makefile?

I thought about something like

ifeq($(MAKE), nmake)
    // nmake code here
else
    // make code here
endif

Unfortunately nmake seems not to understand ifeq, so I cannot use that. I have a working makefile, but that produces very ugly results:

hello: hello.c
    $(CC) hello.c

That works on both systems. The problem is that the outcome depends on the default behaviors of the respective compilers. Under Linux I get an executeable named 'a.out' rather than 'hello'. Under Windows I get 'hello.exe' but there is also 'hello.obj' which I do not want to have.

Is there an alternative way? Or is what I'm trying absolutely impossible?

Body:
I am not able to find a way to use a common makefile to work for both GNU Make and Microsoft NMAKE, mainly because they have an incompatible syntax for "include" and/or "if" directives. Microsoft NMAKE requires to use ! prefix for directives. For example, !if, !include, etc...

If it is allowed to have separate macros, however, it could be tricked around. Here I presents the best way I found so far for making a makefile compatible for both GNU Make and Microsoft NMAKE by observing the followings:

Microsoft NMAKE reads TOOLS.ini file for default macros.

The Microsoft suite uses .obj as the object file extension.

GNU Make reads files defined in a MAKEFILES environment variable.

The GNU suite use .o as the object file extension.

GNU make need not give an executable extension .exe for a target.

Note: The following has been tested using Microsoft Visual Studio 2015 and MINGW32.

Step 1: create a following DOS batch file and let it run whenever the CMD prompt is invoked.

set MAKEFILES=TOOLS.gcc
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"

Step 2: Create a TOOLS.ini file under your working directory as below: (this file is independent of your project dependencies except the libraries possibly)

[NMAKE]
LDLIBS  =
CDEBUG  = /Zi
LDEBUG  = /debug:full
WDFLAGS = /wd4996 /wd4774 /wd4018 /wd4710 /wd4820
CFLAGS  = /nologo $(CDEBUG) /EHsc /Wall $(WDFLAGS)
LDFLAGS = /nologo $(LDEBUG)
RM      = del /F /Q
LINK     = "$(VCINSTALLDIR)bin\link" $(LDFLAGS)
CP    = copy
CC    = cl
CPP = $(CC) /P
X    = .exe
O    = .obj

.obj.exe:
    $(LINK) $** $(LOADLIBES) $(LDLIBS) /Out:$@

Step 3: Create a TOOLS.gcc under your working directory as below: (this file is independent of your project dependencies except the libraries possibly)

LD_LIBS =
LDLIBS  =
CDEBUG  = -g
LDEBUG  = -g
CFLAGS  = $(CDEBUG)
LDFLAGS = $(LDEBUG)
RM      = rm -f
LINK     = gcc $(LDFLAGS)
CP        = cp
CC        = gcc
CPP     = $(CC) -E
X        =
O        = .o

%: %.o
    $(LINK) $^ $(LOADLIBES) $(LDLIBS) -o $@

Step 4: Edit your makefile as below (note $(X) and $(O)) where only dependencies are specified.

SHELL    = /usr/bin/sh
app: app1$(X) app2$(X)
app1$(X): app1$(O)
app2$(X): app2$(O)

clean:
    $(RM) *.exe *.o *.obj *.ilk *.pdb *.tmp *.i *~

Step 5: Enjoy GNU Make and Microsoft NMAKE with the same makefile

$ nmake
$ make clean
$ nmake clean
$ make


问:
Rerender view on browser resize with React
How can I get React to re-render the view when the browser window is resized?

Background

I have some blocks that I want to layout individually on the page, however I also want them to update when the browser window changes. The very end result will be something like Ben Holland's Pinterest layout, but written using React not just jQuery. I’m still a way off.

Code

Here’s my app:

```<code>var MyApp = React.createClass({
  //does the http get from the server
  loadBlocksFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      mimeType: 'textPlain',
      success: function(data) {
        this.setState({data: data.events});
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentWillMount: function() {
    this.loadBlocksFromServer();

  },
  render: function() {
    return (
        <div>
      <Blocks data={this.state.data}/>
      </div>
    );
  }
});

React.renderComponent(
  <MyApp url="url_here"/>,
  document.getElementById('view')
)
</code>```

Then I have the Block component (equivalent to a Pin in the above Pinterest example):

```<code>var Block = React.createClass({
  render: function() {
    return (
        <div class="dp-block" style={{left: this.props.top, top: this.props.left}}>
        <h2>{this.props.title}</h2>
        <p>{this.props.children}</p>
        </div>
    );
  }
});
</code>```

and the list/collection of Blocks:

```<code>var Blocks = React.createClass({

  render: function() {

    //I've temporarily got code that assigns a random position
    //See inside the function below...

    var blockNodes = this.props.data.map(function (block) {
      //temporary random position
      var topOffset = Math.random() * $(window).width() + 'px';
      var leftOffset = Math.random() * $(window).height() + 'px';
      return <Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}>{block.description}</Block>;
    });

    return (
        <div>{blockNodes}</div>
    );
  }
});
</code>```

Question

Should I add jQuery’s window resize? If so, where?

```<code>$( window ).resize(function() {
  // re-render the component
});
</code>```

Is there a more “React” way of doing this?

答:
You don't necessarily need to force a re-render.

This might not help OP, but in my case I only needed to update the width and height attributes on my canvas (which you can't do with CSS).

It looks like this:

```<code>import React from 'react';
import styled from 'styled-components';
import {throttle} from 'lodash';

class Canvas extends React.Component {

    componentDidMount() {
        window.addEventListener('resize', this.resize);
        this.resize();
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.resize);
    }

    resize = throttle(() => {
        this.canvas.width = this.canvas.parentNode.clientWidth;
        this.canvas.height = this.canvas.parentNode.clientHeight;
    },50)

    setRef = node => {
        this.canvas = node;
    }

    render() {
        return <canvas className={this.props.className} ref={this.setRef} />;
    }
}

export default styled(Canvas)`
   cursor: crosshair;
`
</code>```

Body:
How can I get React to re-render the view when the browser window is resized?

Background

I have some blocks that I want to layout individually on the page, however I also want them to update when the browser window changes. The very end result will be something like Ben Holland's Pinterest layout, but written using React not just jQuery. I’m still a way off.

Code

Here’s my app:

var MyApp = React.createClass({
  //does the http get from the server
  loadBlocksFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      mimeType: 'textPlain',
      success: function(data) {
        this.setState({data: data.events});
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentWillMount: function() {
    this.loadBlocksFromServer();

  },
  render: function() {
    return (

      <Blocks data={this.state.data}/>

    );
  }
});

React.renderComponent(
  <MyApp url="url_here"/>,
  document.getElementById('view')
)

Then I have the Block component (equivalent to a Pin in the above Pinterest example):

var Block = React.createClass({
  render: function() {
    return (

{this.props.title}

{this.props.children}

    );
  }
});

and the list/collection of Blocks:

var Blocks = React.createClass({

  render: function() {

    //I've temporarily got code that assigns a random position
    //See inside the function below...

    var blockNodes = this.props.data.map(function (block) {
      //temporary random position
      var topOffset = Math.random() * $(window).width() + 'px';
      var leftOffset = Math.random() * $(window).height() + 'px';
      return <Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}>{block.description}</Block>;
    });

    return (

{blockNodes}

    );
  }
});

Question

Should I add jQuery’s window resize? If so, where?

$( window ).resize(function() {
  // re-render the component
});

Is there a more “React” way of doing this?

Body:
You don't necessarily need to force a re-render.

This might not help OP, but in my case I only needed to update the width and height attributes on my canvas (which you can't do with CSS).

It looks like this:

import React from 'react';
import styled from 'styled-components';
import {throttle} from 'lodash';

class Canvas extends React.Component {

    componentDidMount() {
        window.addEventListener('resize', this.resize);
        this.resize();
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.resize);
    }

    resize = throttle(() => {
        this.canvas.width = this.canvas.parentNode.clientWidth;
        this.canvas.height = this.canvas.parentNode.clientHeight;
    },50)

    setRef = node => {
        this.canvas = node;
    }

    render() {
        return <canvas className={this.props.className} ref={this.setRef} />;
    }
}

export default styled(Canvas)`
   cursor: crosshair;
`


问:
How Should I Set Default Python Version In Windows?
I installed Python 2.6 and Python 3.1 on Windows 7 and set environment variable: path = d:\python2.6.

When I run python in cmd, it displays the python version 2.6, which is what I want!

But, when I wrote a script in a bat file and ran it, the displayed python version was 3.1.

```<code>import sys
print (sys.version)
</code>```

What's going on here?

答:
This worked for me:

Go to

```<code>Control Panel\System and Security\System
</code>```

select

```<code>Advanced system settings from the left panel
from Advanced tab click on Environment Variables
</code>```

In the System variables section search for (create if doesn't exist)

```<code>PYTHONPATH
</code>```

and set

```<code>C:\Python27\;C:\Python27\Scripts;
</code>```

or your desired version

You need to restart CMD.

In case it still doesn't work you might want to leave in the PATH variable only your desired version.

Body:
I installed Python 2.6 and Python 3.1 on Windows 7 and set environment variable: path = d:\python2.6.

When I run python in cmd, it displays the python version 2.6, which is what I want!

But, when I wrote a script in a bat file and ran it, the displayed python version was 3.1.

import sys
print (sys.version)

What's going on here?

Body:
This worked for me:

Go to

Control Panel\System and Security\System

select

Advanced system settings from the left panel
from Advanced tab click on Environment Variables

In the System variables section search for (create if doesn't exist)

PYTHONPATH

and set

C:\Python27\;C:\Python27\Scripts;

or your desired version

You need to restart CMD.

In case it still doesn't work you might want to leave in the PATH variable only your desired version.


问:
How find specific data value from html tag in BeautifulSoup4?
I have a following html and I need to extract TOWN GMBH.

```<code><span class="font-semibold" data-qa="companyName">TOWN GMBH</span>
</code>```

I could do following:

```<code>bs = BeautifulSoup('<span class="font-semibold" data-qa="companyName">TOWN GMBH</span>', "html5lib")

bs.find(class_='font-semibold').contents
</code>```

But font-semibold is not unique, and there are several of them on the page. How can I specifically address html where data-qa="companyName" ?

答:
You can either a dictionary of attributes to be used for filtering:

```<code>bs.find(attrs={'class': 'font-semibold', 'data-qa': 'companyName'})
</code>```

Or, use a more concise CSS selector:

```<code>bs.select_one('.font-semibold[data-qa=companyName]')
</code>```

And, to get the text, I'd use .get_text() method instead of using .contents.

Body:
I have a following html and I need to extract TOWN GMBH.

TOWN GMBH

I could do following:

bs = BeautifulSoup('TOWN GMBH', "html5lib")

bs.find(class_='font-semibold').contents

But font-semibold is not unique, and there are several of them on the page. How can I specifically address html where data-qa="companyName" ?

Body:
You can either a dictionary of attributes to be used for filtering:

bs.find(attrs={'class': 'font-semibold', 'data-qa': 'companyName'})

Or, use a more concise CSS selector:

bs.select_one('.font-semibold[data-qa=companyName]')

And, to get the text, I'd use .get_text() method instead of using .contents.


问:
Wheredoesnthave relation in Laravel
I've a problem doing a query using Eloquent/Laravel.

This is my model:
A request has ZERO or multiple offers. An offer can be hide (it's an attribute set on the offer).

What I need to do is to retrieve all requests that either have or don't have offers. BUT, if there's an offer associated, the offer needs to have the attribute hide=false.

I've tried the following, but doesn't seem to work.

```<code>$requests = Request::whereDoesntHave('offers', function ($query) use ($hideStatus) {
   $query->where('hide', true);
})->get();
</code>```

I think it's returning to me only requests that don't have offers at all.

Any idea?

FYI, I've Laravel 5.4

Any help would be greatly appreciated!

Thanks

答:
Thanks all for your replies. "orDoesntHave" does not work. It seems instead that the following works:</p>

```<code>$requests = Request::whereHas('offers', function ($query) {
                $query->where('hide', false);
            })
            ->doesntHave('offers', 'or')
            ->get();
</code>```

Title: Wheredoesnthave relation in Laravel

Body:
I've a problem doing a query using Eloquent/Laravel.

This is my model:
A request has ZERO or multiple offers. An offer can be hide (it's an attribute set on the offer).

What I need to do is to retrieve all requests that either have or don't have offers. BUT, if there's an offer associated, the offer needs to have the attribute hide=false.

I've tried the following, but doesn't seem to work.

$requests = Request::whereDoesntHave('offers', function ($query) use ($hideStatus) {
   $query->where('hide', true);
})->get();

I think it's returning to me only requests that don't have offers at all.

Any idea?

FYI, I've Laravel 5.4

Any help would be greatly appreciated!

Thanks

Body:
Thanks all for your replies. "orDoesntHave" does not work. It seems instead that the following works:

$requests = Request::whereHas('offers', function ($query) {
                $query->where('hide', false);
            })
            ->doesntHave('offers', 'or')
            ->get();


问:
Git commit to Dropbox repository issues
I'm trying to work on a project with some team members and we are using git as our source control. Our central repository is on Dropbox, which we all have access to.

I'm new to git, but I found some instructions on here to help get it all set up. For me it's working but for my team mates when they try to commit/push it doesn't update the file.
Here's the steps we've followed:

I did this:

```<code>~/project $ git init
~/project $ git add .
~/project $ git commit -m "first commit"
~/project $ cd ~/Dropbox/git

~/Dropbox/git $ mkdir source.git
~/Dropbox/git $ cd source.git
~/Dropbox/git $ git init --bare
~/Dropbox/git $ cd ~/project

~/project $ git remote add origin ~/Dropbox/git/source.git
~/project $ git push origin master
</code>```

Then on my computer I created test.txt, put some stuff in it, did:

```<code>~/project $ git add .
~/project $ git commit -m "second commit"
~/project $ git push
</code>```

The changes got put from my computer to the Dropbox repository.

Now I told my friends to do this:

```<code>~/Desktop $ cd ~/project
~/project $ git clone -o dropbox ~/Dropbox/project/source.git
</code>```

Then they got all the files on their computer, but when they update test.txt, commit and push, the Dropbox test.txt file isn't updated. The .git files are updated to show the new commit, but the repository's test.txt file doesn't show any changes.

What are we doing wrong?
Thanks!

答:
You are doing nothing wrong, that is just, how git works.  The repository (basically the .git) directory and the working copy (the files you edit) are two different things. push only updates the repository, but not the working copy.  The working copy is for good reasons never updated automatically (image, you'd loose your work, just because your co-worker pushed to your repository).

Read the Git documentation about hooks, to install a post-receive hook, which updates the working copy.

Title: Git commit to Dropbox repository issues

Body:
I'm trying to work on a project with some team members and we are using git as our source control. Our central repository is on Dropbox, which we all have access to.

I'm new to git, but I found some instructions on here to help get it all set up. For me it's working but for my team mates when they try to commit/push it doesn't update the file.
Here's the steps we've followed:

I did this:

~/project $ git init
~/project $ git add .
~/project $ git commit -m "first commit"
~/project $ cd ~/Dropbox/git

~/Dropbox/git $ mkdir source.git
~/Dropbox/git $ cd source.git
~/Dropbox/git $ git init --bare
~/Dropbox/git $ cd ~/project

~/project $ git remote add origin ~/Dropbox/git/source.git
~/project $ git push origin master

Then on my computer I created test.txt, put some stuff in it, did:

~/project $ git add .
~/project $ git commit -m "second commit"
~/project $ git push

The changes got put from my computer to the Dropbox repository.

Now I told my friends to do this:

~/Desktop $ cd ~/project
~/project $ git clone -o dropbox ~/Dropbox/project/source.git

Then they got all the files on their computer, but when they update test.txt, commit and push, the Dropbox test.txt file isn't updated. The .git files are updated to show the new commit, but the repository's test.txt file doesn't show any changes.

What are we doing wrong?
Thanks!


问:
Set Firefox profile to download files automatically using Selenium and Java
I want to verify file download using Selenium WebDriver and Java. The file to download is of PDF format. When WebDriver clicks on "Download" link in the AUT, Firefox opens up the following download confirmation window:

I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:

```<code>FirefoxProfile firefoxProfile=new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir",downloadPath);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf");
WebDriver driver=new FirefoxDriver(firefoxProfile);
</code>```

but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?

答:
The way it currently works in Firefox 57.0b13 is

```<code>FirefoxProfile profile = new FirefoxProfile();
// profile.setPreference("browser.download.useDownloadDir", true); This is true by default. Add it if it's not working without it.

profile.setPreference("browser.download.folderList",2); //Use for the default download directory the last folder specified for a download
profile.setPreference("browser.download.dir", "/Path/to/directory"); //Set the last directory used for saving a file from the "What should (browser) do with this file?" dialog.
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf"); //list of MIME types to save to disk without asking what to use to open the file
profile.setPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer

firefoxOptions.setProfile(profile);
</code>```

Detailed info about each Firefox profile setting

Body:
I want to verify file download using Selenium WebDriver and Java. The file to download is of PDF format. When WebDriver clicks on "Download" link in the AUT, Firefox opens up the following download confirmation window:

I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:

FirefoxProfile firefoxProfile=new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir",downloadPath);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf");
WebDriver driver=new FirefoxDriver(firefoxProfile);

but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?

Body:
The way it currently works in Firefox 57.0b13 is

FirefoxProfile profile = new FirefoxProfile();
// profile.setPreference("browser.download.useDownloadDir", true); This is true by default. Add it if it's not working without it.

profile.setPreference("browser.download.folderList",2); //Use for the default download directory the last folder specified for a download
profile.setPreference("browser.download.dir", "/Path/to/directory"); //Set the last directory used for saving a file from the "What should (browser) do with this file?" dialog.
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf"); //list of MIME types to save to disk without asking what to use to open the file
profile.setPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer

firefoxOptions.setProfile(profile);

Detailed info about each Firefox profile setting


问:
c# Regex pattern does not find any matches
I am using this code to find the state in a text file -

```<code>string pattern = @"Lender:\s(?'name'\w.*)\n\n(?'address'\w.*),\s(?'state'\w\w)";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = rgx.Matches(fileContents);
if (matches.Count > 0)
{
    return isStateAbbreviation(matches[0].Groups["state"].Value.Trim()) ? matches[0].Groups["state"].Value.Trim() : null;
}
</code>```

This is my sample string -

```<code>Lender: Monetary Management of California, Inc. d/b/a Money Mart

6311 DEBARR RD UNIT #U ANCHORAGE, AK 99504 907-644-0552
</code>```

The problem is that I count is always 0 but when I use an Online regex tester, it finds all the groups identified.  What is wrong with my Regex pattern?

答:
I think it is probable that your file contains \r\n and not \n at the end of each line since that is the standard for Windows.

Change your pattern to:

```<code>string pattern = @"Lender:\s(?'name'\w.*)\r\n\r\n(?'address'\w.*),\s(?'state'\w\w)";
</code>```

Body:
I am using this code to find the state in a text file -

string pattern = @"Lender:\s(?'name'\w.*)\n\n(?'address'\w.*),\s(?'state'\w\w)";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = rgx.Matches(fileContents);
if (matches.Count > 0)
{
    return isStateAbbreviation(matches[0].Groups["state"].Value.Trim()) ? matches[0].Groups["state"].Value.Trim() : null;
}

This is my sample string -

Lender: Monetary Management of California, Inc. d/b/a Money Mart

6311 DEBARR RD UNIT #U ANCHORAGE, AK 99504 907-644-0552

The problem is that I count is always 0 but when I use an Online regex tester, it finds all the groups identified.  What is wrong with my Regex pattern?

Body:
I think it is probable that your file contains \r\n and not \n at the end of each line since that is the standard for Windows.

Change your pattern to:

string pattern = @"Lender:\s(?'name'\w.*)\r\n\r\n(?'address'\w.*),\s(?'state'\w\w)";


问:
search slide and get page element text
My script searches one specific slide in a presentation. Then it gets the text from the first page element. This page element is a shape with only one word. After this, when I put strings before and after this page element text, there is a break in the text.

```<code>function readShapeText() {
   var presentation = SlidesApp.getActivePresentation();
   var slides = presentation.getSlides();

   for (i = 0; i < slides.length; i++) {

       if(slides[i].getObjectId() == 'mySlideId'){

         var pageElement = slides[i].getPageElements()[0].asShape().getText().asString();

       }
   }

   var myModifiedElement = "My_" + pageElement + "_is_cool";
}
</code>```

The output is with a break, but I need in one line:

My_TestElement

_is_cool

How can I eliminate or suppress the break? And is there a better way to find a specific slide without using "for loop" f.e. like presentation.openSlideById(xxxxxx)?

答:
How about these answers?

Q1: How can I eliminate or suppress the break?

It seems that the end of texts is always given \n. This can be also seen from values retrieved by Slides.Presentations.get(). So if you want to retrieve the values without \n, you can do it using replace("\n", "").

Q2: Is there a better way to find a specific slide without using "for loop" f.e. like presentation.openSlideById(xxxxxx)?

How about the following sample script? It retrieved the specific slide using filter(), because the key of objectId is included in the array. And replace("\n", "") was also used.

```<code>function readShapeText() {
  var mySlideId = "mySlideId"; // Please input this.
  var presentation = SlidesApp.getActivePresentation();
  var slides = presentation.getSlides();
  var slide = slides.filter(function(e){return e.getObjectId() == mySlideId})[0];
  var pageElement = slide.getPageElements()[0].asShape().getText().asString().replace("\n", "");
  var myModifiedElement = "My_" + pageElement + "_is_cool";
  Logger.log(myModifiedElement)
}
</code>```

If I misunderstand your question, I'm sorry.

Title: search slide and get page element text

Body:
My script searches one specific slide in a presentation. Then it gets the text from the first page element. This page element is a shape with only one word. After this, when I put strings before and after this page element text, there is a break in the text.

function readShapeText() {
   var presentation = SlidesApp.getActivePresentation();
   var slides = presentation.getSlides();

   for (i = 0; i < slides.length; i++) {

       if(slides[i].getObjectId() == 'mySlideId'){

         var pageElement = slides[i].getPageElements()[0].asShape().getText().asString();

       }
   }

   var myModifiedElement = "My_" + pageElement + "_is_cool";
}

The output is with a break, but I need in one line:

My_TestElement

_is_cool

How can I eliminate or suppress the break? And is there a better way to find a specific slide without using "for loop" f.e. like presentation.openSlideById(xxxxxx)?

Body:
How about these answers?

Q1: How can I eliminate or suppress the break?

It seems that the end of texts is always given \n. This can be also seen from values retrieved by Slides.Presentations.get(). So if you want to retrieve the values without \n, you can do it using replace("\n", "").

Q2: Is there a better way to find a specific slide without using "for loop" f.e. like presentation.openSlideById(xxxxxx)?

How about the following sample script? It retrieved the specific slide using filter(), because the key of objectId is included in the array. And replace("\n", "") was also used.

function readShapeText() {
  var mySlideId = "mySlideId"; // Please input this.
  var presentation = SlidesApp.getActivePresentation();
  var slides = presentation.getSlides();
  var slide = slides.filter(function(e){return e.getObjectId() == mySlideId})[0];
  var pageElement = slide.getPageElements()[0].asShape().getText().asString().replace("\n", "");
  var myModifiedElement = "My_" + pageElement + "_is_cool";
  Logger.log(myModifiedElement)
}

If I misunderstand your question, I'm sorry.


问:
Render react component with twig conditions
I have backend app in Symfony 3 and I would like process front-end which react. I have two components and I use twig if/else condition to decide witch one will be render

```<code>{% if some_condition %}
    <div id="compA"></div>
{% else %}
    <div id="compB"></div>
{% endif %}
</code>```

If/Else working well and components are rendering well too, but every time only one of them... This one which is on first place in index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Login from './components/compA';
import Logout from './components/compB';
ReactDOM.render(<compA/>, document.getElementById('compA'));
ReactDOM.render(<compB/>, document.getElementById('compB'));
</code>```

In this case if "some_conditon" true it renders compA, and if "some_conditon" false nothing happens if I switch last two rows (RenderDOM) CompA nothing happens and CompB working well... And if I do

```<code><div id="compA"></div>
<div id="compB"></div>
</code>```

Both components are render. Some idea??

答:
Here is what is happening:

On the server, Twig PHP evaluates the expression

Either

 or

 gets generated onto HTML DOM, but not both.

The server sends the HTML + JS (React) to the browser

In the browser, the JS tries to do rendering on both #compA and #compB DOM elements.

One of the elements is missing, so there will be an error. If the first one is missing, the JS breaks and the second one does not render.

In index.js, try:

```<code>if (document.getElementById('compA')) {
    ReactDOM.render(<compA/>, document.getElementById('compA'));
}

if (document.getElementById('compB')) {
    ReactDOM.render(<compB/>, document.getElementById('compB'));
}
</code>```

Body:
I have backend app in Symfony 3 and I would like process front-end which react. I have two components and I use twig if/else condition to decide witch one will be render

{% if some_condition %}

{% else %}

{% endif %}

If/Else working well and components are rendering well too, but every time only one of them... This one which is on first place in index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Login from './components/compA';
import Logout from './components/compB';
ReactDOM.render(<compA/>, document.getElementById('compA'));
ReactDOM.render(<compB/>, document.getElementById('compB'));

In this case if "some_conditon" true it renders compA, and if "some_conditon" false nothing happens if I switch last two rows (RenderDOM) CompA nothing happens and CompB working well... And if I do

Both components are render. Some idea??

Body:
Here is what is happening:

On the server, Twig PHP evaluates the expression

Either <div id="compA"></div> or <div id="compB"></div> gets generated onto HTML DOM, but not both.

The server sends the HTML + JS (React) to the browser

In the browser, the JS tries to do rendering on both #compA and #compB DOM elements.

One of the elements is missing, so there will be an error. If the first one is missing, the JS breaks and the second one does not render.

In index.js, try:

if (document.getElementById('compA')) {
    ReactDOM.render(<compA/>, document.getElementById('compA'));
}

if (document.getElementById('compB')) {
    ReactDOM.render(<compB/>, document.getElementById('compB'));
}


问:
StringIndexOutOfBoundsException while trying to encrypt a read file, and write the encrypted phrase to a different file
I'm trying to code a program that will read in text from a file that the user specifies, will then encrypt the text using the Caesar Cipher, and finally write the encrypted phrase to a different file. I'll also want to eventually have it do the reverse, where it reads encrypted text and decrypts it, but one step at a time.

```<code>package CaeserCipher1;

import java.util.Scanner;
import java.io.*;

public class CaeserCipher1 {
public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWYZ";

//Method to pull the plaintext of a file, followed by how far you want to shift plaintext to the right.
public static String encrypt(String plainText, int shiftKey) {
    String cipherText ="";
    for (int i = 0; i < plainText.length(); i++) {
        int charPosition = ALPHABET.indexOf(plainText.charAt(i));
        int keyVal = (shiftKey + charPosition) % 26;
        char replaceVal = ALPHABET.charAt(keyVal);
        cipherText += replaceVal;
    }
    return cipherText;
}
    //Method to pull the encrypted text of a file, followed by how far you want to shift the text to the left.
   public static String decrypt(String cipherText, int shiftKey)
    {
        String plainText = "";
        for (int i = 0; i < cipherText.length(); i++)
        {
            int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
            int keyVal = (charPosition - shiftKey) % 26;
            if (keyVal < 0)
            {
                keyVal = ALPHABET.length() + keyVal;
            }
            char replaceVal = ALPHABET.charAt(keyVal);
            plainText += replaceVal;
        }
        return plainText;
    }
   public static void main(String[] args) throws IOException {
       Scanner keyboard = new Scanner(System.in);
       System.out.println("Would you like to encrypt or decrypt a file? ");
       String choice;
       choice = keyboard.next();

       if (choice.equals("encrypt")) {
           System.out.println("What is the name of the file you would like to encrypt?: ");
           String readFile = "";
           readFile = keyboard.next();
           System.out.println("What is the name of the file you would like to write the encrypted phrase to?: ");
           String writeFile = "";
           writeFile = keyboard.next();

           FileReader fileReader =
                    new FileReader(readFile);
            BufferedReader bufferedReader =
                    new BufferedReader(fileReader);

            FileWriter fileWriter =
                    new FileWriter(writeFile);
            BufferedWriter bufferedWriter =
                    new BufferedWriter(fileWriter);

            String message = "";
            while ((message = bufferedReader.readLine()) !=" ") {
                bufferedWriter.write(encrypt(message, 8));
                bufferedWriter.newLine();
            }
       }
   }
}
</code>```

The error I receive:

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 25
    at java.lang.String.charAt(Unknown Source)
    at CaeserCipher1.CaeserCipher1.encrypt(CaeserCipher1.java:15)
    at CaeserCipher1.CaeserCipher1.main(CaeserCipher1.java:63)
</code>```

I understand the general idea behind the out of bounds exception by reading other peoples problems, but from reading the answers on other problems I can't find an issue in my own code. I've read in other peoples issues where they use <= in their if loop instead of <, I've seen the one where people are tying to use the substring form, etc.

Any help would be much appreciated.

Edit: The file being read from will only use capital letters, thus the reason ALPHABET only has capital letters.

答:
You forgot to add the letter X into ALPHABET.  Please carefully read over your code before posting questions...

Your code also doesn't handle any characters other than the ones in ALPHABET, so you're going to end up with a whole bunch of H's (for a shift of 8) in the ciphertext that won't decode properly.

Body:
I'm trying to code a program that will read in text from a file that the user specifies, will then encrypt the text using the Caesar Cipher, and finally write the encrypted phrase to a different file. I'll also want to eventually have it do the reverse, where it reads encrypted text and decrypts it, but one step at a time.

package CaeserCipher1;

import java.util.Scanner;
import java.io.*;

public class CaeserCipher1 {
public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWYZ";

//Method to pull the plaintext of a file, followed by how far you want to shift plaintext to the right.
public static String encrypt(String plainText, int shiftKey) {
    String cipherText ="";
    for (int i = 0; i < plainText.length(); i++) {
        int charPosition = ALPHABET.indexOf(plainText.charAt(i));
        int keyVal = (shiftKey + charPosition) % 26;
        char replaceVal = ALPHABET.charAt(keyVal);
        cipherText += replaceVal;
    }
    return cipherText;
}
    //Method to pull the encrypted text of a file, followed by how far you want to shift the text to the left.
   public static String decrypt(String cipherText, int shiftKey)
    {
        String plainText = "";
        for (int i = 0; i < cipherText.length(); i++)
        {
            int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
            int keyVal = (charPosition - shiftKey) % 26;
            if (keyVal < 0)
            {
                keyVal = ALPHABET.length() + keyVal;
            }
            char replaceVal = ALPHABET.charAt(keyVal);
            plainText += replaceVal;
        }
        return plainText;
    }
   public static void main(String[] args) throws IOException {
       Scanner keyboard = new Scanner(System.in);
       System.out.println("Would you like to encrypt or decrypt a file? ");
       String choice;
       choice = keyboard.next();

       if (choice.equals("encrypt")) {
           System.out.println("What is the name of the file you would like to encrypt?: ");
           String readFile = "";
           readFile = keyboard.next();
           System.out.println("What is the name of the file you would like to write the encrypted phrase to?: ");
           String writeFile = "";
           writeFile = keyboard.next();

           FileReader fileReader =
                    new FileReader(readFile);
            BufferedReader bufferedReader =
                    new BufferedReader(fileReader);

            FileWriter fileWriter =
                    new FileWriter(writeFile);
            BufferedWriter bufferedWriter =
                    new BufferedWriter(fileWriter);

            String message = "";
            while ((message = bufferedReader.readLine()) !=" ") {
                bufferedWriter.write(encrypt(message, 8));
                bufferedWriter.newLine();
            }
       }
   }
}

The error I receive:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 25
    at java.lang.String.charAt(Unknown Source)
    at CaeserCipher1.CaeserCipher1.encrypt(CaeserCipher1.java:15)
    at CaeserCipher1.CaeserCipher1.main(CaeserCipher1.java:63)

I understand the general idea behind the out of bounds exception by reading other peoples problems, but from reading the answers on other problems I can't find an issue in my own code. I've read in other peoples issues where they use <= in their if loop instead of <, I've seen the one where people are tying to use the substring form, etc.

Any help would be much appreciated.

Edit: The file being read from will only use capital letters, thus the reason ALPHABET only has capital letters.


Title: How to use SUMIF if criteria contains a ">" symbol?

Body:
So I tried using the SUMIF formula as follows:

=SUMIF(A1:A10, ">30D", B1:B10)

Within my criteria range, there are instances of '>30D' occurring as a value. For instance, my data would look like this:

A        B
>30D     200
0-7D     100
8-14D    200
15D-29D  300
>30D     400

And I would like the formula to return 600. However, in the above formula, I'm getting the wrong values (double checked with a pivot table). I think this is because Excel is is interpreting ">30D" as an expression instead of a value. I've also tried referencing the cell itself with:

=SUMIF(A1:A10, $A$1, B1:B10)

This doesn't work either. Help would be much appreciated!

Body:
Put = in front:

=SUMIF(A:A,"=" & A1,B:B)

Or

=SUMIF(A:A,"=>30D",B:B)


问:
Find a sum with prompt. Stop when user gives -1
Unable to get it to print out the number when the prompt is answered with negative one. It keeps asking for more numbers.

```<code><!DOCTYPE html>
<html>
<body>

<h2>JavaScript Prompt</h2>

<script>
var sum=0;
var number = prompt("Please enter a number:");
while(number>-1)
prompt("Please enter a number:");
sum=number+sum;
if(number=-1) {
document.write(sum);
}
</code>```

答:
It looks like you are working on an assignment so I'll give you some poiters:

number is never getting changed, you need to assign it to what the user enters from within your loop, like you did with the previous prompt.

It looks like you can skip the first prompt, and only prompt inside the loop (as long as you remember to assign that value back to number).  Set var number = 0 initally.

Single equal sign will do assignment.  So if(number=-1) will set the value of number to -1.

To do a comparison in an if statement, use triple equals.  You will always use triple equals when checking if something equals something else (all if statements)

(thanks @acn3) You also need braces to contain all the logic within your while loop, open brace before the prompt and close brace after the if statement.

Body:
Unable to get it to print out the number when the prompt is answered with negative one. It keeps asking for more numbers.

<!DOCTYPE html>

JavaScript Prompt


问:
Only show prime numbers in a NumericUpDown control
```<code>    private void numericUpDown1_ValueChanged_1(object sender, EventArgs e)
    {
        //my numeric up down var name is numrsa1//
    }

    static bool IsPrimeNumber(int value)
    {
        bool result = true;

        for (int i = 2; i < value; i++)
        {
            if (value % i == 0)
            {
                result = false;
                break;
            }
        }

        if (value <= 1)
            result = false;

        return result;
    }`
</code>```

I would like to know if there's a way to show in the Numeric Up Down only prime numbers. I'm trying to make a crypthography work for university and I need give only prime numbers options for the user.

答:
Because you are asking for functionality that is similar to the NumericUpDown control, but with different behavior, then I suggest you create a new control PrimeNumberUpDown that extends the NumericUpDown control.

Here is a quick version I through together.  I tested that it works for up/down using the mouse or arrow keys, and entering a number into the text box.  You may want to test it more exhaustively if it's going into anything critical.

Paste this code into a new file (updating the namespace accordingly), compile, then you should see a PrimeNumberUpDown control appear in your toolbox so you can use it like any other Windows Forms control.

```<code>using System;
using System.Globalization;
using System.Windows.Forms;

namespace YourNameSpace
{
    public class PrimeNumberUpDown : NumericUpDown
    {
        private int _value;

        public PrimeNumberUpDown()
        {
            // Make sure default value is prime
            if (!IsPrime((int)Value))
                SetNextPrimeValue();
            _value = (int)Value;
        }

        public override void DownButton()
        {
            SetNextPrimeValue();
        }

        public override void UpButton()
        {
            SetPreviousPrimeValue();
        }

        private void SetNextPrimeValue()
        {
            int newValue = (int)Value;
            while (newValue <= Maximum)
            {
                if (IsPrime(++newValue))
                {
                    if (newValue <= Maximum)
                    {
                        Value = newValue;
                        _value = newValue;
                    }
                    return;
                }
            }
        }

        private void SetPreviousPrimeValue()
        {
            int newValue = (int)Value;
            while (newValue >= Minimum)
            {
                if (IsPrime(--newValue))
                {
                    if (newValue >= Minimum)
                    {
                        Value = newValue;
                        _value = newValue;
                    }
                    return;
                }
            }
        }

        protected override void ValidateEditText()
        {
            if (_value == 0)
            {
                base.ValidateEditText();
                return;
            }

            int newValue;
            if (int.TryParse(Text, out newValue) && IsPrime(newValue) && newValue >= Minimum && newValue <= Maximum)
            {
                _value = newValue;
                base.ValidateEditText();
            }
            else
            {
                ChangingText = true;
                Text = _value.ToString(CultureInfo.InvariantCulture);
            }
        }

        private static bool IsPrime(int number)
        {
            if (number == 1) return false;
            if (number == 2) return true;
            if (number % 2 == 0) return false;

            int boundary = (int)Math.Floor(Math.Sqrt(number));

            for (int i = 3; i <= boundary; i += 2)
            {
                if (number % i == 0) return false;
            }

            return true;
        }
    }
}
</code>```

Body:
    private void numericUpDown1_ValueChanged_1(object sender, EventArgs e)
    {
        //my numeric up down var name is numrsa1//
    }

    static bool IsPrimeNumber(int value)
    {
        bool result = true;

        for (int i = 2; i < value; i++)
        {
            if (value % i == 0)
            {
                result = false;
                break;
            }
        }

        if (value <= 1)
            result = false;

        return result;
    }`

I would like to know if there's a way to show in the Numeric Up Down only prime numbers. I'm trying to make a crypthography work for university and I need give only prime numbers options for the user.

Body:
Because you are asking for functionality that is similar to the NumericUpDown control, but with different behavior, then I suggest you create a new control PrimeNumberUpDown that extends the NumericUpDown control.

Here is a quick version I through together.  I tested that it works for up/down using the mouse or arrow keys, and entering a number into the text box.  You may want to test it more exhaustively if it's going into anything critical.

Paste this code into a new file (updating the namespace accordingly), compile, then you should see a PrimeNumberUpDown control appear in your toolbox so you can use it like any other Windows Forms control.

using System;
using System.Globalization;
using System.Windows.Forms;

namespace YourNameSpace
{
    public class PrimeNumberUpDown : NumericUpDown
    {
        private int _value;

        public PrimeNumberUpDown()
        {
            // Make sure default value is prime
            if (!IsPrime((int)Value))
                SetNextPrimeValue();
            _value = (int)Value;
        }

        public override void DownButton()
        {
            SetNextPrimeValue();
        }

        public override void UpButton()
        {
            SetPreviousPrimeValue();
        }

        private void SetNextPrimeValue()
        {
            int newValue = (int)Value;
            while (newValue <= Maximum)
            {
                if (IsPrime(++newValue))
                {
                    if (newValue <= Maximum)
                    {
                        Value = newValue;
                        _value = newValue;
                    }
                    return;
                }
            }
        }

        private void SetPreviousPrimeValue()
        {
            int newValue = (int)Value;
            while (newValue >= Minimum)
            {
                if (IsPrime(--newValue))
                {
                    if (newValue >= Minimum)
                    {
                        Value = newValue;
                        _value = newValue;
                    }
                    return;
                }
            }
        }

        protected override void ValidateEditText()
        {
            if (_value == 0)
            {
                base.ValidateEditText();
                return;
            }

            int newValue;
            if (int.TryParse(Text, out newValue) && IsPrime(newValue) && newValue >= Minimum && newValue <= Maximum)
            {
                _value = newValue;
                base.ValidateEditText();
            }
            else
            {
                ChangingText = true;
                Text = _value.ToString(CultureInfo.InvariantCulture);
            }
        }

        private static bool IsPrime(int number)
        {
            if (number == 1) return false;
            if (number == 2) return true;
            if (number % 2 == 0) return false;

            int boundary = (int)Math.Floor(Math.Sqrt(number));

            for (int i = 3; i <= boundary; i += 2)
            {
                if (number % i == 0) return false;
            }

            return true;
        }
    }
}


问:
How to correctly queue up tasks to run in C#
I have an enumeration of items (RunData.Demand), each representing some work involving calling an API over HTTP.  It works great if I just foreach through it all and call the API during each iteration.  However, each iteration takes a second or two so I'd like to run 2-3 threads and divide up the work between them.  Here's what I'm doing:

```<code>ThreadPool.SetMaxThreads(2, 5); // Trying to limit the amount of threads
var tasks = RunData.Demand
   .Select(service => Task.Run(async delegate
   {
      var availabilityResponse = await client.QueryAvailability(service);
      // Do some other stuff, not really important
   }));

await Task.WhenAll(tasks);
</code>```

The client.QueryAvailability call basically calls an API using the HttpClient class:

```<code>public async Task<QueryAvailabilityResponse> QueryAvailability(QueryAvailabilityMultidayRequest request)
{
   var response = await client.PostAsJsonAsync("api/queryavailabilitymultiday", request);

   if (response.IsSuccessStatusCode)
   {
      return await response.Content.ReadAsAsync<QueryAvailabilityResponse>();
   }

   throw new HttpException((int) response.StatusCode, response.ReasonPhrase);
}
</code>```

This works great for a while, but eventually things start timing out.  If I set the HttpClient Timeout to an hour, then I start getting weird internal server errors.

What I started doing was setting a Stopwatch within the QueryAvailability method to see what was going on.

What's happening is all 1200 items in RunData.Demand are being created at once and all 1200 await client.PostAsJsonAsync methods are being called.  It appears it then uses the 2 threads to slowly check back on the tasks, so towards the end I have tasks that have been waiting for 9 or 10 minutes.

Here's the behavior I would like:

I'd like to create the 1,200 tasks, then run them 3-4 at a time as threads become available.  I do not want to queue up 1,200 HTTP calls immediately.

Is there a good way to go about doing this?

答:
Old question, but I would like to propose an alternative lightweight solution using the SemaphoreSlim class. Just reference System.Threading.

```<code>SemaphoreSlim sem = new SemaphoreSlim(4,4);

foreach (var service in RunData.Demand)
{

    await sem.WaitAsync();
    Task t = Task.Run(async () =>
    {
        var availabilityResponse = await client.QueryAvailability(serviceCopy));
        // do your other stuff here with the result of QueryAvailability
    }
    t.ContinueWith(sem.Release());
}
</code>```

The semaphore acts as a locking mechanism. You can only enter the semaphore by calling Wait (WaitAsync) which subtracts one from the count. Calling release adds one to the count.

Body:
I have an enumeration of items (RunData.Demand), each representing some work involving calling an API over HTTP.  It works great if I just foreach through it all and call the API during each iteration.  However, each iteration takes a second or two so I'd like to run 2-3 threads and divide up the work between them.  Here's what I'm doing:

ThreadPool.SetMaxThreads(2, 5); // Trying to limit the amount of threads
var tasks = RunData.Demand
   .Select(service => Task.Run(async delegate
   {
      var availabilityResponse = await client.QueryAvailability(service);
      // Do some other stuff, not really important
   }));

await Task.WhenAll(tasks);

The client.QueryAvailability call basically calls an API using the HttpClient class:

public async Task<QueryAvailabilityResponse> QueryAvailability(QueryAvailabilityMultidayRequest request)
{
   var response = await client.PostAsJsonAsync("api/queryavailabilitymultiday", request);

   if (response.IsSuccessStatusCode)
   {
      return await response.Content.ReadAsAsync<QueryAvailabilityResponse>();
   }

   throw new HttpException((int) response.StatusCode, response.ReasonPhrase);
}

This works great for a while, but eventually things start timing out.  If I set the HttpClient Timeout to an hour, then I start getting weird internal server errors.

What I started doing was setting a Stopwatch within the QueryAvailability method to see what was going on.

What's happening is all 1200 items in RunData.Demand are being created at once and all 1200 await client.PostAsJsonAsync methods are being called.  It appears it then uses the 2 threads to slowly check back on the tasks, so towards the end I have tasks that have been waiting for 9 or 10 minutes.

Here's the behavior I would like:

I'd like to create the 1,200 tasks, then run them 3-4 at a time as threads become available.  I do not want to queue up 1,200 HTTP calls immediately.

Is there a good way to go about doing this?

Body:
Old question, but I would like to propose an alternative lightweight solution using the SemaphoreSlim class. Just reference System.Threading.

SemaphoreSlim sem = new SemaphoreSlim(4,4);

foreach (var service in RunData.Demand)
{

    await sem.WaitAsync();
    Task t = Task.Run(async () =>
    {
        var availabilityResponse = await client.QueryAvailability(serviceCopy));
        // do your other stuff here with the result of QueryAvailability
    }
    t.ContinueWith(sem.Release());
}

The semaphore acts as a locking mechanism. You can only enter the semaphore by calling Wait (WaitAsync) which subtracts one from the count. Calling release adds one to the count.


问:
How to refresh ASPX page and Javascript code that has been cached by proxy service
The Issue

Recently, I deployed a page to production containing javascript which used setInterval() to ping a webservice every few seconds. The behavior can be summed up as follows:

Every X seconds, Javascript on the upcomingEvents.aspx page calls the hitWebService() function, which sits in the hitWebService.js file.

The X interval value set proved to be too small, so, I removed all references to hitWebService(), the hitWebService.js file itself, and the web service it was trying to reach.

Attempts to hit the web service from normal IP addressess dropped off, but I am still getting attempted hits from a number of users who use a proxy service.

My theory is that my upcomingEvents.aspx and hitWebService.js have been cached by the proxy service. Indeed, when I log the referrer strings when a user hits  the error page (every so often, one of these users will get redirected here), they are being referred from upcomingEvents.aspx.

The issue is that the attempts to hit this web service are filling up the IIS logs at an uncomfortable rate, and are causing unnecessary traffic on the server.

What I have attempted

Removed web service completely

Deleting the hitWebService.js file, also replaced it with dummy file

Changed content expiration on IIS so that content expires immediately

Added Response.Cache.SetCacheability(HttpCacheability.NoCache) to the .vb codebehind on page

Completely republished site with changes

Restarted IIS, stopped and started IIS.

Interesting bits

I can alter the vb codebehind on UpcomingEvents.apsx to log session details, etc, and it seems to update almost instantly for the proxy service users

The Question

If my theory is correct, and the proxy server is indeed caching these the files hitWebService.js and upcomingEvents.aspx, are there any other routes that I can go down to force a code refresh, considering the above strategies haven't worked?

Thanks a lot,

答:
In my case, i had a ajax call begin cached by asp.net. I used a param with the javascript date number so each call have a different querystring.

like this:

```<code>function addQueryStringAntiCache(url)
{
    var d = new Date();
    var n = d.getTime();
    return url + (url.indexOf("?") == -1 ? "?" : "&") + "nocache=" + n;
}
</code>```

you can do the same thing for script:

```<code><script src="myScript.js?v=8912398314812" />
</code>```

In case you have access to the machine, use fiddle to check it the browser even call to get the files or if it use it's own cache. In that case you can try to include metaData or http Header to prevent it caching it. Check this response

Hope it help you.

Body:
In my case, i had a ajax call begin cached by asp.net. I used a param with the javascript date number so each call have a different querystring.

like this:

function addQueryStringAntiCache(url)
{
    var d = new Date();
    var n = d.getTime();
    return url + (url.indexOf("?") == -1 ? "?" : "&") + "nocache=" + n;
}

you can do the same thing for script:

<script src="myScript.js?v=8912398314812" />

In case you have access to the machine, use fiddle to check it the browser even call to get the files or if it use it's own cache. In that case you can try to include metaData or http Header to prevent it caching it. Check this response

Hope it help you.


问:
NServiceBus IoC Serialization Exception
I am using a "custom" object builder (Autofac) so I can re-use the registration of many types that I have done in a common assembly. When I run the service, hosted within NServiceBus.Host.exe, I get the following error:

SerializationException was unhandled:

Type 'Autofac.Core.Registration.ComponentNotRegisteredException' in assembly 'Autofac, Version=3.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da' is not marked as serializable.

This seems odd to me because NServiceBus uses Autofac by default and doesn't have this same issue.

I am using Autofac v 3.1.1 and NServiceBus 4.0.3

答:
I ran into a similar error while adding NServiceBus.Distributor.Msmq (4.4.2) to an old solution using NServiceBus 4.4.2. Turned out I'd forgotten to set up the NSB license for the new project. Trying to start the distributor threw this until I included a valid License.xml file in the build output:

Unhandled Exception: System.Runtime.Serialization.SerializationException: Type 'Autofac.Core.DependencyResolutionException' in assembly 'NServiceBus.Core, Version=4.4.0.0, Culture=neutral
 PublicKeyToken=9fc386479f8a226c' is not marked as serializable.

Title: NServiceBus IoC Serialization Exception


问:
Store values from file in arrays depending a value in the array in JAVA
Hello everyone i am new in java .I want to write a programm that reads from a file and by a specific way.My file is mix with strings and ints.
In the first line there is a number that tell us how many lines will follow.
After this, in each line there will be a String and an int.The int value will tell us how many values there are in this line.
For example :
text file:

```<code>2
Coffee       2  Water 200   cofe 300
SweetCoffee  3  Water 200   cofe 300   Sugar 10
</code>```

I want to pass values in different arrays.

```<code>   nameOfProduct[0]=Coffee
   nameOfProduct[1]=SweetCoffee
   numofIngredients[0]=2
   element[0][0]=water
   element[0][1]=cofe
   element[1][3]=sugar
</code>```

i try to find a way that works.This is what i have done until now

```<code>package pkg1;
import java.io.*;
import java.util.*;

public class readfile {

    private Scanner x;
    int count=0;
    int i,j,noIngredients;

    public void openfile() {
        try {
            x = new Scanner(new File("MyRecipes.txt"));
        }
        catch(Exception e) {
            System.out.println("could not find the file");
        }
    }

    public void readFile() {
        i=0;
        int numofRecipes = x.nextInt();

        String nameOfProduct[] = new String[numofRecipes];
        int numofIngredients[]  = new int[numofRecipes];

        while (x.hasNext()) {
        //   String line = x.nextLine();
            nameOfProduct[i] = x.next();

            numofIngredients[i] = x.nextInt();

            noIngredients=numofIngredients[i];

            String element[][] = new String[numofRecipes][noIngredients];

            int quantity[][] = new int[numofRecipes][noIngredients];

            System.out.printf("%s %d ",nameOfProduct,numofIngredients);

            j=0;

            while( x.hasNext() || x.hasNextInt())  {
                element[i][j] = x.next();
                quantity[i][j] = x.nextInt();
                System.out.printf("%s %d ",element[i][j],quantity[i][j]);
                j++;
            }
            i++;
            x.nextLine() ;
        }
    }
 }
</code>```

答:
Change this : while( x.hasNext() || x.hasNextInt())

to: for (int k=0; k<numofIngredients[i]; k++)
and replace j with k inside the loop

and while (x.hasNext())(The first while loop in readFile())

to: for (int tot=0; tot<numOfRecipes; tot++){

Rest is fine I believe.

But yeah, as RAZ_Muh_Taz said, make a Recipe class to get a neater version of code.

Body:
Hello everyone i am new in java .I want to write a programm that reads from a file and by a specific way.My file is mix with strings and ints.
In the first line there is a number that tell us how many lines will follow.
After this, in each line there will be a String and an int.The int value will tell us how many values there are in this line.
For example :
text file:

2
Coffee       2  Water 200   cofe 300
SweetCoffee  3  Water 200   cofe 300   Sugar 10

I want to pass values in different arrays.

   nameOfProduct[0]=Coffee
   nameOfProduct[1]=SweetCoffee
   numofIngredients[0]=2
   element[0][0]=water
   element[0][1]=cofe
   element[1][3]=sugar

i try to find a way that works.This is what i have done until now

package pkg1;
import java.io.*;
import java.util.*;

public class readfile {

    private Scanner x;
    int count=0;
    int i,j,noIngredients;

    public void openfile() {
        try {
            x = new Scanner(new File("MyRecipes.txt"));
        }
        catch(Exception e) {
            System.out.println("could not find the file");
        }
    }

    public void readFile() {
        i=0;
        int numofRecipes = x.nextInt();

        String nameOfProduct[] = new String[numofRecipes];
        int numofIngredients[]  = new int[numofRecipes];

        while (x.hasNext()) {
        //   String line = x.nextLine();
            nameOfProduct[i] = x.next();

            numofIngredients[i] = x.nextInt();

            noIngredients=numofIngredients[i];

            String element[][] = new String[numofRecipes][noIngredients];

            int quantity[][] = new int[numofRecipes][noIngredients];

            System.out.printf("%s %d ",nameOfProduct,numofIngredients);

            j=0;

            while( x.hasNext() || x.hasNextInt())  {
                element[i][j] = x.next();
                quantity[i][j] = x.nextInt();
                System.out.printf("%s %d ",element[i][j],quantity[i][j]);
                j++;
            }
            i++;
            x.nextLine() ;
        }
    }
 }