问:
Rspec testing fail strong params
Trying to get this one to pass for a while, not that familiar with Rspec, tried couple answers, and no luck yet, I have these two parameters being required on my controller as follow:

```<code>class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_back fallback_location: new_user_path
    else
      render :new
    end
  end
private
  def user_params
    params.require(:user).permit(:username, :password)
  end
end
</code>```

and this is the rspec test that is giving me an issue:

```<code>  describe "GET #create" do
    it "returns http success" do
      get :create
      expect(response).to have_http_status(:success)
    end
  end
</code>```

here is the error that I am getting:

```<code>1) UsersController GET #create returns http success
     Failure/Error: params.require(:user).permit(:username, :password)

     ActionController::ParameterMissing:
       param is missing or the value is empty: user
</code>```

I am looking at the rspec documentation right now, but any help would be appreciated it.

答:
Try this:

```<code>describe "POST #create" do
  it "returns http success" do
    post :create, params: { user: { username: "name", password: "password" } }
    expect(response).to have_http_status(:success)
  end
end
</code>```

It should be post :create, not get :create

Title: Rspec testing fail strong params

Body:
Trying to get this one to pass for a while, not that familiar with Rspec, tried couple answers, and no luck yet, I have these two parameters being required on my controller as follow:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_back fallback_location: new_user_path
    else
      render :new
    end
  end
private
  def user_params
    params.require(:user).permit(:username, :password)
  end
end

and this is the rspec test that is giving me an issue:

  describe "GET #create" do
    it "returns http success" do
      get :create
      expect(response).to have_http_status(:success)
    end
  end

here is the error that I am getting:

1) UsersController GET #create returns http success
     Failure/Error: params.require(:user).permit(:username, :password)

     ActionController::ParameterMissing:
       param is missing or the value is empty: user

I am looking at the rspec documentation right now, but any help would be appreciated it.

Body:
Try this:

describe "POST #create" do
  it "returns http success" do
    post :create, params: { user: { username: "name", password: "password" } }
    expect(response).to have_http_status(:success)
  end
end

It should be post :create, not get :create


来源: stackexchange

问:
Accessing the front facing camera. iPhone/iPod 4
Hey I was wondering how I can access the front facing camera. Maybe there's some guide for it?
But I don't want all buttons etc. I just want to access the from facing camera, I don't ant the button to take a photo or anything like that.</p>

答:
You should initiate an AVCaptureSession and specify which AVCaptureDevice to use ( AVCaptureDevicePositionFront in your case).

Start looking for the AVCaptureSession documentation and you should have a better understanding of what to do.

ContentLicense: CC BY-SA 2.5


问:
How do I get the path of the current executed file in Python?
Is there a universal approach in Python, to find out the path to the file that is currently executing?

Failing approaches

path = os.path.abspath(os.path.dirname(sys.argv[0]))

This does not work if you are running from another Python script in another directory, for example by using execfile in 2.x.

path = os.path.abspath(os.path.dirname(__file__))

I found that this doesn't work in the following cases:

py2exe doesn't have a __file__ attribute, although there is a workaround

When the code is run from IDLE using execute(), in which case there is no __file__ attribute

On Mac OS X v10.6 (Snow Leopard), I get NameError: global name '__file__' is not defined

Test case

Directory tree

```<code>C:.
|   a.py
\---subdir
        b.py
</code>```

Content of a.py

```<code>#! /usr/bin/env python
import os, sys

print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print

execfile("subdir/b.py")
</code>```

Content of subdir/b.py

```<code>#! /usr/bin/env python
import os, sys

print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print
</code>```

Output of python a.py (on Windows)

```<code>a.py: __file__= a.py
a.py: os.getcwd()= C:\zzz

b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:\zzz
</code>```

Related (but these answers are incomplete)

Find path to currently running file

Path to current file depends on how I execute the program

How can I know the path of the running script in Python?

Change directory to the directory of a Python script

答:
Simply add the following:

```<code>from sys import *
path_to_current_file = sys.argv[0]
print(path_to_current_file)
</code>```

Or:

```<code>from sys import *
print(sys.argv[0])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a universal approach in Python, to find out the path to the file that is currently executing?

Failing approaches

path = os.path.abspath(os.path.dirname(sys.argv[0]))

This does not work if you are running from another Python script in another directory, for example by using execfile in 2.x.

path = os.path.abspath(os.path.dirname(__file__))

I found that this doesn't work in the following cases:

py2exe doesn't have a __file__ attribute, although there is a workaround

When the code is run from IDLE using execute(), in which case there is no __file__ attribute

On Mac OS X v10.6 (Snow Leopard), I get NameError: global name '__file__' is not defined

Test case

Directory tree

C:.
|   a.py
\---subdir
        b.py

Content of a.py

#! /usr/bin/env python
import os, sys

print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print

execfile("subdir/b.py")

Content of subdir/b.py

#! /usr/bin/env python
import os, sys

print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print

Output of python a.py (on Windows)

a.py: __file__= a.py
a.py: os.getcwd()= C:\zzz

b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:\zzz

Related (but these answers are incomplete)

Find path to currently running file

Path to current file depends on how I execute the program

How can I know the path of the running script in Python?

Change directory to the directory of a Python script

Body:
Simply add the following:

from sys import *
path_to_current_file = sys.argv[0]
print(path_to_current_file)

Or:

from sys import *
print(sys.argv[0])

ContentLicense: CC BY-SA 3.0


问:
How do I get a link in Bootstrap nav bar to disappear/reappear based on window size?
I'm currently building a website using Bootstrap. I have a "Services" link listed in my nav bar, that when hovered over displays a list of services. The user can also click on "Services" itself and they are directed to a link. If the user resizes their screen, or are looking at the website on their mobile device, I need to be able to remove the link from "Services".

The code below sort of works. I am running into a bug when I try to resize the desktop browser multiple times. Once I make the screen smaller, I am unable to recognize a larger browser window and, therefore, get the link in "Services" back. What am I missing?

HTML

```<code><li class="dropdown">
    <a href="#services" class="dropdown-toggle linkedDropDown" data-toggle="dropdown">Services
         <i class="fa fa-angle-down"></i>
    </a>
    <ul class="dropdown-menu">
         <li>
              <a href="">Link 1</a>
         </li>
         <li>
              <a href="">Link 2</a>
         </li>
         <li>
              <a href="">Link 3</a>
         </li>
         <li>
              <a href="">Link 4</a>
         </li>
    </ul>
</li>
</code>```

CSS

```<code>@media (min-width:990px){
    .dropdown:hover .dropdown-menu {
        display: block !important;
        margin-top: 0 !important;
     }
}
</code>```

jQuery

```<code>$(document).ready(function () {
     changeElements();

     $(window).resize(function() {
          changeElements();
     });
 });

function changeElements(){
     if ($(window).width() < 990) {
           $('.linkedDropDown').removeAttr('href');
     }
     else{
           $('.linkedDropDown').attr('href');
     }
 }
</code>```

答:
If you are using Bootstrap you can add the d-*-none class to hide elements at a certain pixel width, or d-*-block to show elements at a particular pixel width.

For example, if you wanted to hide the "Services" link on mobile devices, you could add the classes d-none and d-sm-block to your link tag.  This will hide the link when then screen width is less than 544px but show it on all larger screen sizes.

By adding these classes there will be no need for your current JavaScript.

More documentation on the responsive utility classes can be found here: https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

Body:
I'm currently building a website using Bootstrap. I have a "Services" link listed in my nav bar, that when hovered over displays a list of services. The user can also click on "Services" itself and they are directed to a link. If the user resizes their screen, or are looking at the website on their mobile device, I need to be able to remove the link from "Services".

The code below sort of works. I am running into a bug when I try to resize the desktop browser multiple times. Once I make the screen smaller, I am unable to recognize a larger browser window and, therefore, get the link in "Services" back. What am I missing?

HTML

    Services

              Link 1

              Link 2

              Link 3

              Link 4

CSS

@media (min-width:990px){
    .dropdown:hover .dropdown-menu {
        display: block !important;
        margin-top: 0 !important;
     }
}

jQuery

$(document).ready(function () {
     changeElements();

     $(window).resize(function() {
          changeElements();
     });
 });

function changeElements(){
     if ($(window).width() < 990) {
           $('.linkedDropDown').removeAttr('href');
     }
     else{
           $('.linkedDropDown').attr('href');
     }
 }


问:
ReferenceError: "PropertiesService" is not defined
From the following question, I try to use part of the following code in an Adwords script

```<code>function runMe() {
  var startTime= (new Date()).getTime();

  //do some work here

  var scriptProperties = PropertiesService.getScriptProperties();
  var startRow= scriptProperties.getProperty('start_row');
  for(var ii = startRow; ii <= size; ii++) {
    var currTime = (new Date()).getTime();
    if(currTime - startTime >= MAX_RUNNING_TIME) {
      scriptProperties.setProperty("start_row", ii);
      ScriptApp.newTrigger("runMe")
               .timeBased()
               .at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
               .create();
      break;
    } else {
      doSomeWork();
    }
  }

  //do some more work here

}
</code>```

but I got ReferenceError: "PropertiesService" is not defined. (line 170) from google-apps-script. How could I fix that issue? Can you tell me if it works for you in Adwords?

UPDATED

Here is the function I build in considering the previous function :

```<code>function adjustCPCmax() {
    //min CPC
    var minCPC = 0.50;

    var accountIterator = MccApp.accounts().get();
    var mccAccount = AdWordsApp.currentAccount();
    while(accountIterator.hasNext()) {
        var account = accountIterator.next();
        Logger.log('============================================== ' + account.getName() + ' ====================================================')
        MccApp.select(account)

        var campaignIterator = AdWordsApp.campaigns().get();
        while (campaignIterator.hasNext()) {
            var campaign = campaignIterator.next();
            try {
                var maxCPC = getMaxCPC(account, campaign)
            }
            catch(e) {
            }

            if (maxCPC) {
                var startTime= (new Date()).getTime();

                Logger.log('The entrence worked with max CPC : ' + maxCPC + '\n')
                keywordIterator = campaign.keywords().get();
                while (keywordIterator.hasNext()) {
                    var keyword= keywordIterator.next()
                    var keywordId = Number(keyword.getId()).toPrecision()

                    Logger.log('THE NAME OF THE KEYWORDID IS ' + keywordId + '\n')

                    var report = AdWordsApp.report(
                               'SELECT Id, Criteria, CampaignName, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
                               'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
                               'WHERE ' +
                               'Id = ' + keywordId);
                    var rows = report.rows();
                    while(rows.hasNext()) {
                        var row = rows.next();
                        var keywordIdReport = row['Id'];
                        var keywordNameReport = row['Criteria'];
                        var campaignName = row['CampaignName'];
                        var cpcBid = row['CpcBid'];
                        var firstPageCpc = row['FirstPageCpc'];
                        var firstPositionCpc = row['FirstPositionCpc'];
                        var topOfPageCpc = row['TopOfPageCpc'];

                        Logger.log('INFO')
                        Logger.log(keyword.getText())
                        Logger.log(keywordId)
                        Logger.log(keywordNameReport)
                        Logger.log(keywordIdReport + '\n')

                        if (keywordId === keywordIdReport) {

                            if (firstPositionCpc && (firstPositionCpc > 0 && firstPositionCpc <= maxCPC)) {
                                var newCPC = firstPositionCpc;
                            } else if (topOfPageCpc  && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
                                var newCPC = topOfPageCpc;
                            } else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
                                var newCPC = firstPageCpc;
                            } else {
                                var newCPC = minCPC;
                            }

                            Logger.log('KeywordIdReport :' + keywordIdReport)
                            Logger.log('campaignName :' + campaignName)
                            Logger.log('CPCbid :' + cpcBid)
                            Logger.log('firstPositionCpc : ' + firstPositionCpc)
                            Logger.log('topOfPageCpc : ' + topOfPageCpc)
                            Logger.log('firstPageCpc : ' + firstPageCpc)
                            Logger.log('NewCPC : ' + newCPC + '\n')

                            keyword.bidding().setCpc(newCPC)
                            break;
                        }
                    }
                    var REASONABLE_TIME_TO_WAIT = 4*6000;
                    var MAX_RUNNING_TIME = 1*6000;
                    try {
                        var scriptProperties = PropertiesService.getScriptProperties();
                    }
                    catch(e){
                        Logger.log(e)
                    }
                    var startRow= scriptProperties.getProperty('start_row');
                    for(var ii = startRow; ii <= size; ii++) {
                        var currTime = (new Date()).getTime();
                        if(currTime - startTime >= MAX_RUNNING_TIME) {
                            scriptProperties.setProperty("start_row", ii);
                            ScriptApp.newTrigger("runMe")
                                .timeBased()
                                .at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
                                .create();
                            break;
                        }
                    }
                }
            }
        }
    }
    MccApp.select(mccAccount);
}
</code>```

From that function, what could I do to fix that problem? It is bizarre because I could find documentation on the subject.

答:
You are using AdWords Script which is different from Google Apps Script even though they share many APIs. Google Apps Script has access to Properties Service, AdWords Script does not. Evidence: the AdWords Script reference (screenshot) does not include Properties Service among Script Services.

You are using script properties to store one number, the current row number. An alternative is to store it in a spreadsheet, since AdWords Script has access to Spreadsheet service. So, at the beginning of the script you would have

```<code>var ss = SpreadsheetApp.openByUrl('...'); // url of some spreadsheet
var sheet = ss.getSheets()[0];    // first sheet in it
var cell = sheet.getRange("A1");  // storing the number in A1 cell
</code>```

and then within the body of the script, replace

```<code>var startRow = scriptProperties.getProperty('start_row');
</code>```

by

```<code>var startRow = cell.getValue() || 1;  // 1 by default
</code>```

and also replace

```<code>scriptProperties.setProperty("start_row", ii);
</code>```

by

```<code>cell.setValue(ii);
</code>```

This should do it.

Body:
From the following question, I try to use part of the following code in an Adwords script

function runMe() {
  var startTime= (new Date()).getTime();

  //do some work here

  var scriptProperties = PropertiesService.getScriptProperties();
  var startRow= scriptProperties.getProperty('start_row');
  for(var ii = startRow; ii <= size; ii++) {
    var currTime = (new Date()).getTime();
    if(currTime - startTime >= MAX_RUNNING_TIME) {
      scriptProperties.setProperty("start_row", ii);
      ScriptApp.newTrigger("runMe")
               .timeBased()
               .at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
               .create();
      break;
    } else {
      doSomeWork();
    }
  }

  //do some more work here

}

but I got ReferenceError: "PropertiesService" is not defined. (line 170) from google-apps-script. How could I fix that issue? Can you tell me if it works for you in Adwords?

UPDATED

Here is the function I build in considering the previous function :

function adjustCPCmax() {
    //min CPC
    var minCPC = 0.50;

    var accountIterator = MccApp.accounts().get();
    var mccAccount = AdWordsApp.currentAccount();
    while(accountIterator.hasNext()) {
        var account = accountIterator.next();
        Logger.log('============================================== ' + account.getName() + ' ====================================================')
        MccApp.select(account)

        var campaignIterator = AdWordsApp.campaigns().get();
        while (campaignIterator.hasNext()) {
            var campaign = campaignIterator.next();
            try {
                var maxCPC = getMaxCPC(account, campaign)
            }
            catch(e) {
            }

            if (maxCPC) {
                var startTime= (new Date()).getTime();

                Logger.log('The entrence worked with max CPC : ' + maxCPC + '\n')
                keywordIterator = campaign.keywords().get();
                while (keywordIterator.hasNext()) {
                    var keyword= keywordIterator.next()
                    var keywordId = Number(keyword.getId()).toPrecision()

                    Logger.log('THE NAME OF THE KEYWORDID IS ' + keywordId + '\n')

                    var report = AdWordsApp.report(
                               'SELECT Id, Criteria, CampaignName, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
                               'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
                               'WHERE ' +
                               'Id = ' + keywordId);
                    var rows = report.rows();
                    while(rows.hasNext()) {
                        var row = rows.next();
                        var keywordIdReport = row['Id'];
                        var keywordNameReport = row['Criteria'];
                        var campaignName = row['CampaignName'];
                        var cpcBid = row['CpcBid'];
                        var firstPageCpc = row['FirstPageCpc'];
                        var firstPositionCpc = row['FirstPositionCpc'];
                        var topOfPageCpc = row['TopOfPageCpc'];

                        Logger.log('INFO')
                        Logger.log(keyword.getText())
                        Logger.log(keywordId)
                        Logger.log(keywordNameReport)
                        Logger.log(keywordIdReport + '\n')

                        if (keywordId === keywordIdReport) {

                            if (firstPositionCpc && (firstPositionCpc > 0 && firstPositionCpc <= maxCPC)) {
                                var newCPC = firstPositionCpc;
                            } else if (topOfPageCpc  && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
                                var newCPC = topOfPageCpc;
                            } else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
                                var newCPC = firstPageCpc;
                            } else {
                                var newCPC = minCPC;
                            }

                            Logger.log('KeywordIdReport :' + keywordIdReport)
                            Logger.log('campaignName :' + campaignName)
                            Logger.log('CPCbid :' + cpcBid)
                            Logger.log('firstPositionCpc : ' + firstPositionCpc)
                            Logger.log('topOfPageCpc : ' + topOfPageCpc)
                            Logger.log('firstPageCpc : ' + firstPageCpc)
                            Logger.log('NewCPC : ' + newCPC + '\n')

                            keyword.bidding().setCpc(newCPC)
                            break;
                        }
                    }
                    var REASONABLE_TIME_TO_WAIT = 4*6000;
                    var MAX_RUNNING_TIME = 1*6000;
                    try {
                        var scriptProperties = PropertiesService.getScriptProperties();
                    }
                    catch(e){
                        Logger.log(e)
                    }
                    var startRow= scriptProperties.getProperty('start_row');
                    for(var ii = startRow; ii <= size; ii++) {
                        var currTime = (new Date()).getTime();
                        if(currTime - startTime >= MAX_RUNNING_TIME) {
                            scriptProperties.setProperty("start_row", ii);
                            ScriptApp.newTrigger("runMe")
                                .timeBased()
                                .at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
                                .create();
                            break;
                        }
                    }
                }
            }
        }
    }
    MccApp.select(mccAccount);
}

From that function, what could I do to fix that problem? It is bizarre because I could find documentation on the subject.

Body:
You are using AdWords Script which is different from Google Apps Script even though they share many APIs. Google Apps Script has access to Properties Service, AdWords Script does not. Evidence: the AdWords Script reference (screenshot) does not include Properties Service among Script Services.

You are using script properties to store one number, the current row number. An alternative is to store it in a spreadsheet, since AdWords Script has access to Spreadsheet service. So, at the beginning of the script you would have

var ss = SpreadsheetApp.openByUrl('...'); // url of some spreadsheet
var sheet = ss.getSheets()[0];    // first sheet in it
var cell = sheet.getRange("A1");  // storing the number in A1 cell

and then within the body of the script, replace

var startRow = scriptProperties.getProperty('start_row');

by

var startRow = cell.getValue() || 1;  // 1 by default

and also replace

scriptProperties.setProperty("start_row", ii);

by

cell.setValue(ii);

This should do it.


答:
You can use the following regex and replace it with the empty string:

^\\([0-9]+\\)\\s+ or ^\\(\\d+\\)\\s+

this will remove the starting digits surrounded by parenthesis and it will trim the beginning of your string.

Example:

```<code>(3) Florida State -> Florida State
</code>```

Title: Using R and regex to remove special characters from a string

Body:
I'm using R and have a vector of characters in a data.frame, I need to remove some special characters from specific columns. The data.frame is a table of college football scores. Some of the team names start with '([0-9)' or whatever ranking that particular team currently is. I want to remove the ranking before these team names so only the team names remain. I'm close to getting it with this code below, but I'm struggling with removing the '()' and also having leftover ' ' spaces in front of team names. Any ideas?

# remove the numbers before team names
rr <- Scores$Winner
rr <- gsub("\\([0-9]\\)","",rr)
rr <- gsub("\\([0-9][0-9]\\)","",rr)
rr

Heres an example of the data.frame

> dput(Scores[1:50,])
structure(list(Rk = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
"31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41",
"42", "43", "44", "45", "46", "47", "48", "49", "50"), Wk = c("1",
"1", "1", "1", "1", "2", "2", "2", "2", "2", "2", "2", "2", "2",
"2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2",
"2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2",
"2", "2", "2", "2", "2", "2", "2", "2", "2", "2"), Date = c("Aug 26, 2017",
"Aug 26, 2017", "Aug 26, 2017", "Aug 26, 2017", "Aug 26, 2017",
"Aug 31, 2017", "Aug 31, 2017", "Aug 31, 2017", "Aug 31, 2017",
"Aug 31, 2017", "Aug 31, 2017", "Aug 31, 2017", "Aug 31, 2017",
"Aug 31, 2017", "Aug 31, 2017", "Aug 31, 2017", "Aug 31, 2017",
"Aug 31, 2017", "Sep 1, 2017", "Sep 1, 2017", "Sep 1, 2017",
"Sep 1, 2017", "Sep 1, 2017", "Sep 1, 2017", "Sep 1, 2017", "Sep 1, 2017",
"Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017",
"Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017",
"Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017",
"Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017",
"Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017", "Sep 2, 2017"),
    Time = c("3:00 PM", "2:30 PM", "6:00 PM", "7:30 PM", "10:00 PM",
    "10:30 PM", "8:00 PM", "7:00 PM", "7:00 PM", "7:30 PM", "9:00 PM",
    "9:00 PM", "7:00 PM", "8:00 PM", "7:00 PM", "7:00 PM", "7:30 PM",
    "6:30 PM", "6:00 PM", "9:30 PM", "8:00 PM", "6:30 PM", "8:00 PM",
    "7:00 PM", "8:00 PM", "9:00 PM", "2:00 PM", "8:00 PM", "3:30 PM",
    "11:00 PM", "7:30 PM", "3:45 PM", "12:20 PM", "12:00 PM",
    "12:00 PM", "7:00 PM", "6:00 PM", "10:00 PM", "6:15 PM",
    "11:59 PM", "9:00 PM", "12:00 PM", "12:00 PM", "8:00 PM",
    "6:00 PM", "7:00 PM", "7:10 PM", "4:00 PM", "7:00 PM", "9:30 PM"
    ), Day = c("Sat", "Sat", "Sat", "Sat", "Sat", "Thu", "Thu",
    "Thu", "Thu", "Thu", "Thu", "Thu", "Thu", "Thu", "Thu", "Thu",
    "Thu", "Thu", "Fri", "Fri", "Fri", "Fri", "Fri", "Fri", "Fri",
    "Fri", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat",
    "Sat", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat",
    "Sat", "Sat", "Sat", "Sat", "Sat", "Sat", "Sat"), Winner = c("Brigham Young",
    "Colorado State", "Hawaii", "(19) South Florida", "(14) Stanford",
    "Arizona State", "Arkansas", "Central Michigan", "Cincinnati",
    "Connecticut", "Idaho", "Memphis", "Minnesota", "(2) Ohio State",
    "Tennessee State", "Toledo", "Utah", "Wake Forest", "Army",
    "Boston College", "Colorado", "Eastern Michigan", "Navy",
    "Syracuse", "(8) Washington", "(9) Wisconsin", "Air Force",
    "(1) Alabama", "Alabama-Birmingham", "Arizona", "(12) Auburn",
    "Boise State", "California", "Central Florida", "(5) Clemson",
    "Coastal Carolina", "Duke", "Fresno State", "(15) Georgia",
    "Hawaii", "Howard", "Illinois", "Iowa", "Iowa State", "James Madison",
    "Kansas", "(20) Kansas State", "Kentucky", "Liberty", "(13) Louisiana State"
    ), Pts = c("20", "58", "38", "42", "62", "37", "49", "30",
    "26", "27", "28", "37", "17", "49", "17", "47", "37", "51",
    "64", "23", "17", "24", "42", "50", "30", "59", "62", "24",
    "38", "62", "41", "24", "35", "61", "56", "38", "60", "66",
    "31", "41", "43", "24", "24", "42", "34", "38", "55", "24",
    "48", "27"), c("", "", "@", "@", "", "", "", "", "", "",
    "", "", "", "@", "@", "", "", "", "", "@", "", "", "@", "",
    "@", "", "", "", "", "", "", "", "@", "", "", "", "", "",
    "", "", "@", "", "", "", "@", "", "", "@", "@", ""), Loser = c("Portland State",
    "Oregon State", "Massachusetts", "San Jose State", "Rice",
    "New Mexico State", "Florida A&M", "Rhode Island", "Austin Peay",
    "Holy Cross", "Sacramento State", "Louisiana-Monroe", "Buffalo",
    "Indiana", "Georgia State", "Elon", "North Dakota", "Presbyterian",
    "Fordham", "Northern Illinois", "Colorado State", "Charlotte",
    "Florida Atlantic", "Central Connecticut State", "Rutgers",
    "Utah State", "Virginia Military Institute", "(3) Florida State",
    "Alabama A&M", "Northern Arizona", "Georgia Southern", "Troy",
    "North Carolina", "Florida International", "Kent State",
    "Massachusetts", "North Carolina Central", "Incarnate Word",
    "Appalachian State", "Western Carolina", "Nevada-Las Vegas",
    "Ball State", "Wyoming", "Northern Iowa", "East Carolina",
    "Southeast Missouri State", "Central Arkansas", "Southern Mississippi",
    "Baylor", "Brigham Young"), Pts = c("6", "27", "35", "22",
    "7", "31", "7", "27", "14", "20", "6", "29", "7", "21", "10",
    "13", "16", "7", "6", "20", "3", "7", "19", "7", "14", "10",
    "0", "7", "7", "24", "7", "13", "30", "17", "3", "28", "7",
    "0", "10", "18", "40", "21", "3", "24", "14", "16", "19",
    "17", "45", "0"), TV = c("", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
    "", "", "", "", "", "", "", "", "", "", "", ""), Notes = c("LaVell Edwards Stadium - Provo, Utah",
    "Sonny Lubrick Field at Colorado State Stadium - Fort Collins, Colorado",
    "Warren McGuirk Alumni Stadium - Amherst, Massachusetts",
    "CEFCU Stadium - San Jose, California", "Allianz Stadium - Sydney, AUS",
    "Sun Devil Stadium - Tempe, Arizona", "War Memorial Stadium - Little Rock, Arkansas",
    "Kelly/Shorts Stadium - Mount Pleasant, Michigan", "Nippert Stadium - Cincinnati, Ohio",
    "Pratt & Whitney Stadium at Rentschler Field - East Hartford, Connecticut",
    "Kibbie-Asui Activity Center - Moscow, Idaho", "Liberty Bowl Memorial Stadium - Memphis, Tennessee",
    "TCF Bank Stadium - Minneapolis, Minnesota", "Memorial Stadium \"The Rock\" - Bloomington, Indiana",
    "Georgia State Stadium - Atlanta, Georgia", "Glass Bowl - Toledo, Ohio",
    "Rice-Eccles Stadium - Salt Lake City, Utah", "BB&T Field - Winston-Salem, North Carolina",
    "Michie Stadium - West Point, New York", "Huskie Stadium - DeKalb, Illinois",
    "Sports Authority Field - Denver, Colorado", "Rynearson Stadium - Ypsilanti, Michigan",
    "FAU Football Stadium - Boca Raton, Florida", "Carrier Dome - Syracuse, New York",
    "High Point Solutions Stadium - Piscataway, New Jersey",
    "Camp Randall Stadium - Madison, Wisconsin", "Falcon Stadium - Colorado Springs, Colorado",
    "Mercedes-Benz Stadium - Atlanta, Georgia", "Legion Field - Birmingham, Alabama",
    "Arizona Stadium - Tucson, Arizona", "Jordan-Hare Stadium - Auburn, Alabama",
    "Albertsons Stadium - Boise, Idaho", "Kenan Memorial Stadium - Chapel Hill, North Carolina",
    "", "Clemson Memorial Stadium - Clemson, South Carolina",
    "Brooks Stadium - Conway, South Carolina", "Wallace Wade Stadium - Durham, North Carolina",
    "Bulldog Stadium - Fresno, California", "Sanford Stadium - Athens, Georgia",
    "Aloha Stadium - Honolulu, Hawaii", "Sam Boyd Stadium - Las Vegas, Nevada",
    "Memorial Stadium - Champaign, Illinois", "Kinnick Stadium - Iowa City, Iowa",
    "Jack Trice Stadium - Ames, Iowa", "Dowdy-Ficklen Stadium - Greenville, North Carolina",
    "Memorial Stadium - Lawrence, Kansas", "Bill Snyder Family Stadium - Manhattan, Kansas",
    "M. M. Roberts Stadium - Hattiesburg, Mississippi", "McLane Stadium - Waco, Texas",
    "Mercedes-Benz Superdome - New Orleans, Louisiana")), .Names = c("Rk",
"Wk", "Date", "Time", "Day", "Winner", "Pts", "", "Loser", "Pts",
"TV", "Notes"), row.names = c(1L, 2L, 3L, 4L, 5L, 7L, 8L, 9L,
10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L,
23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L,
36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L,
49L, 50L, 51L), class = "data.frame")

Body:
You can use the following regex and replace it with the empty string:

^\\([0-9]+\\)\\s+ or ^\\(\\d+\\)\\s+

this will remove the starting digits surrounded by parenthesis and it will trim the beginning of your string.

Example:

(3) Florida State -> Florida State


问:
Best way to parse incoming byte stream?
I am wondering what the best way to look for a start and end sequence in a byte stream from a file. The way I have been doing this is:

```<code>begin_msg = [b'B', b'E', b'G', b'I', b'N', b'_', b'M', b'S', b'G', b'#']
end_msg = [b'#', b'E', b'N', b'D', b'_', b'M', b'S', b'G']

with open(file, 'rb') as _file:

begin_id = [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']
end_id = [b'', b'', b'', b'', b'', b'', b'', b'']

if True:

    byte = _file.read(1)

    capturing = False

    while byte != b'':

        begin_id.append(byte)
        begin_id.pop(0)
        end_id.append(byte)
        end_id.pop(0)

        if begin_id == begin_msg:
            capturing = True

        if end_id == end_msg:
            capturing = False
            break

        byte = _file.read(1)

        if capturing:
            byte_message += byte
</code>```

I am sure there is a better way to do this. What is the cleanest way to look for these beginning and ending identifiers?

答:
What you want to do sounds like something Python's re regular expressions (aka regex) module can handle. You can use it to parse a byte-string (instead of the usual text-string) if you pass it a byte-string to parse and also define your pattern as a byte-string. Note: The easiest way to do that is to use the b string prefix in front of them (not in front of each character, as you're doing in your question).

For testing the code coming up I used a file with this in it (sorry, not very imaginative):

BEGIN_MSG#
Douglas was here.
#END_MSG
Other stuff
in here.
BEGIN_MSG#
And so
was Roger.
#END_MSG
```

<p>Then used the module on it with the proper regex <code>pattern</code> like so:</p>

```import re

pattern = rb'BEGIN_MSG#(.+?)#END_MSG'
filename = 'bytestream.txt'

with open(filename, 'rb') as file:
    matches = re.findall(pattern, file.read(), flags=re.DOTALL)
    if not matches:
        print('No matches found')
    else:
        print('Matches:')
        for i, match in enumerate(matches, 1):
            print('#{}: {}'.format(i, match))
```

<p>The output from it looks like this, displaying the list of strings returned from <code>re.findall()</code>:</p>

<pre class="lang-none prettyprint-override"><code>Matches:
#1: b'\r\nDouglas was here.\r\n'
#2: b'\r\nAnd so\r\nwas Roger.\r\n'
</code>```

Title: Best way to parse incoming byte stream?

Body:
I am wondering what the best way to look for a start and end sequence in a byte stream from a file. The way I have been doing this is:

begin_msg = [b'B', b'E', b'G', b'I', b'N', b'_', b'M', b'S', b'G', b'#']
end_msg = [b'#', b'E', b'N', b'D', b'_', b'M', b'S', b'G']

with open(file, 'rb') as _file:

begin_id = [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']
end_id = [b'', b'', b'', b'', b'', b'', b'', b'']

if True:

    byte = _file.read(1)

    capturing = False

    while byte != b'':

        begin_id.append(byte)
        begin_id.pop(0)
        end_id.append(byte)
        end_id.pop(0)

        if begin_id == begin_msg:
            capturing = True

        if end_id == end_msg:
            capturing = False
            break

        byte = _file.read(1)

        if capturing:
            byte_message += byte

I am sure there is a better way to do this. What is the cleanest way to look for these beginning and ending identifiers?

Body:
What you want to do sounds like something Python's re regular expressions (aka regex) module can handle. You can use it to parse a byte-string (instead of the usual text-string) if you pass it a byte-string to parse and also define your pattern as a byte-string. Note: The easiest way to do that is to use the b string prefix in front of them (not in front of each character, as you're doing in your question).

For testing the code coming up I used a file with this in it (sorry, not very imaginative):

BEGIN_MSG#
Douglas was here.
#END_MSG
Other stuff
in here.
BEGIN_MSG#
And so
was Roger.
#END_MSG

Then used the module on it with the proper regex pattern like so:

import re

pattern = rb'BEGIN_MSG#(.+?)#END_MSG'
filename = 'bytestream.txt'

with open(filename, 'rb') as file:
    matches = re.findall(pattern, file.read(), flags=re.DOTALL)
    if not matches:
        print('No matches found')
    else:
        print('Matches:')
        for i, match in enumerate(matches, 1):
            print('#{}: {}'.format(i, match))

The output from it looks like this, displaying the list of strings returned from re.findall():

Matches:
#1: b'\r\nDouglas was here.\r\n'
#2: b'\r\nAnd so\r\nwas Roger.\r\n'


问:
Resize image to full width and variable height with Picasso
I have a listView with an adapter that contains ImageView of variable size (width and height). I need resize the pictures load with Picasso to the max width of layout and a variable height given by the aspect ratio of the picture.

I have checked this question:
Resize image to full width and fixed height with Picasso

The fit() works but I haven't found nothing to keep the aspect ratio of the picture.

This code partially works if I fixed the height in the layout of the adapter:

```<code>Picasso.with(this.context).load(message_pic_url)
.placeholder(R.drawable.profile_wall_picture)
.fit().centerInside()
.into(holder.message_picture);
</code>```

But it generates blank spaces between the pictures of the listView because the pictures may be that not have that height.

答:
extend ImageView then override onMeasure method like the following.</p>

```<code>@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        Drawable d = getDrawable();

        if(d!=null && fittingType == FittingTypeEnum.FIT_TO_WIDTH){
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
            setMeasuredDimension(width, height);
        }else{
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
</code>```

Body:
I have a listView with an adapter that contains ImageView of variable size (width and height). I need resize the pictures load with Picasso to the max width of layout and a variable height given by the aspect ratio of the picture.

I have checked this question:
Resize image to full width and fixed height with Picasso

The fit() works but I haven't found nothing to keep the aspect ratio of the picture.

This code partially works if I fixed the height in the layout of the adapter:

Picasso.with(this.context).load(message_pic_url)
.placeholder(R.drawable.profile_wall_picture)
.fit().centerInside()
.into(holder.message_picture);

But it generates blank spaces between the pictures of the listView because the pictures may be that not have that height.

Body:
extend ImageView then override onMeasure method like the following.

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        Drawable d = getDrawable();

        if(d!=null && fittingType == FittingTypeEnum.FIT_TO_WIDTH){
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
            setMeasuredDimension(width, height);
        }else{
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }


问:
Can't figure out why my image wont move in pygame
I'm just messing around with Pygame and I can't see what I'm doing incorrectly to make the red circle move with the arrow keys. I can't tell if it's in my main loop. I also haven't been able to find very many tutorials on sprite or looping animations with Pygame. If I for example wanted to make a square oscillate for example like a moving platform how would I do that?

```</p>

<code>import pygame
import time

## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250

## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")

# player
def player():
    pygame.draw.circle(game_screen,red,(x,y),15)

# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)

### main loop

dead = False
while dead != True:
     for event in pygame.event.get():
         if event.type == pygame.QUIT:
            dead = True
            if event.type == pygame.KEYDOWN:
             if event.key == pygame.K_LEFT:
                player_x = -1
            elif event.key == pygame.K_RIGHT:
                player_x = +1
            if event.key == pygame.K_UP:
                player_y = +1
            elif event.key == pygame.K_DOWN:
                 player_y = -1
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or pygame.K_RIGHT:
                    player_x = 0
            if event.key == pygame.K_UP or pygame.K_DOWN:
                    player_y = 0

     game_screen.fill(black)
     player()
     pygame.display.update()
     x -= player_x
     y -= player_y

pygame.quit()
quit()
</code>```

答:
Your indendation is all messed up.

Your code won't do anything unless the event is QUIT... which then makes it quit.

Your boolean logic is wrong.

This is not proper syntax event.key == pygame.K_UP or pygame.K_DOWN. The order of precedence here is as follows (event.key == pygame.K_UP) or (K_DOWN). Since K_DOWN is truthy, it is always true and thus this entire statement is always true.

I think you mean: event.key == pygame.K_UP or event.key == pygame.K_DOWN

Lastly, it wont' keep moving as you say you want.

It will only move when there is an event in the queue. You can make it keep moving by generating events. Perhaps with an event timer.

Here is a fixed version, hope this helps:

```<code>import pygame
import time

## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250

## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")

# player
def player(game_screen, red, point):   # Use parameters not globals
    pygame.draw.circle(game_screen, red, point, 15)

# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)

### main loop
pygame.time.set_timer(pygame.USEREVENT, 1)  # 1 per second

dead = False
while not dead:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            dead = True
        elif event.type == pygame.USEREVENT:
            pygame.time.set_timer(pygame.USEREVENT, 1)  # Set another timer for another 1 second

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_x = +10
            elif event.key == pygame.K_RIGHT:
                player_x = -10
            elif event.key == pygame.K_UP:
                player_y = +10
            elif event.key == pygame.K_DOWN:
                player_y = -10
        elif event.type == pygame.KEYUP:
            if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
                player_x = 0
            elif event.key in [pygame.K_UP, pygame.K_DOWN]:
                player_y = 0
        game_screen.fill(black)
        player(game_screen,red,(x,y))
        pygame.display.update()
        x -= player_x
        y -= player_y

pygame.quit()
</code>```

Body:
I'm just messing around with Pygame and I can't see what I'm doing incorrectly to make the red circle move with the arrow keys. I can't tell if it's in my main loop. I also haven't been able to find very many tutorials on sprite or looping animations with Pygame. If I for example wanted to make a square oscillate for example like a moving platform how would I do that?

import pygame
import time

## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250

## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")

# player
def player():
    pygame.draw.circle(game_screen,red,(x,y),15)

# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)

### main loop

dead = False
while dead != True:
     for event in pygame.event.get():
         if event.type == pygame.QUIT:
            dead = True
            if event.type == pygame.KEYDOWN:
             if event.key == pygame.K_LEFT:
                player_x = -1
            elif event.key == pygame.K_RIGHT:
                player_x = +1
            if event.key == pygame.K_UP:
                player_y = +1
            elif event.key == pygame.K_DOWN:
                 player_y = -1
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or pygame.K_RIGHT:
                    player_x = 0
            if event.key == pygame.K_UP or pygame.K_DOWN:
                    player_y = 0

     game_screen.fill(black)
     player()
     pygame.display.update()
     x -= player_x
     y -= player_y

pygame.quit()
quit()

Body:
Your indendation is all messed up.

Your code won't do anything unless the event is QUIT... which then makes it quit.

Your boolean logic is wrong.

This is not proper syntax event.key == pygame.K_UP or pygame.K_DOWN. The order of precedence here is as follows (event.key == pygame.K_UP) or (K_DOWN). Since K_DOWN is truthy, it is always true and thus this entire statement is always true.

I think you mean: event.key == pygame.K_UP or event.key == pygame.K_DOWN

Lastly, it wont' keep moving as you say you want.

It will only move when there is an event in the queue. You can make it keep moving by generating events. Perhaps with an event timer.

Here is a fixed version, hope this helps:

import pygame
import time

## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250

## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")

# player
def player(game_screen, red, point):   # Use parameters not globals
    pygame.draw.circle(game_screen, red, point, 15)

# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)

### main loop
pygame.time.set_timer(pygame.USEREVENT, 1)  # 1 per second

dead = False
while not dead:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            dead = True
        elif event.type == pygame.USEREVENT:
            pygame.time.set_timer(pygame.USEREVENT, 1)  # Set another timer for another 1 second

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_x = +10
            elif event.key == pygame.K_RIGHT:
                player_x = -10
            elif event.key == pygame.K_UP:
                player_y = +10
            elif event.key == pygame.K_DOWN:
                player_y = -10
        elif event.type == pygame.KEYUP:
            if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
                player_x = 0
            elif event.key in [pygame.K_UP, pygame.K_DOWN]:
                player_y = 0
        game_screen.fill(black)
        player(game_screen,red,(x,y))
        pygame.display.update()
        x -= player_x
        y -= player_y

pygame.quit()


问:
Data flow stuck with error message Causes: 606330f83ab24c58
Got an error message in my dataflow job.

I am using 2.1.0 SDK and cloudshell to launch my job.

(606330f83ab2470f): Workflow failed. Causes: (606330f83ab24c58): The
  Dataflow appears to be stuck. Please reach out to the Dataflow team at http://stackoverflow.com/questions/tagged/google-cloud-dataflow.

答:
Internally, Dataflow failed to create worker instances. The error was :

[...] Invalid value for field 'resource.properties.networkInterfaces[0].subnetwork': ''. Network interface must specify a subnet if the network resource is in custom subnet mode. [..]

Can you provide --subnetwork option while launching the job? (brief description here : https://beam.apache.org/documentation/sdks/javadoc/2.0.0/org/apache/beam/runners/dataflow/options/DataflowPipelineWorkerPoolOptions.html#getSubnetwork--)

It might look like something like "regions/us-central1/subnetworks/your-network-name-us-central1"


问:
How to store big matrix(data frame) that can be subsetted easily later
I will generate a big matrix(data frame) in R whose size is about 1300000*10000, about 50 GB. I want to store this matrix in a appropriate format, so later I can feed the data into Python or other program codes to make some analysis. Of course I cannot feed the data one time, so I have to subset the matrix and feed them little by little.
But I don't know how to store the matrix. I think of two ways, but I think neither is appropriate:
(1) plain text(including csv or excel table), because it is very hard to subset(e.g. if I just want some columns and some rows of the data)
(2) database, I have searched information about mysql and sqlite, but it seems that the number of columns is limited in sql database(1024).
So I just want to know if there are any good strategies to store the data, so that I can subset the data by row/column indexes or name.</p>

答:
Have separate column(s) for each of the few columns you need to search/filter on.  Then put the entire 10K columns into some data format that is convenient for the client code to parse.  JSON is one common possibility.

So the table would 1.3M rows and perhaps 3 columns:  an id (auto_increment, primary key), the column search on, and the JSON blob - as datatype JSON or TEXT (depending on software version) for the many data values.


问:
How to add a marker in google maps when the object is moving is React
I'm building React app with API that tracks some objects and I don't use any lib to manage the google maps. When I'm setting a static LatLng it shows where it should be, but when it gets data which is updated every second it's not showing.
can you help me?</p>

```<code>class GoogleMap extends Component {

    shouldComponentUpdate() {
        return false;
    }

    componentWillReceiveProps( nextProps ) {
        this.map.panTo({lat: nextProps.lat, lng: nextProps.lng})
    }

    componentDidMount() {
        // this.myLatLng = {lat: -25.363, lng: 131.044};
        this.position = {
            center: {
                lat: this.props.lat,
                lng: this.props.lng
            }
        };
        this.mapOptions = {
            center: this.position,
            zoom: 5,
            disableDefaultUI: true
        };
        this.map = new google.maps.Map(this.refs.map, this.mapOptions);
        this.marker = new google.maps.Marker({
            position: this.myLatLng,
            map: this.map
        });
    }

    render() {
        return (
            <div id="map" ref="map"/>
        );
    }
}
export default GoogleMap;
</code>```

答:
You have to use marker.setPosition to update the position of a marker, It takes a
LatLng as an argument and moves the marker there.

Here is a reference to the Google Maps Javascript API for marker.
https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker

Body:
I'm building React app with API that tracks some objects and I don't use any lib to manage the google maps. When I'm setting a static LatLng it shows where it should be, but when it gets data which is updated every second it's not showing.
can you help me?

class GoogleMap extends Component {

    shouldComponentUpdate() {
        return false;
    }

    componentWillReceiveProps( nextProps ) {
        this.map.panTo({lat: nextProps.lat, lng: nextProps.lng})
    }

    componentDidMount() {
        // this.myLatLng = {lat: -25.363, lng: 131.044};
        this.position = {
            center: {
                lat: this.props.lat,
                lng: this.props.lng
            }
        };
        this.mapOptions = {
            center: this.position,
            zoom: 5,
            disableDefaultUI: true
        };
        this.map = new google.maps.Map(this.refs.map, this.mapOptions);
        this.marker = new google.maps.Marker({
            position: this.myLatLng,
            map: this.map
        });
    }

    render() {
        return (

        );
    }
}
export default GoogleMap;


问:
is there a class history visualization tool for SVN
I know of codeswarm and gource, but AFAIK they visualize the repository on a class level.

 What i would like to see animated is the history of a single file (or a package) - LOC count is essential, LOComment, dependencies, method count a.s.o. would sure be nice too :)

答: Not an animation either, but probably a very useful tool to find history of a method: http://codicesoftware.blogspot.com/2011/01/method-history-for-subversion-is-here.html</p>


问:
CKContainer.discoverAllIdentities always fails
The CKContainer.discoverAllIdentities request always fails in my CloudKit app. It has continually failed over the course of several days.

A simplified version of the code that is failing (which results in the same error) is:

```<code>private func getContacts(completion: (([CKUserIdentity]?) -> Void)?) {
    container.status(forApplicationPermission: .userDiscoverability) { [weak self] status, error in
        if let error = error {
            print(error)
        }

        switch status {
        case .granted:
            self?.discover(completion: completion)
        default:
            print("status not granted")
        }
    }
}

private func discover(completion: (([CKUserIdentity]?) -> Void)?) {
    let op = CKDiscoverAllUserIdentitiesOperation()
    op.qualityOfService = .userInitiated
    op.discoverAllUserIdentitiesCompletionBlock = { error in
        if let error = error {
            print(error)
        }
    }
    op.userIdentityDiscoveredBlock = { identity in
        print(identity)
    }
    op.start()
}
</code>```

It results in an error being passed to the op.discoverAllUserIdentitiesCompletionBlock. The description of the error in the log is:

<CKError 0x1c4a51a60: "Server Rejected Request" (15/2000); server message = "Internal server error"; uuid = F67453B9-712D-4E5E-9335-929123E3C978; container ID = "iCloud.com.huntermaximillionmonk.topdraw">

Previously, this operation would work, but only for certain iCloud users. Now it's not for both of my test users.

答:
Edit:

Apple fixed this issue day after this answer was posted, coincidence?! I don't think so :)

This is not actually the answer to the question, but a fix that helped me to cross over this error. It will require you to change your app UI interaction and add ContactsUI framework to your project, moreover your user will be responsible for selecting a contact with iCloud related email.

Good news is that the method discoverUserIdentity is still works. So, you can use it to get CKUserIdentity from manually selected contact.

```<code>func addContact(_ contact:CNContact) {

     var lookUpEmails = [CKUserIdentityLookupInfo]()
     for email in contact.emailAddresses {
         lookUpEmails.append(CKUserIdentityLookupInfo(emailAddress: (email.value as String)))
     }

     let checkUserOperation = CKDiscoverUserIdentitiesOperation()

     checkUserOperation.userIdentityLookupInfos = lookUpEmails

     checkUserOperation.userIdentityDiscoveredBlock = { [unowned self] (identity, info) -> Void in
         if identity.hasiCloudAccount {
             if let recordID = identity.userRecordID {
                  //do something with discovered user
             }
             checkUserOperation.cancel()
         }
     }
     checkUserOperation.queuePriority = Operation.QueuePriority.high
     CKContainer.default().add(checkUserOperation)
}
</code>```

It might sound useless, but in my case, it helped me to solve the Server Rejected Request" (15/2000) error, to fix one of the features of my app and continue to use the other feature related code with less efforts than I thought.

I hope someone will find this helpful.

Body:
The CKContainer.discoverAllIdentities request always fails in my CloudKit app. It has continually failed over the course of several days.

A simplified version of the code that is failing (which results in the same error) is:

private func getContacts(completion: (([CKUserIdentity]?) -> Void)?) {
    container.status(forApplicationPermission: .userDiscoverability) { [weak self] status, error in
        if let error = error {
            print(error)
        }

        switch status {
        case .granted:
            self?.discover(completion: completion)
        default:
            print("status not granted")
        }
    }
}

private func discover(completion: (([CKUserIdentity]?) -> Void)?) {
    let op = CKDiscoverAllUserIdentitiesOperation()
    op.qualityOfService = .userInitiated
    op.discoverAllUserIdentitiesCompletionBlock = { error in
        if let error = error {
            print(error)
        }
    }
    op.userIdentityDiscoveredBlock = { identity in
        print(identity)
    }
    op.start()
}

It results in an error being passed to the op.discoverAllUserIdentitiesCompletionBlock. The description of the error in the log is:

<CKError 0x1c4a51a60: "Server Rejected Request" (15/2000); server message = "Internal server error"; uuid = F67453B9-712D-4E5E-9335-929123E3C978; container ID = "iCloud.com.huntermaximillionmonk.topdraw">

Previously, this operation would work, but only for certain iCloud users. Now it's not for both of my test users.

Body:
Edit:

Apple fixed this issue day after this answer was posted, coincidence?! I don't think so :)

This is not actually the answer to the question, but a fix that helped me to cross over this error. It will require you to change your app UI interaction and add ContactsUI framework to your project, moreover your user will be responsible for selecting a contact with iCloud related email.

Good news is that the method discoverUserIdentity is still works. So, you can use it to get CKUserIdentity from manually selected contact.

func addContact(_ contact:CNContact) {

     var lookUpEmails = [CKUserIdentityLookupInfo]()
     for email in contact.emailAddresses {
         lookUpEmails.append(CKUserIdentityLookupInfo(emailAddress: (email.value as String)))
     }

     let checkUserOperation = CKDiscoverUserIdentitiesOperation()

     checkUserOperation.userIdentityLookupInfos = lookUpEmails

     checkUserOperation.userIdentityDiscoveredBlock = { [unowned self] (identity, info) -> Void in
         if identity.hasiCloudAccount {
             if let recordID = identity.userRecordID {
                  //do something with discovered user
             }
             checkUserOperation.cancel()
         }
     }
     checkUserOperation.queuePriority = Operation.QueuePriority.high
     CKContainer.default().add(checkUserOperation)
}

It might sound useless, but in my case, it helped me to solve the Server Rejected Request" (15/2000) error, to fix one of the features of my app and continue to use the other feature related code with less efforts than I thought.

I hope someone will find this helpful.


问:
How do you print the current system time with milliseconds in C++11?
I've got a problem with getting actual system time with milliseconds. The only one good method I found is in Windows.h, but I can't use it. I'm supposed to use std::chrono. How can I do this?

I spent a lot of time trying to google it, but I found only second-precision examples.

I'm trying to get string like this:

```<code>[2014-11-25 22:15:38:449]
</code>```

答:
Did anybody notice that to_time_t rounds the seconds, instead of truncating

```<code>auto now = system_clock::now();
time_t secs = system_clock::to_time_t(now);
now {_MyDur={_MyRep=15107091978759765 } }
secs = 1510709198
</code>```

so when you tack on the milliseconds

```<code>auto tse = now.time_since_epoch();
auto now_ms = duration_cast<milliseconds>(tse);
auto now_s = duration_cast<seconds>(tse);
auto jst_ms = now_ms - now_s;
DWORD msecs = jst_ms.count();
msecs = 875
</code>```

secs should be 1510709197, but look at now_s, it's right

```<code>now_s {_MyRep=1510709197 }
</code>```

Body:
I've got a problem with getting actual system time with milliseconds. The only one good method I found is in Windows.h, but I can't use it. I'm supposed to use std::chrono. How can I do this?

I spent a lot of time trying to google it, but I found only second-precision examples.

I'm trying to get string like this:

[2014-11-25 22:15:38:449]

Body:
Did anybody notice that to_time_t rounds the seconds, instead of truncating

auto now = system_clock::now();
time_t secs = system_clock::to_time_t(now);
now {_MyDur={_MyRep=15107091978759765 } }
secs = 1510709198

so when you tack on the milliseconds

auto tse = now.time_since_epoch();
auto now_ms = duration_cast<milliseconds>(tse);
auto now_s = duration_cast<seconds>(tse);
auto jst_ms = now_ms - now_s;
DWORD msecs = jst_ms.count();
msecs = 875

secs should be 1510709197, but look at now_s, it's right

now_s {_MyRep=1510709197 }


问:
openCV3: Not getting the expected output on morphologically transforming an image in opencv
I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason.

```<code># Top Hat: difference between input image and opening
kernel = np.ones((5,5),np.float32)/25
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat')
plt.xticks([]), plt.yticks([])
plt.show()
</code>```

What is expected

What I am getting

EDIT: Added the kernel.

答:
Do you need to normalize your kernel?
Try removing the division by 25 from the kernel.

Morphological kernels are supposed to be consist of "ones" and "zeros". Therefore, no normalization is required. It will work fine with type CV_8UC1 as well.

Body:
I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason.

# Top Hat: difference between input image and opening
kernel = np.ones((5,5),np.float32)/25
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat')
plt.xticks([]), plt.yticks([])
plt.show()

What is expected

What I am getting

EDIT: Added the kernel.


问:
How do I do a nested database query within a for loop?
```<code>supportChat: function(){
    return functions.https.onRequest((req, res) => {
        var userId = req.query.userId;
        var object = {};
        db.ref("/users/-KwZ2N38Q6a1a87p982/threads").orderByKey().once('value').then(function(snapshot) {
            var snap = snapshot.val();
            var keys = Object.keys(snap);

            for (var i = 0; i < keys.length; i++){
                k = keys[i];
                db.ref("/threads/"+k+"/lastMessage").orderByKey().once('value').then(function(snapshot){
                    var snapshot = snapshot.val();
                    if (snapshot[i]["sender"] != "-KwZ2N38Q6a1a87p982"){
                       object[snap[i]["messageID"]] = snapshot;
                    }
                });
            }
            console.log(object);
            return res.status(200).send(object);
        });
    });
},
</code>```

Each user in my database has a threads child, which shows all the chat threads they have going. Then we have another threads section of the database which has all the data of that thread.

What I'm trying to do is check a particular users' threads id's against the threads section of the database to find all the threads where the last message in the thread was not sent by me (current user).

I have no idea why I'm struggling with this. What is the right way to send all the snapshot.val() of each thread that meets my condition to the endpoint all in one push? Maybe my approach is way off.

答:
To know when all the promises in your for loop are done, you can accumulate the array of promises that you get from the loop and then use Promise.all() to know when they are all done.

You also need to protect your for loop index so that each invocation of the for loop maintains its own index so it is still correct when your async .then() handler is called.  You can do that by switching your for loop to use let i instead of var i.

```<code>supportChat: function(){
    return functions.https.onRequest((req, res) => {
        let userId = req.query.userId;
        let  object = {};
        db.ref("/users/-KwZ2N38Q6a1a87p982/threads").orderByKey().once('value').then(function(snapshot) {
            let snap = snapshot.val();
            let keys = Object.keys(snap);
            let promises = [];

            for (let i = 0; i < keys.length; i++){
                let k = keys[i];
                promises.push(db.ref("/threads/"+k+"/lastMessage").orderByKey().once('value').then(function(snapshot){
                    let snapshot = snapshot.val();
                    if (snapshot[i]["sender"] != "-KwZ2N38Q6a1a87p982"){
                       object[snap[i]["messageID"]] = snapshot;
                    }
                }));
            }
            return Promise.all(promises).then(() => {
                console.log(object);
                return res.send(object);
            });
        }).catch(err => {
            console.log(err);
            return res.sendStatus(500);
        });
    });
},
</code>```

Other comments on the code:

FYI, if you're trying to actually return something from the supportChat() function, please specify what that is.  Right now, it is not clear what you expect to return from that function call.

And, you don't need the .status(200) part of this:

```<code>res.status(200).send(object);
</code>```

You can just do:

```<code>res.send(object);
</code>```

all by itself and that will automatically use a status of 200.

And, you need a .catch() handler to catch errors and send a response in the error condition.

Body:
supportChat: function(){
    return functions.https.onRequest((req, res) => {
        var userId = req.query.userId;
        var object = {};
        db.ref("/users/-KwZ2N38Q6a1a87p982/threads").orderByKey().once('value').then(function(snapshot) {
            var snap = snapshot.val();
            var keys = Object.keys(snap);

            for (var i = 0; i < keys.length; i++){
                k = keys[i];
                db.ref("/threads/"+k+"/lastMessage").orderByKey().once('value').then(function(snapshot){
                    var snapshot = snapshot.val();
                    if (snapshot[i]["sender"] != "-KwZ2N38Q6a1a87p982"){
                       object[snap[i]["messageID"]] = snapshot;
                    }
                });
            }
            console.log(object);
            return res.status(200).send(object);
        });
    });
},

Each user in my database has a threads child, which shows all the chat threads they have going. Then we have another threads section of the database which has all the data of that thread.

What I'm trying to do is check a particular users' threads id's against the threads section of the database to find all the threads where the last message in the thread was not sent by me (current user).

I have no idea why I'm struggling with this. What is the right way to send all the snapshot.val() of each thread that meets my condition to the endpoint all in one push? Maybe my approach is way off.

Body:
To know when all the promises in your for loop are done, you can accumulate the array of promises that you get from the loop and then use Promise.all() to know when they are all done.

You also need to protect your for loop index so that each invocation of the for loop maintains its own index so it is still correct when your async .then() handler is called.  You can do that by switching your for loop to use let i instead of var i.

supportChat: function(){
    return functions.https.onRequest((req, res) => {
        let userId = req.query.userId;
        let  object = {};
        db.ref("/users/-KwZ2N38Q6a1a87p982/threads").orderByKey().once('value').then(function(snapshot) {
            let snap = snapshot.val();
            let keys = Object.keys(snap);
            let promises = [];

            for (let i = 0; i < keys.length; i++){
                let k = keys[i];
                promises.push(db.ref("/threads/"+k+"/lastMessage").orderByKey().once('value').then(function(snapshot){
                    let snapshot = snapshot.val();
                    if (snapshot[i]["sender"] != "-KwZ2N38Q6a1a87p982"){
                       object[snap[i]["messageID"]] = snapshot;
                    }
                }));
            }
            return Promise.all(promises).then(() => {
                console.log(object);
                return res.send(object);
            });
        }).catch(err => {
            console.log(err);
            return res.sendStatus(500);
        });
    });
},

Other comments on the code:

FYI, if you're trying to actually return something from the supportChat() function, please specify what that is.  Right now, it is not clear what you expect to return from that function call.

And, you don't need the .status(200) part of this:

res.status(200).send(object);

You can just do:

res.send(object);

all by itself and that will automatically use a status of 200.

And, you need a .catch() handler to catch errors and send a response in the error condition.


问:
how to create a multi dimensional array out of dynamically created fields and variables
here is my url: http://iadprint.com/products?product=business%20card

the fields that you see on this page are all dynamically created on the backend. i decided to use the fieldnames created as variables to display the price as you can see in the js below. I have two problems one being that when the page refreshes the pricing div values cleans out and the selections do not stay and the second one is i cant figure out how to add all items selected into an array for the cart page.

for the first problem i figured it was best to place each selection into a cookie in an array form and on refresh pull out the data and select the needed fields. unless there is another way.

this is what im guessing the array would look like

```<code>$products = array("product" => "business_card", array("ProdID" => "1"), ("ProdID" => "2") ..and so on)
</code>```

basically i would add only the fields who have a length of greater than zero so that i know it was selected. what my question is would that be the correct way to format the array? and is there a way i can do array_push in javascript to push in new elements each time a selection change is occurred?

as for problem two im hopefully guessing it will be easy once the cookie is created with its correct data.

答:
for the first problem i figured it was
  best to place each selection into a
  cookie in an array form and on refresh
  pull out the data and select the
  needed fields. unless there is another
  way.

You could use AJAX and PHP session vars. On selection change, you send the selection via AJAX to a PHP page which sets some session data. When the page loads, you use the session data to set the selected fields.

is there a way i can do array_push in
  javascript

```<code>var arr = [];
arr.push(obj1);
</code>```

More on push and other js array methods: http://www.javascriptkit.com/jsref/arrays.shtml

Body:
here is my url: http://iadprint.com/products?product=business%20card

the fields that you see on this page are all dynamically created on the backend. i decided to use the fieldnames created as variables to display the price as you can see in the js below. I have two problems one being that when the page refreshes the pricing div values cleans out and the selections do not stay and the second one is i cant figure out how to add all items selected into an array for the cart page.

for the first problem i figured it was best to place each selection into a cookie in an array form and on refresh pull out the data and select the needed fields. unless there is another way.

this is what im guessing the array would look like

$products = array("product" => "business_card", array("ProdID" => "1"), ("ProdID" => "2") ..and so on)

basically i would add only the fields who have a length of greater than zero so that i know it was selected. what my question is would that be the correct way to format the array? and is there a way i can do array_push in javascript to push in new elements each time a selection change is occurred?

as for problem two im hopefully guessing it will be easy once the cookie is created with its correct data.

Body:
for the first problem i figured it was
  best to place each selection into a
  cookie in an array form and on refresh
  pull out the data and select the
  needed fields. unless there is another
  way.

You could use AJAX and PHP session vars. On selection change, you send the selection via AJAX to a PHP page which sets some session data. When the page loads, you use the session data to set the selected fields.

is there a way i can do array_push in
  javascript

var arr = [];
arr.push(obj1);

More on push and other js array methods: http://www.javascriptkit.com/jsref/arrays.shtml


问:
How to fix Xcode error: Could not locate device support files on iPhone with Xcode
I have this error for the new iPhone X:

Could not locate device support files.

This iPhone X (Model A1865, A1901, A1902, A1903) is running iOS 11.1 (15B93), which may not be supported by this version of Xcode.

I'm running the latest version of Xcode (Beta 9.2 9C32c) which doesn't support the iPhone X (iOS 11.1). The problem is it's a brand new iPhone, and there are no older Configuration Files to do the switch talked in most of the solved posts.

Are there any other solution to this issue since downloading the latest version of Xcode is already what I'm running, and finding the Configuration Files to do the switch seems unlikely right now? Does anyone have those Configuration Files or know how to edit them to trick Xcode?

答: I was able to run it, by first using BuddyBuild.com to send me a tester app through email, that I downloaded successfully.  After that, I was able to build the app.</p>


问:
Docker: change folder where to store docker volumes
On my Ubuntu EC2 I host an application using docker containers. db data and upload data is being stored in volumes CaseBook-data-db and CaseBook-data-uploads which are being created with this commands:

```<code>docker volume create --name=CaseBook-data-db
docker volume create --name=CaseBook-data-uploads
</code>```

Volumes being attached through docker-compose file:

```<code>version: '2'
services:
    mongo:
        container_name: "CaseBook-db"
        restart: always
        image: mongo:3.2.7
        ports:
            - "27017"
        volumes:
            - data_db:/data/db
        labels:
            - "ENVIRONMENT_TYPE=meteor"

    app:
        container_name: "CaseBook-app"
        restart: always
        image: "meteor/casebook"
        build: .
        depends_on:
            - mongo
        environment:
            - MONGO_URL=mongodb://mongo:27017/CaseBook
        ports:
            - "80:3000"
        volumes:
            - data_uploads:/Meteor-CaseBook-Container/.uploads
        labels:
            - "ENVIRONMENT_TYPE=meteor"
volumes:
     data_db:
        external:
            name: CaseBook-data-db
     data_uploads:
        external:
            name: CaseBook-data-uploads
</code>```

I need to store those docker volumes in different folder(for example /home/ubuntu/data/) of the host machine. How to change docker storage folder for volumes? Or there is a better way in doing this? Thank you in advance.

答:
Another way with build-in driver local:

```<code>docker volume create --opt type=none --opt device=/home/ubuntu/data/ --opt o=bind data_db
</code>```

(This use DimonVersace example with: data_db declared as external named volume in docker-compose and /home/ubuntu/data/ as the folder on the host machine)

Body:
On my Ubuntu EC2 I host an application using docker containers. db data and upload data is being stored in volumes CaseBook-data-db and CaseBook-data-uploads which are being created with this commands:

docker volume create --name=CaseBook-data-db
docker volume create --name=CaseBook-data-uploads

Volumes being attached through docker-compose file:

version: '2'
services:
    mongo:
        container_name: "CaseBook-db"
        restart: always
        image: mongo:3.2.7
        ports:
            - "27017"
        volumes:
            - data_db:/data/db
        labels:
            - "ENVIRONMENT_TYPE=meteor"

    app:
        container_name: "CaseBook-app"
        restart: always
        image: "meteor/casebook"
        build: .
        depends_on:
            - mongo
        environment:
            - MONGO_URL=mongodb://mongo:27017/CaseBook
        ports:
            - "80:3000"
        volumes:
            - data_uploads:/Meteor-CaseBook-Container/.uploads
        labels:
            - "ENVIRONMENT_TYPE=meteor"
volumes:
     data_db:
        external:
            name: CaseBook-data-db
     data_uploads:
        external:
            name: CaseBook-data-uploads

I need to store those docker volumes in different folder(for example /home/ubuntu/data/) of the host machine. How to change docker storage folder for volumes? Or there is a better way in doing this? Thank you in advance.

Body:
Another way with build-in driver local:

docker volume create --opt type=none --opt device=/home/ubuntu/data/ --opt o=bind data_db

(This use DimonVersace example with: data_db declared as external named volume in docker-compose and /home/ubuntu/data/ as the folder on the host machine)


问:
DynamoDB save to DB
I'm new to AWS and i'm trying to save data to my database using the aws example with News table.

I connected this function to the main storyboard button :

```<code> @IBAction func addButton(_ sender: Any) {

    let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()

    //Create data object using data models you downloaded from Mobile Hub
    let newsItem: News = News();

    // Use AWSIdentityManager.default().identityId here to get the user identity id.
    newsItem._userId = "us-east-1:74c8f7ce-244b-4476-963e-0dcb3216f406"
    newsItem._articleId = "0123"
    newsItem._title = "Banana"
    newsItem._author = "Logan"
    newsItem._content = "Should I stay or should I go now?"
    newsItem._category = "Food"

    //Save a new item
    dynamoDbObjectMapper.save(newsItem, completionHandler: {
        (error: Error?) -> Void in

        if let error = error {
            print("Amazon DynamoDB Save Error: \(error)")
            return
        }
        print("An item was saved.")
    })

}
</code>```

but when I hit the button I get :
mazon DynamoDB Save Error: Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=com.amazon.coral.validate#ValidationException, message=Supplied AttributeValue is empty, must contain exactly one of the supported datatypes}

my News fields are :

```<code>       override class func jsonKeyPathsByPropertyKey() -> [AnyHashable: Any] {
    return [
           "_userId" : "userId",
           "_articleId" : "articleId",
           "_author" : "author",
           "_category" : "category",
           "_content" : "content",
           "_title" : "title",
    ]
}
</code>```

答:
I had the same problem, and I solved adding @objc in eery variable from News(), for example

```<code>class News: AWSDynamoDBObjectModel, AWSDynamoDBModeling {
    @objc var id: String?
    @objc var type: String?
    @objc var cc: String?
}
</code>```

If you add @objc that force to wrap to NS Object, this is a bug for the aws mobile sdk...

Title: DynamoDB save to DB

Body:
I'm new to AWS and i'm trying to save data to my database using the aws example with News table.

I connected this function to the main storyboard button :

 @IBAction func addButton(_ sender: Any) {

    let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()

    //Create data object using data models you downloaded from Mobile Hub
    let newsItem: News = News();

    // Use AWSIdentityManager.default().identityId here to get the user identity id.
    newsItem._userId = "us-east-1:74c8f7ce-244b-4476-963e-0dcb3216f406"
    newsItem._articleId = "0123"
    newsItem._title = "Banana"
    newsItem._author = "Logan"
    newsItem._content = "Should I stay or should I go now?"
    newsItem._category = "Food"

    //Save a new item
    dynamoDbObjectMapper.save(newsItem, completionHandler: {
        (error: Error?) -> Void in

        if let error = error {
            print("Amazon DynamoDB Save Error: \(error)")
            return
        }
        print("An item was saved.")
    })

}

but when I hit the button I get :
mazon DynamoDB Save Error: Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=com.amazon.coral.validate#ValidationException, message=Supplied AttributeValue is empty, must contain exactly one of the supported datatypes}

my News fields are :

       override class func jsonKeyPathsByPropertyKey() -> [AnyHashable: Any] {
    return [
           "_userId" : "userId",
           "_articleId" : "articleId",
           "_author" : "author",
           "_category" : "category",
           "_content" : "content",
           "_title" : "title",
    ]
}

Body:
I had the same problem, and I solved adding @objc in eery variable from News(), for example

class News: AWSDynamoDBObjectModel, AWSDynamoDBModeling {
    @objc var id: String?
    @objc var type: String?
    @objc var cc: String?
}

If you add @objc that force to wrap to NS Object, this is a bug for the aws mobile sdk...


问:
Is there a way for me to randomly generate Strings from an array without duplicating one more than twice?
currently making a program that will generate a list of Strings from two different arrays, but right now all it does is repeatedly generate Strings the desired amount of times, sometimes with multiple duplicates.

```<code>    public class ListGenerator
    {
          public static void main(String[] args)
          {
           //number generator to determine which string to print
           Random generator = new Random();
           int rand;

           //counter to determine number of printed lines
           int counter = 0;

           //coin flip to say which array the string will come from
           Random coinFlip = new Random();
           int coin;

           String[] list1;
           list1 = new String[5]
           list1[0] = "Alpha"
           list1[1] = "Beta"
           list1[2] = "Charlie"
           list1[3] = "Delta"
           list1[4] = "Echo"

           String[] list2;
           list2 = new String[5]
           list2[0] = "Apple"
           list2[1] = "Pear"
           list2[2] = "Grape"
           list2[3] = "Banana"
           list2[4] = "Orange"

           for(counter = 0; counter < 15; counter++)
           {
                coin = coinFlip.nextInt(2)+1;

                if(coin == 1)
                {
                      rand = generator.nextInt(list1.length);
                      System.out.println(list1[rand]);
                }
                else if(coin == 2)
                {
                      rand = generator.nextInt(list2.length);
                      System.out.println(list2[rand]);
                }
           }
           }
    }
</code>```

Is there a way to make it so that I could generate a String like "Apple" or "Beta" no more than twice in the 15 lines generated?

Ex Desired Output:

```<code>    (1) Apple [printed first time]
    (2) Charlie [printed first time]
    (3) Pear [printed first time]
    (4) Beta [printed first time]
    (5) Apple [printed second time]
    (6) Echo [printed first time]
    (7) Banana [printed first time]
    (8) Banana [printed second time]
    (9) Echo [printed second time]
    (10) Alpha [printed first time]
    (11) Grape [printed first time]
    (12) Delta [printed first time]
    (13) Beta [printed second time]
    (14) Orange [printed first time]
    (15) Grape [printed second time]
</code>```

Where 5 of those Strings were generated twice but not more than twice, but instead in my code it could generate any of those Strings 3, 4, 5, etc. times.

I know my code isn't organized the best or the most efficient I just need help on this duplication thing

答:
Create a new ArrayList of 20 values, with each value from list1 and list2 added twice.

Now shuffle() the list and take the first 15 values.

```<code>String[] list1 = { "Alpha", "Beta", "Charlie", "Delta", "Echo" };
String[] list2 = { "Apple", "Pear", "Grape", "Banana", "Orange" };

List<String> allTwice = new ArrayList<>(20);
allTwice.addAll(Arrays.asList(list1));
allTwice.addAll(Arrays.asList(list1));
allTwice.addAll(Arrays.asList(list2));
allTwice.addAll(Arrays.asList(list2));
Collections.shuffle(allTwice);
String[] result = allTwice.subList(0, 15).toArray(new String[15]);

for (String value : result)
    System.out.println(value);
</code>```

Example Output

Alpha
Charlie
Echo
Apple
Grape
Delta
Apple
Echo
Grape
Banana
Orange
Orange
Pear
Charlie
Beta
```

Body:
currently making a program that will generate a list of Strings from two different arrays, but right now all it does is repeatedly generate Strings the desired amount of times, sometimes with multiple duplicates.

    public class ListGenerator
    {
          public static void main(String[] args)
          {
           //number generator to determine which string to print
           Random generator = new Random();
           int rand;

           //counter to determine number of printed lines
           int counter = 0;

           //coin flip to say which array the string will come from
           Random coinFlip = new Random();
           int coin;

           String[] list1;
           list1 = new String[5]
           list1[0] = "Alpha"
           list1[1] = "Beta"
           list1[2] = "Charlie"
           list1[3] = "Delta"
           list1[4] = "Echo"

           String[] list2;
           list2 = new String[5]
           list2[0] = "Apple"
           list2[1] = "Pear"
           list2[2] = "Grape"
           list2[3] = "Banana"
           list2[4] = "Orange"

           for(counter = 0; counter < 15; counter++)
           {
                coin = coinFlip.nextInt(2)+1;

                if(coin == 1)
                {
                      rand = generator.nextInt(list1.length);
                      System.out.println(list1[rand]);
                }
                else if(coin == 2)
                {
                      rand = generator.nextInt(list2.length);
                      System.out.println(list2[rand]);
                }
           }
           }
    }

Is there a way to make it so that I could generate a String like "Apple" or "Beta" no more than twice in the 15 lines generated?

Ex Desired Output:

    (1) Apple [printed first time]
    (2) Charlie [printed first time]
    (3) Pear [printed first time]
    (4) Beta [printed first time]
    (5) Apple [printed second time]
    (6) Echo [printed first time]
    (7) Banana [printed first time]
    (8) Banana [printed second time]
    (9) Echo [printed second time]
    (10) Alpha [printed first time]
    (11) Grape [printed first time]
    (12) Delta [printed first time]
    (13) Beta [printed second time]
    (14) Orange [printed first time]
    (15) Grape [printed second time]

Where 5 of those Strings were generated twice but not more than twice, but instead in my code it could generate any of those Strings 3, 4, 5, etc. times.

I know my code isn't organized the best or the most efficient I just need help on this duplication thing

Body:
Create a new ArrayList of 20 values, with each value from list1 and list2 added twice.

Now shuffle() the list and take the first 15 values.

String[] list1 = { "Alpha", "Beta", "Charlie", "Delta", "Echo" };
String[] list2 = { "Apple", "Pear", "Grape", "Banana", "Orange" };

List<String> allTwice = new ArrayList<>(20);
allTwice.addAll(Arrays.asList(list1));
allTwice.addAll(Arrays.asList(list1));
allTwice.addAll(Arrays.asList(list2));
allTwice.addAll(Arrays.asList(list2));
Collections.shuffle(allTwice);
String[] result = allTwice.subList(0, 15).toArray(new String[15]);

for (String value : result)
    System.out.println(value);

Example Output

Alpha
Charlie
Echo
Apple
Grape
Delta
Apple
Echo
Grape
Banana
Orange
Orange
Pear
Charlie
Beta


问:
is_trial_period stays "on" in Apple's Receipt Sandbox
I'm encountering an issue while debugging Apple's in-app purchase receipt. It seems the field "is_trial_period" stays true although the purchase has already expired.
To my understanding Apple defines short periods for debugging subscriptions, as seen here:

Testing In-App Purchase Products

Do those times apply for trail periods as well?

答:
This is because Apple issues a separate transaction for the trial period.

Here is an example excerpt of a receipt from Apple:

```<code>"latest_receipt_info": [
    {
        "quantity": "1",
        "product_id": "onemonth_freetrial",
        "transaction_id": "1000000328795138",
        "original_transaction_id": "1000000328795138",
        "purchase_date": "2017-08-29 23:13:52 Etc/GMT",
        "purchase_date_ms": "1504048432000",
        "purchase_date_pst": "2017-08-29 16:13:52 America/Los_Angeles",
        "original_purchase_date": "2017-08-29 23:13:53 Etc/GMT",
        "original_purchase_date_ms": "1504048433000",
        "original_purchase_date_pst": "2017-08-29 16:13:53 America/Los_Angeles",
        "expires_date": "2017-08-29 23:16:52 Etc/GMT",
        "expires_date_ms": "1504048612000",
        "expires_date_pst": "2017-08-29 16:16:52 America/Los_Angeles",
        "web_order_line_item_id": "1000000036088032",
        "is_trial_period": "true"
    },
    {
        "quantity": "1",
        "product_id": "onemonth_freetrial",
        "transaction_id": "1000000328796241",
        "original_transaction_id": "1000000328795138",
        "purchase_date": "2017-08-29 23:16:52 Etc/GMT",
        "purchase_date_ms": "1504048612000",
        "purchase_date_pst": "2017-08-29 16:16:52 America/Los_Angeles",
        "original_purchase_date": "2017-08-29 23:13:53 Etc/GMT",
        "original_purchase_date_ms": "1504048433000",
        "original_purchase_date_pst": "2017-08-29 16:13:53 America/Los_Angeles",
        "expires_date": "2017-08-29 23:21:52 Etc/GMT",
        "expires_date_ms": "1504048912000",
        "expires_date_pst": "2017-08-29 16:21:52 America/Los_Angeles",
        "web_order_line_item_id": "1000000036088033",
        "is_trial_period": "false"
    }
]
</code>```

The latest_receipt_info field will contain an array for every 'renewal' or 'transaction'. The way Apple handles free trials is by issuing one transaction that will always have is_trial_period be true, and subsequent non-trial renewal have is_trial_period be false. When you handle the receipt just make sure you are looking at the latest transaction by purchase_date or expiration_date which should represent the latest renewal and the one you should base unlocking content off of.

And regarding length in sandbox, if your IAP product has a free trial, the sandbox environment will issue one trial period, and 5 renewals, for six renewals total.

Body:
This is because Apple issues a separate transaction for the trial period.

Here is an example excerpt of a receipt from Apple:

"latest_receipt_info": [
    {
        "quantity": "1",
        "product_id": "onemonth_freetrial",
        "transaction_id": "1000000328795138",
        "original_transaction_id": "1000000328795138",
        "purchase_date": "2017-08-29 23:13:52 Etc/GMT",
        "purchase_date_ms": "1504048432000",
        "purchase_date_pst": "2017-08-29 16:13:52 America/Los_Angeles",
        "original_purchase_date": "2017-08-29 23:13:53 Etc/GMT",
        "original_purchase_date_ms": "1504048433000",
        "original_purchase_date_pst": "2017-08-29 16:13:53 America/Los_Angeles",
        "expires_date": "2017-08-29 23:16:52 Etc/GMT",
        "expires_date_ms": "1504048612000",
        "expires_date_pst": "2017-08-29 16:16:52 America/Los_Angeles",
        "web_order_line_item_id": "1000000036088032",
        "is_trial_period": "true"
    },
    {
        "quantity": "1",
        "product_id": "onemonth_freetrial",
        "transaction_id": "1000000328796241",
        "original_transaction_id": "1000000328795138",
        "purchase_date": "2017-08-29 23:16:52 Etc/GMT",
        "purchase_date_ms": "1504048612000",
        "purchase_date_pst": "2017-08-29 16:16:52 America/Los_Angeles",
        "original_purchase_date": "2017-08-29 23:13:53 Etc/GMT",
        "original_purchase_date_ms": "1504048433000",
        "original_purchase_date_pst": "2017-08-29 16:13:53 America/Los_Angeles",
        "expires_date": "2017-08-29 23:21:52 Etc/GMT",
        "expires_date_ms": "1504048912000",
        "expires_date_pst": "2017-08-29 16:21:52 America/Los_Angeles",
        "web_order_line_item_id": "1000000036088033",
        "is_trial_period": "false"
    }
]

The latest_receipt_info field will contain an array for every 'renewal' or 'transaction'. The way Apple handles free trials is by issuing one transaction that will always have is_trial_period be true, and subsequent non-trial renewal have is_trial_period be false. When you handle the receipt just make sure you are looking at the latest transaction by purchase_date or expiration_date which should represent the latest renewal and the one you should base unlocking content off of.

And regarding length in sandbox, if your IAP product has a free trial, the sandbox environment will issue one trial period, and 5 renewals, for six renewals total.


问:
How to create a PDF file from a dict() data in Python
I have got a Dict from a .txt data, and I want to create a PDF file with this data.

How can I create it?

答:
```<code>pip install pdfkit
</code>```

Also install wkhtmltopdf:

Debian/Ubuntu:

```<code>$ sudo apt-get install wkhtmltopdf
</code>```

Then in your code:

```<code>import pdfkit
import json
pdfkit.from_string(json.dumps(yourdict))
</code>```

You could also do:

```<code>import pdfkit
pdfkit.from_file('your.txt', 'out.pdf')
</code>```

Body:
pip install pdfkit

Also install wkhtmltopdf:

Debian/Ubuntu:

$ sudo apt-get install wkhtmltopdf

Then in your code:

import pdfkit
import json
pdfkit.from_string(json.dumps(yourdict))

You could also do:

import pdfkit
pdfkit.from_file('your.txt', 'out.pdf')


问:
build/generated/source/apollo dictory not be generate

this is my project sturcture.the project from eclipse project, i want use graphQL,everything is ok,but build/generated/source/apollo dictory did not create.what should i do.for the project

答: my project sturcture is bad,because my project is from eclipse,change the sturture .</p>