问:
How to extract string from complex string?
My start string is:

```<code>$grp = DL-Test1-Test2-RW"
</code>```

My goal is to have

```<code>$grp = "Test1\Test2"
</code>```

So i need to keep string between first and last "-" character. And replace - by \

UPDATED
I tried this:

```<code>$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion
</code>```

答:
Assuming string always has this form and you are interested in the 2nd and 3rd parts:

```<code># $grp.Split("x") - split string on character x, creating an array
# $grp.Split("x")[n] - get the nth element of the array
# x,y -join "\" join the array elements x and y into a string, with "\" inbetween
($grp.Split("-")[1],$grp.Split("-")[2]) -join "\"
</code>```

Edit - For generic number of elements

```<code>$($grp.Split("-") | Select-Object -SkipLast 1 | Select-Object -Last ($grp.Split("-").count - 2)) -join "\"
</code>```

Multiline:

```<code>$Descritpion = $grp.Split("-")
$Descritpion = $Descritpion | Select-Object -SkipLast 1
$Descritpion = $Descritpion | Select-Object -Last ($grp.Split("-").count - 2)
$Descritpion = $Descritpion-join "\"
</code>```

Body:
My start string is:

$grp = DL-Test1-Test2-RW"

My goal is to have

$grp = "Test1\Test2"

So i need to keep string between first and last "-" character. And replace - by \

UPDATED
I tried this:

$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion

Body:
Assuming string always has this form and you are interested in the 2nd and 3rd parts:

# $grp.Split("x") - split string on character x, creating an array
# $grp.Split("x")[n] - get the nth element of the array
# x,y -join "\" join the array elements x and y into a string, with "\" inbetween
($grp.Split("-")[1],$grp.Split("-")[2]) -join "\"

Edit - For generic number of elements

$($grp.Split("-") | Select-Object -SkipLast 1 | Select-Object -Last ($grp.Split("-").count - 2)) -join "\"

Multiline:

$Descritpion = $grp.Split("-")
$Descritpion = $Descritpion | Select-Object -SkipLast 1
$Descritpion = $Descritpion | Select-Object -Last ($grp.Split("-").count - 2)
$Descritpion = $Descritpion-join "\"


来源: stackexchange

问:
unable to add value on nested property
I am struggling to modify the data of properties that are deeply nested in my PSObject. If I try to modify the values Powershell just throws the exception of saying that it cannot find the value, but if I just call upon the value itself it can be found without an issue.

The raw data of the json object looks like this:

```<code>[
    {
        "@CREATED": "2017-05-04 08:36:23",
        "@LAST_MODIFIED": "2017-05-08 08:18:58",
        "STANDARD_FIELDS": {
            "FIRST_NAME": {
                "@FIELD_ID": 2,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "value": "Example"
            },
            "LAST_NAME": {
                "@FIELD_ID": 3,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "value": "User"
            },
            "ORGANIZATION": {
                "@FIELD_ID": 8,
                "@MODE": 0,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "value": "Example Org"
            },
            "NAME": {
                "@FIELD_ID": 1,
                "@MODE": 1,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "@ID": 240
            },
            "SUPERVISOR": {
                "@FIELD_ID": 9,
                "@MODE": 4,
                "@LAST_MODIFIED": "2017-05-04 15:39:30",
                "@VALID_FROM": "2017-05-04",
                "NAME": "Example User2",
                "SYSTEM_ID": "198"
            },
            "JOB_LOCATION": {
                "@FIELD_ID": 14,
                "@MODE": 0,
                "@LAST_MODIFIED": "2017-05-04 14:26:55",
                "@VALID_FROM": "2017-05-04",
                "value": "Stockholm"
            }
        },
        "CUSTOM_FIELDS": {
            "FIELD": [
                {
                    "@FIELD_ID": 1033,
                    "@MODE": 0,
                    "@LAST_MODIFIED": "2017-05-24 10:15:24",
                    "@VALID_FROM": "2017-05-24",
                    "NAME": "Department",
                    "VALUE": {
                        "value": "Example Department"
                    }
                },
                {
                    "@FIELD_ID": 1034,
                    "@MODE": 0,
                    "@LAST_MODIFIED": "2017-05-04 08:36:24",
                    "@VALID_FROM": "2017-05-04",
                    "NAME": "VPN",
                    "VALUE": {
                        "value": "Yes"
                    }
                },
                {
                    "@FIELD_ID": 1036,
                    "@LAST_MODIFIED": "2017-05-04 08:36:24",
                    "@VALID_FROM": "2017-05-04",
                    "NAME": "Titel",
                    "VALUE": {
                        "value": "Test-User"
                    }
                },
                {
                    "@FIELD_ID": 1022,
                    "@MODE": 0,
                    "@LAST_MODIFIED": "2017-05-04 16:43:18",
                    "@VALID_FROM": "2017-05-04",
                    "NAME": "Authorizations",
                    "VALUES": {
                        "VALUE": [
                            {
                                "value": "Auth 1"
                            },
                            {
                                "value": "Auth 2"
                            },
                            {
                                "value": "Auth 3"
                            },
                            {
                                "value": "Auth 4"
                            }
                        ]
                    }
                }
            ]
        }
    }
]
</code>```

My current code:

```<code>$users = get-content "C:\Working-Branch\Temp\NotFoundUsers - Copy.txt"| ConvertFrom-Json

foreach($user in $users){
  $user.CUSTOM_FIELDS.FIELD.values.Value.value
  $NewValue = $user.CUSTOM_FIELDS.FIELD.values.Value.value
  $NewValue += "Test"
  $NewValue
  $($user.CUSTOM_FIELDS.FIELD.values.Value).value = $newValue
}
</code>```

Which results in the following output:

```<code>Auth 1
Auth 2
Auth 3
Auth 4
Auth 1
Auth 2
Auth 3
Auth 4
Test
The property 'value' cannot be found on this object. Verify that the property exists and can be set.
At line:10 char:5
+   $($user.CUSTOM_FIELDS.FIELD.values.Value).value = $newValue
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException
</code>```

So I know the property exists because I call upon it two times, one directly on the Object and one time after I have added the value "test" to it. But when I try to update the Orignal object it says it can not find the value "Value" on the object.

I tried following the what was suggested in This post, but it still fails for me. I both with the "+=" operator and the "=" operator. Same error with both of them.

Result of Get-member

答:
I think you need to find the field with the member Values

```<code>$newvalue =@{
    "value" = "Test"
    }

foreach($user in $users){

  $array = $user.CUSTOM_FIELDS.FIELD.values.value
  $array += $newvalue

  foreach ($field in $user.CUSTOM_FIELDS.FIELD)
  {
    if ($field.values -ne $null)
    {
        $field.values.value = $array
    }
  }

  $user.CUSTOM_FIELDS.FIELD.values.Value
}
</code>```

Then output for $user.CUSTOM_FIELDS.FIELD.values.Value is

```<code>value
-----
Auth 1
Auth 2
Auth 3
Auth 4
Test
</code>```

ContentLicense: CC BY-SA 3.0

Title: unable to add value on nested property

Body:
I am struggling to modify the data of properties that are deeply nested in my PSObject. If I try to modify the values Powershell just throws the exception of saying that it cannot find the value, but if I just call upon the value itself it can be found without an issue.

The raw data of the json object looks like this:

[
    {
        "@CREATED": "2017-05-04 08:36:23",
        "@LAST_MODIFIED": "2017-05-08 08:18:58",
        "STANDARD_FIELDS": {
            "FIRST_NAME": {
                "@FIELD_ID": 2,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "value": "Example"
            },
            "LAST_NAME": {
                "@FIELD_ID": 3,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "value": "User"
            },
            "ORGANIZATION": {
                "@FIELD_ID": 8,
                "@MODE": 0,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "value": "Example Org"
            },
            "NAME": {
                "@FIELD_ID": 1,
                "@MODE": 1,
                "@LAST_MODIFIED": "2017-05-04 08:36:24",
                "@VALID_FROM": "2017-05-04",
                "@ID": 240
            },
            "SUPERVISOR": {
                "@FIELD_ID": 9,
                "@MODE": 4,
                "@LAST_MODIFIED": "2017-05-04 15:39:30",
                "@VALID_FROM": "2017-05-04",
                "NAME": "Example User2",
                "SYSTEM_ID": "198"
            },
            "JOB_LOCATION": {
                "@FIELD_ID": 14,
                "@MODE": 0,
                "@LAST_MODIFIED": "2017-05-04 14:26:55",
                "@VALID_FROM": "2017-05-04",
                "value": "Stockholm"
            }
        },
        "CUSTOM_FIELDS": {
            "FIELD": [
                {
                    "@FIELD_ID": 1033,
                    "@MODE": 0,
                    "@LAST_MODIFIED": "2017-05-24 10:15:24",
                    "@VALID_FROM": "2017-05-24",
                    "NAME": "Department",
                    "VALUE": {
                        "value": "Example Department"
                    }
                },
                {
                    "@FIELD_ID": 1034,
                    "@MODE": 0,
                    "@LAST_MODIFIED": "2017-05-04 08:36:24",
                    "@VALID_FROM": "2017-05-04",
                    "NAME": "VPN",
                    "VALUE": {
                        "value": "Yes"
                    }
                },
                {
                    "@FIELD_ID": 1036,
                    "@LAST_MODIFIED": "2017-05-04 08:36:24",
                    "@VALID_FROM": "2017-05-04",
                    "NAME": "Titel",
                    "VALUE": {
                        "value": "Test-User"
                    }
                },
                {
                    "@FIELD_ID": 1022,
                    "@MODE": 0,
                    "@LAST_MODIFIED": "2017-05-04 16:43:18",
                    "@VALID_FROM": "2017-05-04",
                    "NAME": "Authorizations",
                    "VALUES": {
                        "VALUE": [
                            {
                                "value": "Auth 1"
                            },
                            {
                                "value": "Auth 2"
                            },
                            {
                                "value": "Auth 3"
                            },
                            {
                                "value": "Auth 4"
                            }
                        ]
                    }
                }
            ]
        }
    }
]

My current code:

$users = get-content "C:\Working-Branch\Temp\NotFoundUsers - Copy.txt"| ConvertFrom-Json

foreach($user in $users){
  $user.CUSTOM_FIELDS.FIELD.values.Value.value
  $NewValue = $user.CUSTOM_FIELDS.FIELD.values.Value.value
  $NewValue += "Test"
  $NewValue
  $($user.CUSTOM_FIELDS.FIELD.values.Value).value = $newValue
}

Which results in the following output:

Auth 1
Auth 2
Auth 3
Auth 4
Auth 1
Auth 2
Auth 3
Auth 4
Test
The property 'value' cannot be found on this object. Verify that the property exists and can be set.
At line:10 char:5
+   $($user.CUSTOM_FIELDS.FIELD.values.Value).value = $newValue
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

So I know the property exists because I call upon it two times, one directly on the Object and one time after I have added the value "test" to it. But when I try to update the Orignal object it says it can not find the value "Value" on the object.

I tried following the what was suggested in This post, but it still fails for me. I both with the "+=" operator and the "=" operator. Same error with both of them.

Result of Get-member

Body:
I think you need to find the field with the member Values

$newvalue =@{
    "value" = "Test"
    }

foreach($user in $users){

  $array = $user.CUSTOM_FIELDS.FIELD.values.value
  $array += $newvalue

  foreach ($field in $user.CUSTOM_FIELDS.FIELD)
  {
    if ($field.values -ne $null)
    {
        $field.values.value = $array
    }
  }

  $user.CUSTOM_FIELDS.FIELD.values.Value
}

Then output for $user.CUSTOM_FIELDS.FIELD.values.Value is

value
-----
Auth 1
Auth 2
Auth 3
Auth 4
Test


问:
Nullpointer Exception on null check statement
How is the null check statement below throwing a Nullpointer Exception? Is the request perhaps null? I'm confused Somebody help.

```<code>if(!getTGTid(request).equalsIgnoreCase(null) ||
!getTGTid(request).equalsIgnoreCase("")) {
</code>```

Method

```<code>private String getTGTid(HttpServletRequest request) {
return request.getParameter("tgtId");
}
</code>```

答:
If getTGTid(request) is null, getTGTid(request).equalsIgnoreCase(null) will throw NullPointerException.

Use

```<code>if (getTGTid(request) != null && !getTGTid(request).equalsIgnoreCase(""))
</code>```

Body:
How is the null check statement below throwing a Nullpointer Exception? Is the request perhaps null? I'm confused Somebody help.

if(!getTGTid(request).equalsIgnoreCase(null) ||
!getTGTid(request).equalsIgnoreCase("")) {

Method

private String getTGTid(HttpServletRequest request) {
return request.getParameter("tgtId");
}

Body:
If getTGTid(request) is null, getTGTid(request).equalsIgnoreCase(null) will throw NullPointerException.

Use

if (getTGTid(request) != null && !getTGTid(request).equalsIgnoreCase(""))


问:
Getting 3D image from 2D image
I am doing a project in Matlab on Image processing

Is there any possibility of getting 3d image from 2d image?

答:
a 3d image would be a projection from 4d (and to show one of those you've got to project down to 2d) and most images that can be displayed on computer or in a picture frame are 2d projections of 3d objects due to this projection which in fact selects a slice of the higher dimensional space it doesn't contain the information needed to invert that projection and get back to 3d from a 2d image

but if you have sufficient sampling of the space it is possible to reconstruct a 3d object from 2d images of it but i don't know of any simple ways to do this

Title: Getting 3D image from 2D image

ContentLicense: CC BY-SA 2.5


问:
Binding Button Events in Jquery Datatable in Angular 2
I am trying to Implement the Jquery Datatable in my Angular 2 Application

I could Render the Table in my html file as follows

```<code><sa-datatable [options]="options" tableClass="table table-striped table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                        </sa-datatable>
</code>```

In my component Oninit , I am Initialising my Table as following and adding two Buttons in the Action

```<code>ngOnInit() {
    this.options = {
        dom: "Bfrtip",
        ajax: (data, callback, settings) => {
            //My Service Call
        },
        columns: [
            { data: "result.id" },
            { data: "result.name" },
            {
                data: null, render: function (data, type, row) {
                return '<button id="myButton" class="btn btn-primary editbutton" data-toggle="modal" title="1" data-target="#mymodal" (click)="custcatSelected(' + data.result + ')">Edit</button> / <button #myButton1 class="btn btn-danger deletebutton" (click)=deleteCustCat(' + data.result.id + ')>Delete</button>';
                }
            }
        ],
        buttons: [
            'copy', 'excel', 'pdf', 'print', 'colvis'
        ]
    };
}

public custcatSelected(customercat) {
    //Implemetation for Edit , where customercat is an object
}

public deleteCustCat(custcatId: string) {
    //Implementation for Deleting
}
</code>```

I am not able to Trigger these two events custcatSelected() and deleteCustCat().

I could understand that these events are not compiled by angular ,since its added dynamically . And i do not know how to make these events work

Any Work Around would be helpful Thanks.

答:
One way I can think of is listening the event by jQuery and using the data attribute on the element to handle the event. I haven't tested this code, and
apparently it is not a clean solution. Just to give you an idea.

You will need to add declare var $:any at the top of your component as well. Because TypeScript will complaint about that.

ngOnInit() {
    this.options = {
        dom: "Bfrtip",
        ajax: (data, callback, settings) => {
            //My Service Call
        },
        columns: [
            { data: "result.id" },
            { data: "result.name" },
            {
                data: null, render: function (data, type, row) {
                    return `
                        <button id="selectedBtn" class="btn btn-primary editbutton" data-toggle="modal" title="1"
                                data-target="#mymodal"
                                data-elemnt-obj="${data.result}">Edit</button>

                        <button class="btn btn-danger deletebutton"
                                data-element-id="${data.result.id}">Delete</button>
                    `;
                }
            }
        ],
        buttons: [
            'copy', 'excel', 'pdf', 'print', 'colvis'
        ]
    };

    $(document).on('click', '#selectedBtn', ($event) => {
        let customerCat = JSON.parse($($event).data('elemnt-obj'));
        this.custcatSelected(customerCat);
    });

    $(document).on('click', '.deletebutton', ($event) => {
        let customerId = $($event).data('element-id');
        this.deleteCustCat(customerId);
    });
}

public custcatSelected(customercat) {
    //Implemetation for Edit , where customercat is an object
}

public deleteCustCat(custcatId: string) {
    //Implementation for Deleting
}```

Body:
I am trying to Implement the Jquery Datatable in my Angular 2 Application

I could Render the Table in my html file as follows

<sa-datatable [options]="options" tableClass="table table-striped table-bordered table-hover">

                                    ID
                                    Name
                                    Action

                        </sa-datatable>

In my component Oninit , I am Initialising my Table as following and adding two Buttons in the Action

ngOnInit() {
    this.options = {
        dom: "Bfrtip",
        ajax: (data, callback, settings) => {
            //My Service Call
        },
        columns: [
            { data: "result.id" },
            { data: "result.name" },
            {
                data: null, render: function (data, type, row) {
                return '<button id="myButton" class="btn btn-primary editbutton" data-toggle="modal" title="1" data-target="#mymodal" (click)="custcatSelected(' + data.result + ')">Edit</button> / <button #myButton1 class="btn btn-danger deletebutton" (click)=deleteCustCat(' + data.result.id + ')>Delete</button>';
                }
            }
        ],
        buttons: [
            'copy', 'excel', 'pdf', 'print', 'colvis'
        ]
    };
}

public custcatSelected(customercat) {
    //Implemetation for Edit , where customercat is an object
}

public deleteCustCat(custcatId: string) {
    //Implementation for Deleting
}

I am not able to Trigger these two events custcatSelected() and deleteCustCat().

I could understand that these events are not compiled by angular ,since its added dynamically . And i do not know how to make these events work

Any Work Around would be helpful Thanks.


问:
Adding HTTPS in Local wordpress site
I have install wordpress locally which is deployed on apache on port 8888.
so my website url looks like http://www.localhost:8888/wordpress/*

How can i make this secure ?

答: Does changing siteurl and home in the options table of the database to include "https" not work for you?

Title: Adding HTTPS in Local wordpress site


问:
Unable to parse stringified array within an array
I have this example code:

```<code>let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]

let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);
</code>```

Testing my code using this site: https://es6console.com/

It seems that I'm unable to parse & log the data at all.

Any ideas why this is happening?

答:
Your option string is not following the JSON specs: in JSON every key and string value needs to be enclosed in double quotes. So this would work:

let testData= [{
    name: 'Joshua',
    age: 22,
    option: '[{"value": "test"}]'
}, {
    name: 'Ali',
    age: 200,
    option: '[{"value": "test2"}]'
}];

let parsedData = JSON.parse(testData[0].option);
console.log(parsedData);```

Body:
I have this example code:

let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]

let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);

Testing my code using this site: https://es6console.com/

It seems that I'm unable to parse & log the data at all.

Any ideas why this is happening?


问:
Set spinner title when activity is created
I have a spinner whose elements set by an arrayList.this arraylist gets data by calling an api. I have set title at 0th position of  arrayList .the problem is i want to show this title as activity is created. but this will set only when api calling is successful .it takes some time to load data. can anyone give me better idea to set title to spinner. </p>

答:
Do like this    </p>

```<code> ArrayAdapter stringArrayAdapter = new ArrayAdapter(this,
 R.layout.spinner_item, CatagoryName);

    // create a spinner
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    // add adapter to spinner
    spinner.setAdapter(stringArrayAdapter);
    // create listener and add to spinner
    spinner.setOnItemSelectedListener(new
     AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int
       position, long id) {
              // put code which recognize a selected element
        }
</code>```

Body:
Do like this

 ArrayAdapter stringArrayAdapter = new ArrayAdapter(this,
 R.layout.spinner_item, CatagoryName);

    // create a spinner
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    // add adapter to spinner
    spinner.setAdapter(stringArrayAdapter);
    // create listener and add to spinner
    spinner.setOnItemSelectedListener(new
     AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int
       position, long id) {
              // put code which recognize a selected element
        }


问:
How to do MCRYPT_RIJNDAEL_128 + MCRYPT_MODE_CBC in Python?
I have been translating PHP code to Python because my company is switching language and framework, but i am stuck on this one method, i can't seems to find the Python equivalent for it.

This is the PHP code:

```<code>function addpadding($string, $blocksize = 32) {
  $len = strlen($string);
  $pad = $blocksize - ($len % $blocksize);
  $string .= str_repeat(chr($pad), $pad);
  return $string;
}

function create_mpg_aes_encrypt($parameter = '', $key = '', $iv = '') {
   $return_str = http_build_query($parameter);
   return trim(bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($return_str), MCRYPT_MODE_CBC, $iv)));
}
</code>```

This is my python code:

```<code>def addpadding_pay2go(string, blocksize=32):
   length              = len(string)
   pad                 = blocksize - (length % blocksize)
   padding_strings     = chr(pad) * pad
   new_string          = string + padding_strings
   return new_string
</code>```

Now for the create_mpg_aes_encrypt, i can only re-create the first line in Python, i don't know how to do the second line.

```<code>test_array = {
    'MerchantID'        : 'XXX',
    'RespondType'       : 'JSON',
    'TimeStamp'         : unixtime,
    'Version'           : '1.4',
    'MerchantOrderNo'   : 1,
    'Amt'               : 10,
    'ItemDesc'          : 'product description',
    'Key'               : 'XXXXX',
    'IV'                : 'XXXXX'
}

return_str = urllib.urlencode(test_array)
</code>```

I can do the trim and bin2hex. But my only problem is "how to re-create this in Python?"

```<code>mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($return_str), MCRYPT_MODE_CBC, $iv)
</code>```

答:
I tried this, i don't know whether it is correct or not</p>

```<code>from Crypto.Cipher import AES
import urllib

def addpadding_pay2go(string, blocksize=32):
  length              = len(string)
  pad                 = blocksize - (length % blocksize)
  padding_strings     = chr(pad) * pad
  new_string          = string + padding_strings
  return new_string

def create_mpg_aes_encrypt(test_array, key, iv):
  return_str              = urllib.urlencode(test_array)
  return_str_with_padding = addpadding_pay2go(return_str)

  AES.key_size    = 128
  crypt_object    = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
  encrypted_text  = crypt_object.encrypt(return_str_with_padding)
  hex             = encrypted_text.encode('hex')
  hex_with_strip  = hex.strip()
  return hex_with_strip
</code>```

Body:
I have been translating PHP code to Python because my company is switching language and framework, but i am stuck on this one method, i can't seems to find the Python equivalent for it.

This is the PHP code:

function addpadding($string, $blocksize = 32) {
  $len = strlen($string);
  $pad = $blocksize - ($len % $blocksize);
  $string .= str_repeat(chr($pad), $pad);
  return $string;
}

function create_mpg_aes_encrypt($parameter = '', $key = '', $iv = '') {
   $return_str = http_build_query($parameter);
   return trim(bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($return_str), MCRYPT_MODE_CBC, $iv)));
}

This is my python code:

def addpadding_pay2go(string, blocksize=32):
   length              = len(string)
   pad                 = blocksize - (length % blocksize)
   padding_strings     = chr(pad) * pad
   new_string          = string + padding_strings
   return new_string

Now for the create_mpg_aes_encrypt, i can only re-create the first line in Python, i don't know how to do the second line.

test_array = {
    'MerchantID'        : 'XXX',
    'RespondType'       : 'JSON',
    'TimeStamp'         : unixtime,
    'Version'           : '1.4',
    'MerchantOrderNo'   : 1,
    'Amt'               : 10,
    'ItemDesc'          : 'product description',
    'Key'               : 'XXXXX',
    'IV'                : 'XXXXX'
}

return_str = urllib.urlencode(test_array)

I can do the trim and bin2hex. But my only problem is "how to re-create this in Python?"

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($return_str), MCRYPT_MODE_CBC, $iv)

Body:
I tried this, i don't know whether it is correct or not

from Crypto.Cipher import AES
import urllib

def addpadding_pay2go(string, blocksize=32):
  length              = len(string)
  pad                 = blocksize - (length % blocksize)
  padding_strings     = chr(pad) * pad
  new_string          = string + padding_strings
  return new_string

def create_mpg_aes_encrypt(test_array, key, iv):
  return_str              = urllib.urlencode(test_array)
  return_str_with_padding = addpadding_pay2go(return_str)

  AES.key_size    = 128
  crypt_object    = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
  encrypted_text  = crypt_object.encrypt(return_str_with_padding)
  hex             = encrypted_text.encode('hex')
  hex_with_strip  = hex.strip()
  return hex_with_strip


问:
Setting id to objects on JavaFX Canvas
I would like to draw rectangle, line etc. on canvas with GraphicsContext.

```<code>Rectangle rect = new Rectangle(20,20,10,10);
rect.setId("myRect");
gc.draw(rect);
</code>```

Is there something like this in JavaFX? Or is there a way to access drawn canvas objects?

答:
From what I know you can't draw Rectangles directly on a canvas - Rectangle is a JavaFX node, but the Canvas API is much lower level and only takes very basic drawing commands. For example, for drawing your rectangle, it would be:

```<code>GraphicsContext gc = theCanvas.getGraphicsContext2D();
gc.fillRect(20,20,10,10);
</code>```

This however doesn't let you manipulate the rectangle any further. what I do is create a custom class DrawableRectangle (for example) with a method draw:

```<code>public class DrawableRectangle extends Rectangle {

    Canvas theCanvas;

    public DrawableRectangle(Rectangle r, Canvas c){
        super(r.getX(),r.getY(),r.getWidth(),r.getHeight());
        this.theCanvas = c;
    }
    public DrawableRectangle(int x, int y, int w, int h, Canvas c){
        super(x,y,w,h);
        this.theCanvas = c;
    }

    public void draw(){
        GraphicsContext gc = theCanvas.getGraphicsContext2D();
        gc.setFill(Paint.valueOf("black"));
        gc.fillRect(getX(),getY(),getWidth(),getHeight());
    }

}
</code>```

Which you can then use like this:

```<code>    GraphicsContext gc = theCanvas.getGraphicsContext2D();
    DrawableRectangle rect = new DrawableRectangle(10,10,20,20, theCanvas);

    // Draw it:
    rect.draw();

    // You can then manipulate it:
    rect.setY(40);
    rect.setHeight(60);

    // You need to draw it again to see the changes:
    // First clear the canvas:
    gc.clearRect(0,0,theCanvas.getWidth(),theCanvas.getHeight());
    // Then draw it:
    rect.draw();
</code>```

(I can't guarantee this is the best method, but it worked well for me. If you want to draw different shapes this way you should make an interface Drawable to abstract it.)

Title: Setting id to objects on JavaFX Canvas

Body:
I would like to draw rectangle, line etc. on canvas with GraphicsContext.

Rectangle rect = new Rectangle(20,20,10,10);
rect.setId("myRect");
gc.draw(rect);

Is there something like this in JavaFX? Or is there a way to access drawn canvas objects?

Body:
From what I know you can't draw Rectangles directly on a canvas - Rectangle is a JavaFX node, but the Canvas API is much lower level and only takes very basic drawing commands. For example, for drawing your rectangle, it would be:

GraphicsContext gc = theCanvas.getGraphicsContext2D();
gc.fillRect(20,20,10,10);

This however doesn't let you manipulate the rectangle any further. what I do is create a custom class DrawableRectangle (for example) with a method draw:

public class DrawableRectangle extends Rectangle {

    Canvas theCanvas;

    public DrawableRectangle(Rectangle r, Canvas c){
        super(r.getX(),r.getY(),r.getWidth(),r.getHeight());
        this.theCanvas = c;
    }
    public DrawableRectangle(int x, int y, int w, int h, Canvas c){
        super(x,y,w,h);
        this.theCanvas = c;
    }

    public void draw(){
        GraphicsContext gc = theCanvas.getGraphicsContext2D();
        gc.setFill(Paint.valueOf("black"));
        gc.fillRect(getX(),getY(),getWidth(),getHeight());
    }

}

Which you can then use like this:

    GraphicsContext gc = theCanvas.getGraphicsContext2D();
    DrawableRectangle rect = new DrawableRectangle(10,10,20,20, theCanvas);

    // Draw it:
    rect.draw();

    // You can then manipulate it:
    rect.setY(40);
    rect.setHeight(60);

    // You need to draw it again to see the changes:
    // First clear the canvas:
    gc.clearRect(0,0,theCanvas.getWidth(),theCanvas.getHeight());
    // Then draw it:
    rect.draw();

(I can't guarantee this is the best method, but it worked well for me. If you want to draw different shapes this way you should make an interface Drawable to abstract it.)


问:
Excel VBA: Looping through a combo box's items from another user form
I want to loop through a combo box's items but not get their values. I just want to loop through how many items there are. Here is how I add items to it.

```<code>Private Sub UserForm_Initialize()

    Chapter.AddItem "Chapter 1"
    Chapter.AddItem "Chapter 2"
    Chapter.AddItem "Chapter 3"
    Chapter.AddItem "No　Chapter"

End Sub
</code>```

And this is what I tried on looping through it.

```<code>        Dim itm As Object

        For Each itm In UserForm.ComboBox1.Items.Count

        Next
</code>```

But error prompt; Compile error: Method or data member not found

Does it matter that these codes aren't on one user form? I have two user forms and the adding of items to the combo box is on the second and the looping through the combo box is on the first one. Does that matter?

答:
If you only want to loop for items count, you can try

```<code>    Dim itm As Object

    For i = 1 to UserForm1.Chapter.ListCount

    Next
</code>```

Where Userform1 is the name of the Form that contains Combobox and
Chapter is the name of the ComboBox

Body:
I want to loop through a combo box's items but not get their values. I just want to loop through how many items there are. Here is how I add items to it.

Private Sub UserForm_Initialize()

    Chapter.AddItem "Chapter 1"
    Chapter.AddItem "Chapter 2"
    Chapter.AddItem "Chapter 3"
    Chapter.AddItem "No　Chapter"

End Sub

And this is what I tried on looping through it.

        Dim itm As Object

        For Each itm In UserForm.ComboBox1.Items.Count

        Next

But error prompt; Compile error: Method or data member not found

Does it matter that these codes aren't on one user form? I have two user forms and the adding of items to the combo box is on the second and the looping through the combo box is on the first one. Does that matter?

Body:
If you only want to loop for items count, you can try

    Dim itm As Object

    For i = 1 to UserForm1.Chapter.ListCount

    Next

Where Userform1 is the name of the Form that contains Combobox and
Chapter is the name of the ComboBox


问:
AWS Lambda verify user token sent by mobile app?
I'm using Amazon Mobile Hub to build a mobile app. I used AWS Cognito within the MobileHub to authenticate users with sign up and sign in. I'm now trying to use AWS Lambda to communicate with DynamoDB to do some operations.

While doing that, I stumbled upon a problem which is that I'm not sure how to verify a user. In a sense that if I send the Access Token via Cloud Logic to my Lambda function, how would I verify that token and move forward with my operations with the username retrieved from that token?

This SDK allows Lambda functions to communicate with AWS Cognito features but I didn't find any useful functions to actually verify tokens. https://github.com/aws/amazon-cognito-identity-js

答:
So you have two options when using Cognito for authorization.

1) You can attach a Cognito Authorizer to the API, which "Just works", under the hood cognito verifies the token. You don't get much control over the authorization process, it's either a yes or a no basically.

2) As prateek said you can use a custom authorizer, something a bit like this, note: I've put the key in the code this is a very bad idea and you should store it in an environment variable KMS encrypted.

```<code>import jwt from 'jsonwebtoken'

export default (event, context, callback) => {

    const key = '' // <--- YOU GET THIS KEY FROM https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json.
    jwt.verify(event.authorizationToken, key, (err, decoded) => {
        if (err) {
            console.log('JWT VALIDATION ERROR')
            callback(null, responder.unAuthorised())
            return
        }

        const principalId = decoded.user.username

        const apiOptions = {}
        const tmp = event.methodArn.split(':')
        const apiGatewayArnTmp = tmp[5].split('/')
        const awsAccountId = tmp[4]
        apiOptions.region = tmp[3]
        apiOptions.restApiId = apiGatewayArnTmp[0]
        apiOptions.stage = apiGatewayArnTmp[1]
        const method = apiGatewayArnTmp[2]
        let resource = '/' // root resource
        if (apiGatewayArnTmp[3]) {
            resource += apiGatewayArnTmp[3]
        }

        const policy = new AuthPolicy(principalId, awsAccountId, apiOptions)

        // DENY
        policy.denyMethod(AuthPolicy.HttpVerb.POST, "/someEndpoint")

        // PERMIT
        policy.allowMethod(AuthPolicy.HttpVerb.POST, "/someEndpoint")

        const authResponse = policy.build()

        // YOU CAN EMBED ANYTHING ELSE YOU WANT TO ADD LIKE SO:
        authResponse.context = {
            username: decoded.username,
            someKey: someInfo,
        }

        callback(null, authResponse)

    }) //  jwt.verify(
}
</code>```

I can't remember what claims cognito puts in its token, but after you jwt.verify just console log the decoded token and you'll see a load of information from you user pool, you can then pass that down in authResponse.context and it'll appear within your lambda under event.requestContext.authorizer.

Remember that the Identity Token is the one that'll contain the info from the user pool.

Body:
So you have two options when using Cognito for authorization.

1) You can attach a Cognito Authorizer to the API, which "Just works", under the hood cognito verifies the token. You don't get much control over the authorization process, it's either a yes or a no basically.

2) As prateek said you can use a custom authorizer, something a bit like this, note: I've put the key in the code this is a very bad idea and you should store it in an environment variable KMS encrypted.

import jwt from 'jsonwebtoken'

export default (event, context, callback) => {

    const key = '' // <--- YOU GET THIS KEY FROM https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json.
    jwt.verify(event.authorizationToken, key, (err, decoded) => {
        if (err) {
            console.log('JWT VALIDATION ERROR')
            callback(null, responder.unAuthorised())
            return
        }

        const principalId = decoded.user.username

        const apiOptions = {}
        const tmp = event.methodArn.split(':')
        const apiGatewayArnTmp = tmp[5].split('/')
        const awsAccountId = tmp[4]
        apiOptions.region = tmp[3]
        apiOptions.restApiId = apiGatewayArnTmp[0]
        apiOptions.stage = apiGatewayArnTmp[1]
        const method = apiGatewayArnTmp[2]
        let resource = '/' // root resource
        if (apiGatewayArnTmp[3]) {
            resource += apiGatewayArnTmp[3]
        }

        const policy = new AuthPolicy(principalId, awsAccountId, apiOptions)

        // DENY
        policy.denyMethod(AuthPolicy.HttpVerb.POST, "/someEndpoint")

        // PERMIT
        policy.allowMethod(AuthPolicy.HttpVerb.POST, "/someEndpoint")

        const authResponse = policy.build()

        // YOU CAN EMBED ANYTHING ELSE YOU WANT TO ADD LIKE SO:
        authResponse.context = {
            username: decoded.username,
            someKey: someInfo,
        }

        callback(null, authResponse)

    }) //  jwt.verify(
}

I can't remember what claims cognito puts in its token, but after you jwt.verify just console log the decoded token and you'll see a load of information from you user pool, you can then pass that down in authResponse.context and it'll appear within your lambda under event.requestContext.authorizer.

Remember that the Identity Token is the one that'll contain the info from the user pool.


问:
Excel Macro Help - Stacking Macros
I am using the following subroutine to combine multiple Excel files from a single folder into a single workbook with multiple worksheets.

```<code>Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
    Set wsSrc = wbSrc.Worksheets(1)
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
    wbSrc.Close False
    strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub
</code>```

The end product is an excel file with multiple worksheets (as well as one blank Sheet 1). I was wondering how I can then apply another macro to this newly created Workbook. As an example, I wish for all the worksheets within this new workbook to have their Headers bold and coloured a certain way, and to have the empty Worksheet deleted.

eg:

```<code>Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub
</code>```

答:
Add a parameter to Headers that specifies a sheet, then call the sub somewhere in the Do Loop after the copy, like:

```<code>Call Headers(wbDst.Worksheets(wbDst.Worksheets.Count))
</code>```

with your second sub looking like this:

```<code>Sub Headers(workingSheet As Worksheet)

workingSheet.Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
.
.
.
</code>```

Title: Excel Macro Help - Stacking Macros

Body:
I am using the following subroutine to combine multiple Excel files from a single folder into a single workbook with multiple worksheets.

Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
    Set wsSrc = wbSrc.Worksheets(1)
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
    wbSrc.Close False
    strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

The end product is an excel file with multiple worksheets (as well as one blank Sheet 1). I was wondering how I can then apply another macro to this newly created Workbook. As an example, I wish for all the worksheets within this new workbook to have their Headers bold and coloured a certain way, and to have the empty Worksheet deleted.

eg:

Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub

Body:
Add a parameter to Headers that specifies a sheet, then call the sub somewhere in the Do Loop after the copy, like:

Call Headers(wbDst.Worksheets(wbDst.Worksheets.Count))

with your second sub looking like this:

Sub Headers(workingSheet As Worksheet)

workingSheet.Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
.
.
.


问:
Restriction on object property ontology in Protege
I have created an ontology in Protege 5.2 and now I am trying to create correctly the object properties of my corresponding classes. Here is a snippet of my UML diagram according to which I have built my ontology:
Snippet of my ontology

Regarding the isLocated object property, they are characterized in the following way: If a Node X has a SITE value Z, and the same value Z appears in SITEIST of a Location Y, then Node X is Located in Location Y.

Should I look into  SWRL rules or is there some way to encode this without having to go there?

Thank you guys in advance!

答:
In SWRL you can achieve that straightforward:

```<code>locationHasSiteIst(?l, ?s) ^ nodeHasSite(?n, ?s) -> nodeLocatedInLocation(?n, ?l)
</code>```

If you want yo make it in OWL, you need to make locationHasSiteIst and nodeHasSite as object properties, and Site as a class instead of a datatype, then you can use object property chaining and inclusion in Protege as follows:

```<code>nodeHasSite o inverse(locationHasSiteIst) SubPropertyOf nodeLocatedInLocation
</code>```

The last line means that if a node n1 is located in site1, and a location l1 is located in s1 as well, then n1 is located in l1.

Body:
In SWRL you can achieve that straightforward:

locationHasSiteIst(?l, ?s) ^ nodeHasSite(?n, ?s) -> nodeLocatedInLocation(?n, ?l)

If you want yo make it in OWL, you need to make locationHasSiteIst and nodeHasSite as object properties, and Site as a class instead of a datatype, then you can use object property chaining and inclusion in Protege as follows:

nodeHasSite o inverse(locationHasSiteIst) SubPropertyOf nodeLocatedInLocation

The last line means that if a node n1 is located in site1, and a location l1 is located in s1 as well, then n1 is located in l1.


问:
using wp_set_auth_cookie with out any hook
Wordpress version 4.7.5

I am signing up new users from Instagram, I am successfully able signup the new user. after signup I am trying to logged in the user.

I can use hook, but would like better solution than the dirty one, I
  have posted as that will be totally unuseful .

```<code>if( $user_created ) {
    $new_user = get_user_by( 'id', $user_created );
    //$loggedin = programmatic_login( $new_user->user_login );
    //ob_start();
    if ( !is_user_logged_in() ) {
        wp_clear_auth_cookie();
        wp_set_current_user( $user_created, $new_user->user_login );
        wp_set_auth_cookie( $user_created, true );
        do_action( 'wp_login', $new_user->user_login );
        // wp_safe_redirect(site_url() . '/profile/');
        // exit;
        // $redirect_to=user_admin_url();
        // wp_safe_redirect($redirect_to);
        // exit();
    }
    //ob_end_clean();
} ?>
<script>jQuery(document).ready(function(){ window.location.href = "<?php echo site_url() . '/profile/'; ?>";});</script> <?php
</code>```

also tried with a custom programmatic_login function from another post.

if I am trying to var_dump  wp_get_current_user() and $_COOKIE below this, I am getting user object for wp_get_current_user() and array(1) { ["wordpress_test_cookie"]=> string(15) "WP Cookie check" } for $_COOKIE .

Important Edit

The code is inside a function, which is hooked to a hook, that is called in side a page that is after header is getting displayed, so we could not use init here. any other way of doing it and also because of this wp_safe_redirect() or header('Location: ') also not working .

Important Update with what I have just tried

A dirty work around

when I created the user from Instagram login, After successful creation I redirected the user to a page with get parameter something like ?user_id=$inserted_id and on wp hook, I tried to  get the GET['user_id'] and logged it and it worked, trying to find a proper solution.

```<code>if ( $wpdb->insert_id ){  //that is registration with instagram
   ?>
    <script>jQuery(document).ready(function(){ window.location.href = "<?php echo get_bloginfo('url') . '/profile/?id=' . $wpdb->insert_id; ?>";});</script>
   <?php
}
</code>```

and then

```<code>add_action( 'wp', 'login_current_user' );
function login_current_user(){
    if ( is_page() && get_the_id() == 863 ){
        if ( isset( $_GET['id'] ) ){
            if ( !is_user_logged_in() ) {
                $user_id = $_GET['id'];
                $user = get_user_by( 'id', $user_id );
                wp_clear_auth_cookie();
                wp_set_current_user( $user_id, $user->user_login );
                wp_set_auth_cookie( $user_id, true );
                do_action( 'wp_login', $user->user_login );
                if ( is_user_logged_in() ){
                    $redirect_to=site_url() . '/profile';
                    wp_safe_redirect($redirect_to);
                    exit();
                }
            }
        }
    }
}
</code>```

Proble with dirty trick. If the id we are passing as get parameter
  exists in wp_users table then with no verification that will be logged
  in .

Update

I created a user_meta before redirecting to profile page and after verification login the user and removed the usermeta, just like an OTP . Trying to make it better if possible.

Below the code:-

```<code>if ( $wpdb->insert_id ){  //that is registration with instagram
    $temporary_token = sha1(rand());
    update_user_meta( $wpdb->insert_id, 'temporary_token', $temporary_token);
   ?>
    <script>jQuery(document).ready(function(){ window.location.href = "<?php echo get_bloginfo('url') . '/profile/?id=' . $wpdb->insert_id . '&token=' . $temporary_token; ?>";});</script>
   <?php
}
</code>```

and then

```<code>add_action( 'wp', 'login_current_user' );
    function login_current_user(){
        if ( is_page() && get_the_id() == 863 ){
            if ( isset( $_GET['id'] ) ){
                if ( !is_user_logged_in() ) {
                    $user_id = $_GET['id'];
                    $user = get_user_by( 'id', $user_id );
                    if ( $_GET['token'] == get_user_meta( $user_id, 'temporary_token', true ) ){
                        delete_user_meta( $user_id, 'temporary_token', $_GET['token'] );
                        wp_clear_auth_cookie();
                        wp_set_current_user( $user_id, $user->user_login );
                        wp_set_auth_cookie( $user_id, true );
                        do_action( 'wp_login', $user->user_login );
                        if ( is_user_logged_in() ){
                            $redirect_to=site_url() . '/profile';
                            wp_safe_redirect($redirect_to);
                            exit();
                        }
                    }
                }
            }
        }
    }
</code>```

答:
If headers have been sent before wp_clear_auth_cookie() or wp_set_auth_cookie() are called then neither will work as both rely on PHP's setcookie function. The after_setup_theme action will occur before headers have been sent so hooking that and setting the cookies there should fix the issue.

```<code>function myPlugin_createUser(){
  // Probably need to put code that creates user here too otherwise $user_created will never return true
  if( $user_created ) {
      $new_user = get_user_by( 'id', $user_created );
      if ( !is_user_logged_in() ) {
          wp_clear_auth_cookie();
          wp_set_current_user( $user_created, $new_user->user_login );
          wp_set_auth_cookie( $user_created, true );
          do_action( 'wp_login', $new_user->user_login );
      }
  }
}

add_action( 'after_setup_theme', 'myPlugin_createUser' );
</code>```

Update:

If you're outputting view elements before triggering your createUser function it won't work so we need to make sure they run completely independent of each other. Below I've put together a simple example of how to achieve this - to the view we output a link which passes a GET parameter, this parameter is picked up by the plugin and runs the action before anything is rendered allowing us to set the cookie.

my-plugin.php

```<code>// Note: you'll need to include a completed version of myPlugin_createUser() function as above for these examples to work
add_shortcode( 'my-plugin', function() {
   // I've used a GET request for simplicity- a form + POST request may be more practical for your purposes and will prevent caching issues.
   echo "<a href='?my_plugin_login_user=1'>Login</a>";
});

// Check for our GET parameter
if( isset( $_GET['my_plugin_login_user'] ) ) {
  // Nothing should be rendered yet as plugin template hasn't even started loading yet so cookies should set fine
  add_action( 'plugins_loaded', 'myPlugin_createUser' );
}
</code>```

page-my-template.php

```<code><div> ...
    <?php
        do_shortcode( 'my-plugin' );
    ?>
</div>
</code>```

Update 2:
If using Instagrams Authentication API the explicit flow outlined https://www.instagram.com/developer/authentication/ (most of the examples used below are taken from there) is probably the best approach. Below I'll give a brief rundown of how you could implement it. Much of it is taken from there with notes added.

Send the user off to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

You could include the WordPress user ID as a parameter on the callback URL or if the user hasn't yet been created and you need to maintain state then you'll need to generate a temporary token that you can use later that's been associated with said data or store that data client side if it's not sensitive which is probably easier and better as it doesn't require a user to be logged in to function.

The user will then login

Not much to say about this step - if an error occurs they'll be redirected to http://your-redirect-uri?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request

If login is successful the user will be redirected to http://your-redirect-uri?code=CODE

The CODE passed back on the redirect URL we can redeem for an access token.

So from here there's a multitude of ways we can handle it but essentially what we need is an endpoint for the redirect that we have sufficient control over to send HTTP headers before any of the HTTP response body is sent.

Methods of approaching this (not an exhaustive list):

Conditionally hooking on pages Instagram auths are allowed (as in your examples). This has the advantage of not requiring an additional redirect.

Custom page template

External script that manually bootstraps WordPress does what we need, then redirects back in

So now once we've got an endpoint setup we need to redeem the CODEfor an access token. Adapted this snippet from https://gist.github.com/arturmamedov/7f5a90b85a20e06e344ebb88dc898d25

```<code>$uri = 'https://api.instagram.com/oauth/access_token';
$data = [
    'client_id' => '213esdaedasdasd12...YOUR_CLIENT_ID',
    'client_secret' => 'a8b4aaf06c0da310...YOUR_CLIENT_SECRET',
    'grant_type' => 'authorization_code',
    'redirect_uri' => 'http://www.YOUR_REDIRECT_URL.it',      // The exact redirect URL as used previously
    'code' => $_GET['code']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); // uri
curl_setopt($ch, CURLOPT_POST, true); // POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // POST DATA
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN RESULT true
curl_setopt($ch, CURLOPT_HEADER, 0); // RETURN HEADER false
curl_setopt($ch, CURLOPT_NOBODY, 0); // NO RETURN BODY false / we need the body to return
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // VERIFY SSL HOST false
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VERIFY SSL PEER false
$result = json_decode(curl_exec($ch));
</code>```

$result will be an object representation of the JSON response:

```<code>{
"access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
"user": {
    "id": "1574083",
    "username": "snoopdogg",
    "full_name": "Snoop Dogg",
    "profile_picture": "..."
  }
}
</code>```

From here we just create our user/authenticate with WordPress and redirect to the desired page/render the template (no need to redirect if handled via conditional hooks) and restore the page state if needed.

Body:
Wordpress version 4.7.5

I am signing up new users from Instagram, I am successfully able signup the new user. after signup I am trying to logged in the user.

I can use hook, but would like better solution than the dirty one, I
  have posted as that will be totally unuseful .

if( $user_created ) {
    $new_user = get_user_by( 'id', $user_created );
    //$loggedin = programmatic_login( $new_user->user_login );
    //ob_start();
    if ( !is_user_logged_in() ) {
        wp_clear_auth_cookie();
        wp_set_current_user( $user_created, $new_user->user_login );
        wp_set_auth_cookie( $user_created, true );
        do_action( 'wp_login', $new_user->user_login );
        // wp_safe_redirect(site_url() . '/profile/');
        // exit;
        // $redirect_to=user_admin_url();
        // wp_safe_redirect($redirect_to);
        // exit();
    }
    //ob_end_clean();
} ?>
 <?php

also tried with a custom programmatic_login function from another post.

if I am trying to var_dump  wp_get_current_user() and $_COOKIE below this, I am getting user object for wp_get_current_user() and array(1) { ["wordpress_test_cookie"]=> string(15) "WP Cookie check" } for $_COOKIE .

Important Edit

The code is inside a function, which is hooked to a hook, that is called in side a page that is after header is getting displayed, so we could not use init here. any other way of doing it and also because of this wp_safe_redirect() or header('Location: ') also not working .

Important Update with what I have just tried

A dirty work around

when I created the user from Instagram login, After successful creation I redirected the user to a page with get parameter something like ?user_id=$inserted_id and on wp hook, I tried to  get the GET['user_id'] and logged it and it worked, trying to find a proper solution.

if ( $wpdb->insert_id ){  //that is registration with instagram
   ?>

   <?php
}

and then

add_action( 'wp', 'login_current_user' );
function login_current_user(){
    if ( is_page() && get_the_id() == 863 ){
        if ( isset( $_GET['id'] ) ){
            if ( !is_user_logged_in() ) {
                $user_id = $_GET['id'];
                $user = get_user_by( 'id', $user_id );
                wp_clear_auth_cookie();
                wp_set_current_user( $user_id, $user->user_login );
                wp_set_auth_cookie( $user_id, true );
                do_action( 'wp_login', $user->user_login );
                if ( is_user_logged_in() ){
                    $redirect_to=site_url() . '/profile';
                    wp_safe_redirect($redirect_to);
                    exit();
                }
            }
        }
    }
}

Proble with dirty trick. If the id we are passing as get parameter
  exists in wp_users table then with no verification that will be logged
  in .

Update

I created a user_meta before redirecting to profile page and after verification login the user and removed the usermeta, just like an OTP . Trying to make it better if possible.

Below the code:-

if ( $wpdb->insert_id ){  //that is registration with instagram
    $temporary_token = sha1(rand());
    update_user_meta( $wpdb->insert_id, 'temporary_token', $temporary_token);
   ?>

   <?php
}

and then

add_action( 'wp', 'login_current_user' );
    function login_current_user(){
        if ( is_page() && get_the_id() == 863 ){
            if ( isset( $_GET['id'] ) ){
                if ( !is_user_logged_in() ) {
                    $user_id = $_GET['id'];
                    $user = get_user_by( 'id', $user_id );
                    if ( $_GET['token'] == get_user_meta( $user_id, 'temporary_token', true ) ){
                        delete_user_meta( $user_id, 'temporary_token', $_GET['token'] );
                        wp_clear_auth_cookie();
                        wp_set_current_user( $user_id, $user->user_login );
                        wp_set_auth_cookie( $user_id, true );
                        do_action( 'wp_login', $user->user_login );
                        if ( is_user_logged_in() ){
                            $redirect_to=site_url() . '/profile';
                            wp_safe_redirect($redirect_to);
                            exit();
                        }
                    }
                }
            }
        }
    }

Body:
If headers have been sent before wp_clear_auth_cookie() or wp_set_auth_cookie() are called then neither will work as both rely on PHP's setcookie function. The after_setup_theme action will occur before headers have been sent so hooking that and setting the cookies there should fix the issue.

function myPlugin_createUser(){
  // Probably need to put code that creates user here too otherwise $user_created will never return true
  if( $user_created ) {
      $new_user = get_user_by( 'id', $user_created );
      if ( !is_user_logged_in() ) {
          wp_clear_auth_cookie();
          wp_set_current_user( $user_created, $new_user->user_login );
          wp_set_auth_cookie( $user_created, true );
          do_action( 'wp_login', $new_user->user_login );
      }
  }
}

add_action( 'after_setup_theme', 'myPlugin_createUser' );

Update:

If you're outputting view elements before triggering your createUser function it won't work so we need to make sure they run completely independent of each other. Below I've put together a simple example of how to achieve this - to the view we output a link which passes a GET parameter, this parameter is picked up by the plugin and runs the action before anything is rendered allowing us to set the cookie.

my-plugin.php

// Note: you'll need to include a completed version of myPlugin_createUser() function as above for these examples to work
add_shortcode( 'my-plugin', function() {
   // I've used a GET request for simplicity- a form + POST request may be more practical for your purposes and will prevent caching issues.
   echo "<a href='?my_plugin_login_user=1'>Login</a>";
});

// Check for our GET parameter
if( isset( $_GET['my_plugin_login_user'] ) ) {
  // Nothing should be rendered yet as plugin template hasn't even started loading yet so cookies should set fine
  add_action( 'plugins_loaded', 'myPlugin_createUser' );
}

page-my-template.php

<div> ...
    <?php
        do_shortcode( 'my-plugin' );
    ?>
</div>

Update 2:
If using Instagrams Authentication API the explicit flow outlined https://www.instagram.com/developer/authentication/ (most of the examples used below are taken from there) is probably the best approach. Below I'll give a brief rundown of how you could implement it. Much of it is taken from there with notes added.

Send the user off to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

You could include the WordPress user ID as a parameter on the callback URL or if the user hasn't yet been created and you need to maintain state then you'll need to generate a temporary token that you can use later that's been associated with said data or store that data client side if it's not sensitive which is probably easier and better as it doesn't require a user to be logged in to function.

The user will then login

Not much to say about this step - if an error occurs they'll be redirected to http://your-redirect-uri?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request

If login is successful the user will be redirected to http://your-redirect-uri?code=CODE

The CODE passed back on the redirect URL we can redeem for an access token.

So from here there's a multitude of ways we can handle it but essentially what we need is an endpoint for the redirect that we have sufficient control over to send HTTP headers before any of the HTTP response body is sent.

Methods of approaching this (not an exhaustive list):

Conditionally hooking on pages Instagram auths are allowed (as in your examples). This has the advantage of not requiring an additional redirect.

Custom page template

External script that manually bootstraps WordPress does what we need, then redirects back in

So now once we've got an endpoint setup we need to redeem the CODEfor an access token. Adapted this snippet from https://gist.github.com/arturmamedov/7f5a90b85a20e06e344ebb88dc898d25

$uri = 'https://api.instagram.com/oauth/access_token';
$data = [
    'client_id' => '213esdaedasdasd12...YOUR_CLIENT_ID',
    'client_secret' => 'a8b4aaf06c0da310...YOUR_CLIENT_SECRET',
    'grant_type' => 'authorization_code',
    'redirect_uri' => 'http://www.YOUR_REDIRECT_URL.it',      // The exact redirect URL as used previously
    'code' => $_GET['code']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); // uri
curl_setopt($ch, CURLOPT_POST, true); // POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // POST DATA
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN RESULT true
curl_setopt($ch, CURLOPT_HEADER, 0); // RETURN HEADER false
curl_setopt($ch, CURLOPT_NOBODY, 0); // NO RETURN BODY false / we need the body to return
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // VERIFY SSL HOST false
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VERIFY SSL PEER false
$result = json_decode(curl_exec($ch));

$result will be an object representation of the JSON response:

{
"access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
"user": {
    "id": "1574083",
    "username": "snoopdogg",
    "full_name": "Snoop Dogg",
    "profile_picture": "..."
  }
}

From here we just create our user/authenticate with WordPress and redirect to the desired page/render the template (no need to redirect if handled via conditional hooks) and restore the page state if needed.


问:
How to Rollback the ngModel two Way binding data in angular2
I have a form in angular 2 with two way binding data value ([(ngModel)]) for edit and add functionality.

User clicks the edit from the listing page and changes the value in the input , while editing the changed(new) values appear in the list page also, instead of the save clicks cancel button. Need to display the old value in listing page.

```<code>project-form.component.html
---------------------------
   <input class="form-control"  type="text" size="30" pInputText [(ngModel)]="project.title" name="title" pTooltip="Enter your username"/>

    <ul class="list-group">
          <li *ngFor="let event of project" class="list-group-item">
            <span class="event_release">{{event.startDate | date: 'dd/MM/yyyy'}} </span><br />
            <strong>{{event.title}}</strong>
          </li>
        </ul>

Project-form.component.ts
-------------------------
@Input() project: Project;
</code>```

While submitting sending the variable  (this.project) holds updated values (tow way binding variable), need to be roll-backed if the user click the cancel button (this.project).

答:
just create a deep copy of project object. the problem you are facing is due the fact that list page and edit page is working on same copy of the object so change the object at one place will be reflected in other place also.

use this javascript code(do this in edit page)

let project_copy =JSON.parse(JSON.stringify(project))

and then in edit instead of working on project variable work with this project_copy

Body:
I have a form in angular 2 with two way binding data value ([(ngModel)]) for edit and add functionality.

User clicks the edit from the listing page and changes the value in the input , while editing the changed(new) values appear in the list page also, instead of the save clicks cancel button. Need to display the old value in listing page.

project-form.component.html
---------------------------
   <input class="form-control"  type="text" size="30" pInputText [(ngModel)]="project.title" name="title" pTooltip="Enter your username"/>

            {{event.startDate | date: 'dd/MM/yyyy'}}

            {{event.title}}

Project-form.component.ts
-------------------------
@Input() project: Project;

While submitting sending the variable  (this.project) holds updated values (tow way binding variable), need to be roll-backed if the user click the cancel button (this.project).


问:
Dagger 2 error: android.content.Context cannot be provided without an @Provides-annotated method
I am working on implementing dagger 2 in my project. For this, i have written below lines of code:

```<code>@Inject
VideoControllerView mediaController;

@Module
public class PlayerModule {

    @Provides
    VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
        return new VideoControllerView(context, cntrls);
    }
}

@Component(modules = PlayerModule.class)
public interface PlayerComponent {
    VideoControllerView getVideoControllerView();
}
</code>```

But when i am trying to compile my app, i am getting below given error:

```<code>Error:(14, 25) error: android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at
com.multitv.multitvplayersdk.module.PlayerModule.providesVideoControllerView(context, …)
com.multitv.multitvplayersdk.controls.VideoControllerView is provided at
com.multitv.multitvplayersdk.component.PlayerComponent.getVideoControllerView()
</code>```

I have looked around on how to resolve this issue but of no avail. Please help me.

答:
Please try to understand the error.

PlayerModule.providesVideoControllerView(context, …) requires a context, but Dagger does not have access to any Context object, so it cannot pass in any Context. It thus creates the error, telling you that it can't find any Context and that you should add a way for it to do so.

Context cannot be provided without an @Provides-annotated method.

Hence...A context cannot be provided without a @Provides-annotated method.

Make sure that the component your PlayerModule is a part of has access to a context.

Either make it a subcomponent of your ApplicationComponent, add a Context to your PlayerModule, bind your Activity instance as a Context, etc

There's a lot of ways to do this, but in the end you require a method like the following in one of your modules:

```<code>@Provides Context provideContext() { return myContext; }
</code>```

Once Dagger can find a Context the error will go away.

Body:
I am working on implementing dagger 2 in my project. For this, i have written below lines of code:

@Inject
VideoControllerView mediaController;

@Module
public class PlayerModule {

    @Provides
    VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
        return new VideoControllerView(context, cntrls);
    }
}

@Component(modules = PlayerModule.class)
public interface PlayerComponent {
    VideoControllerView getVideoControllerView();
}

But when i am trying to compile my app, i am getting below given error:

Error:(14, 25) error: android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at
com.multitv.multitvplayersdk.module.PlayerModule.providesVideoControllerView(context, …)
com.multitv.multitvplayersdk.controls.VideoControllerView is provided at
com.multitv.multitvplayersdk.component.PlayerComponent.getVideoControllerView()

I have looked around on how to resolve this issue but of no avail. Please help me.

Body:
Please try to understand the error.

PlayerModule.providesVideoControllerView(context, …) requires a context, but Dagger does not have access to any Context object, so it cannot pass in any Context. It thus creates the error, telling you that it can't find any Context and that you should add a way for it to do so.

Context cannot be provided without an @Provides-annotated method.

Hence...A context cannot be provided without a @Provides-annotated method.

Make sure that the component your PlayerModule is a part of has access to a context.

Either make it a subcomponent of your ApplicationComponent, add a Context to your PlayerModule, bind your Activity instance as a Context, etc

There's a lot of ways to do this, but in the end you require a method like the following in one of your modules:

@Provides Context provideContext() { return myContext; }

Once Dagger can find a Context the error will go away.


问:
New e-commerce website. Use a framework or start fresh?
I am looking to build an e-commerce website and have it ready within a month or so. The website is nothing complicated, it is a bunch of products that will be sorted by category and provide online check out. I actually have already started and almost finished it, but I'm using drupal 7 and Ubercart. It is my first time building a drupal site and was following a tutorial, then I noticed how outdated the stuff I'm using are. Would you recommend  starting fresh with a drupal 8 core and using the commerce module?
I've seen many benefits to this, but I'm not entirely sure it's worth it, since commerce module on drupal 8 is still in beta and payment gateways such as stripe which I'm looking to use, and I believe many more useful ones aren't developed for drupal 8 yet. Any advice would be appreciated. Thank you!  </p>

答:
Your questions is opinion based and it will probably be closed because of that, but I'll give you my (opinion based) answer anyway.

If you want to develop e-commerce site fast and you don't need too much customization then Ubercart is probably best solution Drupal world can offer you. Drupal commerce could give you more, but it's also more demanding. You would need more time to make website in it (if you are not experienced with DC).

About D8 vs. D7 dilemma  - IMHO, D8 is still not mature enough. Lot of modules are still missing, lot of them in alpha / beta state.

So if it's working and it's not making you any problems I would stick with it.

ContentLicense: CC BY-SA 4.0


问:
TSLint get rid of missing-whitespace
I've been trying to scour the internet to solve this but to no avail. Perhaps you can help me. I am getting tslint 'missing whitespace' warnings that say something like:

WARNING in ./src/app/content/content.controller.ts
[4, 13]: missing whitespace
[5, 21]: missing whitespace

I want to get rid of the warning

Here's an example of the code.... basically anywhere I have a colon for declaring type is where the error is happening. I don't want to put a space between it so I'd like the linter to not bug me about it...

```<code>export class ContentCtrl {
filters:IFilter[];
selectedFilters:IFilter[];
filterToAdd:IFilter;

/** @ngInject */
constructor(private $log:angular.ILogService,
            private $timeout:any,
            private toastr:any,
            private filterService:FilterService) {
    const self = this;
</code>```

I looked through the tslint.json file and could not figure out how to get rid of it.

I saw a promising property that said: "typedef-whitespace"

I changed it to the following but, alas, to no-avail:

```<code>"typedef-whitespace": [true,
        {
            "callSignature": "noSpace",
            "catchClause": "noSpace",
            "indexSignature": "noSpace",
            "parameter": "noSpace"
        }
    ],
</code>```

How do I get rid of the 'missing whitespace' error?

答:
You should search whitespace in tslint.json,and replace all result whith false.

And you questions can set like there:

```<code>"whitespace": [
  false,
  "check-branch",
  "check-decl",
  "check-operator",
  "check-separator",
  "check-type"
],
</code>```

set it ,if you write private nima:string, : with no space will no err.

other,

if you set one-line 's metadata to false,the class can  follow no space.

if yout set no-trailing-whitespace to false, the line can use tab.

——end

Title: TSLint get rid of missing-whitespace

Body:
I've been trying to scour the internet to solve this but to no avail. Perhaps you can help me. I am getting tslint 'missing whitespace' warnings that say something like:

WARNING in ./src/app/content/content.controller.ts
[4, 13]: missing whitespace
[5, 21]: missing whitespace

I want to get rid of the warning

Here's an example of the code.... basically anywhere I have a colon for declaring type is where the error is happening. I don't want to put a space between it so I'd like the linter to not bug me about it...

export class ContentCtrl {
filters:IFilter[];
selectedFilters:IFilter[];
filterToAdd:IFilter;

/** @ngInject */
constructor(private $log:angular.ILogService,
            private $timeout:any,
            private toastr:any,
            private filterService:FilterService) {
    const self = this;

I looked through the tslint.json file and could not figure out how to get rid of it.

I saw a promising property that said: "typedef-whitespace"

I changed it to the following but, alas, to no-avail:

"typedef-whitespace": [true,
        {
            "callSignature": "noSpace",
            "catchClause": "noSpace",
            "indexSignature": "noSpace",
            "parameter": "noSpace"
        }
    ],

How do I get rid of the 'missing whitespace' error?

Body:
You should search whitespace in tslint.json,and replace all result whith false.

And you questions can set like there:

"whitespace": [
  false,
  "check-branch",
  "check-decl",
  "check-operator",
  "check-separator",
  "check-type"
],

set it ,if you write private nima:string, : with no space will no err.

other,

if you set one-line 's metadata to false,the class can  follow no space.

if yout set no-trailing-whitespace to false, the line can use tab.

——end


问:
How to take PostgreSQL database backup using Java
I want to use a PostgreSQL db for backup using java.
I've tried with the below code but I am getting:

error pg_dump: too many command-line arguments (first is " postgres") Try "pg_dump --help" for more information.

```<code>Runtime r = Runtime.getRuntime();
Process p;
ProcessBuilder pb;
r = Runtime.getRuntime();
pb = new ProcessBuilder(
        "/usr/pgsql-9.3/bin/pg_dump",
        "--host", "localhost",
        "--port", "5432",
        "--username", "postgres",
        "--dbname", "postfixdb",
        "--role", "postgres",
        "--password"," postgres",
        "--verbose",
       "/usr/pg_dump.backup");
pb.redirectErrorStream(true);
p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String ll;
while ((ll = br.readLine()) != null) { System.out.println(ll); }
</code>```

答:
Consult the psql documentation for the invocation syntax and a list of allowed options.

Try to run it on the command line first, and only when that succeeds, try to run it from Java.

A list ob obvious mistakes:

The option for “user” is -U (capitalized).

-p is for the TCP port number.

There is no -B option.

There is no -r option.

Body:
I want to use a PostgreSQL db for backup using java.
I've tried with the below code but I am getting:

error pg_dump: too many command-line arguments (first is " postgres") Try "pg_dump --help" for more information.

Runtime r = Runtime.getRuntime();
Process p;
ProcessBuilder pb;
r = Runtime.getRuntime();
pb = new ProcessBuilder(
        "/usr/pgsql-9.3/bin/pg_dump",
        "--host", "localhost",
        "--port", "5432",
        "--username", "postgres",
        "--dbname", "postfixdb",
        "--role", "postgres",
        "--password"," postgres",
        "--verbose",
       "/usr/pg_dump.backup");
pb.redirectErrorStream(true);
p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String ll;
while ((ll = br.readLine()) != null) { System.out.println(ll); }


问:
Python: Google API if loop
I'm checking Google API response:

```<code>url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {'location': '-38.30000000,176.15000000',
          'radius': '5000',
          'type': 'movie_theater',
          'key': 'MY_KEY'}
response = requests.get(url = url, params=params)
# if response.status_code == 200:
response_data = response.json()

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')
</code>```

If you search with Postman for that specific location:

```<code>https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY
</code>```

there are no cinemas and Google API reports:

```<code>{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}
</code>```

unfortunately my if, elif seems not working because it doesn't print nothing.
Where am I wrong?

答:
But "results" is in the response data. It just contains an empty list.

One way of fixing this might be to swap the order of your conditions.

Title: Python: Google API if loop

Body:
I'm checking Google API response:

url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {'location': '-38.30000000,176.15000000',
          'radius': '5000',
          'type': 'movie_theater',
          'key': 'MY_KEY'}
response = requests.get(url = url, params=params)
# if response.status_code == 200:
response_data = response.json()

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

If you search with Postman for that specific location:

https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY

there are no cinemas and Google API reports:

{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}

unfortunately my if, elif seems not working because it doesn't print nothing.
Where am I wrong?


问:
remove extra + from text SQL
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

```<code>Name     Value
A+B+C+   1+2+3+
A++B     1++2
</code>```

this should be updated to

```<code>   Name     Value
    A+B+C   1+2+3
    A+B     1+2
</code>```

once this update has taken place, I can run the solution provided in the previous question.

Thanks

答:
You need to replace ++ with + and to remove the + at the end of the string.

```<code>/* sample data */
with input(Name, Value) as (
                            select 'A+B+C+'   ,'1+2+3+' from dual union all
                            select 'A++B'     ,'1++2'   from dual
                            )
/* query */
select trim('+' from regexp_replace(name,  '\+{2,}', '+') ) as name,
       trim('+' from regexp_replace(value, '\+{2,}', '+') ) as value
from input
</code>```

If you need to update a table, you may need:

```<code>update yourTable
set name = trim('+' from regexp_replace(name, '\+{2,}', '+') ),
    value= trim('+' from regexp_replace(value, '\+{2,}', '+') )
</code>```

In a more compact way, without the external trim ( assuming you have no leading +):

```<code>/* sample data */
with input(Name, Value) as (
                            select 'A+B+C+'      ,'1+2+3+' from dual union all
                            select 'A++B+++C+'   ,'1++2+++3+' from dual union all
                            select 'A+B'         ,'1+2'   from dual
                            )
/* query */
select regexp_replace(name,  '(\+)+(\+|$)', '\2') as name,
       regexp_replace(value, '(\+)+(\+|$)', '\2') as value
from input
</code>```

Title: remove extra + from text SQL

Body:
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

Name     Value
A+B+C+   1+2+3+
A++B     1++2

this should be updated to

   Name     Value
    A+B+C   1+2+3
    A+B     1+2

once this update has taken place, I can run the solution provided in the previous question.

Thanks

Body:
You need to replace ++ with + and to remove the + at the end of the string.

/* sample data */
with input(Name, Value) as (
                            select 'A+B+C+'   ,'1+2+3+' from dual union all
                            select 'A++B'     ,'1++2'   from dual
                            )
/* query */
select trim('+' from regexp_replace(name,  '\+{2,}', '+') ) as name,
       trim('+' from regexp_replace(value, '\+{2,}', '+') ) as value
from input

If you need to update a table, you may need:

update yourTable
set name = trim('+' from regexp_replace(name, '\+{2,}', '+') ),
    value= trim('+' from regexp_replace(value, '\+{2,}', '+') )

In a more compact way, without the external trim ( assuming you have no leading +):

/* sample data */
with input(Name, Value) as (
                            select 'A+B+C+'      ,'1+2+3+' from dual union all
                            select 'A++B+++C+'   ,'1++2+++3+' from dual union all
                            select 'A+B'         ,'1+2'   from dual
                            )
/* query */
select regexp_replace(name,  '(\+)+(\+|$)', '\2') as name,
       regexp_replace(value, '(\+)+(\+|$)', '\2') as value
from input


问:
Unable to display relations data from eloquent relationship
I'm trying to display in my view data from an eloquent relationship but i seem to be doing a tiny bit wrong. dd shows the relation in the collection but i just can't call the data correctly in my view. Below is what i have done

Employee model

```<code>public function task()
{
    return $this->hasMany(Task::class);
}
</code>```

Task model

```<code>public function employee()
{
    return $this->belongsTo(Employee::class);
}
</code>```

TaskController

```<code>public function index()
{
    $alltask = Task::with('employee')->get();

    dd($alltask);

    /*return view('task.task', compact('alltask', 'empwithtask'));*/
}
</code>```

task view

```<code>@foreach ($alltask as $task)
<tr>
    <td>{{ $task->priority }}</td>
    <td>{{ $task->firstname }}</td>
    /* this is meant to be the  employee.firstname */
    <td>{{ $task->title }}</td>
    <td>{{ $task->begin }}</td>
</tr>
@endforeach
</code>```

I'm not able to display $task->firstname, firstname is from the employees table. Below is a snapshot of the result of dd

How do I show the employee firstname?

Body:
I'm trying to display in my view data from an eloquent relationship but i seem to be doing a tiny bit wrong. dd shows the relation in the collection but i just can't call the data correctly in my view. Below is what i have done

Employee model

public function task()
{
    return $this->hasMany(Task::class);
}

Task model

public function employee()
{
    return $this->belongsTo(Employee::class);
}

TaskController

public function index()
{
    $alltask = Task::with('employee')->get();

    dd($alltask);

    /*return view('task.task', compact('alltask', 'empwithtask'));*/
}

task view

@foreach ($alltask as $task)

    {{ $task->priority }}
    {{ $task->firstname }}
    /* this is meant to be the  employee.firstname */
    {{ $task->title }}
    {{ $task->begin }}

@endforeach

I'm not able to display $task->firstname, firstname is from the employees table. Below is a snapshot of the result of dd

How do I show the employee firstname?

Body: $task->employee->firstname


问:
Python ftplib.error_perm 550: No such file or directory?
I've written a Python script that is part of my attempt to automate daily ftp transfers from my server. I've tested the script with a number of files and file types (html, mp3, png, jpg, etc.) and everything seems to work out fine so far.
However, when I try to download a simple text file, 'file.txt' (9 kb), the download fails, although I account for text files and switch from binary to text mode for the transfer. The following exception is thrown by ftplib:

```<code>ftplib.error_perm: 550 file.txt: No such file or directory
</code>```

Here's my script:

```<code>from ftplib import FTP_TLS, error_perm
import os

def open_connection(server, user, pwd, work_dir=None):
    global ftps
    try:
        ftps = FTP_TLS(host=server)
        ftps.login(user=user, passwd=pwd)
        ftps.prot_p() # switch to secure data connection
        if work_dir != None:
           ftps.cwd(work_dir)
        else:
            pass
    except:
        pass

def download_file(remote_path, local_path):
    remote_file = os.path.basename(remote_path)
    local_file_path = os.path.join(local_path, remote_file)

    # differentiate between text and binary files
    file_type, encoding = guess_type_and_encoding(remote_file)

    # possibly needs a permission exception catch
    if file_type.split("/")[0] == "text" and encoding == None:
        # use text mode for transfer
        local_file = open(local_file_path, 'w')
        def callback(line): local_file.write(line + "\n")
        ftps.retrlines("RETR " + remote_file, callback)
        local_file.close()

    else:
        # use binary mode for transfer
        local_file = open(local_file_path, 'wb')
        ftps.retrbinary("RETR " + remote_file, local_file.write)
        local_file.close()
    return

def guess_type_and_encoding(filename):
    from mimetypes import guess_type, add_type
    add_type('text/x-python-win', '.pyw') # not in tables
    mimetype, encoding = guess_type(filename, False) # allow extras
    mimetype = mimetype or "?/?" # type unknown
    return mimetype, encoding

open_connection(server, user, pwd, work_dir)
download_file("/files/dir/file.txt", "/Users/username/Desktop")
ftps.close()
</code>```

I don't get why the error is raised!? The arguments 'remote_path' and 'local_path' are correctly provided. Both paths exist! 'file.txt' exists on the server under /files/dir and /Users/username/Desktop points to my desktop on OS X.

Here's the detailed ftplib error:

```<code>Traceback (most recent call last):
    File "ftp2.py", line 138, in <module>
        download_file("/files/dir/file.txt", "/Users/username/Desktop")
    File "ftp2.py", line 93, in download_file
        ftps.retrlines("RETR " + remote_file, callback)
    File  "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 735, in retrlines
        conn = self.transfercmd(cmd)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 376, in transfercmd
        return self.ntransfercmd(cmd, rest)[0]
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 710, in ntransfercmd
        conn, size = FTP.ntransfercmd(self, cmd, rest)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 339, in ntransfercmd
        resp = self.sendcmd(cmd)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 249, in sendcmd
        return self.getresp()
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 224, in getresp
        raise error_perm, resp
ftplib.error_perm: 550 file.txt: No such file or directory
</code>```

Any help is greatly appreciated.
Thanks. :)

答:
Try to
replace remote_file
in ftps.retrlines("RETR " + remote_file, callback)
with remote_path.

Body:
I've written a Python script that is part of my attempt to automate daily ftp transfers from my server. I've tested the script with a number of files and file types (html, mp3, png, jpg, etc.) and everything seems to work out fine so far.
However, when I try to download a simple text file, 'file.txt' (9 kb), the download fails, although I account for text files and switch from binary to text mode for the transfer. The following exception is thrown by ftplib:

ftplib.error_perm: 550 file.txt: No such file or directory

Here's my script:

from ftplib import FTP_TLS, error_perm
import os

def open_connection(server, user, pwd, work_dir=None):
    global ftps
    try:
        ftps = FTP_TLS(host=server)
        ftps.login(user=user, passwd=pwd)
        ftps.prot_p() # switch to secure data connection
        if work_dir != None:
           ftps.cwd(work_dir)
        else:
            pass
    except:
        pass

def download_file(remote_path, local_path):
    remote_file = os.path.basename(remote_path)
    local_file_path = os.path.join(local_path, remote_file)

    # differentiate between text and binary files
    file_type, encoding = guess_type_and_encoding(remote_file)

    # possibly needs a permission exception catch
    if file_type.split("/")[0] == "text" and encoding == None:
        # use text mode for transfer
        local_file = open(local_file_path, 'w')
        def callback(line): local_file.write(line + "\n")
        ftps.retrlines("RETR " + remote_file, callback)
        local_file.close()

    else:
        # use binary mode for transfer
        local_file = open(local_file_path, 'wb')
        ftps.retrbinary("RETR " + remote_file, local_file.write)
        local_file.close()
    return

def guess_type_and_encoding(filename):
    from mimetypes import guess_type, add_type
    add_type('text/x-python-win', '.pyw') # not in tables
    mimetype, encoding = guess_type(filename, False) # allow extras
    mimetype = mimetype or "?/?" # type unknown
    return mimetype, encoding

open_connection(server, user, pwd, work_dir)
download_file("/files/dir/file.txt", "/Users/username/Desktop")
ftps.close()

I don't get why the error is raised!? The arguments 'remote_path' and 'local_path' are correctly provided. Both paths exist! 'file.txt' exists on the server under /files/dir and /Users/username/Desktop points to my desktop on OS X.

Here's the detailed ftplib error:

Traceback (most recent call last):
    File "ftp2.py", line 138, in <module>
        download_file("/files/dir/file.txt", "/Users/username/Desktop")
    File "ftp2.py", line 93, in download_file
        ftps.retrlines("RETR " + remote_file, callback)
    File  "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 735, in retrlines
        conn = self.transfercmd(cmd)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 376, in transfercmd
        return self.ntransfercmd(cmd, rest)[0]
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 710, in ntransfercmd
        conn, size = FTP.ntransfercmd(self, cmd, rest)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 339, in ntransfercmd
        resp = self.sendcmd(cmd)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 249, in sendcmd
        return self.getresp()
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 224, in getresp
        raise error_perm, resp
ftplib.error_perm: 550 file.txt: No such file or directory

Any help is greatly appreciated.
Thanks. :)