问:
Get SQL of failed statement inside exit handler of MySQL stored procedure
I am building a stored procedure that executes 10-12 SQL statements.  I'm getting an error 1172, Result consisted of more than one row.  I'm trying to figure out which statement is responsible.

The most obvious way is to return the SQL of the statement that raised the error.

Here is my exit handler:

```<code>  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    GET DIAGNOSTICS @n = NUMBER, @c = ROW_COUNT;
    GET DIAGNOSTICS CONDITION @n
      @s = RETURNED_SQLSTATE,
      @m = MESSAGE_TEXT,
      @e = MYSQL_ERRNO;
    ROLLBACK;
    SELECT @s as RETURNED_SQLSTATE, @e as MYSQL_ERRNO, @m as MESSAGE_TEXT, @n as NUMBER, @c as ROW_COUNT;
  END;
</code>```

What can I add so that it will tell me which of my SQL statements generated the error?

For reference, here is the full stored procedure:

```<code>DROP PROCEDURE IF EXISTS `unlink_item`;
CREATE PROCEDURE `unlink_item` (
  IN item_id         varchar(36),
  IN parent_id       varchar(36),
  IN author          varchar(64),
  IN conversation_id varchar(36),
  IN transaction_id  varchar(36)
)
BEGIN

  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    GET DIAGNOSTICS @n = NUMBER, @c = ROW_COUNT;
    GET DIAGNOSTICS CONDITION @n
      @s = RETURNED_SQLSTATE,
      @m = MESSAGE_TEXT,
      @e = MYSQL_ERRNO;
    ROLLBACK;
    SELECT @s as RETURNED_SQLSTATE, @e as MYSQL_ERRNO, @m as MESSAGE_TEXT, @n as NUMBER, @c as ROW_COUNT;
  END;

  START TRANSACTION;

  SET @when = now();

  -- identify the record we are supposed to delete --
  SET @deleted = '123';
  SELECT  `id`
    FROM  `item_contains`
    WHERE `parent_id` = parent_id
    AND   `child_id`  = item_id
    INTO @deleted;

  -- delete the record --
  DELETE FROM `item_contains`
  WHERE `id` = @deleted;

  -- update the change history for the item_contains table --
  INSERT INTO `change_history` (
    `date_time`,
    `author`,
    `action`,
    `table_name`,
    `record_id`,
    `conversation_id`,
    `transaction_id`
  ) VALUES (
    @when,
    author,
    'delete',
    'item_contains',
    @deleted,
    conversation_id,
    transaction_id
  );

  -- update the change history for the parent item --
  INSERT INTO `change_history` (
    `date_time`,
    `author`,
    `action`,
    `table_name`,
    `record_id`,
    `conversation_id`,
    `transaction_id`
  ) VALUES (
    @when,
    author,
    concat('unlink from ',parent_id),
    'item',
    item_id,
    conversation_id,
    transaction_id
  );

  -- update the change history for the item being unlinked --
  INSERT INTO `change_history` (
    `date_time`,
    `author`,
    `action`,
    `table_name`,
    `record_id`,
    `conversation_id`,
    `transaction_id`
  ) VALUES (
    @when,
    author,
    concat('unlink ',item_id, ' from this'),
    'item',
    parent_id,
    conversation_id,
    transaction_id
  );

  -- if the unlinked item is now orphaned either delete it if it is empty, or re-attach it somewhere to make it accessible --
  SET @instances = 0;

  SELECT count(`id`)
    FROM `item_contains`
    WHERE `child_id` = item_id
    INTO @instances;

  IF ( @instances = 0 ) THEN

    SET @children = 0;
    SELECT count(`id`)
      FROM `item_contains`
      WHERE `parent_id` = item_id
      INTO @children;

    IF ( @children = 0 ) THEN

      -- delete the now inaccessible item from the database --
      DELETE FROM `item`
      WHERE `id` = item_id;

      -- update the change history for that item --
      INSERT INTO `change_history` (
        `date_time`,
        `author`,
        `action`,
        `table_name`,
        `record_id`,
        `conversation_id`,
        `transaction_id`
      ) VALUES (
        @when,
        author,
        'delete',
        'item',
        item_id,
        conversation_id,
        transaction_id
      );

    ELSE

      -- get the ID of the orphan folder --
      SET @orphan_id = '123';
      SELECT `id`
        FROM `item`
        WHERE `name` = '### orphans ###'
        INTO @orphan_id;

      -- move the item into the orphan folder --
      SET @inserted = uuid();
      INSERT INTO `item_contains` (
        `id`,
        `parent_id`,
        `child_id`
      ) VALUES (
        @inserted,
        @orphan_id,
        item_id
      );

      -- update the change history to reflect the orphaning of the item --
      INSERT INTO `change_history` (
        `date_time`,
        `author`,
        `action`,
        `table_name`,
        `record_id`,
        `conversation_id`,
        `transaction_id`
      ) VALUES (
        @when,
        author,
        'orphaned',
        'item',
        item_id,
        conversation_id,
        transaction_id
      );

    END IF;

  END IF;

  SELECT
    0 AS `RETURNED_SQLSTATE`,
    0 AS `MYSQL_ERRNO`,
    'Item unlinked' AS `MESSAGE_TEXT`,
    1 as `ROW_COUNT`;

  COMMIT;

END;
</code>```

UPDATE: The root problem was in the first SELECT statement:

```<code>SELECT `id` FROM `item_contains`
WHERE  `parent_id` = parent_id
AND    `child_id` = item_id
</code>```

I had assumed that the left parent_id would be the one from item_contains and the right parent_id would be the stored procedure parameter.  I was mistaken.  Both are interpreted as the stored procedure parameter.  The solution was to alias the table and refer to the fields via the alias, like so:

```<code>SELECT ic.id FROM item_contains AS ic
WHERE  ic.parent_id = parent_id
AND    ic.child_id = item_id
</code>```

HOWEVER: the original question still stands:

Is there something that I can add to my EXIT HANDLER that will tell me WHERE in my stored procedure that the error was raised?

答:
All SELECT ... INTO statements must return only one row.

For example, The below code may return more than 1 record:

```<code>SELECT  `id`
  FROM  `item_contains`
  WHERE `parent_id` = parent_id
  AND   `child_id`  = item_id
  INTO @deleted;
</code>```

You can debug statement storing the result in another variable and select:

```<code>SELECT  count(*)
  FROM  `item_contains`
  WHERE `parent_id` = parent_id
  AND   `child_id`  = item_id
  INTO @supposed_to_delete;

SELECT @supposed_to_delete;  /*you will see the value after execute*/
</code>```

Another way to make sure only one record (not recommended) is adding a limit

```<code>SELECT  `id`
  FROM  `item_contains`
  WHERE `parent_id` = parent_id
  AND   `child_id`  = item_id
  LIMIT 1   /* <-- force to return only one record */
  INTO @deleted;
</code>```

Body:
I am building a stored procedure that executes 10-12 SQL statements.  I'm getting an error 1172, Result consisted of more than one row.  I'm trying to figure out which statement is responsible.

The most obvious way is to return the SQL of the statement that raised the error.

Here is my exit handler:

  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    GET DIAGNOSTICS @n = NUMBER, @c = ROW_COUNT;
    GET DIAGNOSTICS CONDITION @n
      @s = RETURNED_SQLSTATE,
      @m = MESSAGE_TEXT,
      @e = MYSQL_ERRNO;
    ROLLBACK;
    SELECT @s as RETURNED_SQLSTATE, @e as MYSQL_ERRNO, @m as MESSAGE_TEXT, @n as NUMBER, @c as ROW_COUNT;
  END;

What can I add so that it will tell me which of my SQL statements generated the error?

For reference, here is the full stored procedure:

DROP PROCEDURE IF EXISTS `unlink_item`;
CREATE PROCEDURE `unlink_item` (
  IN item_id         varchar(36),
  IN parent_id       varchar(36),
  IN author          varchar(64),
  IN conversation_id varchar(36),
  IN transaction_id  varchar(36)
)
BEGIN

  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    GET DIAGNOSTICS @n = NUMBER, @c = ROW_COUNT;
    GET DIAGNOSTICS CONDITION @n
      @s = RETURNED_SQLSTATE,
      @m = MESSAGE_TEXT,
      @e = MYSQL_ERRNO;
    ROLLBACK;
    SELECT @s as RETURNED_SQLSTATE, @e as MYSQL_ERRNO, @m as MESSAGE_TEXT, @n as NUMBER, @c as ROW_COUNT;
  END;

  START TRANSACTION;

  SET @when = now();

  -- identify the record we are supposed to delete --
  SET @deleted = '123';
  SELECT  `id`
    FROM  `item_contains`
    WHERE `parent_id` = parent_id
    AND   `child_id`  = item_id
    INTO @deleted;

  -- delete the record --
  DELETE FROM `item_contains`
  WHERE `id` = @deleted;

  -- update the change history for the item_contains table --
  INSERT INTO `change_history` (
    `date_time`,
    `author`,
    `action`,
    `table_name`,
    `record_id`,
    `conversation_id`,
    `transaction_id`
  ) VALUES (
    @when,
    author,
    'delete',
    'item_contains',
    @deleted,
    conversation_id,
    transaction_id
  );

  -- update the change history for the parent item --
  INSERT INTO `change_history` (
    `date_time`,
    `author`,
    `action`,
    `table_name`,
    `record_id`,
    `conversation_id`,
    `transaction_id`
  ) VALUES (
    @when,
    author,
    concat('unlink from ',parent_id),
    'item',
    item_id,
    conversation_id,
    transaction_id
  );

  -- update the change history for the item being unlinked --
  INSERT INTO `change_history` (
    `date_time`,
    `author`,
    `action`,
    `table_name`,
    `record_id`,
    `conversation_id`,
    `transaction_id`
  ) VALUES (
    @when,
    author,
    concat('unlink ',item_id, ' from this'),
    'item',
    parent_id,
    conversation_id,
    transaction_id
  );

  -- if the unlinked item is now orphaned either delete it if it is empty, or re-attach it somewhere to make it accessible --
  SET @instances = 0;

  SELECT count(`id`)
    FROM `item_contains`
    WHERE `child_id` = item_id
    INTO @instances;

  IF ( @instances = 0 ) THEN

    SET @children = 0;
    SELECT count(`id`)
      FROM `item_contains`
      WHERE `parent_id` = item_id
      INTO @children;

    IF ( @children = 0 ) THEN

      -- delete the now inaccessible item from the database --
      DELETE FROM `item`
      WHERE `id` = item_id;

      -- update the change history for that item --
      INSERT INTO `change_history` (
        `date_time`,
        `author`,
        `action`,
        `table_name`,
        `record_id`,
        `conversation_id`,
        `transaction_id`
      ) VALUES (
        @when,
        author,
        'delete',
        'item',
        item_id,
        conversation_id,
        transaction_id
      );

    ELSE

      -- get the ID of the orphan folder --
      SET @orphan_id = '123';
      SELECT `id`
        FROM `item`
        WHERE `name` = '### orphans ###'
        INTO @orphan_id;

      -- move the item into the orphan folder --
      SET @inserted = uuid();
      INSERT INTO `item_contains` (
        `id`,
        `parent_id`,
        `child_id`
      ) VALUES (
        @inserted,
        @orphan_id,
        item_id
      );

      -- update the change history to reflect the orphaning of the item --
      INSERT INTO `change_history` (
        `date_time`,
        `author`,
        `action`,
        `table_name`,
        `record_id`,
        `conversation_id`,
        `transaction_id`
      ) VALUES (
        @when,
        author,
        'orphaned',
        'item',
        item_id,
        conversation_id,
        transaction_id
      );

    END IF;

  END IF;

  SELECT
    0 AS `RETURNED_SQLSTATE`,
    0 AS `MYSQL_ERRNO`,
    'Item unlinked' AS `MESSAGE_TEXT`,
    1 as `ROW_COUNT`;

  COMMIT;

END;

UPDATE: The root problem was in the first SELECT statement:

SELECT `id` FROM `item_contains`
WHERE  `parent_id` = parent_id
AND    `child_id` = item_id

I had assumed that the left parent_id would be the one from item_contains and the right parent_id would be the stored procedure parameter.  I was mistaken.  Both are interpreted as the stored procedure parameter.  The solution was to alias the table and refer to the fields via the alias, like so:

SELECT ic.id FROM item_contains AS ic
WHERE  ic.parent_id = parent_id
AND    ic.child_id = item_id

HOWEVER: the original question still stands:

Is there something that I can add to my EXIT HANDLER that will tell me WHERE in my stored procedure that the error was raised?

Body:
All SELECT ... INTO statements must return only one row.

For example, The below code may return more than 1 record:

SELECT  `id`
  FROM  `item_contains`
  WHERE `parent_id` = parent_id
  AND   `child_id`  = item_id
  INTO @deleted;

You can debug statement storing the result in another variable and select:

SELECT  count(*)
  FROM  `item_contains`
  WHERE `parent_id` = parent_id
  AND   `child_id`  = item_id
  INTO @supposed_to_delete;

SELECT @supposed_to_delete;  /*you will see the value after execute*/

Another way to make sure only one record (not recommended) is adding a limit

SELECT  `id`
  FROM  `item_contains`
  WHERE `parent_id` = parent_id
  AND   `child_id`  = item_id
  LIMIT 1   /* <-- force to return only one record */
  INTO @deleted;


来源: stackexchange

问:
Using CACornerMask with Objective-C
With iOS 11 we now have CACornerMask and the maskedCorners property on CALayers. However I am unable to set multiple corners to be rounded at the same time in Objective-C.

The swift implementation is:

```<code>view.layer.cornerRadius = 10
view.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
</code>```

But in Objective-C this does not work:

```<code>view.layer.maskedCorners = @[kCALayerMinXMinYCorner, kCALayerMaxXMinYCorner];
</code>```

I think this is because Swift is using an OptionSetType but I don't know what the Objective-C equivalent to that is.

Has anyone been able to successfully use multiple masked corners with Objective-C? Thanks in advance for your help.

答:
In Objective-C you need to use bitwise OR (|) to combine the values:

```<code>view.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using CACornerMask with Objective-C

Body:
With iOS 11 we now have CACornerMask and the maskedCorners property on CALayers. However I am unable to set multiple corners to be rounded at the same time in Objective-C.

The swift implementation is:

view.layer.cornerRadius = 10
view.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]

But in Objective-C this does not work:

view.layer.maskedCorners = @[kCALayerMinXMinYCorner, kCALayerMaxXMinYCorner];

I think this is because Swift is using an OptionSetType but I don't know what the Objective-C equivalent to that is.

Has anyone been able to successfully use multiple masked corners with Objective-C? Thanks in advance for your help.

Body:
In Objective-C you need to use bitwise OR (|) to combine the values:

view.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;


问:
Is this too many dependencies to inject into an object through the constructor?
I am working on a social network type project in OO PHP and I do not want to use an existing framework.  The main point of doing this project is to help me learn about more stuff.

This question is more about dependency injection.

Let's say I have these classes:

core class - some core methods to do stuff in the app

config class - loads site config stuff

database class - connects to mysql and does all database related stuff

logger class - used to log errors and debug info

captcha class - for captcha on forms

session class - initiates a session start and adds, removes, gets session variables to use in the app

cache class - similar to session class but for caches items (files cache, memcache, apc cache.  I may even add my session stuff to this class someday since all these cache's can use the same type of methods)

All the classes above will most likely be used on every page load in my app (I probably missed some more classes that will be added later on)

Now in addition to the above classes which will need to be injected into most other classes, I will have many many more classes.  I will have a secion called modules which will have stuff like...

account class - creates new users, authenticates users, logs users in and out of the app, update user settings, and much more.

users class - shows users profiles, shows users online, new users, all stuff to show users of the site

forums class - will be for the forums section

blogs class - for the blogs section

photos class - all photo related stuff

comments class - handles comments for photos and profiles

There will be many more of these type of classes for different sections of the site.

This second set of classes listed above for sections will most likely require most of the classes from the first set to be injected into them.

So should I use a registry to store the objects from the first set of classes and just inject the registry into all the class objects in the second set of classes?

Or should I use the constructor to load them?  In this example there would be like 7 objects to inject into the other classes, that seems like a lot.  Am I going about this wrong?

---EDIT---

I am aware of the singleton pattern but I don't think it is my best option here

---EDIT 2---

As some have mention, needing to pass in as much as 7 objects does seem like a LOT and that is why I am looking for suggestions.  Luckily for me this project is at the beginning stages so now is the time for changes to the structure.

An example would be a class in my forums section.  The forums class would need access to session data, possible cached data, the configs object, database object.  AM I going about this the wrong way?

答:
I've always preferred the Registry approach.

Reasons:

Larger Scope

Simple to get

constructors are freed from having objects as variables (allows better usage)

Allows you use more objects in your classes as your free to grab what you need, when you want.

Although there is another method you can try and thats using the singleton pattern, where you would have a method in every class that keeps track of its own object.

Fors example, create an interface like so:

```<code>interface ISingleton
{
    public static getInstnace();
}
</code>```

Then for every object you can add the method that is used for the getting of the instance.

```<code>class SomeObject implements ISingleton, ISomeThingElse
{
    private static $_instance;
    public static getInstance()
    {
        if(self::$_instance === null)
        {
           self::$_instance = new SomeObject();
        }
        return self::$_instance;
    }
}
</code>```

This way your always keeping your same instance of the object as well as having a global scope.

Example:

```<code>public function GetUser($id)
{
    return Database::getInstance()->fetchUserById($id);
}
</code>```

Hope this helps.

There is another way you can do and that's creating a context class, let me try and explain:

The class would act like a registry but disposable, for example:

```<code>class Context
{
    private $objects = array();

    public function Add($key,$Object)
    {
        $this->objects[$key] = $object;
    }

    public function __get($key)
    {
        return isset($this->objects[$key]) ? $this->objects[$key] : null;
    }
}
</code>```

And use that as a container to hold your objects like so:

```<code>$Context = new Context();
$Context->Add("database",$database);
$Context->Add("logger",$logger);
$Context->Add("session",$session);

$UserObject = new RegularUser($Context);
</code>```

This way you can group a set of objects and pass the same context into several other library objects.

Body:
I've always preferred the Registry approach.

Reasons:

Larger Scope

Simple to get

constructors are freed from having objects as variables (allows better usage)

Allows you use more objects in your classes as your free to grab what you need, when you want.

Although there is another method you can try and thats using the singleton pattern, where you would have a method in every class that keeps track of its own object.

Fors example, create an interface like so:

interface ISingleton
{
    public static getInstnace();
}

Then for every object you can add the method that is used for the getting of the instance.

class SomeObject implements ISingleton, ISomeThingElse
{
    private static $_instance;
    public static getInstance()
    {
        if(self::$_instance === null)
        {
           self::$_instance = new SomeObject();
        }
        return self::$_instance;
    }
}

This way your always keeping your same instance of the object as well as having a global scope.

Example:

public function GetUser($id)
{
    return Database::getInstance()->fetchUserById($id);
}

Hope this helps.

There is another way you can do and that's creating a context class, let me try and explain:

The class would act like a registry but disposable, for example:

class Context
{
    private $objects = array();

    public function Add($key,$Object)
    {
        $this->objects[$key] = $object;
    }

    public function __get($key)
    {
        return isset($this->objects[$key]) ? $this->objects[$key] : null;
    }
}

And use that as a container to hold your objects like so:

$Context = new Context();
$Context->Add("database",$database);
$Context->Add("logger",$logger);
$Context->Add("session",$session);

$UserObject = new RegularUser($Context);

This way you can group a set of objects and pass the same context into several other library objects.

ContentLicense: CC BY-SA 2.5


问:
How can I catch corrupt JPEGs when loading an image with imread() in OpenCV?
OpenCV says something like

```<code>Corrupt JPEG data: premature end of data segment
</code>```

or

```<code>Corrupt JPEG data: bad Huffman code
</code>```

or

```<code>Corrupt JPEG data: 22 extraneous bytes before marker 0xd9
</code>```

when loading a corrupt jpeg image with imread().
Can I somehow catch that? Why would I get this information otherwise?
Do I have to check the binary file on my own?

答:
I am using opencv python package to read some image and also met this error message. This error can not be catch by Python. But if you want to find which image is corrupted without recompiling opencv as @Robbert suggested, you can try the following method.

First, you can pinpoint the directory where the corrupt images reside, which is fairly easy. Then you go to the directory, and use mogrify command line tool provided by ImageMagick  to change the image meta info, as suggest by @goe.

```<code>mogrify -set comment "errors fixed in meta info" -format png *.jpg
</code>```

The above command will convert the original jpg image to png format and also clean the original image to remove errors in meta info. When you run mogrify command, it will also output some message about which image is corrupted in the directory so that you can accurately find the corrupted image.

After that, you can do whatever you want with the original corrupted jpg image.

Body:
OpenCV says something like

Corrupt JPEG data: premature end of data segment

or

Corrupt JPEG data: bad Huffman code

or

Corrupt JPEG data: 22 extraneous bytes before marker 0xd9

when loading a corrupt jpeg image with imread().
Can I somehow catch that? Why would I get this information otherwise?
Do I have to check the binary file on my own?

Body:
I am using opencv python package to read some image and also met this error message. This error can not be catch by Python. But if you want to find which image is corrupted without recompiling opencv as @Robbert suggested, you can try the following method.

First, you can pinpoint the directory where the corrupt images reside, which is fairly easy. Then you go to the directory, and use mogrify command line tool provided by ImageMagick  to change the image meta info, as suggest by @goe.

mogrify -set comment "errors fixed in meta info" -format png *.jpg

The above command will convert the original jpg image to png format and also clean the original image to remove errors in meta info. When you run mogrify command, it will also output some message about which image is corrupted in the directory so that you can accurately find the corrupted image.

After that, you can do whatever you want with the original corrupted jpg image.


问:
download list of url csv files python IOError: [Errno 22]
I have the following code below. Credit to this answer. I keep getting an error before it downloads any of the csv files. USW00000100.csv is the first csv file name. I'm not sure why I am getting the error. There doesn't seem to be any unsupported characters in my filename.

```<code>import os
import urllib

DOWNLOADS_DIR = "C:/py-testing/downloads"

# For every line in the file
for url in open("C:/py-testing/urls.txt"):
    # Split on the rightmost / and take everything on the right side of that
    name = url.rsplit('/', 1)[-1]

    # Combine the name and the downloads directory to get the local filename
    filename = os.path.join(DOWNLOADS_DIR, name)
    urllib.urlretrieve(url, filename)
</code>```

Error:

IOError: [Errno 22] invalid mode ('wb') or filename: 'C:/py-testing/downloads\USW00000100.csv\n'

答:
The problem is probably the newline at the end of the filename. When you read the line in from the CSV, it's including the newline. There's a couple of ways you can handle this.

You can simply strip the newline from the end like so.

```<code>raw_name = url.rsplit('/', 1)[-1]
name = raw_name.strip()
# your code here
</code>```

Another way, with a terser functional style (thanks @fenceop)

```<code>for url in map(str.strip, file):
    # your code here
</code>```

Body:
I have the following code below. Credit to this answer. I keep getting an error before it downloads any of the csv files. USW00000100.csv is the first csv file name. I'm not sure why I am getting the error. There doesn't seem to be any unsupported characters in my filename.

import os
import urllib

DOWNLOADS_DIR = "C:/py-testing/downloads"

# For every line in the file
for url in open("C:/py-testing/urls.txt"):
    # Split on the rightmost / and take everything on the right side of that
    name = url.rsplit('/', 1)[-1]

    # Combine the name and the downloads directory to get the local filename
    filename = os.path.join(DOWNLOADS_DIR, name)
    urllib.urlretrieve(url, filename)

Error:

IOError: [Errno 22] invalid mode ('wb') or filename: 'C:/py-testing/downloads\USW00000100.csv\n'

Body:
The problem is probably the newline at the end of the filename. When you read the line in from the CSV, it's including the newline. There's a couple of ways you can handle this.

You can simply strip the newline from the end like so.

raw_name = url.rsplit('/', 1)[-1]
name = raw_name.strip()
# your code here

Another way, with a terser functional style (thanks @fenceop)

for url in map(str.strip, file):
    # your code here


问:
Can't access NodeJS api from Angular app
I have trouble trying to get to my NodeJs server from my angular app. Here's my router:

```<code>app.get('/new12345',function(req,res){
    console.log("Http Get Recently Gone from /new12345");
    var results = userData;
    res.send(results);
});
</code>```

Here where I try getting to my api.

```<code>this.http.get('/new12345').subscribe(data => {
  this.resultInArray = data['results'];
}
</code>```

I am getting this error though:

```<code>Error: Cannot match any routes. URL Segment: 'new12345'
</code>```

Thanks!

答:
You did not specify your api base url. You are currently getting to your angular app (hence the angular router error you are getting).

For example, that might look like this:

```<code>this.http.get('http://localhost:3000/new12345').subscribe(data => {
    this.resultInArray = data['results'];
}
</code>```

Body:
I have trouble trying to get to my NodeJs server from my angular app. Here's my router:

app.get('/new12345',function(req,res){
    console.log("Http Get Recently Gone from /new12345");
    var results = userData;
    res.send(results);
});

Here where I try getting to my api.

this.http.get('/new12345').subscribe(data => {
  this.resultInArray = data['results'];
}

I am getting this error though:

Error: Cannot match any routes. URL Segment: 'new12345'

Thanks!

Body:
You did not specify your api base url. You are currently getting to your angular app (hence the angular router error you are getting).

For example, that might look like this:

this.http.get('http://localhost:3000/new12345').subscribe(data => {
    this.resultInArray = data['results'];
}


问:
Why does SPARQL LIMIT on Inner Query seem to limit the outer query under RDF4J?
I'm using RDF4J version 2.2.2 workbench and server under Windows 10.  I need to use an inner query to limit results.  My particular application is in accumulating an event concept from a series of correlated reports.  Each report has a time stamp as one of its properties.  I need the inner query with a LIMIT and an ORDER BY to get the latest time stamp from the reports contributing each event.  The event is established by a triple in the outer query. Since the full application is rather complex, I've come up with a simple case to illustrate my question.  Basically, I'm expecting the outer query to produce several results with an inner query limited to 1, but the LIMIT seems to be applied to the outer query.   I'm wondering why I'm getting only one result when I expect more.  In the example case herein, I expect two results but get only one...

The example case is set up in RDF4J workbench using an repository with RDFS+SPIN support.

Clear the repository (RDF4J workbench Modify/Clear).

Load the Nuvio ontology version 1.0.0 using the workbench Modify/Add function

Set up the test condition using the following SPARQL update query using the RDF4J Modify/SPARQL Update function.

```<code>PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>
PREFIX inst: <http://www.disa.mil/dso/a2i/ontologies/PBSM/Sharing/Instantiations#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

INSERT {
    inst:aTestObject1 Nuvio:hasValue _:b0 ;
        Nuvio:hasValue _:b1 .
    inst:aTestObject2 Nuvio:hasValue _:b2 ;
        Nuvio:hasValue _:b3 .

    _:b0 Nuvio:hasDataValue "2017-11-13T13:46:00.000-06:00"^^xsd:dateTime .
    _:b1 Nuvio:hasDataValue "2017-11-13T13:46:01.000-06:00"^^xsd:dateTime .
    _:b2 Nuvio:hasDataValue "2017-11-13T13:46:02.000-06:00"^^xsd:dateTime .
    _:b3 Nuvio:hasDataValue "2017-11-13T13:46:03.000-06:00"^^xsd:dateTime .
}
WHERE {
}
</code>```

Now run the following SPARQL Query using the RDF4J Workbench Explore/Query function:

```<code>PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>

SELECT DISTINCT *
WHERE {
  ?o a Nuvio:Quantity .
  ?o Nuvio:hasValue/Nuvio:hasDataValue ?value .
}
</code>```

which produces the expected four results (both time stamps for both test individuals):

Now attempt to limit the results to one time stamp per individual (inst:aTestObject1 and inst:aTestObject2) using the following query containing an inner query (a simple extension of the first query):

```<code>PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>

SELECT DISTINCT *
WHERE {
  ?o a Nuvio:Quantity .
  {
    SELECT DISTINCT *
    WHERE {
      ?o Nuvio:hasValue/Nuvio:hasDataValue ?value .
    } LIMIT 1
  }
}
</code>```

which produces only one result:

I'm expecting two results, one for each of inst:aTestObject1 and inst:aTestObject2 since each has two timestamps.  But I only get a result for inst:aTestObject2.  Why only one?

答:
Following @AKSW's comment that the inner select is always evaluated first and recovering from my brain fade, the solution to what I wanted (each test object with the latest xsd:dateTime value) can be achieved using the following simple query...

```<code>PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>

SELECT DISTINCT ?o (MAX(?value) as ?maxValue)
WHERE {
  ?o a Nuvio:Quantity .
  ?o Nuvio:hasValue/Nuvio:hasDataValue ?value .
} GROUP BY ?o
</code>```

Which returns the desired two results:

Thanks @AKSW.

Body:
I'm using RDF4J version 2.2.2 workbench and server under Windows 10.  I need to use an inner query to limit results.  My particular application is in accumulating an event concept from a series of correlated reports.  Each report has a time stamp as one of its properties.  I need the inner query with a LIMIT and an ORDER BY to get the latest time stamp from the reports contributing each event.  The event is established by a triple in the outer query. Since the full application is rather complex, I've come up with a simple case to illustrate my question.  Basically, I'm expecting the outer query to produce several results with an inner query limited to 1, but the LIMIT seems to be applied to the outer query.   I'm wondering why I'm getting only one result when I expect more.  In the example case herein, I expect two results but get only one...

The example case is set up in RDF4J workbench using an repository with RDFS+SPIN support.

Clear the repository (RDF4J workbench Modify/Clear).

Load the Nuvio ontology version 1.0.0 using the workbench Modify/Add function

Set up the test condition using the following SPARQL update query using the RDF4J Modify/SPARQL Update function.

PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>
PREFIX inst: <http://www.disa.mil/dso/a2i/ontologies/PBSM/Sharing/Instantiations#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

INSERT {
    inst:aTestObject1 Nuvio:hasValue _:b0 ;
        Nuvio:hasValue _:b1 .
    inst:aTestObject2 Nuvio:hasValue _:b2 ;
        Nuvio:hasValue _:b3 .

    _:b0 Nuvio:hasDataValue "2017-11-13T13:46:00.000-06:00"^^xsd:dateTime .
    _:b1 Nuvio:hasDataValue "2017-11-13T13:46:01.000-06:00"^^xsd:dateTime .
    _:b2 Nuvio:hasDataValue "2017-11-13T13:46:02.000-06:00"^^xsd:dateTime .
    _:b3 Nuvio:hasDataValue "2017-11-13T13:46:03.000-06:00"^^xsd:dateTime .
}
WHERE {
}

Now run the following SPARQL Query using the RDF4J Workbench Explore/Query function:

PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>

SELECT DISTINCT *
WHERE {
  ?o a Nuvio:Quantity .
  ?o Nuvio:hasValue/Nuvio:hasDataValue ?value .
}

which produces the expected four results (both time stamps for both test individuals):

Now attempt to limit the results to one time stamp per individual (inst:aTestObject1 and inst:aTestObject2) using the following query containing an inner query (a simple extension of the first query):

PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>

SELECT DISTINCT *
WHERE {
  ?o a Nuvio:Quantity .
  {
    SELECT DISTINCT *
    WHERE {
      ?o Nuvio:hasValue/Nuvio:hasDataValue ?value .
    } LIMIT 1
  }
}

which produces only one result:

I'm expecting two results, one for each of inst:aTestObject1 and inst:aTestObject2 since each has two timestamps.  But I only get a result for inst:aTestObject2.  Why only one?

Body:
Following @AKSW's comment that the inner select is always evaluated first and recovering from my brain fade, the solution to what I wanted (each test object with the latest xsd:dateTime value) can be achieved using the following simple query...

PREFIX Nuvio: <http://cogradio.org/ont/Nuvio.owl#>

SELECT DISTINCT ?o (MAX(?value) as ?maxValue)
WHERE {
  ?o a Nuvio:Quantity .
  ?o Nuvio:hasValue/Nuvio:hasDataValue ?value .
} GROUP BY ?o

Which returns the desired two results:

Thanks @AKSW.


问:
external LDAP connection using JpsContextFactory
I am trying to connect to an external weblogic embeded LDAP in Oracle ADF.
I've just found a good sample code that uses JpsContextFactory class, it doesnt get any url, username and password. it seems that it connects to local weblogic ldap by defult. I could not figure out how to set a connection to an external weblogic ldap using this class.

the sample code :

```<code>private void initIdStoreFactory() {
    JpsContextFactory ctxFactory;
    try {
        ctxFactory = JpsContextFactory.getContextFactory();
        JpsContext ctx = ctxFactory.getContext();
        LdapIdentityStore idStoreService = (LdapIdentityStore) ctx.getServiceInstance(IdentityStoreService.class);

        ldapFactory = idStoreService.getIdmFactory();

        storeEnv.put(OIDIdentityStoreFactory.RT_USER_SEARCH_BASES, USER_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_SEARCH_BASES, GROUP_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_USER_CREATE_BASES, USER_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_CREATE_BASES, GROUP_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_SELECTED_CREATE_BASE, GROUP_BASES[0]);
        storeEnv.put(OIDIdentityStoreFactory.RT_USER_SELECTED_CREATE_BASE, USER_BASES[0]);
    } catch (JpsException e) {
        e.printStackTrace();
        throw new RuntimeException("Jps Exception encountered", e);
    }
}
</code>```

any suggestion how to use this code to connect to external ldap will be appreciated.

答:
JpsContextFactory is utilised to retrieve the current information of the identity store(s) inside weblogic. In order to use it with an external LDAP, you need first to add a new security provider in Weblogic and declare it as required in order for your application to utilise the new external ldap.

Check this old article of how to do it (http://www.itbuzzpress.com/weblogic-tutorials/securing-oracle-weblogic/configuring-oracle-weblogic-security-providers.html)

Body:
I am trying to connect to an external weblogic embeded LDAP in Oracle ADF.
I've just found a good sample code that uses JpsContextFactory class, it doesnt get any url, username and password. it seems that it connects to local weblogic ldap by defult. I could not figure out how to set a connection to an external weblogic ldap using this class.

the sample code :

private void initIdStoreFactory() {
    JpsContextFactory ctxFactory;
    try {
        ctxFactory = JpsContextFactory.getContextFactory();
        JpsContext ctx = ctxFactory.getContext();
        LdapIdentityStore idStoreService = (LdapIdentityStore) ctx.getServiceInstance(IdentityStoreService.class);

        ldapFactory = idStoreService.getIdmFactory();

        storeEnv.put(OIDIdentityStoreFactory.RT_USER_SEARCH_BASES, USER_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_SEARCH_BASES, GROUP_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_USER_CREATE_BASES, USER_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_CREATE_BASES, GROUP_BASES);
        storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_SELECTED_CREATE_BASE, GROUP_BASES[0]);
        storeEnv.put(OIDIdentityStoreFactory.RT_USER_SELECTED_CREATE_BASE, USER_BASES[0]);
    } catch (JpsException e) {
        e.printStackTrace();
        throw new RuntimeException("Jps Exception encountered", e);
    }
}

any suggestion how to use this code to connect to external ldap will be appreciated.


问:
Correct way to return an rvalue reference to this
The code below results in Undefined Behaviour. Be sure to read ALL the answers for completeness.

When chaining an object via the operator<< I want to preserve the lvalue-ness / rvalue-ness of the object:

```<code>class Avenger {
  public:
    Avenger& operator<<(int) & {
      return *this;
    }
    Avenger&& operator<<(int) && {
      return *this; // compiler error cannot bind lvalue to rvalue
      return std::move(*this);
    }
};
void doJustice(const Avenger &) {};
void doJustice(Avenger &&) {};

int main() {
  Avenger a;
  doJustice(a << 24); // parameter should be Avenger&
  doJustice(Avenger{} << 24); // parameter should be Avenger&&

  return 0;
}
</code>```

I cannot simply return *this which implies that the type of *this of an rvalue object is still an lvalue reference. I would have expected to be an rvalue reference.

Is it correct / recommended to return std::move(*this) on an member overloaded for the && qualifier, or should other method be used? I know that std::move is just a cast, so I think it’s ok, I just want to double check.

What is the reason/explanation that *this of an rvalue is an lvalue reference and not an rvalue reference?

I remember seeing in C++14 something about move semantics of *this. Is that related to this? Will any of the above change in C++14?

答:
My git copy of the C++ Standard (page 290, section15.2, point 6) says:

"The exceptions to this lifetime rule [of a reference binding to a

  temporary extending the lifetime of that temporary] are:

sub 9 - A temporary object bound to a reference parameter in a
             function call persists until the completion of the
             full-expression containing the call.

sub 10 - The lifetime of a temporary bound to the returned value
             in a function return statement (9.6.3) is not extended;
             the temporary is destroyed at the end of the
             full-expression in the return statement.  [...]"

Therefore, the implicit this `parameter' passed to

```<code>Avenger&& operator<<(int) &&
{
      return std::move(*this);
}
</code>```

ends its life at the ; of the statement that calls operator<< on a temporary object, even if a reference is bound to it. So this fails:

```<code>Avenger &&dangler = Avenger{} << 24; // destructor already called
dangler << 1; // Operator called on dangling reference
</code>```

If OTOH the return is by value:

```<code>Avenger operator<<(int) &&
{
      return std::move(*this);
}
</code>```

then none of that misery happens, and there is often no extra cost in terms of copying. And indeed, if you don't offer the compiler to create that return value by move-constructing from *this, then it 'll make a copy.
So snatch *this from the brink of oblivion, and have the best of both worlds.

Body:
The code below results in Undefined Behaviour. Be sure to read ALL the answers for completeness.

When chaining an object via the operator<< I want to preserve the lvalue-ness / rvalue-ness of the object:

class Avenger {
  public:
    Avenger& operator<<(int) & {
      return *this;
    }
    Avenger&& operator<<(int) && {
      return *this; // compiler error cannot bind lvalue to rvalue
      return std::move(*this);
    }
};
void doJustice(const Avenger &) {};
void doJustice(Avenger &&) {};

int main() {
  Avenger a;
  doJustice(a << 24); // parameter should be Avenger&
  doJustice(Avenger{} << 24); // parameter should be Avenger&&

  return 0;
}

I cannot simply return *this which implies that the type of *this of an rvalue object is still an lvalue reference. I would have expected to be an rvalue reference.

Is it correct / recommended to return std::move(*this) on an member overloaded for the && qualifier, or should other method be used? I know that std::move is just a cast, so I think it’s ok, I just want to double check.

What is the reason/explanation that *this of an rvalue is an lvalue reference and not an rvalue reference?

I remember seeing in C++14 something about move semantics of *this. Is that related to this? Will any of the above change in C++14?

Body:
My git copy of the C++ Standard (page 290, section15.2, point 6) says:

"The exceptions to this lifetime rule [of a reference binding to a

  temporary extending the lifetime of that temporary] are:

sub 9 - A temporary object bound to a reference parameter in a
             function call persists until the completion of the
             full-expression containing the call.

sub 10 - The lifetime of a temporary bound to the returned value
             in a function return statement (9.6.3) is not extended;
             the temporary is destroyed at the end of the
             full-expression in the return statement.  [...]"

Therefore, the implicit this `parameter' passed to

Avenger&& operator<<(int) &&
{
      return std::move(*this);
}

ends its life at the ; of the statement that calls operator<< on a temporary object, even if a reference is bound to it. So this fails:

Avenger &&dangler = Avenger{} << 24; // destructor already called
dangler << 1; // Operator called on dangling reference

If OTOH the return is by value:

Avenger operator<<(int) &&
{
      return std::move(*this);
}

then none of that misery happens, and there is often no extra cost in terms of copying. And indeed, if you don't offer the compiler to create that return value by move-constructing from *this, then it 'll make a copy.
So snatch *this from the brink of oblivion, and have the best of both worlds.


问:
Bash addition by the first column, if data in second column is the same
I have a list with delimiters |

```<code>40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2
</code>```

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

```<code>40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11
</code>```

How you can see, we have counted the numbers from first column.

答:
Modifying the sample data to include different users for ip address 192.168.1.25:

```<code>$ cat ipfile
40|192.168.1.2|user4
42|192.168.1.25|user1      <=== same ip, different user
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user9      <=== same ip, different user
</code>```

And a simple awk script:

```<code>$ awk '
BEGIN { FS="|" ; OFS="|" }
{ sum[$2]+=$1 ; if (user[$2]=="") { user[$2]=$3 } }
END { for (idx in sum) { print sum[idx],idx,user[idx] } }
' ipfile

58|192.168.1.55|user3
40|192.168.1.2|user4
118|192.168.1.3|user11
109|192.168.1.25|user1     <=== captured first user id
</code>```

BEGIN { FS="|" ; OFS="|" } : define input and output field separators; executed once at beginning

sum[$2]+=$1 : store/add field #1 to array (indexed by ip address == field #2); executed once for each row in data file

if .... : if a user hasn't already been stored for a given ip address, then store it now; this has the effect of saving the first user id we find for a given ip address; executed once for each row in data file

END { for .... / print ...} : loop through array indexes, printing our sum, ip address and (first) user id; executed once at the end

NOTE: No sorting requirement was provided in the original question; sorting could be added as needed ...

Body:
I have a list with delimiters |

40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11

How you can see, we have counted the numbers from first column.

Body:
Modifying the sample data to include different users for ip address 192.168.1.25:

$ cat ipfile
40|192.168.1.2|user4
42|192.168.1.25|user1      <=== same ip, different user
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user9      <=== same ip, different user

And a simple awk script:

$ awk '
BEGIN { FS="|" ; OFS="|" }
{ sum[$2]+=$1 ; if (user[$2]=="") { user[$2]=$3 } }
END { for (idx in sum) { print sum[idx],idx,user[idx] } }
' ipfile

58|192.168.1.55|user3
40|192.168.1.2|user4
118|192.168.1.3|user11
109|192.168.1.25|user1     <=== captured first user id

BEGIN { FS="|" ; OFS="|" } : define input and output field separators; executed once at beginning

sum[$2]+=$1 : store/add field #1 to array (indexed by ip address == field #2); executed once for each row in data file

if .... : if a user hasn't already been stored for a given ip address, then store it now; this has the effect of saving the first user id we find for a given ip address; executed once for each row in data file

END { for .... / print ...} : loop through array indexes, printing our sum, ip address and (first) user id; executed once at the end

NOTE: No sorting requirement was provided in the original question; sorting could be added as needed ...


问:
In React, how to bind an input's value when rendering a list of inputs?
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

```<code>class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}
</code>```

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

答:
You really should use a state here and make your tweets variable be part of it. To do that, add a constructor:

```<code>constructor() {
  super();
  this.state = {
    tweets: [
      { id: 1, link: 'example.com' },
      { id: 2, link: 'example2.com' }
    ]
  };
}
</code>```

Then you need to mutate each linkwhenever you type in one of the inputs. There are a few pitfalls here, so let me go through them one-by-one:

```<code>changeTweet = (id, e) => {
  let arr = this.state.tweets.slice();
  let index = arr.findIndex(i => i.id === id);
  let obj = Object.assign({}, arr[index]);
  obj.link = e.target.value;
  arr[index] = obj;
  this.setState({tweets: arr});
}
</code>```

First, you need to create a copy of your state variable. This gives you something to work with, without mutating the state directly which is anti-pattern. This can be done with slice().

Since you are sending in the id of the object to modify, we need to find it in our array (in case the items are unordered). This is done with findIndex(). You might want to handle the scenario in which such index is not found (I have not done that).

Now we know where in the array the object with the given id key is. Now, create a copy of that item (which is an object). This is also to prevent mutating the state directly. Do this with Object.assign().

Now change the link to the input value we typed in. Replace the old item object with the new one (obj) and replace the old tweets array with the new one (arr).

Here's the full example:

class App extends React.Component {
  constructor() {
    super();
   this.state = {
     tweets: [
        { id: 1, link: 'example.com' },
        { id: 2, link: 'example2.com' }
      ]
    };
  }

  changeTweet = (id, e) => {
    let arr = this.state.tweets.slice();
    let index = arr.findIndex(i => i.id === id);
    let obj = Object.assign({}, arr[index]);
    obj.link = e.target.value;
    arr[index] = obj;
   this.setState({tweets: arr});
  }

  render() {
    return (

        {this.state.tweets.map(tweet =>

            <input type="text" placeholder="text" onChange={(e) => this.changeTweet(tweet.id, e)} />
            Tweet

        )}

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (

        {this.tweets.map(tweet =>

            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet

        )}

    );
  }
}

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

Body:
You really should use a state here and make your tweets variable be part of it. To do that, add a constructor:

constructor() {
  super();
  this.state = {
    tweets: [
      { id: 1, link: 'example.com' },
      { id: 2, link: 'example2.com' }
    ]
  };
}

Then you need to mutate each linkwhenever you type in one of the inputs. There are a few pitfalls here, so let me go through them one-by-one:

changeTweet = (id, e) => {
  let arr = this.state.tweets.slice();
  let index = arr.findIndex(i => i.id === id);
  let obj = Object.assign({}, arr[index]);
  obj.link = e.target.value;
  arr[index] = obj;
  this.setState({tweets: arr});
}

First, you need to create a copy of your state variable. This gives you something to work with, without mutating the state directly which is anti-pattern. This can be done with slice().

Since you are sending in the id of the object to modify, we need to find it in our array (in case the items are unordered). This is done with findIndex(). You might want to handle the scenario in which such index is not found (I have not done that).

Now we know where in the array the object with the given id key is. Now, create a copy of that item (which is an object). This is also to prevent mutating the state directly. Do this with Object.assign().

Now change the link to the input value we typed in. Replace the old item object with the new one (obj) and replace the old tweets array with the new one (arr).

Here's the full example:

class App extends React.Component {
  constructor() {
    super();
   this.state = {
     tweets: [
        { id: 1, link: 'example.com' },
        { id: 2, link: 'example2.com' }
      ]
    };
  }

  changeTweet = (id, e) => {
    let arr = this.state.tweets.slice();
    let index = arr.findIndex(i => i.id === id);
    let obj = Object.assign({}, arr[index]);
    obj.link = e.target.value;
    arr[index] = obj;
   this.setState({tweets: arr});
  }

  render() {
    return (
      <div>
        {this.state.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={(e) => this.changeTweet(tweet.id, e)} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.link}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
Snap UICollection View Cell to centre using Objective C
I am implementing a Horizontal UICollectionView in Objective C. I want to snap the cell to the centre of the collection view as shown in image below. When an item is snapped to centre I want the items on left and right partially visible. How can I achieve this?

I have used custom IOCOllectionViewFlowLayout and override the

```<code>- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
</code>```

but its not working for me ,

```<code>CGFloat approximatePage = self.collectionView.contentOffset.x / self.pageWidth;
    CGFloat currentPage = (velocity.x < 0.0) ? floor(approximatePage) : ceil(approximatePage);

    NSInteger flickedPages = ceil(velocity.x / self.flickVelocity);
    float pageWidth = self.pageWidth;
    if (flickedPages) {
        proposedContentOffset.x = flickedPages * self.pageWidth;
    } else {
        proposedContentOffset.x = currentPage * self.pageWidth;
    }
    return proposedContentOffset;
</code>```

How to implement it using Objective C?

答: You need to manipulate with scrollViewWillEndDragging delegate of the UIViewController scroll view. Further reading here https://rolandleth.com/uicollectionview-snap-scrolling-and-pagination</p>

Body:
I am implementing a Horizontal UICollectionView in Objective C. I want to snap the cell to the centre of the collection view as shown in image below. When an item is snapped to centre I want the items on left and right partially visible. How can I achieve this?

I have used custom IOCOllectionViewFlowLayout and override the

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

but its not working for me ,

CGFloat approximatePage = self.collectionView.contentOffset.x / self.pageWidth;
    CGFloat currentPage = (velocity.x < 0.0) ? floor(approximatePage) : ceil(approximatePage);

    NSInteger flickedPages = ceil(velocity.x / self.flickVelocity);
    float pageWidth = self.pageWidth;
    if (flickedPages) {
        proposedContentOffset.x = flickedPages * self.pageWidth;
    } else {
        proposedContentOffset.x = currentPage * self.pageWidth;
    }
    return proposedContentOffset;

How to implement it using Objective C?


问:
Using alias inside a class instead of declaring a new class
I have a complex event args class in a webservice

```<code>public partial class PROJECT.WCF.MyActionCompletedEventArgs
{
...
};
</code>```

Now I have a class that wraps this web service in some way

```<code>public class WebserviceCtrl
{
...
</code>```

Now I want to add my own handler with the same event args already defined. So I want a using alias (like a typedef in C++) inside the class like this:

```<code>public class WebserviceCtrl
{
  using ActionCompletedEventArgs = PROJECT.WCF.MyActionCompletedEventArgs;
  ...
</code>```

But I get a syntax error directly in front of the using statement. I can use this using statement directly in front of the class declaration (inside a namespace). It doesn't matter where I place this statement inside the class definition.

I know about the possibilities of declaring my own ActionCompletedEventArgs class, but in this case I have to provide specific constructors and forces me to write specific constructors that aren't "needed", if I just use an alias...
 So I don't want to declare my own class!

I already studied the C# using documentation, but I could find any information about this.

My question is, why can't I use using classx = classy; inside my class?

答:
Consider using a generic class like:

```<code>public class WebserviceCtrl<T> where T : MyActionCompletedEventArgs
</code>```

What you are trying to do isn't supported in the way you are trying to do it, but if you're trying to reference a variable class, generics are how that's accomplished in C#.

Body:
I have a complex event args class in a webservice

public partial class PROJECT.WCF.MyActionCompletedEventArgs
{
...
};

Now I have a class that wraps this web service in some way

public class WebserviceCtrl
{
...

Now I want to add my own handler with the same event args already defined. So I want a using alias (like a typedef in C++) inside the class like this:

public class WebserviceCtrl
{
  using ActionCompletedEventArgs = PROJECT.WCF.MyActionCompletedEventArgs;
  ...

But I get a syntax error directly in front of the using statement. I can use this using statement directly in front of the class declaration (inside a namespace). It doesn't matter where I place this statement inside the class definition.

I know about the possibilities of declaring my own ActionCompletedEventArgs class, but in this case I have to provide specific constructors and forces me to write specific constructors that aren't "needed", if I just use an alias...
 So I don't want to declare my own class!

I already studied the C# using documentation, but I could find any information about this.

My question is, why can't I use using classx = classy; inside my class?

Body:
Consider using a generic class like:

public class WebserviceCtrl<T> where T : MyActionCompletedEventArgs

What you are trying to do isn't supported in the way you are trying to do it, but if you're trying to reference a variable class, generics are how that's accomplished in C#.


问:
BLE scan Record- Not getting all the advertisement data (service data)
We are developing an app in react-native in which we need to scan and read all the manufacturer data and service data as well from the BLE device.

The issue is that we are getting a few details in service data (only 9 bytes) and we supposed to get 31 bytes of data.

Plugin Used - https://github.com/Polidea/react-native-ble-plx

BLE Device details-   It is a custom-made hardware that is using nRF52832 SoC

Below is the sample code that we are using:

```<code>import { BleManager } from 'react-native-ble-plx';
this.manager = new BleManager();

//Checking Bluetooth state
const subscription = this.manager.onStateChange((state) => {
            if (state === 'PoweredOn') {
                this.startDeviceScan(scanTimeout);
                subscription.remove();
            }
    }, true);

//Start Scan
startDeviceScan(scanTimeout) {
        var me = this;
        this.manager.startDeviceScan(null, null, (error, device) => {
            if (error) {
                // Handle error (scanning will be stopped automatically)
                console.log("scanningError" + error.message);
                me.startDeviceScan();
                return;
            }
            if (device)
                            // Here we are supposed to get the advertisment data(Manufacturer data) in device object
                this.emit('startScanSuccess', device);
        });
    }
</code>```

Results we are getting in device object is as follows
serviceData - Object  =  {00006612-0000-1000-8000-00805f9b34fb:"/QosfgB5h/hZ↵"}
manufacturerData =  "P/8AAQ=="

Required result - According to our device specification it should be
Service data - We should get at least 31 Bytes of data.

With the below plugin we are getting all the data but it does not work in react-native: https://github.com/randdusing/cordova-plugin-bluetoothle

答:
I think you are in fact getting 31 bytes of data. Lets look at the structure of the advertising data, following from the Bluetooth Core Spec V5.0 and the Core Specfication Supplement V6.

The Core Spec specifies that the advertising data should have the following pattern: N structures, each consisting of a length octet, an AD type octet (e.g. manufacturer data) and the corresponding data (see Vol 3, Part C, chap. 11).

You receive the types "service data" and "manufacturer data". These are two structures, each containing a length field, a type field and the data field. The data field of serviceData has a length of 16 bytes, together with length and type we have a structure of 18 bytes. The data field of manufacturer data has a length of 8 bytes, together with length and type we have a structure of 10 bytes.

So now we have 28 bytes. Furthermore, advertising needs a flags field where it is defined if this is limited or general discovery, if BR/EDR is supported etc. (see Core Supplement, Part A, chap. 1.3).

This flags field has a data field of one octet. Together with length and type we have an additional structure of 3 bytes, so all in all you get an advertisement with 31 bytes. And that is the maximum; any byte exceeding the maximum will be cut off.

What to do now? Put the information into the scan response data. By using an active scan, you can request the scan response data in addition to the advertising data. Remove the manufacturer data from the advertising data and put it in the scan response data. Then it should work.

Body:
We are developing an app in react-native in which we need to scan and read all the manufacturer data and service data as well from the BLE device.

The issue is that we are getting a few details in service data (only 9 bytes) and we supposed to get 31 bytes of data.

Plugin Used - https://github.com/Polidea/react-native-ble-plx

BLE Device details-   It is a custom-made hardware that is using nRF52832 SoC

Below is the sample code that we are using:

import { BleManager } from 'react-native-ble-plx';
this.manager = new BleManager();

//Checking Bluetooth state
const subscription = this.manager.onStateChange((state) => {
            if (state === 'PoweredOn') {
                this.startDeviceScan(scanTimeout);
                subscription.remove();
            }
    }, true);

//Start Scan
startDeviceScan(scanTimeout) {
        var me = this;
        this.manager.startDeviceScan(null, null, (error, device) => {
            if (error) {
                // Handle error (scanning will be stopped automatically)
                console.log("scanningError" + error.message);
                me.startDeviceScan();
                return;
            }
            if (device)
                            // Here we are supposed to get the advertisment data(Manufacturer data) in device object
                this.emit('startScanSuccess', device);
        });
    }

Results we are getting in device object is as follows
serviceData - Object  =  {00006612-0000-1000-8000-00805f9b34fb:"/QosfgB5h/hZ↵"}
manufacturerData =  "P/8AAQ=="

Required result - According to our device specification it should be
Service data - We should get at least 31 Bytes of data.

With the below plugin we are getting all the data but it does not work in react-native: https://github.com/randdusing/cordova-plugin-bluetoothle


问:
How to run the same query on all tables in Access Database?
All tables have the same structure the same column names.

Here is a code:

UPDATE Table1
INNER JOIN TableX ON Table1.Column1= TableX.Column1
SET Table1.Column2 = TableX.Column2

But I would like to run this code on all tables: Table2, Table3, Table4....Table30

答:
if i understood well, that's it works for you ...</p>

```<code>SELECT AllTables.*
FROM AllTables
WHERE AllTables.ColumnName_X = AllTables.ColumnName_Y
</code>```

Body:
if i understood well, that's it works for you ...

SELECT AllTables.*
FROM AllTables
WHERE AllTables.ColumnName_X = AllTables.ColumnName_Y


问:
Running DOS COMMAND on SQlcmd does not work
Hi I am trying execute the DOS COMMAND on sqlcmd on a DOS TERMINAL but it simply does not return anything even error.

When I execute it on SSMS it works.

Do you know that is going on?

答:
I have found out the problem.
The problem is: I have to version on my machine 32 bit and 64 bit, by default when I open the DOS PROMPT and run the sqlcmd it assumes the 32 bit version. As my OS is 64 bit the 32 bit does not work.

So I just renamed the sqlcmd 32 bit on the folder the it is in. Now when I open the prompt and run the sqlcmd the 64 bit comes to play and every command started with :!! works.


问:
Is this actually mutating the state?
I've just put together a really basic bit of React functionality to show someone and my console tab is accusing me of mutating the state directly.  I thought that as long as you're using this.setState() that you're basically fine.

This little bit of code just spits out the first person from the person object stored in the state and then when you click the button it increments the age (this actually all works, incidentally).

Am I actually directly mutating the state by doing this?  And if I am, what is the correct way of doing this?

```<code>import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Stephanie', age: 26 },
      { name: 'Manu', age: 29 },
    ],
  }

  increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

  render() {
    return (
      <div className="App">
        <h1>This is an app</h1>
        <button onClick={this.increaseAgeHandler}>Add to age</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />
      </div>
    );
  }
}

export default App;
</code>```

答:
When you call setState(), React merges the object you provide into the current state

```<code>constructor(props) {
    super(props);
    this.state = {
      persons: [
       { name: 'Max', age: 28 },
       { name: 'Stephanie', age: 26 },
       { name: 'Manu', age: 29 },
      ]
    };
  }
</code>```

this.state it's only assinable on the constructor, then you can update them independently with separate setState() calls.
Do Not Modify State Directly

For example, this will not re-render a component:

```<code>this.state.persons[0].age += 1
</code>```

Instead, use setState():

```<code>increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }
</code>```

More info about React lifecycle

Title: Is this actually mutating the state?

Body:
I've just put together a really basic bit of React functionality to show someone and my console tab is accusing me of mutating the state directly.  I thought that as long as you're using this.setState() that you're basically fine.

This little bit of code just spits out the first person from the person object stored in the state and then when you click the button it increments the age (this actually all works, incidentally).

Am I actually directly mutating the state by doing this?  And if I am, what is the correct way of doing this?

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Stephanie', age: 26 },
      { name: 'Manu', age: 29 },
    ],
  }

  increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

  render() {
    return (

This is an app

        <button onClick={this.increaseAgeHandler}>Add to age</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />

    );
  }
}

export default App;

Body:
When you call setState(), React merges the object you provide into the current state

constructor(props) {
    super(props);
    this.state = {
      persons: [
       { name: 'Max', age: 28 },
       { name: 'Stephanie', age: 26 },
       { name: 'Manu', age: 29 },
      ]
    };
  }

this.state it's only assinable on the constructor, then you can update them independently with separate setState() calls.
Do Not Modify State Directly

For example, this will not re-render a component:

this.state.persons[0].age += 1

Instead, use setState():

increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

More info about React lifecycle


问:
Python how to store "\" inside an arrey to use in a subprocess.call bash command
i have a python program that creates a bash command and then uses it in subprocess.call(command)

i wand to send it a file location with spaces.

```<code>import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  "\\ is"
subprocess.call(command)
</code>```

but when it is used by subprocess it becomes a new directory with the name
 this\ is

this is the full code

```<code>import pyxhook
import subprocess

command = [""]
isActive = False
element = 0
isSpace = False

def OnKeyPress(event):
    global command
    global isActive
    global element
    global isSpace
    if event.Ascii == 96:
        if isActive == False:
            isActive = True
        elif isActive == True:
            subprocess.call(command)
            command = [""]
            element = 0
            isActive = False
    elif isActive == True:
        if event.Ascii == 32:
            if isSpace == False:
                command.append("")
                element += 1
            else:
                command[element] += " "
                isSpace = False
        elif event.Key == "BackSpace":
            command[element] = command[element][:-1]
        elif event.Key == "slash":
            command[element] += "/"
        elif event.Key == "Shift_L" :
            command = command
        elif event.Key =="Shift_R":
            command = command
        elif event.Key == "backslash":
            isSpace = True
            command[element] +=  "\\"
        else:
            command[element] += (event.Key)

#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()
</code>```

答:
thank you for helping

```<code>import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  " is"
subprocess.call(command)
</code>```

you don't need to use \ when using subprocess

Body:
i have a python program that creates a bash command and then uses it in subprocess.call(command)

i wand to send it a file location with spaces.

import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  "\\ is"
subprocess.call(command)

but when it is used by subprocess it becomes a new directory with the name
 this\ is

this is the full code

import pyxhook
import subprocess

command = [""]
isActive = False
element = 0
isSpace = False

def OnKeyPress(event):
    global command
    global isActive
    global element
    global isSpace
    if event.Ascii == 96:
        if isActive == False:
            isActive = True
        elif isActive == True:
            subprocess.call(command)
            command = [""]
            element = 0
            isActive = False
    elif isActive == True:
        if event.Ascii == 32:
            if isSpace == False:
                command.append("")
                element += 1
            else:
                command[element] += " "
                isSpace = False
        elif event.Key == "BackSpace":
            command[element] = command[element][:-1]
        elif event.Key == "slash":
            command[element] += "/"
        elif event.Key == "Shift_L" :
            command = command
        elif event.Key =="Shift_R":
            command = command
        elif event.Key == "backslash":
            isSpace = True
            command[element] +=  "\\"
        else:
            command[element] += (event.Key)

#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()

Body:
thank you for helping

import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  " is"
subprocess.call(command)

you don't need to use \ when using subprocess


问:
Splitting words to rows in DataFrame
I have a DataFrame where one of the columns contains strings. I would like to split the strings by spaces and then transform the DataTable, so that it contains one word per row.

```<code>dat = pd.DataFrame(data = {'x' : [1,2],
                           'y' : ['Lorem ipsum dolor sit amet',
                                  'consectetur adipiscing elit']})
</code>```

I would like to get DataFrame like below:

```<code> x   y
 1   Lorem
 1   ipsum
 ...
 2   consectetur
 2   adipiscing
 ...
</code>```

What is the best way to achieve this?

答:
str to list , then we using stack

```<code>dat.y=dat.y.str.split(' ')
dat.set_index('x').y.apply(pd.Series).stack().reset_index().\
        drop('level_1',1).rename(columns={0:'y'})
Out[484]:
   x            y
0  1        Lorem
1  1        ipsum
2  1        dolor
3  1          sit
4  1         amet
5  2  consectetur
6  2   adipiscing
7  2         elit
</code>```

Title: Splitting words to rows in DataFrame

Body:
I have a DataFrame where one of the columns contains strings. I would like to split the strings by spaces and then transform the DataTable, so that it contains one word per row.

dat = pd.DataFrame(data = {'x' : [1,2],
                           'y' : ['Lorem ipsum dolor sit amet',
                                  'consectetur adipiscing elit']})

I would like to get DataFrame like below:

 x   y
 1   Lorem
 1   ipsum
 ...
 2   consectetur
 2   adipiscing
 ...

What is the best way to achieve this?

Body:
str to list , then we using stack

dat.y=dat.y.str.split(' ')
dat.set_index('x').y.apply(pd.Series).stack().reset_index().\
        drop('level_1',1).rename(columns={0:'y'})
Out[484]:
   x            y
0  1        Lorem
1  1        ipsum
2  1        dolor
3  1          sit
4  1         amet
5  2  consectetur
6  2   adipiscing
7  2         elit


问:
Are C constant character strings always null terminated?
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

```<code>const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}
</code>```

答:
A string is only a string if it contains a null character.

A string is a contiguous sequence of characters terminated by and including the first null character.  C11 §7.1.1 1

"abc" is a string literal.  It also always contains a null character.  A string literal may contain more than 1 null character.

```<code>"def\0ghi"  // 2 null characters.
</code>```

In the following, though, x is not a string (it is an array of char without a null character).  y and z are both arrays of char and both are strings.

```<code>char x[3] = "abc";
char y[4] = "abc";
char z[] = "abc";
</code>```

With OP's code, s points to a string, the string literal "abc", *(s + 3) and s[3] have the value of 0.  To attempt to modified s[3] is undefined behavior as 1) s is a const char * and 2) the data pointed to by s is a string literal.  Attempting to modify a string literal is also undefined behavior.

```<code>const char* s = "abc";
</code>```

Deeper: C does not define "constant character strings".

The language defines a string literal, like "abc" to be a character array of size 4 with the value of 'a', 'b', 'c', '\0'.  Attempting to modify these is UB.  How this is used depends on context.

The standard C library defines string.

With const char* s = "abc";, s is a pointer to data of type char.  As a const some_type * pointer, using s to modify data is UB.  s is initialized to point to the string literal "abc".  s itself is not a string.  The memory s initial points to is a string.

Body:
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}

Body:
A string is only a string if it contains a null character.

A string is a contiguous sequence of characters terminated by and including the first null character.  C11 §7.1.1 1

"abc" is a string literal.  It also always contains a null character.  A string literal may contain more than 1 null character.

"def\0ghi"  // 2 null characters.

In the following, though, x is not a string (it is an array of char without a null character).  y and z are both arrays of char and both are strings.

char x[3] = "abc";
char y[4] = "abc";
char z[] = "abc";

With OP's code, s points to a string, the string literal "abc", *(s + 3) and s[3] have the value of 0.  To attempt to modified s[3] is undefined behavior as 1) s is a const char * and 2) the data pointed to by s is a string literal.  Attempting to modify a string literal is also undefined behavior.

const char* s = "abc";

Deeper: C does not define "constant character strings".

The language defines a string literal, like "abc" to be a character array of size 4 with the value of 'a', 'b', 'c', '\0'.  Attempting to modify these is UB.  How this is used depends on context.

The standard C library defines string.

With const char* s = "abc";, s is a pointer to data of type char.  As a const some_type * pointer, using s to modify data is UB.  s is initialized to point to the string literal "abc".  s itself is not a string.  The memory s initial points to is a string.


问:
how to edit the width of menu bar in dreamweaver
any one can give me a quick indication.
I am trying to create a menu bar on my website, but after put it on, don't know how to edit the website, and it show on dreamweaver is different show on the website after I upload it online. and I tried to edit the css file which can't change the width as well.

please check the image that on the website here:
http://www.xuanyinwen.com/images/temp/test.jpg

and on dreamweaver:
http://www.xuanyinwen.com/images/temp/test1.jpg

Thank you very much for your time

Wayne

答:
Dreamweaver is not a dependable tool for previewing HTML. Always preview it in the browser.

Dreamweaver will give you an approximate representation, but it will never be 100% accurate, especially when it comes to how your page will look in different browsers. It can't possibly represent three different rendering engines at the same time.


问:
What is the intended way to pass a parameter to a flask blueprint?
After asking a previous question someone told me the organization of my application was weird, so I looked at other examples to see how I could handle what I want to do.

The clearest example I found is a school case of flask application. From what I understand:

The app object is declared in the app module

Routes are declared in the routes module

The blueprint import the routes as I want

However in my application to answer some of the routes I need to access parameters that are defined in the app module (they are used before creating the app object).

How can I make these parameters accessible in the routes module?

I can't just import them from app since that would be a circular import.

I could use a constructor function like suggested in this question but considering the remarks to my previous question it seems like it is not the usual way to deal with this issue.

答:
It sounds like you might need to use class-based views.

The problem that you're facing is that you need values in your view functions when they run, but it's difficult to get them imported in your routes module where the functions are defined. You originally tried to solve this problem with your functions in a function (which, while perfectly valid, isn't very Python-y).

I would suggest creating a views.py file and defining a class-based view (or you can call it routes.py, it doesn't really matter):

```<code>from flask.views import View

class MyView(View):
    methods = ['GET']

    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

    def dispatch_request(self):
        return 'param1: {}\nparam2: {}'.format(self.param1, self.param2)

def add_routes(app, param1, param2):
    # `param1` and `param2` will get passed to the view class constructor
    app.add_url_rule('/', view_func=MyView.as_view('myview', param1, param2))
</code>```

Then, in your server.py file (or whatever you've called it), you can pass the app and the parameters to the add_routes function:

```<code>from flask import Flask
from .views import add_routes

param1 = 'foo'
param2 = 'bar'
app = Flask(__name__)

add_routes(app, param1, param2)
</code>```

add_routes doesn't have to live in views.py, it could live anywhere. Or, you could just get rid of it altogether if you don't have many routes:

```<code>from flask import Flask
from .views import MyView

param1 = 'foo'
param2 = 'bar'

app = Flask(__name__)
app.add_url_rule('/', view_func=MyView.as_view('myview', param1, param2))
</code>```

Note that the class will be instantiated on each request, not just once. So you shouldn't do anything particularly intensive in the constructor (like reading a file).

Body:
It sounds like you might need to use class-based views.

The problem that you're facing is that you need values in your view functions when they run, but it's difficult to get them imported in your routes module where the functions are defined. You originally tried to solve this problem with your functions in a function (which, while perfectly valid, isn't very Python-y).

I would suggest creating a views.py file and defining a class-based view (or you can call it routes.py, it doesn't really matter):

from flask.views import View

class MyView(View):
    methods = ['GET']

    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

    def dispatch_request(self):
        return 'param1: {}\nparam2: {}'.format(self.param1, self.param2)

def add_routes(app, param1, param2):
    # `param1` and `param2` will get passed to the view class constructor
    app.add_url_rule('/', view_func=MyView.as_view('myview', param1, param2))

Then, in your server.py file (or whatever you've called it), you can pass the app and the parameters to the add_routes function:

from flask import Flask
from .views import add_routes

param1 = 'foo'
param2 = 'bar'
app = Flask(__name__)

add_routes(app, param1, param2)

add_routes doesn't have to live in views.py, it could live anywhere. Or, you could just get rid of it altogether if you don't have many routes:

from flask import Flask
from .views import MyView

param1 = 'foo'
param2 = 'bar'

app = Flask(__name__)
app.add_url_rule('/', view_func=MyView.as_view('myview', param1, param2))

Note that the class will be instantiated on each request, not just once. So you shouldn't do anything particularly intensive in the constructor (like reading a file).


问:
Python : Read constants directly in php file (no passing values)
there are plenty of examples around which show how to pass parameters while executing a python file and they work fine.

My question is about a slightly different subject.

Above the root of my server I have a dbinfo.inc.php configuration file with constants in use for my server:

```<code><?php
define('DB_SERVER', '127.0.0.1');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'password');
?>
</code>```

I was wondering if there was a way to read those constants directly in Python.

答:
Came to a solution thanks to tyteen4a03:

Created a file to grab and store in a array the constants I was looking for :

In Php:

```<code><?php
include "dbinfo.inc.php";

$config = array(
    "DB_SERVER" => DB_SERVER,
    "DB_USERNAME" => DB_USERNAME,
    "DB_PASSWORD" => DB_PASSWORD);

echo json_encode($config);
?>
</code>```

In Python:

```<code>from subprocess import check_output
import json

config = check_output(['php', '../../inc/pythondbinfo.inc.php']).decode('utf-8')
config = json.loads(config)
</code>```

So it's all fine.

Body:
there are plenty of examples around which show how to pass parameters while executing a python file and they work fine.

My question is about a slightly different subject.

Above the root of my server I have a dbinfo.inc.php configuration file with constants in use for my server:

<?php
define('DB_SERVER', '127.0.0.1');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'password');
?>

I was wondering if there was a way to read those constants directly in Python.

Body:
Came to a solution thanks to tyteen4a03:

Created a file to grab and store in a array the constants I was looking for :

In Php:

<?php
include "dbinfo.inc.php";

$config = array(
    "DB_SERVER" => DB_SERVER,
    "DB_USERNAME" => DB_USERNAME,
    "DB_PASSWORD" => DB_PASSWORD);

echo json_encode($config);
?>

In Python:

from subprocess import check_output
import json

config = check_output(['php', '../../inc/pythondbinfo.inc.php']).decode('utf-8')
config = json.loads(config)

So it's all fine.


答:
Use split for lists first and then numpy.repeat with numpy.concatenate and last DataFrame constructor:

```<code>s = dat['y'].str.split()
a = np.repeat(dat['x'].values, s.str.len())
b = np.concatenate(s.values)

df = pd.DataFrame({'x':a,'y':b})
print (df)
   x            y
0  1        Lorem
1  1        ipsum
2  1        dolor
3  1          sit
4  1         amet
5  2  consectetur
6  2   adipiscing
7  2         elit
</code>```

Title: Splitting words to rows in DataFrame

Body:
Use split for lists first and then numpy.repeat with numpy.concatenate and last DataFrame constructor:

s = dat['y'].str.split()
a = np.repeat(dat['x'].values, s.str.len())
b = np.concatenate(s.values)

df = pd.DataFrame({'x':a,'y':b})
print (df)
   x            y
0  1        Lorem
1  1        ipsum
2  1        dolor
3  1          sit
4  1         amet
5  2  consectetur
6  2   adipiscing
7  2         elit


问:
How to capture screen using a private API in iOS 10?
I was the developer for an app called iCapture now known as iProRec which was a non jailbroken screen recorder that made its way on the App Store. I know how to record using airplay mirroring and I want to see if it is possible to do the same but with no wifi. I know it will use private API but I'm just curious to know if it is possible still with iOS 10 frameworks. What would be the best place to start?</p>

答: No, Apple has closed off IOMobileFrameBuffer and the previous private framework used for capturing device screen after the 9.3.3 jailbreak. Now you really have a single option and that would be using the AirPlay protocol to "record" the devices screen. </p>


问:
how to check if container is up to date
I'm using docker-compose to mange my container 'abc' in a linux server (centos).

my steps that I want to perofrm:

1) docker compose pull 'abc' in order to pull my latest image

```<code>docker-compose --file docker-compose.yml pull
</code>```

2) docker command to check if my container 'abc' need to be updated (possible???)

3) if my container 'abc'  I will perform docker-compose up -d

```<code>docker-compose --file docker-compose.yml up -d
</code>```

Remark: I know that step 3 is checking and than update the container if necessary but I need to perform pre tasks if step 2 return True

答:
To restate your question as I read it:

Prior to updating a container, do X

Changes Include:

Image changes

Environment changes for containers

Networking changes

..etc

TLDR; What you want is a dry-run feature of docker-compose. You are not alone: https://github.com/docker/compose/issues/1203

More; I think you are out of luck trying to use docker-compose itself for this purpose until this issue is tackled by the developer community. To be completely safe you would want to perform your pre-flight action when anything affecting the running container is about to change.

Potential Direction: If we were to wish for this, we'd build a shell script that does the examination for us, as simple as a diff on the compose file, or more complex as locating each image e.g., grep image docker-compose.yml | sed "s/^.*\: \(.*\),$/\1/g" ... etc and so forth.

Title: how to check if container is up to date

Body:
I'm using docker-compose to mange my container 'abc' in a linux server (centos).

my steps that I want to perofrm:

1) docker compose pull 'abc' in order to pull my latest image

docker-compose --file docker-compose.yml pull

2) docker command to check if my container 'abc' need to be updated (possible???)

3) if my container 'abc'  I will perform docker-compose up -d

docker-compose --file docker-compose.yml up -d

Remark: I know that step 3 is checking and than update the container if necessary but I need to perform pre tasks if step 2 return True


问:
How can I reference xaml Template from a Converter?
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

```<code>        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>
</code>```

and I have this control using this converter:

```<code><ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>
</code>```

My Converter:

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }
</code>```

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

答:
I think you can accomplish this better with DataTriggers:

```<code>    <ControlTemplate>
        <StackPanel Name="TemplateA" Grid.Column="0" Margin="0,0,5,0">
            <Blah />
        </StackPanel>
        <StackPanel Name="TemplateB" Grid.Column="0" Margin="0,0,5,0">
            <Blah Blah />
        </StackPanel>

        <ControlTemplate.Triggers>
        <DataTrigger Binding="{Binding YourProp}" Value="1">
          <Setter TargetName="TemplateA" Property="Visibility" Value="Visible" />
          <Setter TargetName="TemplateB" Property="Visibility" Value="Collapsed" />
        </DataTrigger>
        <DataTrigger Binding="{Binding YourProp}" Value="0">
          <Setter TargetName="TemplateA" Property="Visibility" Value="Collapsed" />
          <Setter TargetName="TemplateB" Property="Visibility" Value="Visible" />
        </DataTrigger>
        </ControlTemplate.Triggers>

    </ControlTemplate>
</code>```

This is off the top of my head, so TargetName might be SourceName, etc.

Body:
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>

and I have this control using this converter:

<ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>

My Converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

Body:
I think you can accomplish this better with DataTriggers:

    <ControlTemplate>
        <StackPanel Name="TemplateA" Grid.Column="0" Margin="0,0,5,0">
            <Blah />
        </StackPanel>
        <StackPanel Name="TemplateB" Grid.Column="0" Margin="0,0,5,0">
            <Blah Blah />
        </StackPanel>

        <ControlTemplate.Triggers>
        <DataTrigger Binding="{Binding YourProp}" Value="1">
          <Setter TargetName="TemplateA" Property="Visibility" Value="Visible" />
          <Setter TargetName="TemplateB" Property="Visibility" Value="Collapsed" />
        </DataTrigger>
        <DataTrigger Binding="{Binding YourProp}" Value="0">
          <Setter TargetName="TemplateA" Property="Visibility" Value="Collapsed" />
          <Setter TargetName="TemplateB" Property="Visibility" Value="Visible" />
        </DataTrigger>
        </ControlTemplate.Triggers>

    </ControlTemplate>

This is off the top of my head, so TargetName might be SourceName, etc.


问:
Image source change on hover not working as expected
I'm trying to create an image that plays a GIF on hover. I found some jquery on this site that supposedly works but for some reason isn't working for me. Any ideas as to why?

This is the html and javascript:

$(document).ready(function(){

//animate image on hover
    $(document).ready(function()
    {
        $("#imgAnimate").hover(
            function()
            {
                $(this).attr("src", "Videos/Mathew-Demo.gif");
            },
            function()
            {
                $(this).attr("src", "Static shots/Mathew-Demo.png");
            });
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="team.css">
  <script src="team.js" type="text/javascript">
  <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">

</body>

</html></code>```

There is probably a very simple reason why not.

答:
Your script fails because it tries to use jQuery's "$" before jQuery is loaded. you should move your script declaration to the bottom auf your body tag like this:

```<code><!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="team.css">
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">

    <script src="team.js" type="text/javascript">
</body>
</code>```

Body:
I'm trying to create an image that plays a GIF on hover. I found some jquery on this site that supposedly works but for some reason isn't working for me. Any ideas as to why?

This is the html and javascript:

$(document).ready(function(){

//animate image on hover
    $(document).ready(function()
    {
        $("#imgAnimate").hover(
            function()
            {
                $(this).attr("src", "Videos/Mathew-Demo.gif");
            },
            function()
            {
                $(this).attr("src", "Static shots/Mathew-Demo.png");
            });
    });

});

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="team.css">

There is probably a very simple reason why not.

Body:
Your script fails because it tries to use jQuery's "$" before jQuery is loaded. you should move your script declaration to the bottom auf your body tag like this:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="team.css">
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">

    <script src="team.js" type="text/javascript">
</body>