问:
AWS PHP SDK 3.36 GetObject method throwing SignatureDoesNotMatch error
We are currently unable to download objects from S3, using the AWS PHP SDK v. 3.36. via the GetObject method.

We are seeing the following error:

```<code>Error executing "GetObject" on "<object path>";
AWS HTTP error: Client error: `GET <object path>` resulted in a `403 Forbidden` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>SignatureDoesNotMatch</Code>
  <Message>The request signature we calcul (truncated...)  SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you
    provided. Check your key and signing method.
    - <?xml version="1.0" encoding="UTF-8"?>
      <Error>
        <Code>SignatureDoesNotMatch</Code>
        <Message>The request signature we calculated does not match the signature you provided.
          Check your key and signing method.

<remaining message redacted>
</code>```

S3 Client setup:

```<code>public function __construct($key, $secret, $region='us-east-1') {
    $this->key = $key;
    $this->secret = $secret;
    $this->handler = new S3Client([
        'credentials' => [
            'key'    => $key,
            'secret' => $secret
        ],
        'region' =>$region,
        'version' => '2006-03-01'
    ]);
}
</code>```

Call to GetObject method:

```<code>public function getFile($bucket, $sourcefile, $saveToDestination = null) {
    $getarray = array(
        'Bucket' => $bucket,
        'Key' => $sourcefile,
    );

    if ($saveToDestination) {
        $getarray['SaveAs'] = $saveToDestination;
    }

    return $this->handler->getObject($getarray);

}
</code>```

For the IAM user in question, full access to S3 is provided and the credentials used above have been verified.

IAM policy (AmazonS3FullAccess):

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "*"
        }
    ]
}
</code>```

答:
It turns out that, in v3 of the AWS PHP SDK, if there are additional bucket subpaths in between the provided bucket and key parameters, this failure gets seen.

The following code was added to the method that calls the getFile method above:

```<code>protected function getS3File($s3_bucket, $s3_key){

         /// if the bucket contains additional paths, S3 will choke
         if (strpos($s3_bucket, '/')!==false){
             $paths = explode('/', $s3_bucket);
             $s3_bucket = array_shift($paths);

             /// so prepend them to the key!
             $s3_key=implode('/', $paths) .'/'.$s3_key;
         }

         return $this->makeTempFile($this->s3Handler->getFileContents($s3_bucket, $s3_key));
      }
</code>```

Body:
We are currently unable to download objects from S3, using the AWS PHP SDK v. 3.36. via the GetObject method.

We are seeing the following error:

Error executing "GetObject" on "<object path>";
AWS HTTP error: Client error: `GET <object path>` resulted in a `403 Forbidden` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
  SignatureDoesNotMatch
  <Message>The request signature we calcul (truncated...)  SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you
    provided. Check your key and signing method.
    - <?xml version="1.0" encoding="UTF-8"?>
      <Error>
        SignatureDoesNotMatch
        <Message>The request signature we calculated does not match the signature you provided.
          Check your key and signing method.

<remaining message redacted>

S3 Client setup:

public function __construct($key, $secret, $region='us-east-1') {
    $this->key = $key;
    $this->secret = $secret;
    $this->handler = new S3Client([
        'credentials' => [
            'key'    => $key,
            'secret' => $secret
        ],
        'region' =>$region,
        'version' => '2006-03-01'
    ]);
}

Call to GetObject method:

public function getFile($bucket, $sourcefile, $saveToDestination = null) {
    $getarray = array(
        'Bucket' => $bucket,
        'Key' => $sourcefile,
    );

    if ($saveToDestination) {
        $getarray['SaveAs'] = $saveToDestination;
    }

    return $this->handler->getObject($getarray);

}

For the IAM user in question, full access to S3 is provided and the credentials used above have been verified.

IAM policy (AmazonS3FullAccess):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "*"
        }
    ]
}

Body:
It turns out that, in v3 of the AWS PHP SDK, if there are additional bucket subpaths in between the provided bucket and key parameters, this failure gets seen.

The following code was added to the method that calls the getFile method above:

protected function getS3File($s3_bucket, $s3_key){

         /// if the bucket contains additional paths, S3 will choke
         if (strpos($s3_bucket, '/')!==false){
             $paths = explode('/', $s3_bucket);
             $s3_bucket = array_shift($paths);

             /// so prepend them to the key!
             $s3_key=implode('/', $paths) .'/'.$s3_key;
         }

         return $this->makeTempFile($this->s3Handler->getFileContents($s3_bucket, $s3_key));
      }


来源: stackexchange

问:
UIPicker - how record the standard selectedRow if user only click the OK button
I have a UIpicker in modal window. Everything works fine, except one thing. When the user click the input text field, the modal window with the UIpickerView opens as expected. If the selected row is the correct one and the user click the OK button, then the current code is not able to registrer the value.

```<code>// Set the default row, so if user click ok without changing it is recorded
self.picker.selectRow(0, inComponent: 0, animated: false)
</code>```

Is there an alternative to didSelectRow? I assume that is the issue, as they user don't select a row as it is already preselected by the code.

```<code>// Capture the picker selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
    selectedType = pickerData[row] as String
}
</code>```

答:
Well solved it. just add a test to see if the selectedType was nil.    </p>

```<code>@IBAction func OkBtnWasPressed(_ sender: Any) {
        // update text to selected value
        if selectedType == nil {
            typeTextField.text = pickerData[defaultRow]
        } else {
             typeTextField.text = selectedType
        }
        animateOut()
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a UIpicker in modal window. Everything works fine, except one thing. When the user click the input text field, the modal window with the UIpickerView opens as expected. If the selected row is the correct one and the user click the OK button, then the current code is not able to registrer the value.

// Set the default row, so if user click ok without changing it is recorded
self.picker.selectRow(0, inComponent: 0, animated: false)

Is there an alternative to didSelectRow? I assume that is the issue, as they user don't select a row as it is already preselected by the code.

// Capture the picker selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
    selectedType = pickerData[row] as String
}

Body:
Well solved it. just add a test to see if the selectedType was nil.

@IBAction func OkBtnWasPressed(_ sender: Any) {
        // update text to selected value
        if selectedType == nil {
            typeTextField.text = pickerData[defaultRow]
        } else {
             typeTextField.text = selectedType
        }
        animateOut()
    }


问:
How to get Generic class<T> name of typescript?
My Generic class

```<code> export class BaseService<T> {
 public subUrl;
 constructor(public repo:RepogitoryService) { }
}
</code>```

How can I store the class name of T on a local variable?

答:
You cannot, unfortunately. Typescript is a static type checker and has no support for type reflection at runetime such as java does. This is because its sources are transpiled to javascript.

However, there is hope for such support in the future, with a new typescript feature called "custom transformers". Those transformers are plugins that hook the transpilation process, opening the road to rich features regarding type reflection. A first example of such is ts-transformer-keys.

Body:
My Generic class

 export class BaseService<T> {
 public subUrl;
 constructor(public repo:RepogitoryService) { }
}

How can I store the class name of T on a local variable?


问:
access a secure api
Can anyone tell me why this happen when i install the real device on my
blackberry.
I am using blackberry web/widget to develop app BB and the language that i used
is
phonegap which is support .html, .css, .javascript.

The app can be installed but after install the app does not have icon.

Then when click on run the error msg is,
“Error starting Carl’s Jr. Module CarlsJr attempt to access a secure api”

Any answer will be highly appreciated!

thanks,

regards,
Jamaley.

答:
It sounds very much like you haven't signed your code.

RIM track the use of some sensitive BlackBerry APIs. This is indicated in the API reference documentation by a lock icon or are otherwise noted as "signed".

Please see the following url for more information about these keys and how to request yours

http://us.blackberry.com/developers/javaappdev/codekeys.jsp

Cheers

Ray

ContentLicense: CC BY-SA 2.5

Title: access a secure api


问:
Convert a decimal number to a fraction / rational number
In JavaScript, is there any way to convert a decimal number (such as 0.0002) to a fraction represented as a string (such as "2/10000")?

If a function called decimalToFraction had been written for this purpose, then decimalToFraction(0.0002) would return the string "2/10000".

答:
I know this is an old question, but I have created a function that has been greatly simplified.

```<code>Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}
</code>```

Call it with Math.fraction(2.56)

It will:

return NaN if the input is not a number

return undefined if the input is undefined

reduce the fraction

return a string (use Math.fraction(2.56).split("/") for an array containing the numerator and denominator)

Please note that this uses the deprecated arguments.callee, and thus may be incompatible in some browsers.

Test it here

Body:
I know this is an old question, but I have created a function that has been greatly simplified.

Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}

Call it with Math.fraction(2.56)

It will:

return NaN if the input is not a number

return undefined if the input is undefined

reduce the fraction

return a string (use Math.fraction(2.56).split("/") for an array containing the numerator and denominator)

Please note that this uses the deprecated arguments.callee, and thus may be incompatible in some browsers.

Test it <a href="https://ayunami2000.github.io/?html=&css=&js=TWF0aC5mcmFjdGlvbj1mdW5jdGlvbih4KXsKcmV0dXJuIHg/K3g/eC50b1N0cmluZygpLmluY2x1ZGVzKCIuIik/eC50b1N0cmluZygpLnJlcGxhY2UoIi4iLCIiKS8oZnVuY3Rpb24oYSxiKXtyZXR1cm4gYj9hcmd1bWVudHMuY2FsbGVlKGIsYSViKTphO30pKHgudG9TdHJpbmcoKS5yZXBsYWNlKCIuIiwiIiksIjEiKyIwIi5yZXBlYXQoeC50b1N0cmluZygpLnNwbGl0KCIuIilbMV0ubGVuZ3RoKSkrIi8iKygiMSIrIjAiLnJlcGVhdCh4LnRvU3RyaW5nKCkuc3BsaXQoIi4iKVsxXS5sZW5ndGgpKS8oZnVuY3Rpb24oYSxiKXtyZXR1cm4gYj9hcmd1bWVudHMuY2FsbGVlKGIsYSViKTphO30pKHgudG9TdHJpbmcoKS5yZXBsYWNlKCIuIiwiIiksIjEiKyIwIi5yZXBlYXQoeC50b1N0cmluZygpLnNwbGl0KCIuIilbMV0ubGVuZ3RoKSk6eCsiLzEiOk5hTjp2b2lkIDA7Cn0KCmFsZXJ0KE1hdGguZnJhY3Rpb24od2luZG93LnByb21wdCgiZW50ZXIgZGVjaW1hbCIpKSk7&tab=3" rel="nofollow noreferrer">here


问:
Unable to click or select the value which is displayed in dropdown
I am trying to implement some code using Selenium Webdriver using Java.

Basically, I have a website with a text box. Once user enter the first letter, based on that a value will be displayed(using AJAX). I need to select the particular value, which i mentioned in send keys .

```<code>WebElement fromCity = driver.findElement(By.id("pickUpLocation"));
fromCity.sendKeys("A Ma Temple / 媽閣");

Thread.sleep(2000);

WebElement ajaxContainer1 = driver.findElement(By.className("txt-box ng-touched ng-dirty ng-valid"));
WebElement ajaxHolder1 = ajaxContainer1.findElement(By.tagName("ul"));
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));

for (WebElement value1 : ajaxValues1) {
    if (value1.getText().equals("A Ma Temple ")) {
        ((WebElement)ajaxValues1).click();
        break;
    }
}
</code>```

答:
I think u can try selecting through index. It should be like this

```<code>List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));
Select dropdown= new Select(ajaxValues1);
dropdown.selectByIndex(0);
dropdown.selectByIndex(1);
dropdown.selectByIndex(2);
</code>```

0 represents the first element in the dropdown. Based on index number of that element, feed the corresponding number in selectByIndex(0)

Let me know if this helps. Thanks

Body:
I am trying to implement some code using Selenium Webdriver using Java.

Basically, I have a website with a text box. Once user enter the first letter, based on that a value will be displayed(using AJAX). I need to select the particular value, which i mentioned in send keys .

WebElement fromCity = driver.findElement(By.id("pickUpLocation"));
fromCity.sendKeys("A Ma Temple / 媽閣");

Thread.sleep(2000);

WebElement ajaxContainer1 = driver.findElement(By.className("txt-box ng-touched ng-dirty ng-valid"));
WebElement ajaxHolder1 = ajaxContainer1.findElement(By.tagName("ul"));
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));

for (WebElement value1 : ajaxValues1) {
    if (value1.getText().equals("A Ma Temple ")) {
        ((WebElement)ajaxValues1).click();
        break;
    }
}

Body:
I think u can try selecting through index. It should be like this

List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));
Select dropdown= new Select(ajaxValues1);
dropdown.selectByIndex(0);
dropdown.selectByIndex(1);
dropdown.selectByIndex(2);

0 represents the first element in the dropdown. Based on index number of that element, feed the corresponding number in selectByIndex(0)

Let me know if this helps. Thanks


问:
Restoring and use multiple tensorflow model in the same time
I'm quiet new to tensorflow and I struggle to understand how to us it. I'm am currently trying to use it to identify numbers so I used the code providing in the mnist tutorial ( https://www.tensorflow.org/get_started/mnist/pros ) with few modification. I used my own sources rather that the sources given in mnist and I change few part of the code so that I can creat model with sources of different sizes. (28x28 and 56x56)
The, I saved the model as follow :

```<code>def save_progression(sess, id_collec, x, y_conv, y_, accuracy, keep_prob,  train_step, i, modelDir):
  saver = tf.train.Saver()
  print(modelDir)
  modelNamePrefix=os.path.join(modelDir,  "step%s" % str(i))
  if (os.path.isdir(modelNamePrefix) == False):
    os.makedirs(modelNamePrefix)
  if (len(tf.get_collection(id_collec)) > 0):
    tf.get_collection_ref(id_collec)[0] = x
    tf.get_collection_ref(id_collec)[1] = y_conv
    tf.get_collection_ref(id_collec)[2] = y_
    tf.get_collection_ref(id_collec)[3] = accuracy
    tf.get_collection_ref(id_collec)[4] = keep_prob
    tf.get_collection_ref(id_collec)[5] = train_step
  else:
    tf.add_to_collection(id_collec, x)
    tf.add_to_collection(id_collec, y_conv)
    tf.add_to_collection(id_collec, y_)
    tf.add_to_collection(id_collec, accuracy)
    tf.add_to_collection(id_collec, keep_prob)
    tf.add_to_collection(id_collec, train_step)
  saver.save(sess, os.path.join(modelNamePrefix, "myModel"));
</code>```

with
sess beign the tf.InteractiveSession()
id_collec is '28x28' or '56x56'
x being the placeholder for input imagies
y_conv the result of a tf.matmul
accuracy beign the result of tf.reduce_mean
y_ the placeholder that defined the number of class
keep_prob a placeholder for a float
train_step = the result of tf.train.AdamOptimizer
i is just a number to change the out directory for the model
modelDir = where the model directory will be created

Then in another program I restore the model as follow:

```<code>self._sess = tf.Session()
print("import meta graph %s.meta" % (os.path.join(modelDir, modelName)))
saver = tf.train.import_meta_graph("%s.meta" % (os.path.join(modelDir, modelName)))
print("restoring %s" % (os.path.join(modelDir, modelName)))
saver.restore(self._sess, "%s" % (os.path.join(modelDir, modelName)));
self._placeHolder_x, self._predictNode, _, _, self._placeHolder_keep_prob, _ = tf.get_collection('%dx%d' % (dim, dim))
</code>```

When I load one model it's ok, but when I load two different model (one base on 28x28 images and one base on 56x56 images) I got an error on the second tf.restore.

```<code>[...]
tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [3136,1024] rhs shape= [5,5,64,128]    [[Node: save/Assign_14 = Assign[T=DT_FLOAT,
_class=["loc:@Variable_4"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_4/Adam_1, save/RestoreV2_14)]]

Caused by op u'save/Assign_14'
[...]
InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [3136,1024] rhs shape= [5,5,64,128]      [[Node: save/Assign_14 = Assign[T=DT_FLOAT, _class=["loc:@Variable_4"], use_locking=true, validate_shape=true,
_device="/job:localhost/replica:0/task:0/cpu:0"](Variable_4/Adam_1, save/RestoreV2_14)]]
</code>```

What do I do wrong ? clearly, the two model use some variables or something.
I first though it was because I use the same id for the collection so I made it different. But the error is in the restore itself not even the get collection.
I heard there is a way somehow to make a scope of somekind allowing to avoid the two model to share things together but I'm don't understabd how that work.

When I seek answer to the web I found many informations but being new to tensorflow I failed to apply those information tu my code.
any idea ?

Ps: If I put those value in colelction if because I need them, either to continue training in a later date if I want two, or to launch the sess.run.

答:
The problem might be that you're restoring both models into the same Graph. You might want to initialize separate graphs for each of your models:</p>

```<code>graph1 = tf.Graph()
graph2 = tf.Graph()

with tf.Session(graph = graph1) as sess1:
    saver.restore(.....)
with tf.Session(graph = graph2) as sess2:
    saver.restore(...)
</code>```

Body:
I'm quiet new to tensorflow and I struggle to understand how to us it. I'm am currently trying to use it to identify numbers so I used the code providing in the mnist tutorial ( https://www.tensorflow.org/get_started/mnist/pros ) with few modification. I used my own sources rather that the sources given in mnist and I change few part of the code so that I can creat model with sources of different sizes. (28x28 and 56x56)
The, I saved the model as follow :

def save_progression(sess, id_collec, x, y_conv, y_, accuracy, keep_prob,  train_step, i, modelDir):
  saver = tf.train.Saver()
  print(modelDir)
  modelNamePrefix=os.path.join(modelDir,  "step%s" % str(i))
  if (os.path.isdir(modelNamePrefix) == False):
    os.makedirs(modelNamePrefix)
  if (len(tf.get_collection(id_collec)) > 0):
    tf.get_collection_ref(id_collec)[0] = x
    tf.get_collection_ref(id_collec)[1] = y_conv
    tf.get_collection_ref(id_collec)[2] = y_
    tf.get_collection_ref(id_collec)[3] = accuracy
    tf.get_collection_ref(id_collec)[4] = keep_prob
    tf.get_collection_ref(id_collec)[5] = train_step
  else:
    tf.add_to_collection(id_collec, x)
    tf.add_to_collection(id_collec, y_conv)
    tf.add_to_collection(id_collec, y_)
    tf.add_to_collection(id_collec, accuracy)
    tf.add_to_collection(id_collec, keep_prob)
    tf.add_to_collection(id_collec, train_step)
  saver.save(sess, os.path.join(modelNamePrefix, "myModel"));

with
sess beign the tf.InteractiveSession()
id_collec is '28x28' or '56x56'
x being the placeholder for input imagies
y_conv the result of a tf.matmul
accuracy beign the result of tf.reduce_mean
y_ the placeholder that defined the number of class
keep_prob a placeholder for a float
train_step = the result of tf.train.AdamOptimizer
i is just a number to change the out directory for the model
modelDir = where the model directory will be created

Then in another program I restore the model as follow:

self._sess = tf.Session()
print("import meta graph %s.meta" % (os.path.join(modelDir, modelName)))
saver = tf.train.import_meta_graph("%s.meta" % (os.path.join(modelDir, modelName)))
print("restoring %s" % (os.path.join(modelDir, modelName)))
saver.restore(self._sess, "%s" % (os.path.join(modelDir, modelName)));
self._placeHolder_x, self._predictNode, _, _, self._placeHolder_keep_prob, _ = tf.get_collection('%dx%d' % (dim, dim))

When I load one model it's ok, but when I load two different model (one base on 28x28 images and one base on 56x56 images) I got an error on the second tf.restore.

[...]
tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [3136,1024] rhs shape= [5,5,64,128]    [[Node: save/Assign_14 = Assign[T=DT_FLOAT,
_class=["loc:@Variable_4"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_4/Adam_1, save/RestoreV2_14)]]

Caused by op u'save/Assign_14'
[...]
InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [3136,1024] rhs shape= [5,5,64,128]      [[Node: save/Assign_14 = Assign[T=DT_FLOAT, _class=["loc:@Variable_4"], use_locking=true, validate_shape=true,
_device="/job:localhost/replica:0/task:0/cpu:0"](Variable_4/Adam_1, save/RestoreV2_14)]]

What do I do wrong ? clearly, the two model use some variables or something.
I first though it was because I use the same id for the collection so I made it different. But the error is in the restore itself not even the get collection.
I heard there is a way somehow to make a scope of somekind allowing to avoid the two model to share things together but I'm don't understabd how that work.

When I seek answer to the web I found many informations but being new to tensorflow I failed to apply those information tu my code.
any idea ?

Ps: If I put those value in colelction if because I need them, either to continue training in a later date if I want two, or to launch the sess.run.

Body:
The problem might be that you're restoring both models into the same Graph. You might want to initialize separate graphs for each of your models:

graph1 = tf.Graph()
graph2 = tf.Graph()

with tf.Session(graph = graph1) as sess1:
    saver.restore(.....)
with tf.Session(graph = graph2) as sess2:
    saver.restore(...)


问:
How to create training data for RASA NLU through program nodejs
How to create training data through program for RASA NLU?
Actually I am developing an application using MEAN stack, this application prepares the data that needs to be trained with RASA NLU.

But I don't know how to pass this info from my nodejs server to RASA NLU. Is there any supported api's to achieve this?

答:
I use a python library which is pretty good to power your conversational software, based on the latest Machine Learning research.

In order to use this, you have to build a python service that will interact with your nodejs server.

It would be also easy for you to scale and maintain both in the future

Or you can check this opensource app https://github.com/aashreys/chatbot-example


问:
How to construct a set out of list items in python?
I have a list of filenames in python and I would want to construct a set out of all the filenames.

```<code>filelist=[]
for filename in filelist:
    set(filename)
</code>```

This does not seem to work. How can do this?

答:
You can do

```<code>my_set = set(my_list)
</code>```

or, in Python 3,

```<code>my_set = {*my_list}
</code>```

to create a set from a list. Conversely, you can also do

```<code>my_list = list(my_set)
</code>```

or, in Python 3,

```<code>my_list = [*my_set]
</code>```

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

Body:
I have a list of filenames in python and I would want to construct a set out of all the filenames.

filelist=[]
for filename in filelist:
    set(filename)

This does not seem to work. How can do this?

Body:
You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

ContentLicense: CC BY-SA 4.0


问:
Python: Create text file, write to it, replace string
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar
</code>```

Thanks.

答:
You are writing to the file before editing the text.

You should open, edit, then write.

Body:
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar

Thanks.


问:
EmbeddedKafka sending messages to consumer after delay in subsequent test
I'm using EmbeddedKafka from kafka-spring-test, version 2.0.1.RELEASE (the latest).
I have very simple tests which work correctly when running only one test. But whenever I run them one after another (so just running whole test class) then second one fails - consumer doest not receive any message.

```<code>public class KafkaControllerTest {

    private static final String FOO_TOPIC = "fooTopic";

    @Rule
    public KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, FOO_TOPIC);

    MessageConsumer msgConsumerFoo = mock(MessageConsumer.class);

    @Before
    public void before() {
        assertTrue(embeddedKafka.getBrokerAddresses().length == 1);
        KafkaController controller = new KafkaController(
                embeddedKafka.getBrokerAddress(0).toString(),
                new Consumer(FOO_TOPIC, msgConsumerFoo));
        MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void kafkaFirstTest() throws Exception {
        sendMessage(FOO_TOPIC, "foo message");

        verify(msgConsumerFoo).consume(any());
    }

    @Test
    public void kafkaSecondTest() throws Exception {
        sendMessage(FOO_TOPIC, "foo2 message");

        verify(msgConsumerFoo).consume(any());
    }

    void sendMessage(String topic, String notification) throws ExecutionException, InterruptedException {
        Map<String, Object> props = KafkaTestUtils.producerProps(embeddedKafka);
        Producer<Integer, String> producer = new DefaultKafkaProducerFactory<Integer, String>(props).createProducer();
        producer.send(new ProducerRecord<>(topic, notification)).get();
    }
}
</code>```

And code of tested class:

```<code>public class KafkaController {

    public KafkaController(String brokerAddress, Consumer... consumers) {
        for (Consumer consumer : consumers) {
            addTopicListener(brokerAddress, consumer.topic, consumer.messageConsumer);
        }
    }

    private void addTopicListener(String brokerAddress, String topic, MessageConsumer consumer) {
        HashMap<String, Object> consumerConfig = new HashMap<>();
        consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerAddress);
        consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
        DefaultKafkaConsumerFactory<String, String> cf = new DefaultKafkaConsumerFactory<>(
                consumerConfig,
                new StringDeserializer(),
                new StringDeserializer());

        ContainerProperties containerProperties = new ContainerProperties(topic);
        containerProperties.setMessageListener((MessageListener<String, String>) data -> {
            consumer.consume(data.value());
        });
        ConcurrentMessageListenerContainer container = new ConcurrentMessageListenerContainer<>(cf, containerProperties);
        container.start();
    }

    public interface MessageConsumer {
        void consume(String message);
    }

    public static class Consumer {
        private final String topic;
        private final MessageConsumer messageConsumer;

        public Consumer(String topic, MessageConsumer messageConsumer) {
            this.topic = topic;
            this.messageConsumer = messageConsumer;
        }
    }
}
</code>```

I believe the problem is caused by KafkaEmbedded as consumers tested with local Kafka instance work correctly.

Is there something I'm missing? I didn't find any consumer property that could be helpful.

Kafka-spring-test doc say:

It is generally recommended to use the rule as a @ClassRule to avoid starting/stopping the broker between tests (and use a different topic for each test).

However, I tried both making KafkaEmbedded as @ClassRule and using different topic in tests and still nothing.

This issue has something to do with asynchronicity, because adding delays in second test helps:

```<code>@Test
public void kafkaSecondTest() throws Exception {
    Thread.sleep(1000);
    sendMessage(FOO_TOPIC, "foo2 message");
    Thread.sleep(1000);

    verify(msgConsumerFoo).consume(any());
}
</code>```

Yes, somehow it works only when Thread.sleep(1000) is added both before and after sending message.

So how can I check if KafkaEmbedded or some other component is ready to send/consume messages?

答:
You probably need to set auto.offset.reset=earliest (ConsumerConfig.AUTO_OFFSET_RESET_CONFIG). Otherwise you might send the message before the container completely starts.

Of course, if you use the same topic, the second consumer should get 2 messages.

Also, I would recommend stopping the container at the end of each test. Debug logging should help too.

EDIT

An alternative is to use ContainerTestUtils.waitForAssignment() before sending the message in the test; we do that a lot in the framework tests.

Body:
I'm using EmbeddedKafka from kafka-spring-test, version 2.0.1.RELEASE (the latest).
I have very simple tests which work correctly when running only one test. But whenever I run them one after another (so just running whole test class) then second one fails - consumer doest not receive any message.

public class KafkaControllerTest {

    private static final String FOO_TOPIC = "fooTopic";

    @Rule
    public KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, FOO_TOPIC);

    MessageConsumer msgConsumerFoo = mock(MessageConsumer.class);

    @Before
    public void before() {
        assertTrue(embeddedKafka.getBrokerAddresses().length == 1);
        KafkaController controller = new KafkaController(
                embeddedKafka.getBrokerAddress(0).toString(),
                new Consumer(FOO_TOPIC, msgConsumerFoo));
        MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void kafkaFirstTest() throws Exception {
        sendMessage(FOO_TOPIC, "foo message");

        verify(msgConsumerFoo).consume(any());
    }

    @Test
    public void kafkaSecondTest() throws Exception {
        sendMessage(FOO_TOPIC, "foo2 message");

        verify(msgConsumerFoo).consume(any());
    }

    void sendMessage(String topic, String notification) throws ExecutionException, InterruptedException {
        Map<String, Object> props = KafkaTestUtils.producerProps(embeddedKafka);
        Producer<Integer, String> producer = new DefaultKafkaProducerFactory<Integer, String>(props).createProducer();
        producer.send(new ProducerRecord<>(topic, notification)).get();
    }
}

And code of tested class:

public class KafkaController {

    public KafkaController(String brokerAddress, Consumer... consumers) {
        for (Consumer consumer : consumers) {
            addTopicListener(brokerAddress, consumer.topic, consumer.messageConsumer);
        }
    }

    private void addTopicListener(String brokerAddress, String topic, MessageConsumer consumer) {
        HashMap<String, Object> consumerConfig = new HashMap<>();
        consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerAddress);
        consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
        DefaultKafkaConsumerFactory<String, String> cf = new DefaultKafkaConsumerFactory<>(
                consumerConfig,
                new StringDeserializer(),
                new StringDeserializer());

        ContainerProperties containerProperties = new ContainerProperties(topic);
        containerProperties.setMessageListener((MessageListener<String, String>) data -> {
            consumer.consume(data.value());
        });
        ConcurrentMessageListenerContainer container = new ConcurrentMessageListenerContainer<>(cf, containerProperties);
        container.start();
    }

    public interface MessageConsumer {
        void consume(String message);
    }

    public static class Consumer {
        private final String topic;
        private final MessageConsumer messageConsumer;

        public Consumer(String topic, MessageConsumer messageConsumer) {
            this.topic = topic;
            this.messageConsumer = messageConsumer;
        }
    }
}

I believe the problem is caused by KafkaEmbedded as consumers tested with local Kafka instance work correctly.

Is there something I'm missing? I didn't find any consumer property that could be helpful.

Kafka-spring-test doc say:

It is generally recommended to use the rule as a @ClassRule to avoid starting/stopping the broker between tests (and use a different topic for each test).

However, I tried both making KafkaEmbedded as @ClassRule and using different topic in tests and still nothing.

This issue has something to do with asynchronicity, because adding delays in second test helps:

@Test
public void kafkaSecondTest() throws Exception {
    Thread.sleep(1000);
    sendMessage(FOO_TOPIC, "foo2 message");
    Thread.sleep(1000);

    verify(msgConsumerFoo).consume(any());
}

Yes, somehow it works only when Thread.sleep(1000) is added both before and after sending message.

So how can I check if KafkaEmbedded or some other component is ready to send/consume messages?


问:
Fastest way to negate a std::vector
Assume I have a std::vector of double, namely

```<code>std::vector<double> MyVec(N);
</code>```

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

```<code>std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
</code>```

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

答:
```<code>#include <vector>
#include <algorithm>
#include <functional>
void check()
{
    std::vector<double> MyVec(255);
    std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
}
</code>```

This code on https://godbolt.org/ with copile option -O3 generate nice assembly

```<code>.L3:
[...]
  cmp r8, 254
  je .L4
  movsd xmm0, QWORD PTR [rdi+2032]
  xorpd xmm0, XMMWORD PTR .LC0[rip]
  movsd QWORD PTR [rdi+2032], xmm0
.L4:
</code>```

It's difficult to imagine faster. Your code is already perfect, don't try to outsmart the compiler and use clean C++ code it works almost every times.

Title: Fastest way to negate a std::vector

Body:
Assume I have a std::vector of double, namely

std::vector<double> MyVec(N);

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

Body:
#include <vector>
#include <algorithm>
#include <functional>
void check()
{
    std::vector<double> MyVec(255);
    std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
}

This code on https://godbolt.org/ with copile option -O3 generate nice assembly

.L3:
[...]
  cmp r8, 254
  je .L4
  movsd xmm0, QWORD PTR [rdi+2032]
  xorpd xmm0, XMMWORD PTR .LC0[rip]
  movsd QWORD PTR [rdi+2032], xmm0
.L4:

It's difficult to imagine faster. Your code is already perfect, don't try to outsmart the compiler and use clean C++ code it works almost every times.


问:
How to move pseudo-element under its parent block?
I want the green element to be under the text box and also under image.

I tried to set the z-index for each element, but nothing has changed.

Can I reach this through the z-index property?

I can't change html. And I also want the pseudo-element to be a child of the text block for the adaptive height

.item {
  display: flex;
  align-items: flex-start;
  width: 400px;
  height: 250px;
}

.col1 {
  margin-right: 20px;
}

.col2 {
  position: relative;
  z-index: 1;
  width: 200px;
  height: auto;
  padding: 5px;
  background-color: gray;
}

.col2::before {
  content: "";
  position: absolute;
  bottom: -20px;
  left: -60px;
  width: 150px;
  min-height: 100px;
  height: 100%;
  z-index: -1;
  background-color: seagreen;
}

.image {
  position: relative;
  z-index: 2;
  width: 200px;
  height: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="item">
  <div class="col1">
    <img class="image" src="http://satyr.io/200x150/1" />
  </div>
  <div class="col2">
    <p class="title">Lorem ipsum dolor</p>
    <p class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima esse ipsam error repudiandae ut amet.</p>
  </div>
</div></code>```

答:
You could place an element inside
 because the pseudo element cannot have a lower z-index that the element itself. And then place an div inside of
 which you could apply the z-index and the gray background on.

Body:
I want the green element to be under the text box and also under image.

I tried to set the z-index for each element, but nothing has changed.

Can I reach this through the z-index property?

I can't change html. And I also want the pseudo-element to be a child of the text block for the adaptive height

.item {
  display: flex;
  align-items: flex-start;
  width: 400px;
  height: 250px;
}

.col1 {
  margin-right: 20px;
}

.col2 {
  position: relative;
  z-index: 1;
  width: 200px;
  height: auto;
  padding: 5px;
  background-color: gray;
}

.col2::before {
  content: "";
  position: absolute;
  bottom: -20px;
  left: -60px;
  width: 150px;
  min-height: 100px;
  height: 100%;
  z-index: -1;
  background-color: seagreen;
}

.image {
  position: relative;
  z-index: 2;
  width: 200px;
  height: 150px;
}

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima esse ipsam error repudiandae ut amet.

Body: You could place an element inside <div class="col2"> because the pseudo element cannot have a lower z-index that the element itself. And then place an div inside of <div class="col2"> which you could apply the z-index and the gray background on.


问:
FsCheck integration with NUnit in C#
TL;DR: I'm not able to successfully use FsCheck with NUnit in C#: either:

it tells me on stdout that the test failed but the test still appears green

it tells me that it doesn't find any test to run

or I don't understand how to apply in C# the doc I read

I think a dummy but complete example would help...

(More details)

1st step: test remains green

I installed the Nuget package FsCheck.NUnit (2.10.4), and naively tried:

```<code>[NUnit.Framework.Test]
public void SomeTest()
{
    // Note the subtle bug: I Reverse only once, because I want the test to fail
    Func<int[],bool> revRevIsOrig = xs => xs.Reverse().SequenceEqual( xs );
    Prop.ForAll(revRevIsOrig).QuickCheck();
}
</code>```

When I run it as I would run any NUnit test, it ends up green, even though I see on stdout that

```<code>Falsifiable, after 3 tests (1 shrink) (StdGen (2129798881,296376481)):
Original:
[|-1; 0|]
Shrunk:
[|1; 0|]
</code>```

2nd step: test inconclusive

So I went on, found some doc, and noticed that I should use Property instead of Test. So I changed my code to

```<code>[FsCheck.NUnit.Property] // <-- the line that changed
public void SomeTest()
{
    Func<int[],bool> revRevIsOrig = xs => xs.Reverse().SequenceEqual( xs );
    Prop.ForAll(revRevIsOrig).QuickCheck();
}
</code>```

I launched the test from Visual, and it ended up with the status inconclusive. And some log was telling me:

Cannot run tests: No suitable tests found in 'xxx.exe'. Either assembly contains no tests or proper test driver has not been found

3rd step: I notice I didn't understood the doc

When I re-read the doc, I notice that it says that my test method can take argument and should return a property. I'm obviously not doing it since I return nothing.

The sad thing is that I don't understand what I'm actually supposed to do (and I'm not familiar enough with F# to understand the example below...)... (I've blindly tried some random stuff that looked they could make sense, but I never ended up with a red test)

I would really appreciate any pointer to help me get this test red!

答:
Try using the QuickCheckThrowOnFailure function

the QuickThrowOnFailure ensures that if the test fails, an exception with the necessary information is raised so the runner know the test failed.

```<code>[Test]
public void SomeTest() {
    // Note the subtle bug: I Reverse only once, because I want the test to fail
    Func<int[],bool> revRevIsOrig = xs => xs.Reverse().SequenceEqual( xs );
    Prop.ForAll(revRevIsOrig).QuickCheckThrowOnFailure();
}
</code>```

Title: FsCheck integration with NUnit in C#

Body:
TL;DR: I'm not able to successfully use FsCheck with NUnit in C#: either:

it tells me on stdout that the test failed but the test still appears green

it tells me that it doesn't find any test to run

or I don't understand how to apply in C# the doc I read

I think a dummy but complete example would help...

(More details)

1st step: test remains green

I installed the Nuget package FsCheck.NUnit (2.10.4), and naively tried:

[NUnit.Framework.Test]
public void SomeTest()
{
    // Note the subtle bug: I Reverse only once, because I want the test to fail
    Func<int[],bool> revRevIsOrig = xs => xs.Reverse().SequenceEqual( xs );
    Prop.ForAll(revRevIsOrig).QuickCheck();
}

When I run it as I would run any NUnit test, it ends up green, even though I see on stdout that

Falsifiable, after 3 tests (1 shrink) (StdGen (2129798881,296376481)):
Original:
[|-1; 0|]
Shrunk:
[|1; 0|]

2nd step: test inconclusive

So I went on, found some doc, and noticed that I should use Property instead of Test. So I changed my code to

[FsCheck.NUnit.Property] // <-- the line that changed
public void SomeTest()
{
    Func<int[],bool> revRevIsOrig = xs => xs.Reverse().SequenceEqual( xs );
    Prop.ForAll(revRevIsOrig).QuickCheck();
}

I launched the test from Visual, and it ended up with the status inconclusive. And some log was telling me:

Cannot run tests: No suitable tests found in 'xxx.exe'. Either assembly contains no tests or proper test driver has not been found

3rd step: I notice I didn't understood the doc

When I re-read the doc, I notice that it says that my test method can take argument and should return a property. I'm obviously not doing it since I return nothing.

The sad thing is that I don't understand what I'm actually supposed to do (and I'm not familiar enough with F# to understand the example below...)... (I've blindly tried some random stuff that looked they could make sense, but I never ended up with a red test)

I would really appreciate any pointer to help me get this test red!

Body:
Try using the QuickCheckThrowOnFailure function

the QuickThrowOnFailure ensures that if the test fails, an exception with the necessary information is raised so the runner know the test failed.

[Test]
public void SomeTest() {
    // Note the subtle bug: I Reverse only once, because I want the test to fail
    Func<int[],bool> revRevIsOrig = xs => xs.Reverse().SequenceEqual( xs );
    Prop.ForAll(revRevIsOrig).QuickCheckThrowOnFailure();
}


问:
EDIT (judge harshly): My display() method won't display and I'm not sure why
I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.

The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.

I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.

My constructor looks like this:

==================================================

```<code> public class Salesperson
   {
   private String salesName;
   private int salesID;
   private double annualSales;

   public Salesperson(String salesName, int salesIDNum, double yearlySales)
   {
       this.salesName = salesName;
       salesID = salesIDNum;
       annualSales = yearlySales;
   }

   public String getSalesName()
   {
       return salesName;
   }
   public void setSalesName(String salesName)
   {
       this.salesName = salesName;
   }
   public double getSalesID()
   {
       return salesID;
   }
   public void setSalesID(int salesIDNum)
   {
       salesID = salesIDNum;
   }
   public double getAnnualSales()
   {
       return annualSales;
   }
   public void setAnnualSales(double yearlySales)
   {
       annualSales = yearlySales;
   }
   @Override
   public String toString()
   {
       return String.format("%s-%-10s%-10.2f", salesName,
                salesID, annualSales);
    }
</code>```

       }

```<code>And my code for application looks like this:

    import java.util.Arrays;
    import java.util.Scanner;
     public class CreateSalesperson
     {
       private static final Scanner USER_INPUT = new Scanner(System.in);
       private static final int UPPER_SIZE_LIMIT = 20;
       private static final int LOWER_SIZE_LIMIT = 0;
       private static Salesperson[] salesStaffInDatabase = new
      Salesperson[20];
       private static int numOfSalesPpl = 0;
       private static boolean loop = true;
       public static void main(String[] args)
      {
       String selection;
       selection = programMenu();
       String response;

            while(loop)
              switch(selection)
              {
                  case "A":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                  case "a":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                    case "C":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "c":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "E":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                    case "e":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                }
                }

      public static void changeRecord()
        {
            String idNum;
            String salesName;
            double salesAmount;
            String response;

            System.out.print("Enter Sales ID: ");
            idNum = USER_INPUT.nextLine();
            if(isValidID(idNum))

            {
            int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
            System.out.println(salesStaffInDatabase[searchResult]);
            }
            else
            {
                System.out.println("Invalid Sales ID");
            }
        }
     public static boolean isValidID(String idNum)
     {
     boolean isValid= false;
     for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
     {
         if(salesStaffInDatabase[val].equals(idNum))
                 {
                   isValid = true;
                 }
     }
     return isValid;
     }
     public static void addRecord()
     {
        int idNum;
        String salesName;
        double salesAmount;
        String idNo;
        String response;

       do
       {
        System.out.print("Please enter sales ID: ");
        idNum = USER_INPUT.nextInt();
        idNo = Integer.toString(idNum);
        if(idNo.length() != 8)

           System.out.println("Sales ID must be 8 digits long: ");

       }
       while(idNo.length() < 8 || idNo.length() > 8);

        System.out.print("Name: ");
        salesName = USER_INPUT.nextLine();
        USER_INPUT.nextLine();
        System.out.print("Sales Amount: ");
        salesAmount = Double.parseDouble(USER_INPUT.nextLine());
        salesStaffInDatabase[numOfSalesPpl] = new
     Salesperson(salesName,idNum,salesAmount);

        salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
        salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
        salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);

        System.out.print("Do you want to display database Y/N?: ");
        response = USER_INPUT.nextLine();
        while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
        {
          displayDatabase();
        }
    }

    public static void displayDatabase()
    {

        for(int val=0;val < numOfSalesPpl; val++)
        {
              System.out.println(salesStaffInDatabase[val]);
        }

    }
    public static String programMenu()
    {
    String selection;
     do
        {

         System.out.println("(A)dd a Record");
         System.out.println("(C)hange a Record");
         System.out.println("(E)xit Database");
         System.out.print("Enter selection: ");
         selection = USER_INPUT.nextLine();
        }
        while(!selection.equalsIgnoreCase("a") &&
    !selection.equalsIgnoreCase("c")
        && !selection.equalsIgnoreCase("e"));
        return selection;
    }
    }
</code>```

=================================================================

答:
edit the toString()method in Salesperson class :

```<code>      @Override
public String toString() {
    return "Salesperson{" +
            "salesFirstName='" + salesFirstName + '\'' +
            ", salesLastName='" + salesLastName + '\'' +
            ", salesID='" + salesID + '\'' +
            ", annualSales=" + String.format("%-10.2f",  annualSales)+
            '}';
}
</code>```

Body:
I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.

The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.

I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.

My constructor looks like this:

==================================================

 public class Salesperson
   {
   private String salesName;
   private int salesID;
   private double annualSales;

   public Salesperson(String salesName, int salesIDNum, double yearlySales)
   {
       this.salesName = salesName;
       salesID = salesIDNum;
       annualSales = yearlySales;
   }

   public String getSalesName()
   {
       return salesName;
   }
   public void setSalesName(String salesName)
   {
       this.salesName = salesName;
   }
   public double getSalesID()
   {
       return salesID;
   }
   public void setSalesID(int salesIDNum)
   {
       salesID = salesIDNum;
   }
   public double getAnnualSales()
   {
       return annualSales;
   }
   public void setAnnualSales(double yearlySales)
   {
       annualSales = yearlySales;
   }
   @Override
   public String toString()
   {
       return String.format("%s-%-10s%-10.2f", salesName,
                salesID, annualSales);
    }

       }

And my code for application looks like this:

    import java.util.Arrays;
    import java.util.Scanner;
     public class CreateSalesperson
     {
       private static final Scanner USER_INPUT = new Scanner(System.in);
       private static final int UPPER_SIZE_LIMIT = 20;
       private static final int LOWER_SIZE_LIMIT = 0;
       private static Salesperson[] salesStaffInDatabase = new
      Salesperson[20];
       private static int numOfSalesPpl = 0;
       private static boolean loop = true;
       public static void main(String[] args)
      {
       String selection;
       selection = programMenu();
       String response;

            while(loop)
              switch(selection)
              {
                  case "A":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                  case "a":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                    case "C":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "c":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "E":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                    case "e":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                }
                }

      public static void changeRecord()
        {
            String idNum;
            String salesName;
            double salesAmount;
            String response;

            System.out.print("Enter Sales ID: ");
            idNum = USER_INPUT.nextLine();
            if(isValidID(idNum))

            {
            int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
            System.out.println(salesStaffInDatabase[searchResult]);
            }
            else
            {
                System.out.println("Invalid Sales ID");
            }
        }
     public static boolean isValidID(String idNum)
     {
     boolean isValid= false;
     for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
     {
         if(salesStaffInDatabase[val].equals(idNum))
                 {
                   isValid = true;
                 }
     }
     return isValid;
     }
     public static void addRecord()
     {
        int idNum;
        String salesName;
        double salesAmount;
        String idNo;
        String response;

       do
       {
        System.out.print("Please enter sales ID: ");
        idNum = USER_INPUT.nextInt();
        idNo = Integer.toString(idNum);
        if(idNo.length() != 8)

           System.out.println("Sales ID must be 8 digits long: ");

       }
       while(idNo.length() < 8 || idNo.length() > 8);

        System.out.print("Name: ");
        salesName = USER_INPUT.nextLine();
        USER_INPUT.nextLine();
        System.out.print("Sales Amount: ");
        salesAmount = Double.parseDouble(USER_INPUT.nextLine());
        salesStaffInDatabase[numOfSalesPpl] = new
     Salesperson(salesName,idNum,salesAmount);

        salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
        salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
        salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);

        System.out.print("Do you want to display database Y/N?: ");
        response = USER_INPUT.nextLine();
        while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
        {
          displayDatabase();
        }
    }

    public static void displayDatabase()
    {

        for(int val=0;val < numOfSalesPpl; val++)
        {
              System.out.println(salesStaffInDatabase[val]);
        }

    }
    public static String programMenu()
    {
    String selection;
     do
        {

         System.out.println("(A)dd a Record");
         System.out.println("(C)hange a Record");
         System.out.println("(E)xit Database");
         System.out.print("Enter selection: ");
         selection = USER_INPUT.nextLine();
        }
        while(!selection.equalsIgnoreCase("a") &&
    !selection.equalsIgnoreCase("c")
        && !selection.equalsIgnoreCase("e"));
        return selection;
    }
    }

=================================================================

Body:
edit the toString()method in Salesperson class :

      @Override
public String toString() {
    return "Salesperson{" +
            "salesFirstName='" + salesFirstName + '\'' +
            ", salesLastName='" + salesLastName + '\'' +
            ", salesID='" + salesID + '\'' +
            ", annualSales=" + String.format("%-10.2f",  annualSales)+
            '}';
}


问:
Oracle Open Cursor Execution time
I'm trying to figure out how long this cursor takes to execute. However, I'm getting the same start and end time.

Please note I didn't include the actual sql statement. But I'm sure it is takes quite long time to execute.

```<code>PROCEDURE GetData (p1 IN VARCHAR2,myREFCURSOR OUT SYS_REFCURSOR)
IS
    DynamicStatement       CLOB;
BEGIN
    INSERT INTO TimeTable VALUES ('StartTime',SYSDATE);
    COMMIT;

    OPEN myREFCURSOR FOR DynamicStatement;

    INSERT INTO TimeTable VALUES ('EndTime',SYSDATE);
    COMMIT;
END;
</code>```

答:
A Ref Cursor is a pointer to a chunk of memory where a query is stashed. Opening one is just an assignment operation, it doesn't execute the query. That's why it appears to take no time at all.

If you want to see how long it takes to run the actual query you need to FETCH records into some record variable.

```<code>PROCEDURE GetData (p1 IN VARCHAR2,myREFCURSOR OUT SYS_REFCURSOR)
IS
    DynamicStatement       CLOB;
    type rec is record (id number, blah varchar2(128));
    lrec rec;
BEGIN
    INSERT INTO TimeTable VALUES ('StartTime',SYSDATE);
    COMMIT;

    OPEN myREFCURSOR FOR DynamicStatement;

    loop
        fetch myREFCURSOR into rec;
        exit when myREFCURSOR%notfound;
    end loop;
    close myREFCURSOR;

    INSERT INTO TimeTable VALUES ('EndTime',SYSDATE);
    COMMIT;
END;
</code>```

Obviously the record variable must match the projection of your query. Given that you're executing DynamicStatement that may be difficult.

Title: Oracle Open Cursor Execution time

Body:
I'm trying to figure out how long this cursor takes to execute. However, I'm getting the same start and end time.

Please note I didn't include the actual sql statement. But I'm sure it is takes quite long time to execute.

PROCEDURE GetData (p1 IN VARCHAR2,myREFCURSOR OUT SYS_REFCURSOR)
IS
    DynamicStatement       CLOB;
BEGIN
    INSERT INTO TimeTable VALUES ('StartTime',SYSDATE);
    COMMIT;

    OPEN myREFCURSOR FOR DynamicStatement;

    INSERT INTO TimeTable VALUES ('EndTime',SYSDATE);
    COMMIT;
END;

Body:
A Ref Cursor is a pointer to a chunk of memory where a query is stashed. Opening one is just an assignment operation, it doesn't execute the query. That's why it appears to take no time at all.

If you want to see how long it takes to run the actual query you need to FETCH records into some record variable.

PROCEDURE GetData (p1 IN VARCHAR2,myREFCURSOR OUT SYS_REFCURSOR)
IS
    DynamicStatement       CLOB;
    type rec is record (id number, blah varchar2(128));
    lrec rec;
BEGIN
    INSERT INTO TimeTable VALUES ('StartTime',SYSDATE);
    COMMIT;

    OPEN myREFCURSOR FOR DynamicStatement;

    loop
        fetch myREFCURSOR into rec;
        exit when myREFCURSOR%notfound;
    end loop;
    close myREFCURSOR;

    INSERT INTO TimeTable VALUES ('EndTime',SYSDATE);
    COMMIT;
END;

Obviously the record variable must match the projection of your query. Given that you're executing DynamicStatement that may be difficult.


问:
Convert IP between IPv4 and numerical format in java
An IPv4 can have more representations: as string (a.b.c.d) or numerical (as an unsigned int of 32 bits). (Maybe other, but I will ignore them.)

Is there any built in support in Java (8), simple and easy to use, without network access, to convert between these formats?

I need something like this:

```<code>long ip = toNumerical("1.2.3.4"); // returns 0x0000000001020304L
String ipv4 = toIPv4(0x0000000001020304L); // returns "1.2.3.4"
</code>```

If there is no built in such functions in Java, feel free to suggest other solutions.

Thank you

答:
Heres is a way to Convert IP to Number. I found it a valid way to accomplish the task in Java.

```<code>public long ipToLong(String ipAddress) {

    String[] ipAddressInArray = ipAddress.split("\\.");

    long result = 0;
    for (int i = 0; i < ipAddressInArray.length; i++) {

        int power = 3 - i;
        int ip = Integer.parseInt(ipAddressInArray[i]);
        result += ip * Math.pow(256, power);

    }

    return result;
  }
</code>```

This is also how you would implement it in Scala.

```<code>  def convertIPToLong(ipAddress: String): Long = {

    val ipAddressInArray = ipAddress.split("\\.")
    var result = 0L

    for (i  <- 0  to ipAddressInArray.length-1) {
      val power = 3 - i
      val ip = ipAddressInArray(i).toInt
      val longIP = (ip * Math.pow(256, power)).toLong
      result = result +longIP
    }
    result
  }
</code>```

Body:
An IPv4 can have more representations: as string (a.b.c.d) or numerical (as an unsigned int of 32 bits). (Maybe other, but I will ignore them.)

Is there any built in support in Java (8), simple and easy to use, without network access, to convert between these formats?

I need something like this:

long ip = toNumerical("1.2.3.4"); // returns 0x0000000001020304L
String ipv4 = toIPv4(0x0000000001020304L); // returns "1.2.3.4"

If there is no built in such functions in Java, feel free to suggest other solutions.

Thank you

Body:
Heres is a way to Convert IP to Number. I found it a valid way to accomplish the task in Java.

public long ipToLong(String ipAddress) {

    String[] ipAddressInArray = ipAddress.split("\\.");

    long result = 0;
    for (int i = 0; i < ipAddressInArray.length; i++) {

        int power = 3 - i;
        int ip = Integer.parseInt(ipAddressInArray[i]);
        result += ip * Math.pow(256, power);

    }

    return result;
  }

This is also how you would implement it in Scala.

  def convertIPToLong(ipAddress: String): Long = {

    val ipAddressInArray = ipAddress.split("\\.")
    var result = 0L

    for (i  <- 0  to ipAddressInArray.length-1) {
      val power = 3 - i
      val ip = ipAddressInArray(i).toInt
      val longIP = (ip * Math.pow(256, power)).toLong
      result = result +longIP
    }
    result
  }


问:
Event sourcing / CQRS read model - projections
I have a microservice-based application running on AWS Lambda. Two of the microservices, the most crucial ones, use event-sourcing/cqrs.

Background: (this is also for me to organize my thoughts)

I'm using this library  and storing events in DynamoDB and projections in AWS S3.

The write part works like a charm: Each command invocation loads the current state of the aggregate from DynamoDB (by running events through a handler and/or loading an cached aggregate), it decides to accept or reject the command based on some business logic, then writes to DynamoDB with KeyConditionExpression: 'aggregateId = :a AND version >= :v' where the version is a count of events processed for that aggregate. If there's a conflict, the write fails. Seems like a good system to me!

Each event is then broadcast to SNS (topic name is the service name) so other services can react to the event, if they want.

The part that I really struggle with is the read. Projections are stored in S3 and tagged with the last commitId processed for each event source. When a read query comes in, it loads the entire projected state from S3 (for all aggregates), queries the event sources for all newer events, computes the latest state (again, for all aggregates - and writing an updated object to S3 if it's newer), and returns relevant parts of the state based on the query params.

My problem: (or one of them)

I think I'm doing projections wrong.

Most of my projections only group ids by important attribute, so the files stay relatively small. But I also need a way to retrieve an individual aggregate. Using projections for that seems crazy, because I need to load the entire state each time (i.e. every projected aggregate) apply new events to that, then retrieve the record I want (it may not have even changed).

This is what I'm doing now, it's performing fine (<100k records) but I can't imagine it will continue much longer.

The other problem is queries. I need to build a projection mapping value to matching aggregateIds for every attribute I need to query on!! There's got to be a better way!

No matter what way I think about this problem, projections always need the entire current state + any new events before it can return even a single record that hasn't changed.

答:
I think I'm doing projections wrong.

I think so too; it sounds like you have your queries coupled to your projections

When a read query comes in, it loads the entire projected state from S3 (for all aggregates), queries the event sources for all newer events, computes the latest state

Yeah, that sounds like a mess.  Or more specifically, that sounds like the query is triggering the work to be done by the projection.

If you can decouple the queries from the projections, then things get easier.  The basic idea being that your queries don't describe the current state, they describe the state as of the last time the projection ran.

Same idea, different spelling: you answer queries from the documents that you cache in S3.  When new events are detected, your projections run, load the new data as needed, compute the new document, and replace the entries in the cache.

I think of a triangle

Commands bring information from the outside to the book of record

Projections bring information from the book of record to the cache

Queries bring information from the cache to the outside world

where each leg of the triangle runs asynchronously with the others.

I suggest you work backwards from the queries - what documents do you need to support each query? what are the latency targets that you have to beat?  Then you start balancing tradeoffs - for this new query, do I create the result from the existing documents, or do I need a new document built with a finer grain?

if I understand correctly, I should be triggering the projection updates as events come in, instead of in aggregate when the query is made. That saves me from querying the event store for new events on every query

Yes, and... events are only one way of triggering; you could also have the projection processes triggered by a clock (check every 15 minutes to see if we need to update) or at the whim of a human operator (hmm, it looks like your account balance is stale, let me try to update that for you).  More than one way to do it, and you can mix and match strategies.

I would still need to load the entire state, both when updating the projection, and when loading a single aggregate.

Not necessarily.  There's no rule that says you can't use the previously cached representation as a starting point, and then pull from the book of record only the changes that you need.

For instance, suppose you are building a view that combines aggregates A{id:7} and B{id:9}.  You grab the cached copy, and look in its meta data (where you put it on your previous write) and find something inside it like metadata:{A:{id:7, version:21}, B:{id:9, version:19}}.  Now you only need to load the events after the ones you used last time, update your local copy in memory, update the local copy of the metadata, and push the lot to the cache.


问:
Mouse manipulation on OSX
I asked a similar question a few weeks back but it failed to attract an answer but this is a more open query (it was a couple of days before the holidays though).  Previous question is here

Is there any way to prevent mouse movement or clicks being passed to whatever app is in the foreground, or give the impression that it is.  I'm particularly interested in preventing the mouse being moved by the trackpad or magicpad.

I basically want the user to perform a gesture on the magicpad, disable the mouse functionality/system gestures, monitor/react to further gestures on the pad and at some point re-instate the mouse functionality.   The closest I have come to keep warping the mouse cursor back to where it was on activation for each mouse move event, but this causes the mouse to flitter back and forth which is very distracting.  I have managed to hide the cursor globally but the mouse is still moving and clicks occurring, which while you can't see it can be very distracting confusing when the app underneath reacts to it.

答:
Are you manipulating your own application's events, or other applications?

Would the CGAssociateMouseAndMouseCursorPosition() function be helpful in eliminating the flickering mouse?

```<code>CGAssociateMouseAndMouseCursorPosition(false);
...
CGAssociateMouseAndMouseCursorPosition(true);
</code>```

From Apple's Quartz Display Services Programming - Controlling the Mouse Cursor

Title: Mouse manipulation on OSX

Body:
Are you manipulating your own application's events, or other applications?

Would the CGAssociateMouseAndMouseCursorPosition() function be helpful in eliminating the flickering mouse?

CGAssociateMouseAndMouseCursorPosition(false);
...
CGAssociateMouseAndMouseCursorPosition(true);

From Apple's Quartz Display Services Programming - Controlling the Mouse Cursor


问:
How to connect WordPress to ActiveCampaign database?
I am developing a website for a company on WordPress. Their old client/contact database was with WildApricot. They wanted to now use ActiveCampaign as a hosting service, and I've since exported all our our client/contact data to ActiveCampaign.

Now here's the problem. The ActiveCampaign database has all of our client information, including passwords, emails, and profile information.

What I am trying to do is create a new connection in WordPress to ActiveCampaign, but I am unsure of how to do this. I understand the gist of it, but cannot find any information on how to get database information for ActiveCampaign. Stuff like, DB name, host, etc. so I can use that in a new wpdb class.

Keep in mind my PHP is limited, as I haven't had much exposure to it.

答:
You need to use the ActiveCampaign PHP API to connect with ActiveCampaign.

https://github.com/ActiveCampaign/activecampaign-api-php

For that you will need your API KEY and API URL, that you can find in AC under "settings" > "developer".

Using the API you can retrieve the information from your contacts and store in WP in the way you want it to be.

Another option is try to use Zapier and see if they have an integration for what you need.


问:
Detecting of flat landscape / portrait orientation
Is there way to detect if it is flat and landscape or flat and portrait orientation of device ?

I am asking about that becouse I have UICollectionView in my UIViewController and in Portrait mode cells are placed in one row, in line. In Landscape they are in only column - they swaped from horizontal to vertical. I have update of collection data for every 60 seconds. After this time have to call reloadData() to actualize the data and If I will leave device *inFlat orientation, layout will get destroyed, cuz of sizeForItemAt. None of conditions would be perfect.

```<code>let isPortrait = UIDevice.current.orientation.isPortrait
if !isPortrait {
    return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4)
} else {
    return CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height)
}
</code>```

There is no way to place it like this:

```<code>let isFlat = UIDevice.currentorientation.isFlat
if isFlat && isPortrait {
//
}
</code>```

It can't be in same time isPortrait and isFlat.

Is there any work around this ?

答:
In my opinion, to resolve it, you should save last size of item. When our device stays in flat, sizeForItemAt will return last size of item.

```<code>var currentSize : CGSize?

override func viewDidLoad() {
  super.viewDidLoad()

  // In viewDidLoad, need to set default value for currentSize. Make sure in case
  // your app start at flat orientation, you collectionView still has a size
  currentSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4);
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  if UIDevice.current.orientation.isPortrait {
    currentSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4)
  } else if UIDevice.current.orientation.isPortrait {
    currentSize = CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height)
  }
  return currentSize;
}
</code>```

Only update value of currentSize when your device stays in portrait or landscape mode. If not, use current size of item.

Body:
Is there way to detect if it is flat and landscape or flat and portrait orientation of device ?

I am asking about that becouse I have UICollectionView in my UIViewController and in Portrait mode cells are placed in one row, in line. In Landscape they are in only column - they swaped from horizontal to vertical. I have update of collection data for every 60 seconds. After this time have to call reloadData() to actualize the data and If I will leave device *inFlat orientation, layout will get destroyed, cuz of sizeForItemAt. None of conditions would be perfect.

let isPortrait = UIDevice.current.orientation.isPortrait
if !isPortrait {
    return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4)
} else {
    return CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height)
}

There is no way to place it like this:

let isFlat = UIDevice.currentorientation.isFlat
if isFlat && isPortrait {
//
}

It can't be in same time isPortrait and isFlat.

Is there any work around this ?

Body:
In my opinion, to resolve it, you should save last size of item. When our device stays in flat, sizeForItemAt will return last size of item.

var currentSize : CGSize?

override func viewDidLoad() {
  super.viewDidLoad()

  // In viewDidLoad, need to set default value for currentSize. Make sure in case
  // your app start at flat orientation, you collectionView still has a size
  currentSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4);
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  if UIDevice.current.orientation.isPortrait {
    currentSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4)
  } else if UIDevice.current.orientation.isPortrait {
    currentSize = CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height)
  }
  return currentSize;
}

Only update value of currentSize when your device stays in portrait or landscape mode. If not, use current size of item.


问:
Using a Blob as a Flash object
I am trying to use a Flash object stored in a blob, however my approach using the URL returned by URL.createObjectURL as the src of the embed tag just results in the browser downloading the blob as a file.

Here's my generated HTML:

```<code><object height="500" width="1000">
    <embed height="500" width="1000" src="blob:http://127.0.0.1:34721/1fa7a01c-25b7-4ad0-ba1d-1ddef61617ce"/>
</object>
</code>```

And here's JavaScript used to generate the Blob and object tag:

```<code>var blob = new Blob(data, {
               type: 'application/x-shockwave-flash'
           });

document.body.innerHTML += '<object height="500" width="1000" ><embed height="500" width="1000" src="' + URL.createObjectURL(blob) + '"/></object>'
</code>```

Where data is an array of Uint8Arrays, each containing 256 bytes of the binary data.

The blob in question has a type of application/x-shockwave-flash and is identical to the original .swf file (I checked). The file itself works when used in place of the Object URL.

From what I have read, an Object URL pointing to a blob can be used any place a normal URL could. Are embed tags an exception to this?

答:
The embed tag may miss the mime type that it normally gets from a response header. Try setting "type="application/x-shockwave-flash" as an attribute inside your embed tag.

Still, Flash isn't widely supported anymore, I'd test across browsers to see if it's the same error. You may need to add the type to the object tag in legacy browsers.

Title: Using a Blob as a Flash object

Body:
I am trying to use a Flash object stored in a blob, however my approach using the URL returned by URL.createObjectURL as the src of the embed tag just results in the browser downloading the blob as a file.

Here's my generated HTML:

<object height="500" width="1000">
    <embed height="500" width="1000" src="blob:http://127.0.0.1:34721/1fa7a01c-25b7-4ad0-ba1d-1ddef61617ce"/>
</object>

And here's JavaScript used to generate the Blob and object tag:

var blob = new Blob(data, {
               type: 'application/x-shockwave-flash'
           });

document.body.innerHTML += '<object height="500" width="1000" ><embed height="500" width="1000" src="' + URL.createObjectURL(blob) + '"/></object>'

Where data is an array of Uint8Arrays, each containing 256 bytes of the binary data.

The blob in question has a type of application/x-shockwave-flash and is identical to the original .swf file (I checked). The file itself works when used in place of the Object URL.

From what I have read, an Object URL pointing to a blob can be used any place a normal URL could. Are embed tags an exception to this?


问:
sed - how to replace meta character
In the following example I am looking to include the * metacharacter in the string replacement. If I understand correctly, I should be able to escape the character using \ but after doing that this is the result I am seeing:

```<code>❯ echo 'foo(*)' | sed s/foo\(\*/bar/g
bar*)
</code>```

I was expecting to see the following:

```<code>❯ echo 'foo(*)' | sed s/foo\(\*/bar/g
bar)
</code>```

答:
You need to quote your sed command:</p>

```<code>echo 'foo(*)' | sed 's/foo(\*/bar/g'
bar)
</code>```

Title: sed - how to replace meta character

Body:
In the following example I am looking to include the * metacharacter in the string replacement. If I understand correctly, I should be able to escape the character using \ but after doing that this is the result I am seeing:

❯ echo 'foo(*)' | sed s/foo\(\*/bar/g
bar*)

I was expecting to see the following:

❯ echo 'foo(*)' | sed s/foo\(\*/bar/g
bar)

Body:
You need to quote your sed command:

echo 'foo(*)' | sed 's/foo(\*/bar/g'
bar)


问:
Animating List in Angular 5
Created an animation in Angular 5 when adding and removing an item from the list.

When adding an item, it appears from top, ease in slowly and get placed in the list, and when an item is removed, the item is eased out slowly to the top and disappears. The issue i'm trying to solve is, when an item is removed, it eases out nice and slow and disappears, then the remaining items in the list, just snaps. I need the remaining items to move smoothly instead of snapping. How can i do that?

Here is my code:

app.component.ts

```<code>import { Component } from '@angular/core';
import { trigger, state, style, transition, animate, group } from '@angular/animations'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('itemAnim', [
      transition(':enter', [
    style({ transform: 'translateY(-20%)' }),
    animate(500)
  ]),
  transition(':leave', [
    group([
          animate('0.1s ease', style({ transform: 'translateY(-20%)' })),
          animate('0.5s 0.2s ease', style({ opacity: 0 }))
        ])
      ])
    ])
  ]
})
export class AppComponent {
  title = 'Item';
  items:string[]=[];
  i=0;
  addItem(){
    this.items.push(this.title+this.i++);
  }
  removeItem(){
    this.items.shift();
  }
}
</code>```

app.component.html

```<code><button (click)="addItem()">Add</button>
<button (click)="removeItem()">Remove</button>
<br/>
<ul>
  <li [@itemAnim]="items.length" *ngFor="let item of items">
    {{item}}
  </li>
</ul>
</code>```

Here is the working plunker
Click here

答:
You could use the height of the
 element, so when you change it to 0px to make it disappear, it moves a bit more smoothly the elements that are under :

```<code>transition(':leave', [
   group([
      animate('0.5s ease', style({ transform: 'translateY(-20%)', 'height':'0px' })),
      animate('0.5s 0.2s ease', style({ opacity: 0 }))
   ])
])
</code>```

I also increased the transition lasting time from 0.1s to 0.5s to make it more obvious.

Title: Animating List in Angular 5

Body:
Created an animation in Angular 5 when adding and removing an item from the list.

When adding an item, it appears from top, ease in slowly and get placed in the list, and when an item is removed, the item is eased out slowly to the top and disappears. The issue i'm trying to solve is, when an item is removed, it eases out nice and slow and disappears, then the remaining items in the list, just snaps. I need the remaining items to move smoothly instead of snapping. How can i do that?

Here is my code:

app.component.ts

import { Component } from '@angular/core';
import { trigger, state, style, transition, animate, group } from '@angular/animations'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('itemAnim', [
      transition(':enter', [
    style({ transform: 'translateY(-20%)' }),
    animate(500)
  ]),
  transition(':leave', [
    group([
          animate('0.1s ease', style({ transform: 'translateY(-20%)' })),
          animate('0.5s 0.2s ease', style({ opacity: 0 }))
        ])
      ])
    ])
  ]
})
export class AppComponent {
  title = 'Item';
  items:string[]=[];
  i=0;
  addItem(){
    this.items.push(this.title+this.i++);
  }
  removeItem(){
    this.items.shift();
  }
}

app.component.html

<button (click)="addItem()">Add</button>
<button (click)="removeItem()">Remove</button>

    {{item}}

Here is the working plunker
Click here

Body:
You could use the height of the <li> element, so when you change it to 0px to make it disappear, it moves a bit more smoothly the elements that are under :

transition(':leave', [
   group([
      animate('0.5s ease', style({ transform: 'translateY(-20%)', 'height':'0px' })),
      animate('0.5s 0.2s ease', style({ opacity: 0 }))
   ])
])

I also increased the transition lasting time from 0.1s to 0.5s to make it more obvious.