问:
Error print user.default swift 3
I have two screens the first of login and the second shows the user information. On the login screen I keep the user_id value in user.defaults and when I go to the second screen I use that value to call a web service and show its information, but I have an error and that the value saved in user.default is nil. and finally when user click cerrar_sesion I remove the user.defaults How can I solve it? This is my code:

```<code>func login(){
        let id_usuario = 7
        Constants.lbd.set(id_usuario, forKey: "id_usuario")
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.synchronize()
}
</code>```

Second view:

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        btn_cerrarSesion.addTarget(self, action: #selector(cerar_sesion), for: .touchUpInside)
        info_usuario()
}

    func info_usuario(){
            let auth = "ASASDWDASD!"
            let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
print(id_usuario)
            Services.objServices.ServObtUsuario(auth: auth!, id_usuario: id_usuario!).then{
                data -> Void in
                let res = JSON(data)
                let status = res["status"].boolValue
                if(status){
                    let info_usuario = res["data"]["usuarios"]
                    for(_, sub_res):(String, JSON) in info_usuario{
                        self.lbl_nombres_usuario.text = sub_res["nombres"].stringValue+" "+sub_res["apellidos"].stringValue
                        self.lbl_username.text = sub_res["username"].stringValue
                    }
                }else{
                    let error = res["error"]["error_data"].stringValue
                    print(error)
                }
                }.catch{
                    error -> Void in
            }
        }

func cerar_sesion(){
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.object(forKey: "id_usuario")
        Constants.lbd.removeObject(forKey: "id_empresa")
        Constants.lbd.removeObject(forKey: "rol")
        Constants.lbd.removeObject(forKey: "auth")
        Constants.lbd.synchronize()
    }
</code>```

finally I get this in console:
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks in advance

答:
You need to call synchronize method of Userdefaults immediately after saving the value.

By default, user default will take some time to save the new value into Plist.

The only disadvantage of calling synchronizes method of Userdefaults is it will take process time.

Additionally, avoid forced unwrapping.

Title: Error print user.default swift 3

Body:
I have two screens the first of login and the second shows the user information. On the login screen I keep the user_id value in user.defaults and when I go to the second screen I use that value to call a web service and show its information, but I have an error and that the value saved in user.default is nil. and finally when user click cerrar_sesion I remove the user.defaults How can I solve it? This is my code:

func login(){
        let id_usuario = 7
        Constants.lbd.set(id_usuario, forKey: "id_usuario")
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.synchronize()
}

Second view:

override func viewDidLoad() {
        super.viewDidLoad()
        btn_cerrarSesion.addTarget(self, action: #selector(cerar_sesion), for: .touchUpInside)
        info_usuario()
}

    func info_usuario(){
            let auth = "ASASDWDASD!"
            let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
print(id_usuario)
            Services.objServices.ServObtUsuario(auth: auth!, id_usuario: id_usuario!).then{
                data -> Void in
                let res = JSON(data)
                let status = res["status"].boolValue
                if(status){
                    let info_usuario = res["data"]["usuarios"]
                    for(_, sub_res):(String, JSON) in info_usuario{
                        self.lbl_nombres_usuario.text = sub_res["nombres"].stringValue+" "+sub_res["apellidos"].stringValue
                        self.lbl_username.text = sub_res["username"].stringValue
                    }
                }else{
                    let error = res["error"]["error_data"].stringValue
                    print(error)
                }
                }.catch{
                    error -> Void in
            }
        }

func cerar_sesion(){
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.object(forKey: "id_usuario")
        Constants.lbd.removeObject(forKey: "id_empresa")
        Constants.lbd.removeObject(forKey: "rol")
        Constants.lbd.removeObject(forKey: "auth")
        Constants.lbd.synchronize()
    }

finally I get this in console:
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks in advance


来源: stackexchange

问:
Why does this simple Java bytecode cause a StackOverflow error?
I need to instrument native methods to make a simple static call before executing normally. Because the methods are native, I have to use the "setNativePrefix" feature and wrap the native methods with an intermediate call with the original method signature.

After what I thought was a simple bytecode change to accomplish this, I'm getting a StackOverflowError right before the wrapper method gets executed even though the stack is basically empty. Here's my test class:

```<code>public class SimpleTest {
    public static void main(String[] args) throws IOException {
        Perf.getPerf().highResCounter();
    }
}
</code>```

Normally, that program would produce nothing on the console. However, my instrumented bytecode executes a println() before executing the native method $wrapper$highResCounter(). This can be seen in the relevant Perf class bytecode after instrumentation:

```<code>public long highResCounter() {
    getstatic PrintStream System.out
    ldc String Constant "this is an instrumented println"
    invokevirtual void PrintStream.println(String)
    aload 0
    invokevirtual long Perf.$wrapped$highResCounter()
    lreturn
}

public native long $wrapped$highResCounter();
</code>```

I'm sort of new to Java bytecode, so I probably made a mistake here. Here's the output of the program, which shows that the println() gets executed, but somewhere after the first
invokevirtual call a StackOverflowError is thrown:

```<code>this is an instrumented println call
Exception in thread "main" java.lang.StackOverflowError
   at com.foo.SimpleTest.main(SimpleTest.java:17)
</code>```

What could be causing this StackOverflowError? And how do I fix it?

答:
Your highResCounter method is calling itself:

```<code>public long highResCounter() {
    [...]
    invokevirtual long Perf.$wrapped$highResCounter()
</code>```

Do you have any more code you can show us to find out why?

ContentLicense: CC BY-SA 2.5

Body:
I need to instrument native methods to make a simple static call before executing normally. Because the methods are native, I have to use the "setNativePrefix" feature and wrap the native methods with an intermediate call with the original method signature.

After what I thought was a simple bytecode change to accomplish this, I'm getting a StackOverflowError right before the wrapper method gets executed even though the stack is basically empty. Here's my test class:

public class SimpleTest {
    public static void main(String[] args) throws IOException {
        Perf.getPerf().highResCounter();
    }
}

Normally, that program would produce nothing on the console. However, my instrumented bytecode executes a println() before executing the native method $wrapper$highResCounter(). This can be seen in the relevant Perf class bytecode after instrumentation:

public long highResCounter() {
    getstatic PrintStream System.out
    ldc String Constant "this is an instrumented println"
    invokevirtual void PrintStream.println(String)
    aload 0
    invokevirtual long Perf.$wrapped$highResCounter()
    lreturn
}

public native long $wrapped$highResCounter();

I'm sort of new to Java bytecode, so I probably made a mistake here. Here's the output of the program, which shows that the println() gets executed, but somewhere after the first
invokevirtual call a StackOverflowError is thrown:

this is an instrumented println call
Exception in thread "main" java.lang.StackOverflowError
   at com.foo.SimpleTest.main(SimpleTest.java:17)

What could be causing this StackOverflowError? And how do I fix it?

Body:
Your highResCounter method is calling itself:

public long highResCounter() {
    [...]
    invokevirtual long Perf.$wrapped$highResCounter()

Do you have any more code you can show us to find out why?


问:
How to decide with duplicate values on column VBA
If I have the following table:

```<code>Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
host1 | N/A     | N/A
host1 | 1.1.1.1 | N/A
host1 | N/A     | Windows
</code>```

How can I remove duplicates, and just keep the row with more values?

Output should be like this:

```<code>Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
</code>```

I tried ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1 but it removes all duplicates host1 i.e the result is this

```<code>Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
      | N/A     | N/A
      | 1.1.1.1 | N/A
      | N/A     | Windows
</code>```

答:
This is what I've got so far. Assuming your data is like

Origin Data

```<code>Name    IP      OS      Country
host1   1.1.1.1 Windows N/A
host1   1.1.1.1 Windows Taiwan
host1   1.1.1.1 N/A     N/A
host1   N/A     N/A     Taiwan
host2   N/A     Apple   N/A
host2   N/A     Apple   Taiwan
host2   N/A     N/A     Taiwan
host2   1.1.1.1 N/A     N/A
host2   1.1.1.1 Apple   Taiwan
</code>```

Output

```<code>Name    IP      OS      Country
host1   1.1.1.1 Windows Taiwan
host2   1.1.1.1 Apple   Taiwan
</code>```

Code

```<code>Private Sub test()
    With ActiveSheet
        Dim i, startRow, endRow As Long
        Dim NACount, LessNACount As Integer
        'Set a large enough number
        LessNACount = 1000
        Dim cell As Range

        'Assuming Row 1 is title
        startRow = 2

        Dim DeleteRange, SameNARange As Range
        'Setting it a dummy range
        Set DeleteRange = .Rows(.Rows.Count)

        For i = 2 To .Range("A" & .Rows.Count).End(xlUp).Row
            NACount = WorksheetFunction.CountIf(.Rows(i), "N/A")
            'Cells with N/A are more than the least row
            If NACount > LessNACount Then
                Set DeleteRange = Union(DeleteRange, .Rows(i))
            'Cells with N/A are equal than the least row
            ElseIf NACount = LessNACount Then
                Set SameNARange = Union(SameNARange, .Rows(i))
            'Cells with N/A are less than the least row, so it becomes the new least row
            Else
                'We have found at least a row, abandon them
                If Not SameNARange Is Nothing Then
                    Set DeleteRange = Union(DeleteRange, SameNARange)
                End If
                Set SameNARange = .Rows(i)
                LessNACount = NACount
            End If

            'host1 is done, goes into host2
            If .Range("A" & i).Value <> .Range("A" & i + 1).Value Then
                LessNACount = 1000
                Set SameNARange = Nothing
            End If
        Next i

        DeleteRange.Delete
    End With
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I have the following table:

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
host1 | N/A     | N/A
host1 | 1.1.1.1 | N/A
host1 | N/A     | Windows

How can I remove duplicates, and just keep the row with more values?

Output should be like this:

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows

I tried ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1 but it removes all duplicates host1 i.e the result is this

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
      | N/A     | N/A
      | 1.1.1.1 | N/A
      | N/A     | Windows

Body:
This is what I've got so far. Assuming your data is like

Origin Data

Name    IP      OS      Country
host1   1.1.1.1 Windows N/A
host1   1.1.1.1 Windows Taiwan
host1   1.1.1.1 N/A     N/A
host1   N/A     N/A     Taiwan
host2   N/A     Apple   N/A
host2   N/A     Apple   Taiwan
host2   N/A     N/A     Taiwan
host2   1.1.1.1 N/A     N/A
host2   1.1.1.1 Apple   Taiwan

Output

Name    IP      OS      Country
host1   1.1.1.1 Windows Taiwan
host2   1.1.1.1 Apple   Taiwan

Code

Private Sub test()
    With ActiveSheet
        Dim i, startRow, endRow As Long
        Dim NACount, LessNACount As Integer
        'Set a large enough number
        LessNACount = 1000
        Dim cell As Range

        'Assuming Row 1 is title
        startRow = 2

        Dim DeleteRange, SameNARange As Range
        'Setting it a dummy range
        Set DeleteRange = .Rows(.Rows.Count)

        For i = 2 To .Range("A" & .Rows.Count).End(xlUp).Row
            NACount = WorksheetFunction.CountIf(.Rows(i), "N/A")
            'Cells with N/A are more than the least row
            If NACount > LessNACount Then
                Set DeleteRange = Union(DeleteRange, .Rows(i))
            'Cells with N/A are equal than the least row
            ElseIf NACount = LessNACount Then
                Set SameNARange = Union(SameNARange, .Rows(i))
            'Cells with N/A are less than the least row, so it becomes the new least row
            Else
                'We have found at least a row, abandon them
                If Not SameNARange Is Nothing Then
                    Set DeleteRange = Union(DeleteRange, SameNARange)
                End If
                Set SameNARange = .Rows(i)
                LessNACount = NACount
            End If

            'host1 is done, goes into host2
            If .Range("A" & i).Value <> .Range("A" & i + 1).Value Then
                LessNACount = 1000
                Set SameNARange = Nothing
            End If
        Next i

        DeleteRange.Delete
    End With
End Sub


问:
Checking if elements in array are even and sort them in specific order
I've been trying to get my head around this but I can't seem to find a good way to do this, so basically what I'm trying to achieve is sorting array in a way that numbers are sorted for example like this:

```<code>Array output (unsorted)
7777777777
7777777777
6666666666
6666666666
2222222222

Array output (sorted)
7777777777
6666666666
2222222222
6666666666
7777777777
</code>```

I was thinking about making an array NxN and sort it in a way that if there are like 2 array elements of sevens and sixes it will sort them like

```<code>7
6
6
7
</code>```

and all odd numbers like in this exemple 2 it will sort them like

```<code>7
6
2
6
7
</code>```

答:
Count the values in the array.

```<code>$values = array_count_values($array);
</code>```

(You can asort($values); or arsort($values); after this if you want larger groups of even values to be sorted toward the inside or outside of the symmetrical part of the result array. Or if you don't care, don't.)

Build arrays of evens and odds based on those counts.

```<code>foreach ($values as $value => $count) {
    if ($count % 2) {
        while ($count--) $odds[] = $value;
    } else {
        $count /= 2;  // half the size, so half can go at the beginning and half at the end
        while ($count--) $evens[] = $value;
    }
}
</code>```

Merge the even and odd arrays together to create the result.

```<code>$result = array_merge($evens, $odds, array_reverse($evens));
</code>```

Body:
I've been trying to get my head around this but I can't seem to find a good way to do this, so basically what I'm trying to achieve is sorting array in a way that numbers are sorted for example like this:

Array output (unsorted)
7777777777
7777777777
6666666666
6666666666
2222222222

Array output (sorted)
7777777777
6666666666
2222222222
6666666666
7777777777

I was thinking about making an array NxN and sort it in a way that if there are like 2 array elements of sevens and sixes it will sort them like

7
6
6
7

and all odd numbers like in this exemple 2 it will sort them like

7
6
2
6
7

Body:
Count the values in the array.

$values = array_count_values($array);

(You can asort($values); or arsort($values); after this if you want larger groups of even values to be sorted toward the inside or outside of the symmetrical part of the result array. Or if you don't care, don't.)

Build arrays of evens and odds based on those counts.

foreach ($values as $value => $count) {
    if ($count % 2) {
        while ($count--) $odds[] = $value;
    } else {
        $count /= 2;  // half the size, so half can go at the beginning and half at the end
        while ($count--) $evens[] = $value;
    }
}

Merge the even and odd arrays together to create the result.

$result = array_merge($evens, $odds, array_reverse($evens));


问:
Laravel not displaying images in storage folder while using artisan server
The image is stored in 'storage/app/public/gallery'

I have already used  php artisan storage:link command.

The images are being displayed when I run the app in apache.
But not in artisan or my ipage server

http://vazz.edottechno.com/storage/gallery/33.jpg

答:
Maybe you have to give www-data the permission to read files in storage/ path.
If not, check if you are using a dynamic url (url helper). In this case, that might be because the env_url is not properly set.</p>


问:
Replacing values in same column and same dataset in R
I have a dataset like this:

```<code>Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121
</code>```

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

```<code>ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"
</code>```

But the column still has a bunch of LS in there. Any ideas?

答:
Your dataframe

```<code>ds <-
    read.table(text = "Name Material Project
                        John LS        222
                        Jack Limestone 111
                        Job  LI        121
                      ", header = TRUE, stringsAsFactors = FALSE)
</code>```

```<code>> ds
  Name  Material Project
1 John        LS     222
2 Jack Limestone     111
3  Job        LI     121
</code>```

Subsetting the column where only LS is found.

```<code>ds$Material[grep("^L[SI]$", ds$Material, ignore.case = TRUE)] <- "Limestone"
</code>```

Result

```<code>> ds
  Name  Material Project
1 John Limestone     222
2 Jack Limestone     111
3  Job        LI     121
</code>```

In dplyr:

```<code>ds %>% mutate(Materials = gsub("L[SI]", "Limestone", Materials))
</code>```

Body:
I have a dataset like this:

Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"

But the column still has a bunch of LS in there. Any ideas?

Body:
Your dataframe

ds <-
    read.table(text = "Name Material Project
                        John LS        222
                        Jack Limestone 111
                        Job  LI        121
                      ", header = TRUE, stringsAsFactors = FALSE)

> ds
  Name  Material Project
1 John        LS     222
2 Jack Limestone     111
3  Job        LI     121

Subsetting the column where only LS is found.

ds$Material[grep("^L[SI]$", ds$Material, ignore.case = TRUE)] <- "Limestone"

Result

> ds
  Name  Material Project
1 John Limestone     222
2 Jack Limestone     111
3  Job        LI     121

In dplyr:

ds %>% mutate(Materials = gsub("L[SI]", "Limestone", Materials))


问:
JavaScript sync two arrays (of objects) / find delta
I have two arrays, old and new, which hold objects at each position. How would I sync or find the delta (i.e. what is new, updated and deleted from the new array compared to the old array)

```<code>var o = [
    {id:1, title:"title 1", type:"foo"},
    {id:2, title:"title 2", type:"foo"},
    {id:3, title:"title 3", type:"foo"}
];

var n = [
    {id:1, title:"title 1", type:"foo"},
    {id:2, title:"title updated", type:"foo"},
    {id:4, title:"title 4", type:"foo"}
];
</code>```

With the above data, using id as the key, we'd find that item with id=2 has an updated title, item with id=3 is deleted, and item with id=4 is new.

Is there an existing library out there that has useful functions, or is it a case of loop and inner loop, compare each row..e.g.

```<code>for(var i=0, l=o.length; i<l; i++)
{
    for(var x=0, ln=n.length; x<ln; x++)
    {
        //compare when o[i].id == n[x].id
    }
}
</code>```

Do this kind of comparison three times, to find new, updated and deleted?

答:
This is typescript version of @Juan Mendes answer

```<code>  mapFromArray(array: Array<any>, prop: string): { [index: number]: any } {
    const map = {};
    for (let i = 0; i < array.length; i++) {
      map[array[i][prop]] = array[i];
    }
    return map;
  }

  isEqual(a, b): boolean {
    return a.title === b.title && a.type === b.type;
  }

  getDelta(o: Array<any>, n: Array<any>, comparator: (a, b) => boolean): { added: Array<any>, deleted: Array<any>, changed: Array<any> } {
    const delta = {
      added: [],
      deleted: [],
      changed: []
    };
    const mapO = this.mapFromArray(o, 'id');
    const mapN = this.mapFromArray(n, 'id');
    for (const id in mapO) {
      if (!mapN.hasOwnProperty(id)) {
        delta.deleted.push(mapO[id]);
      } else if (!comparator(mapN[id], mapO[id])) {
        delta.changed.push(mapN[id]);
      }
    }

    for (const id in mapN) {
      if (!mapO.hasOwnProperty(id)) {
        delta.added.push(mapN[id]);
      }
    }
    return delta;
  }
</code>```

Body:
I have two arrays, old and new, which hold objects at each position. How would I sync or find the delta (i.e. what is new, updated and deleted from the new array compared to the old array)

var o = [
    {id:1, title:"title 1", type:"foo"},
    {id:2, title:"title 2", type:"foo"},
    {id:3, title:"title 3", type:"foo"}
];

var n = [
    {id:1, title:"title 1", type:"foo"},
    {id:2, title:"title updated", type:"foo"},
    {id:4, title:"title 4", type:"foo"}
];

With the above data, using id as the key, we'd find that item with id=2 has an updated title, item with id=3 is deleted, and item with id=4 is new.

Is there an existing library out there that has useful functions, or is it a case of loop and inner loop, compare each row..e.g.

for(var i=0, l=o.length; i<l; i++)
{
    for(var x=0, ln=n.length; x<ln; x++)
    {
        //compare when o[i].id == n[x].id
    }
}

Do this kind of comparison three times, to find new, updated and deleted?

Body:
This is typescript version of @Juan Mendes answer

  mapFromArray(array: Array<any>, prop: string): { [index: number]: any } {
    const map = {};
    for (let i = 0; i < array.length; i++) {
      map[array[i][prop]] = array[i];
    }
    return map;
  }

  isEqual(a, b): boolean {
    return a.title === b.title && a.type === b.type;
  }

  getDelta(o: Array<any>, n: Array<any>, comparator: (a, b) => boolean): { added: Array<any>, deleted: Array<any>, changed: Array<any> } {
    const delta = {
      added: [],
      deleted: [],
      changed: []
    };
    const mapO = this.mapFromArray(o, 'id');
    const mapN = this.mapFromArray(n, 'id');
    for (const id in mapO) {
      if (!mapN.hasOwnProperty(id)) {
        delta.deleted.push(mapO[id]);
      } else if (!comparator(mapN[id], mapO[id])) {
        delta.changed.push(mapN[id]);
      }
    }

    for (const id in mapN) {
      if (!mapO.hasOwnProperty(id)) {
        delta.added.push(mapN[id]);
      }
    }
    return delta;
  }


问:
Firing the application_start for a plugin
I have the plugin architecture described http://www.squarewidget.com/pluggable-architecture-in-asp.net-mvc-4

This appears to be working fine, but now I need the plugin to be able to modify some aspects of the host, in my case, to add a new role to the Roles.

I think the best place for the role to be added would be in the application_start of the plugin's global.asax, but it seems that is not being fired.

I have very limited knowledge of ninject, which is how the plugin architecture is managed, but I am assuming I need to put something in the RegisterServices of the NinjectWebCommon.cs which is in my host.

How do I force my plugin's global.asax to be called when my application is started?

This is MVC4. C#
Thanks.

答:
Have a closer look at the NinjectWebCommon.cs file you will notice some attributes at the beginning WebActivatorEx.PreApplicationStartMethod and WebActivatorEx.ApplicationShutdownMethod (or maybe just WebActivator. depending on your version)

WebActivatorEx is the library allowing to execute code automatically upon events of the application's lifecycle.

What you have to do is "jsut" adding a MyModuleStartup.cs file in the App_Start folder of your module with the following code :

```<code>[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyModule.App_Start.MyModuleStartup), "Start")]
namespace MyModule.App_Start
{
    public static class MyModuleStartup
    {
      public static void Start()
      {
         MyBusinessClass.RegisterMyCustomRole("MyNewRole");
      }
    }
}
</code>```

You may have to test PostApplicationStartMethod instead of PreApplicationStartMethod if you need your app to be completely set-up before adding your new role.

Body:
Have a closer look at the NinjectWebCommon.cs file you will notice some attributes at the beginning WebActivatorEx.PreApplicationStartMethod and WebActivatorEx.ApplicationShutdownMethod (or maybe just WebActivator. depending on your version)

WebActivatorEx is the library allowing to execute code automatically upon events of the application's lifecycle.

What you have to do is "jsut" adding a MyModuleStartup.cs file in the App_Start folder of your module with the following code :

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyModule.App_Start.MyModuleStartup), "Start")]
namespace MyModule.App_Start
{
    public static class MyModuleStartup
    {
      public static void Start()
      {
         MyBusinessClass.RegisterMyCustomRole("MyNewRole");
      }
    }
}

You may have to test PostApplicationStartMethod instead of PreApplicationStartMethod if you need your app to be completely set-up before adding your new role.


问:
How to loop over object with unknown keys and values
I get a JSON response of shoe sizes from an API endpoint that looks like this:

```<code>data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]
</code>```

The data shows e.g that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be A-Z or basically anything else.

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size.

What would be the best way to loop over an object like this to get the value of every shape? I would expect it to be an array of sizes.

ES6 or ES7 is fine but I would prefer to do it without jQuery.

EDIT:
Let me be more clear.
First of all I have considered improving data structure but unfortunately that's not an option.

I have tried Object.keys(sizes) which returns an array of the keys. Sure that's one step forward. But I would like to call a function that returns an object with the keys and its values. In my mind, that return value should be something like this:

```<code>sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]
</code>```

Does that makes sense? Of course, length is not absolutely necessary to include in the object.

答:
Use Object.keys() and .reduce() to sum the values of the keys.

NOTE: I had to clean your data, and remove a level to simplify the example. You'll need to adapt it to your real data.

const data = [
 {
  system: 'US',
  sizes: {
   7: {
    B: 3,
    C: 6,
    D: 1,
    E: 1,
   },
   7.5: {
    A: 6,
    B: 7,
    C: 14,
    D: 11,
    E: 2,
   },
   8: {
    '2E': 1,
    A: 5,
    B: 32,
    C: 38,
    D: 23,
   },
   8.5: {
    '2E': 2,
    A: 9,
    B: 56,
    C: 79,
    D: 61,
   },
   9: {
    '2A': 5,
    '2E': 4,
    A: 17,
    B: 92,
    C: 143,
   },
   9.5: {
    '2A': 3,
    '2E': 3,
    A: 26,
    B: 132,
    C: 194,
   },
   10: {
    '2A': 5,
    '2E': 3,
    '3A': 1,
    A: 53,
    B: 159,
   },
  },
 },
];

const { // We use destructuration to make a copy
 sizes = {} // We assign a default value in case sizes is undefined
} = data[0];
const sumOfSizes = {}; // Future object we will fill
Object.keys(sizes).forEach((sizeIndex) => { // We get the keys of the object, and loop over it.
 const size = sizes[sizeIndex]; // For clarity, I assigned the needed value to a var.
 const sumOfShapes = Object.keys(size).reduce((prevSum, shapeIndex) => { // We get the sub-keys of the object and sum the values of them.
  const shapeValue = size[shapeIndex];
  return prevSum + shapeValue;
 }, 0);
 sumOfSizes[sizeIndex] = sumOfShapes; // We assign the sum of shapes to the current shoe size.
});
console.log(sumOfSizes);```

Body:
I get a JSON response of shoe sizes from an API endpoint that looks like this:

data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]

The data shows e.g that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be A-Z or basically anything else.

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size.

What would be the best way to loop over an object like this to get the value of every shape? I would expect it to be an array of sizes.

ES6 or ES7 is fine but I would prefer to do it without jQuery.

EDIT:
Let me be more clear.
First of all I have considered improving data structure but unfortunately that's not an option.

I have tried Object.keys(sizes) which returns an array of the keys. Sure that's one step forward. But I would like to call a function that returns an object with the keys and its values. In my mind, that return value should be something like this:

sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]

Does that makes sense? Of course, length is not absolutely necessary to include in the object.


问:
php: loop through json array
I have a json array:

```<code>[
    {
        "var1": "9",
        "var2": "16",
        "var3": "16"
    },
    {
        "var1": "8",
        "var2": "15",
        "var3": "15"
    }
]
</code>```

How can I loop through this array using php?

答:
Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

```<code>$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
</code>```

Title: php: loop through json array

Body:
I have a json array:

[
    {
        "var1": "9",
        "var2": "16",
        "var3": "16"
    },
    {
        "var1": "8",
        "var2": "15",
        "var3": "15"
    }
]

How can I loop through this array using php?

Body:
Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );


问:
Getting data from a database without duplicates
I have an ArrayList variable named counties and I am extracting data from my database and adding it to this ArrayList with the following code:

```<code>//Get all data from database
        Cursor cursor = database.rawQuery("SELECT * FROM " + tableName, null);

//Add Counties to ArrayList
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
            counties.add(cursor.getString(cursor.getColumnIndex("COUNTY")));
            cursor.moveToNext();
        }
</code>```

I am then displaying this data in a ListView which will allow the user to select a County and be taken to another activity.

The data is such that there are multiple records with the same county, thus it looks like:

```<code>COUNTIES
______________
West Yorkshire
West Yorkshire
Lancashire
Warwickshire
Cornwall
Lancashire
West Yorkshire
</code>```

I want only one instance of each county to be shown and have struggled thus far to find a solution.

答:
Use this

Cursor cursor =  database.rawQuery("SELECT DISTINCT "+city_column_name+" FROM "+tableName, null);

Instead of :

Cursor cursor =  database.rawQuery("SELECT *  FROM "+tableName, null);

Body:
I have an ArrayList variable named counties and I am extracting data from my database and adding it to this ArrayList with the following code:

//Get all data from database
        Cursor cursor = database.rawQuery("SELECT * FROM " + tableName, null);

//Add Counties to ArrayList
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
            counties.add(cursor.getString(cursor.getColumnIndex("COUNTY")));
            cursor.moveToNext();
        }

I am then displaying this data in a ListView which will allow the user to select a County and be taken to another activity.

The data is such that there are multiple records with the same county, thus it looks like:

COUNTIES
______________
West Yorkshire
West Yorkshire
Lancashire
Warwickshire
Cornwall
Lancashire
West Yorkshire

I want only one instance of each county to be shown and have struggled thus far to find a solution.


问:
MVC redirect to previous page (exclude not httppost action)
i have three action on controller

```<code>public ActionResult Index() {}
public ActionResult Insert() {}

[HttpPost]
public ActionResult Insert() {
     //some insert code
     redirect to where you come from but exclude Insert page
}
</code>```

and other controller

```<code>public ActionResult Example() {}
</code>```

i am going to Insert page from Index or maybe from Example then submit the form to HttpPost action. i am trying redirect to Index page or Example page (im trying to find i came from which page). how can i achieve that (UrlReferrer is redirect to Insert page)

答:
All you need to do is ,keep track of where the request comes from. There are multiple ways to do it. Here is one

In your insert GET action method, you can read the UrlReferrer value and pass that to the view, where you will keep that inside a hidden input inside the form.  When the form is submitted, you can read this in your HttpPost action method and do a redirect to that.

```<code>public ActionResult Insert()
{
    ViewBag.ReturnUrl = Request.UrlReferrer;
    return View(new InsertVm());
}
</code>```

and in your form

```<code>@model InsertVm
@using (Html.BeginForm("Insert", "Users"))
{
    <input type="hidden" name="returnUrl" value="@ViewBag.ReturnUrl" />
    @Html.TextBoxFor(a=>a.EmailAddress)
    <button type="submit">Send</button>
}
</code>```

Now in your Insert HttpPost action, add a parameter with the same name as your hidden input

```<code>[HttpPost]
public ActionResult Insert(InsertVm model,string returnUrl)
{
    // to do : Save data

    if(!String.IsNullOrEmpty(returnUrl))
    {
        return Redirect(returnUrl);
    }
    //fall back
    return RedirectToAction("Index","Home");
}
</code>```

Body:
i have three action on controller

public ActionResult Index() {}
public ActionResult Insert() {}

[HttpPost]
public ActionResult Insert() {
     //some insert code
     redirect to where you come from but exclude Insert page
}

and other controller

public ActionResult Example() {}

i am going to Insert page from Index or maybe from Example then submit the form to HttpPost action. i am trying redirect to Index page or Example page (im trying to find i came from which page). how can i achieve that (UrlReferrer is redirect to Insert page)

Body:
All you need to do is ,keep track of where the request comes from. There are multiple ways to do it. Here is one

In your insert GET action method, you can read the UrlReferrer value and pass that to the view, where you will keep that inside a hidden input inside the form.  When the form is submitted, you can read this in your HttpPost action method and do a redirect to that.

public ActionResult Insert()
{
    ViewBag.ReturnUrl = Request.UrlReferrer;
    return View(new InsertVm());
}

and in your form

@model InsertVm
@using (Html.BeginForm("Insert", "Users"))
{
    <input type="hidden" name="returnUrl" value="@ViewBag.ReturnUrl" />
    @Html.TextBoxFor(a=>a.EmailAddress)
    <button type="submit">Send</button>
}

Now in your Insert HttpPost action, add a parameter with the same name as your hidden input

[HttpPost]
public ActionResult Insert(InsertVm model,string returnUrl)
{
    // to do : Save data

    if(!String.IsNullOrEmpty(returnUrl))
    {
        return Redirect(returnUrl);
    }
    //fall back
    return RedirectToAction("Index","Home");
}


问:
Looking for assistance with batch file logic whether to determine whether a user has logged into AD or not
In attempting a proof of concept, we a script run by our desk for the creation of user home directories, group membership, profile, set home directory, etc.

I'd like to add a section that checks whether the account has the lastLogonTimeStamp (LLTS) value set in AD. I'm able query the user in AD. What I'm unable to figure out is how to parse out and run separate steps in the .cmd file whether there's a value in the LLTS attribute vs no value. I don't need to look at the age, just whether it's there or not.  I believe my issue is that I'm getting a string returned when I'm trying to compare a value, and if the LLTS isn't present, I'm not sure if it's a zero value or a null value.

I understand there may be better ways to do this using PS or VBS, but we're not at that point of converting our scripts, but we'd like to try an figure out this piece.

Here's what I have so far as a POC / test.

```<code>@echo off
:START
cls
echo Enter EMP ID
set /p EMPID=
SetLocal EnableDelayedExpansion
set count=0

:: queries for the existence of the lastLogonTimeStamp value
for /F "delims=" %%a in ('dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(samaccountname=%empid%))" -attr lastLogonTimeStamp') do (
set LLTS=%%a
set /a count=!count! + 1
if %%a GTR 1 GOTO COMPARE
)

:COMPARE
echo.
echo OLD-LLTS=%LLTS%
set MODLLTS=%LLTS:  =%
echo MOD-LLTS=%MODLLTS%
IF %MODLLTS% GTR 1 GOTO HAS

:HASNOT
:: Run these commands if the lastLogonTimeStamp is not present
ECHO Has NO previous Logon info.
pause
GOTO END

:HAS
:: Run these commands if the lastLogonTimeStamp is present, regardless of value.
ECHO Has previous Logon info.
w32tm.exe /ntte %MODLLTS%
pause
GOTO END

:END
EXIT
</code>```

Here's example output with a user has previously logged in:

```<code>    administrator
      lastLogonTimeStamp
      131545455582093968
</code>```

Here's example output with a user who's never logged in:

```<code>    guest
      lastLogonTimeStamp
</code>```

Note:There's an empty linebelow the attribute name for the guest that's not showing in the preview.

答:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q47309403.txt"
SET "filename2=%sourcedir%\q47309403_2.txt"

FOR %%a IN (logonname logonjunktext logontimestamp) DO SET "%%a="
FOR /f "usebackqdelims= " %%a IN ("%filename1%") DO (
 IF DEFINED logonname (
  IF DEFINED logonjunktext (
   SET "logontimestamp=%%a"
  ) ELSE (
   SET "logonjunktext=%%a"
  )
 ) ELSE (
  SET "logonname=%%a"
 )
)

:done1
ECHO name=%logonname% junk text=%logonjunktext% timestamp=%logontimestamp%

FOR %%a IN (logonname logonjunktext logontimestamp) DO SET "%%a="
FOR /f "usebackqdelims= " %%a IN ("%filename2%") DO (
 IF DEFINED logonname (
  IF DEFINED logonjunktext (
   SET "logontimestamp=%%a"
  ) ELSE (
   SET "logonjunktext=%%a"
  )
 ) ELSE (
  SET "logonname=%%a"
 )
)

:done2
ECHO name=%logonname% junk text=%logonjunktext% timestamp=%logontimestamp%

GOTO :EOF
```

I used files named q47309403.txt, q47309403_2.txt containing your data for my testing. Obviously, replace such with your dsquery command.

The code is simply the same, repeated for each file for demo purposes.

The data reported in the variables should enable you to derive any consequential actions, if your report on the dsquery output is representative.

Operation is simply clear three variables, then accumulate each depending on the defined state for the variable.

Body:
In attempting a proof of concept, we a script run by our desk for the creation of user home directories, group membership, profile, set home directory, etc.

I'd like to add a section that checks whether the account has the lastLogonTimeStamp (LLTS) value set in AD. I'm able query the user in AD. What I'm unable to figure out is how to parse out and run separate steps in the .cmd file whether there's a value in the LLTS attribute vs no value. I don't need to look at the age, just whether it's there or not.  I believe my issue is that I'm getting a string returned when I'm trying to compare a value, and if the LLTS isn't present, I'm not sure if it's a zero value or a null value.

I understand there may be better ways to do this using PS or VBS, but we're not at that point of converting our scripts, but we'd like to try an figure out this piece.

Here's what I have so far as a POC / test.

@echo off
:START
cls
echo Enter EMP ID
set /p EMPID=
SetLocal EnableDelayedExpansion
set count=0

:: queries for the existence of the lastLogonTimeStamp value
for /F "delims=" %%a in ('dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(samaccountname=%empid%))" -attr lastLogonTimeStamp') do (
set LLTS=%%a
set /a count=!count! + 1
if %%a GTR 1 GOTO COMPARE
)

:COMPARE
echo.
echo OLD-LLTS=%LLTS%
set MODLLTS=%LLTS:  =%
echo MOD-LLTS=%MODLLTS%
IF %MODLLTS% GTR 1 GOTO HAS

:HASNOT
:: Run these commands if the lastLogonTimeStamp is not present
ECHO Has NO previous Logon info.
pause
GOTO END

:HAS
:: Run these commands if the lastLogonTimeStamp is present, regardless of value.
ECHO Has previous Logon info.
w32tm.exe /ntte %MODLLTS%
pause
GOTO END

:END
EXIT

Here's example output with a user has previously logged in:

    administrator
      lastLogonTimeStamp
      131545455582093968

Here's example output with a user who's never logged in:

    guest
      lastLogonTimeStamp

Note:There's an empty linebelow the attribute name for the guest that's not showing in the preview.

Body:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q47309403.txt"
SET "filename2=%sourcedir%\q47309403_2.txt"

FOR %%a IN (logonname logonjunktext logontimestamp) DO SET "%%a="
FOR /f "usebackqdelims= " %%a IN ("%filename1%") DO (
 IF DEFINED logonname (
  IF DEFINED logonjunktext (
   SET "logontimestamp=%%a"
  ) ELSE (
   SET "logonjunktext=%%a"
  )
 ) ELSE (
  SET "logonname=%%a"
 )
)

:done1
ECHO name=%logonname% junk text=%logonjunktext% timestamp=%logontimestamp%

FOR %%a IN (logonname logonjunktext logontimestamp) DO SET "%%a="
FOR /f "usebackqdelims= " %%a IN ("%filename2%") DO (
 IF DEFINED logonname (
  IF DEFINED logonjunktext (
   SET "logontimestamp=%%a"
  ) ELSE (
   SET "logonjunktext=%%a"
  )
 ) ELSE (
  SET "logonname=%%a"
 )
)

:done2
ECHO name=%logonname% junk text=%logonjunktext% timestamp=%logontimestamp%

GOTO :EOF

I used files named q47309403.txt, q47309403_2.txt containing your data for my testing. Obviously, replace such with your dsquery command.

The code is simply the same, repeated for each file for demo purposes.

The data reported in the variables should enable you to derive any consequential actions, if your report on the dsquery output is representative.

Operation is simply clear three variables, then accumulate each depending on the defined state for the variable.


问:
Subset dataframe based on duplicate values in multiple rows
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

```<code>Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5
</code>```

I would like to return the following result.

```<code>Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4
</code>```

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

```<code>Dat %>% distinct(AAA, BBB, CCC)
</code>```

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

```<code>Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27
</code>```

with the desired result being

```<code>> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
</code>```

答:
Here's another solution with apply and all:

```<code>Dat[apply(Dat[,-1], 1, function(x) all(x==x[1])),]
</code>```

or with filter_at from dplyr:

```<code>library(dplyr)
Dat %>%
  filter_at(vars(AAA:CCC), all_vars(. == .data$AAA))
</code>```

Result:

```<code>  IndID AAA BBB CCC
1     A   1   1   1
4     D   2   2   2
8     H   4   4   4
</code>```

Edit:

In response to OP's additional example, the apply example would work regardless of variable type. So the following would work for the new example:

```<code>Dat[apply(Dat[,-1], 1, function(x) all(x==x[1])),]
</code>```

Result:

```<code>    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
</code>```

For filter_at, however, if the columns to compare are factor's, one would need to first convert to character:

```<code>Dat %>%
  filter_at(vars(-1), all_vars(as.character(.) == .data$CptrDate))
</code>```

Notice that you only need to convert . to character, but not .data$CptrDate because factors can be compered with characters, but not with another factor with different levels.

An alternative would be:

```<code>Dat %>%
  mutate_at(vars(-1), as.character) %>%
  filter_at(vars(-1), all_vars(. == .data$CptrDate))
</code>```

Result:

```<code>  GenIndID   CptrDate DtLastAlive  DtFnlFate
1  BHS_635 2016-02-04  2016-02-04 2016-02-04
2  BHS_636 2016-02-04  2016-02-04 2016-02-04
3  BHS_637 2016-02-04  2016-02-04 2016-02-04
</code>```

Body:
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5

I would like to return the following result.

Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

Dat %>% distinct(AAA, BBB, CCC)

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27

with the desired result being

> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04

Body:
Here's another solution with apply and all:

Dat[apply(Dat[,-1], 1, function(x) all(x==x[1])),]

or with filter_at from dplyr:

library(dplyr)
Dat %>%
  filter_at(vars(AAA:CCC), all_vars(. == .data$AAA))

Result:

  IndID AAA BBB CCC
1     A   1   1   1
4     D   2   2   2
8     H   4   4   4

Edit:

In response to OP's additional example, the apply example would work regardless of variable type. So the following would work for the new example:

Dat[apply(Dat[,-1], 1, function(x) all(x==x[1])),]

Result:

    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04

For filter_at, however, if the columns to compare are factor's, one would need to first convert to character:

Dat %>%
  filter_at(vars(-1), all_vars(as.character(.) == .data$CptrDate))

Notice that you only need to convert . to character, but not .data$CptrDate because factors can be compered with characters, but not with another factor with different levels.

An alternative would be:

Dat %>%
  mutate_at(vars(-1), as.character) %>%
  filter_at(vars(-1), all_vars(. == .data$CptrDate))

Result:

  GenIndID   CptrDate DtLastAlive  DtFnlFate
1  BHS_635 2016-02-04  2016-02-04 2016-02-04
2  BHS_636 2016-02-04  2016-02-04 2016-02-04
3  BHS_637 2016-02-04  2016-02-04 2016-02-04


问:
Carousel stacks images: Webkit, Chrome, Safari only
http://174.120.239.48/~peakperf/?page_id=260

If you view that page with a webkit browser, Chrome/Safari you will see that the carousels contents get layered on top of one another.

If you view it in Mozilla or IE the contents display properly.

I've never had a bug like this in webkit so it's all new to me.

Any help would be appreciated.

Thanks!

CSS:

```<code>.theme-twentycarousels {
    width: 610px;
}

.scrollertitle p{
    margin: 0;
    padding: 0;
}
.scrollertitle h2{
    padding-left: 10px;
    padding-top: 10px;
    text-transform:uppercase;
    font-size: 15px;
    font-weight: bold;
}
.scrollertitle .arrow-right {
    width:12px;
    float:right;
    height: 37px;
}

 .scrollertitle .arrow-left {
    width:12px;
    height:37px;
    float:left;

}

.scrollertitle .arrow-left a {
    margin:-20px 0 0 0;
    width:12px;
    height:37px;
    background:url(img/arrow_left.png) top left no-repeat;
    display:block;

}

.scrollertitle .arrow-right a {
    margin:-20px 0 0 0;
    width:12px;
    height:37px;
    background:url(img/arrow_right.png) top right no-repeat;
    display:block;
}

.theme-twentycarousels .hide { display:none; }

.theme-twentycarousels .stepcarousel {
    position: relative; /* Leave this value alone */
    overflow: scroll; /* Leave this value alone */
    height: 155px;
    background:#EEEFF4;
    width: 610px;

}

.theme-twentycarousels .stepcarousel .belt{
    position: absolute; /* Leave this value alone */
    left: 0;
    top: 0;
    margin: 0px;

}

.theme-twentycarousels .stepcarousel .panel {
    height:100px;
    float: left; /* Leave this value alone */
    padding:10px;
    background:#EEEFF4;
    display:block;
    width: auto;
}

.theme-twentycarousels .stepcarousel .panel .panel-text {
    font-family: "Helvetica Neue", Arial, Helvetica, "Nimbus Sans L", sans-serif;
    color:#FFF;
}

.wp_carousel_twentycarousels_pagination {
    padding:5px 10px;
    background:#000;
    text-align:center;
    visibility:hidden;
}
.scrollertitle{
    height: 37px;
    background: url(img/scrollertitle.jpg) no-repeat;
    width: 610px;
}
.arrowcontainer{
    width: 50px;
    height: 37px;
    float: right;
    margin-right: 10px;
}
</code>```

答:
For some reason, your divs holding the images, the ones with the class=panel, have inline styles when I look at them in the inspector in Chrome.

```<code>style="float: none; position: absolute; left: 0px;"
</code>```

Removing that from all of those particular divs stopped them from piling up on top of each other -- but, they didn't fit all in a row anymore.

I also noticed that you have

```<code>.theme-twentycarousels .stepcarousel .panel
</code>```

at two places in your stylesheet. Not sure if that's causing any problems.

Body:
http://174.120.239.48/~peakperf/?page_id=260

If you view that page with a webkit browser, Chrome/Safari you will see that the carousels contents get layered on top of one another.

If you view it in Mozilla or IE the contents display properly.

I've never had a bug like this in webkit so it's all new to me.

Any help would be appreciated.

Thanks!

CSS:

.theme-twentycarousels {
    width: 610px;
}

.scrollertitle p{
    margin: 0;
    padding: 0;
}
.scrollertitle h2{
    padding-left: 10px;
    padding-top: 10px;
    text-transform:uppercase;
    font-size: 15px;
    font-weight: bold;
}
.scrollertitle .arrow-right {
    width:12px;
    float:right;
    height: 37px;
}

 .scrollertitle .arrow-left {
    width:12px;
    height:37px;
    float:left;

}

.scrollertitle .arrow-left a {
    margin:-20px 0 0 0;
    width:12px;
    height:37px;
    background:url(img/arrow_left.png) top left no-repeat;
    display:block;

}

.scrollertitle .arrow-right a {
    margin:-20px 0 0 0;
    width:12px;
    height:37px;
    background:url(img/arrow_right.png) top right no-repeat;
    display:block;
}

.theme-twentycarousels .hide { display:none; }

.theme-twentycarousels .stepcarousel {
    position: relative; /* Leave this value alone */
    overflow: scroll; /* Leave this value alone */
    height: 155px;
    background:#EEEFF4;
    width: 610px;

}

.theme-twentycarousels .stepcarousel .belt{
    position: absolute; /* Leave this value alone */
    left: 0;
    top: 0;
    margin: 0px;

}

.theme-twentycarousels .stepcarousel .panel {
    height:100px;
    float: left; /* Leave this value alone */
    padding:10px;
    background:#EEEFF4;
    display:block;
    width: auto;
}

.theme-twentycarousels .stepcarousel .panel .panel-text {
    font-family: "Helvetica Neue", Arial, Helvetica, "Nimbus Sans L", sans-serif;
    color:#FFF;
}

.wp_carousel_twentycarousels_pagination {
    padding:5px 10px;
    background:#000;
    text-align:center;
    visibility:hidden;
}
.scrollertitle{
    height: 37px;
    background: url(img/scrollertitle.jpg) no-repeat;
    width: 610px;
}
.arrowcontainer{
    width: 50px;
    height: 37px;
    float: right;
    margin-right: 10px;
}

Body:
For some reason, your divs holding the images, the ones with the class=panel, have inline styles when I look at them in the inspector in Chrome.

style="float: none; position: absolute; left: 0px;"

Removing that from all of those particular divs stopped them from piling up on top of each other -- but, they didn't fit all in a row anymore.

I also noticed that you have

.theme-twentycarousels .stepcarousel .panel

at two places in your stylesheet. Not sure if that's causing any problems.


问:
How to use recursive_directory_iterator with algorithm library and std::remove_if in particular?
I want to filter out some entries from the recursive directory listing using the standard algorithms. Let say leave only regular files.
Some algorithms from STL do work, e.g. std::count_if, but others, e.g std::remove_if, do not.

Should it work or is the recursive_directory_iterator intentionally not (fully) compatible with STL?

Given recursive_directory_iterator is there a way to proceed regular files only in a functional-programming style (and possible chain other filters afterwards)?

```<code>#include <algorithm>
#include <experimental/filesystem>
#include <iostream>

namespace fs = std::experimental::filesystem;

int main()
{
  { // count_if is fine
    auto dir_listing = fs::recursive_directory_iterator("/tmp/myfiles");
    auto n = std::count_if(begin(dir_listing), end(dir_listing), [](auto &p) { return fs::is_regular_file(p); });
    std::cout << n << '\n';
  }

  { // remove_if does not even compile
    auto dir_listing = fs::recursive_directory_iterator("/tmp/myfiles");
    auto my_files = std::remove_if(begin(dir_listing), end(dir_listing), [](const fs::path &p) { return !fs::is_regular_file(p); });
    for (auto &f : my_files)
    {
      std::cout << f << '\n';
    }
  }
}
</code>```

Compiling with gcc-7 leads to an error (clang-5 as well)

```<code>g++-7 myfiles.cpp -std=c++1z -lstdc++fs
...
/usr/include/c++/7/bits/stl_algo.h:871:16: error: passing ‘const std::experimental::filesystem::v1::directory_entry’ as ‘this’ argument discards qualifiers [-fpermissive]
      *__result = _GLIBCXX_MOVE(*__first);
</code>```

And after adding -fpermissive it just segfaults.

答:
std::remove_if expects forward iterators, pointing to move assignable values. recursive_directory_iterator is an input iterator, and the values it points to are const (so not move assignable).

I'm not sure exactly what you're trying to do, but std::remove/remove_if is for removing items from a collection. Not all iterators point into collections, as is the case with recursive_directory_iterator.

If you're trying to use it as a filter that you want to possibly forward to other algorithms, unfortunately the standard library does not have direct support for that. The best you can probably do (with the standard library) is use remove_copy_if with back_inserter to filter elements into a vector, and then do further processing on that vector.

```<code>std::vector<fs::path> paths;
std::remove_copy_if(begin(dir_listing), end(dir_listing), std::back_inserter(paths),
    [](const fs::path& p) {
        return !fs::is_regular_file(p);
    });
</code>```

Body:
I want to filter out some entries from the recursive directory listing using the standard algorithms. Let say leave only regular files.
Some algorithms from STL do work, e.g. std::count_if, but others, e.g std::remove_if, do not.

Should it work or is the recursive_directory_iterator intentionally not (fully) compatible with STL?

Given recursive_directory_iterator is there a way to proceed regular files only in a functional-programming style (and possible chain other filters afterwards)?

#include <algorithm>
#include <experimental/filesystem>
#include <iostream>

namespace fs = std::experimental::filesystem;

int main()
{
  { // count_if is fine
    auto dir_listing = fs::recursive_directory_iterator("/tmp/myfiles");
    auto n = std::count_if(begin(dir_listing), end(dir_listing), [](auto &p) { return fs::is_regular_file(p); });
    std::cout << n << '\n';
  }

  { // remove_if does not even compile
    auto dir_listing = fs::recursive_directory_iterator("/tmp/myfiles");
    auto my_files = std::remove_if(begin(dir_listing), end(dir_listing), [](const fs::path &p) { return !fs::is_regular_file(p); });
    for (auto &f : my_files)
    {
      std::cout << f << '\n';
    }
  }
}

Compiling with gcc-7 leads to an error (clang-5 as well)

g++-7 myfiles.cpp -std=c++1z -lstdc++fs
...
/usr/include/c++/7/bits/stl_algo.h:871:16: error: passing ‘const std::experimental::filesystem::v1::directory_entry’ as ‘this’ argument discards qualifiers [-fpermissive]
      *__result = _GLIBCXX_MOVE(*__first);

And after adding -fpermissive it just segfaults.

Body:
std::remove_if expects forward iterators, pointing to move assignable values. recursive_directory_iterator is an input iterator, and the values it points to are const (so not move assignable).

I'm not sure exactly what you're trying to do, but std::remove/remove_if is for removing items from a collection. Not all iterators point into collections, as is the case with recursive_directory_iterator.

If you're trying to use it as a filter that you want to possibly forward to other algorithms, unfortunately the standard library does not have direct support for that. The best you can probably do (with the standard library) is use remove_copy_if with back_inserter to filter elements into a vector, and then do further processing on that vector.

std::vector<fs::path> paths;
std::remove_copy_if(begin(dir_listing), end(dir_listing), std::back_inserter(paths),
    [](const fs::path& p) {
        return !fs::is_regular_file(p);
    });


问:
Perl captured digits from string are always 1
On my journey to start learning perl...

I encountered this funny behaviour, and can't seem to wrap my head around it.

```<code>my $username = "bandit0";
my $command = "";

sub next_command {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
        return "cat readme";
    }
    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . $num++;
    return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";
</code>```

After running this small perl program, I would expect something like this:

```<code>0
cat readme
1
ls
</code>```

However I get something like this...

```<code>1
ls
1
ls
</code>```

I don't understand why, at first string bandit0 the $num will be 1 instead of 0

答:
The match operator in scalar context evaluates to a boolean that indicates whether the match succeeded or not.

```<code>my $success = $user =~ /(\d+)/;
</code>```

The match operator in list context returns the captured strings (or 1 if there are no captures) on success and an empty list on error.

```<code>my ($num) = $user =~ /(\d+)/;
</code>```

You used the former, but you want the latter. That gives you the following (after a few other small fixes):

```<code>sub next_level {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)\z/;
    $user =~ s/\d+\z//g;
    $user .= ++$num;
    return $user;
}
</code>```

But that approach is complicated and inefficient. Simpler solution:

```<code>sub next_level {
    my ($user) = @_;
    $user =~ s/(\d+)\z/ $1 + 1 /e;
    return $user;
}
</code>```

Body:
On my journey to start learning perl...

I encountered this funny behaviour, and can't seem to wrap my head around it.

my $username = "bandit0";
my $command = "";

sub next_command {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
        return "cat readme";
    }
    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . $num++;
    return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";

After running this small perl program, I would expect something like this:

0
cat readme
1
ls

However I get something like this...

1
ls
1
ls

I don't understand why, at first string bandit0 the $num will be 1 instead of 0

Body:
The match operator in scalar context evaluates to a boolean that indicates whether the match succeeded or not.

my $success = $user =~ /(\d+)/;

The match operator in list context returns the captured strings (or 1 if there are no captures) on success and an empty list on error.

my ($num) = $user =~ /(\d+)/;

You used the former, but you want the latter. That gives you the following (after a few other small fixes):

sub next_level {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)\z/;
    $user =~ s/\d+\z//g;
    $user .= ++$num;
    return $user;
}

But that approach is complicated and inefficient. Simpler solution:

sub next_level {
    my ($user) = @_;
    $user =~ s/(\d+)\z/ $1 + 1 /e;
    return $user;
}


问:
Error in update-database command in code first migration
I am working on Desktop application in WPF and creating SqlRepository with LocalDB to store data.  I am using following tools

Visual Studio 2013 Community with update 2

Entity Framework 6.1.2 for Code first migration

I have created local database with Microsoft SQL Server Database File (SqlClient) configuration. Database created successfully and below is connection string fetched from Sql

```<code>Data Source=(LocalDB)\v11.0;Initial Catalog=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False
</code>```

I am using same connection string in app.config.  I can view database object in SQL Server Database explorer in Visual Studio.  But when run update-database command in Nuget package manager console, I am getting below error:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

答:
I was able to solve this by adding parameters to the update-database command:</p>

```<code>update-database -StartupProjectName MyApp.Web -ConnectionStringName MyAppConnectStringInWebConfig
</code>```

Body:
I am working on Desktop application in WPF and creating SqlRepository with LocalDB to store data.  I am using following tools

Visual Studio 2013 Community with update 2

Entity Framework 6.1.2 for Code first migration

I have created local database with Microsoft SQL Server Database File (SqlClient) configuration. Database created successfully and below is connection string fetched from Sql

Data Source=(LocalDB)\v11.0;Initial Catalog=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False

I am using same connection string in app.config.  I can view database object in SQL Server Database explorer in Visual Studio.  But when run update-database command in Nuget package manager console, I am getting below error:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

Body:
I was able to solve this by adding parameters to the update-database command:

update-database -StartupProjectName MyApp.Web -ConnectionStringName MyAppConnectStringInWebConfig


问:
Pass path with spaces as parameter to bat file
I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?

In my code i have the following

```<code>:READ_PWA_PATH
    if "%1" == "" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
            IF ERRORLEVEL ==2 GOTO CANCEL
            IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
    )
</code>```

If I simply call the script I get the following error:

```<code>C:\Projects\Setup>install.cmd "C:\program files (x86)"

-----------------
SETUP SCRIPT
-----------------

files was unexpected at this time.
C:\Projects\Setup>
</code>```

答:
If you have a path with spaces you must surround it with quotation marks (").

Not sure if that's exactly what you're asking though?

Body:
I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?

In my code i have the following

:READ_PWA_PATH
    if "%1" == "" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
            IF ERRORLEVEL ==2 GOTO CANCEL
            IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
    )

If I simply call the script I get the following error:

C:\Projects\Setup>install.cmd "C:\program files (x86)"

-----------------
SETUP SCRIPT
-----------------

files was unexpected at this time.
C:\Projects\Setup>


问:
Scala expression to replace a file extension in a string
Here is a version I wrote using split:

```<code>fileName.split('.').init ++ Seq("js") mkString "."
</code>```

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

答:
I'm afraid you actually have to make it longer to do what is probably the most sensible robust thing:

```<code>scala> "oops".split('.').init ++ Seq("js") mkString "."
res0: String = js
</code>```

Kinda unexpected to lose the name of your file (at least if you're an end user)!

Let's try regex:

```<code>scala> "oops".replaceAll("\\.[^.]*$", ".js")
res1: java.lang.String = oops
</code>```

Didn't lose the file name, but there's no extension either.  Ack.

Let's fix it:

```<code>def extensor(orig: String, ext: String) = (orig.split('.') match {
  case xs @ Array(x) => xs
  case y => y.init
}) :+ "js" mkString "."

scala> extensor("oops","js")
res2: String = oops.js

scala> extensor("oops.txt","js")
res3: String = oops.js

scala> extensor("oops...um...","js")
res4: String = oops...js
</code>```

Or with regex:

```<code>scala> "oops".replaceAll("\\.[^.]*$", "") + ".js"
res5: java.lang.String = oops.js

scala> "oops.txt".replaceAll("\\.[^.]*$", "") + ".js"
res6: java.lang.String = oops.js

scala> "oops...um...".replaceAll("\\.[^.]*$", "") + ".js"
res7: java.lang.String = oops...um...js
</code>```

(Note the different behavior on the corner case where the filename ends with periods.)

Body:
Here is a version I wrote using split:

fileName.split('.').init ++ Seq("js") mkString "."

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

Body:
I'm afraid you actually have to make it longer to do what is probably the most sensible robust thing:

scala> "oops".split('.').init ++ Seq("js") mkString "."
res0: String = js

Kinda unexpected to lose the name of your file (at least if you're an end user)!

Let's try regex:

scala> "oops".replaceAll("\\.[^.]*$", ".js")
res1: java.lang.String = oops

Didn't lose the file name, but there's no extension either.  Ack.

Let's fix it:

def extensor(orig: String, ext: String) = (orig.split('.') match {
  case xs @ Array(x) => xs
  case y => y.init
}) :+ "js" mkString "."

scala> extensor("oops","js")
res2: String = oops.js

scala> extensor("oops.txt","js")
res3: String = oops.js

scala> extensor("oops...um...","js")
res4: String = oops...js

Or with regex:

scala> "oops".replaceAll("\\.[^.]*$", "") + ".js"
res5: java.lang.String = oops.js

scala> "oops.txt".replaceAll("\\.[^.]*$", "") + ".js"
res6: java.lang.String = oops.js

scala> "oops...um...".replaceAll("\\.[^.]*$", "") + ".js"
res7: java.lang.String = oops...um...js

(Note the different behavior on the corner case where the filename ends with periods.)


问:
Python asyncio http request module
Here is how I'm making a request:

```<code>    from aiohttp import request
    def make_request(self, request_payload, request_headers, request_method, request_url_path):
        url = self.config["HOST_URL"] + "/" + request_url_path
        response = yield from request(request_method, url=url, params=request_payload, headers=request_headers, allow_redirects=False)
        return response
</code>```

The expected response in case of successful request here is response status 302 and a Location header in response, which will contain the url on which redirect needs to be done.

The issue is, I'm getting response status as 200, which is response from the final url. How can I achieve what I want?

"allow_redirects=False" should have worked, but it doesn't. I'm not sure how can I get it to work as I need.

答:
Note: if you use old generator-based syntax you should use decorator asyncio.coroutine. If you're using Python 3.5+ use new syntax for coroutines.

Please provide also minimal code snippet that can be reproduced (including url, other params, your Python version), since I don't get behavior you're talking about:

```<code>import asyncio
from aiohttp import request

@asyncio.coroutine
def make_request():
    url = 'http://httpbin.org/redirect/1'
    response = yield from request(method='GET', url=url, allow_redirects=False)
    print(response)

loop = asyncio.get_event_loop()
loop.run_until_complete(make_request())
</code>```

Output:

```<code><ClientResponse(http://httpbin.org/redirect/1) [302 FOUND]>
<CIMultiDictProxy('Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Wed, 15 Nov 2017 16:28:55 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '215', 'Location': '/get', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000524044036865', 'Via': '1.1 vegur')>
</code>```

Title: Python asyncio http request module

Body:
Here is how I'm making a request:

    from aiohttp import request
    def make_request(self, request_payload, request_headers, request_method, request_url_path):
        url = self.config["HOST_URL"] + "/" + request_url_path
        response = yield from request(request_method, url=url, params=request_payload, headers=request_headers, allow_redirects=False)
        return response

The expected response in case of successful request here is response status 302 and a Location header in response, which will contain the url on which redirect needs to be done.

The issue is, I'm getting response status as 200, which is response from the final url. How can I achieve what I want?

"allow_redirects=False" should have worked, but it doesn't. I'm not sure how can I get it to work as I need.

Body:
Note: if you use old generator-based syntax you should use decorator asyncio.coroutine. If you're using Python 3.5+ use new syntax for coroutines.

Please provide also minimal code snippet that can be reproduced (including url, other params, your Python version), since I don't get behavior you're talking about:

import asyncio
from aiohttp import request

@asyncio.coroutine
def make_request():
    url = 'http://httpbin.org/redirect/1'
    response = yield from request(method='GET', url=url, allow_redirects=False)
    print(response)

loop = asyncio.get_event_loop()
loop.run_until_complete(make_request())

Output:

<ClientResponse(http://httpbin.org/redirect/1) [302 FOUND]>
<CIMultiDictProxy('Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Wed, 15 Nov 2017 16:28:55 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '215', 'Location': '/get', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000524044036865', 'Via': '1.1 vegur')>


问:
order by absolute values of one column while keeping equal values of another column together in R
Example data.frame:

```<code>df <- data.frame(study = c('A', 'A', 'B', 'C', 'D', 'D'),
                 similarity = c(0.61, 0.58, -0.605, 0.4, 0.607, 0.3))

df
   study similarity
1     A      0.610
2     A      0.580
3     B     -0.605
4     C      0.400
5     D      0.607
6     D      0.300
</code>```

I want to order by absolute similarity, but keeping equal values of study together. For the above example the result should be:

```<code>   study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400
</code>```

答:
Here is an approach using tidyverse</p>

```<code>library(tidyverse)

 df %>%
    group_by(study) %>%  #group by study
    mutate(arr = max(abs(similarity))) %>% #get maximum absolute similarity by group
    ungroup() %>%
    arrange(desc(arr)) %>% #arrange according to by group maximum absolute similarity
    select(-arr) #leave the helper column out
#ouput

# A tibble: 6 x 2
   study similarity
  <fctr>      <dbl>
1      A      0.610
2      A      0.580
3      D      0.607
4      D      0.300
5      B     -0.605
6      C      0.400
</code>```

Body:
Example data.frame:

df <- data.frame(study = c('A', 'A', 'B', 'C', 'D', 'D'),
                 similarity = c(0.61, 0.58, -0.605, 0.4, 0.607, 0.3))

df
   study similarity
1     A      0.610
2     A      0.580
3     B     -0.605
4     C      0.400
5     D      0.607
6     D      0.300

I want to order by absolute similarity, but keeping equal values of study together. For the above example the result should be:

   study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400

Body:
Here is an approach using tidyverse

library(tidyverse)

 df %>%
    group_by(study) %>%  #group by study
    mutate(arr = max(abs(similarity))) %>% #get maximum absolute similarity by group
    ungroup() %>%
    arrange(desc(arr)) %>% #arrange according to by group maximum absolute similarity
    select(-arr) #leave the helper column out
#ouput

# A tibble: 6 x 2
   study similarity
  <fctr>      <dbl>
1      A      0.610
2      A      0.580
3      D      0.607
4      D      0.300
5      B     -0.605
6      C      0.400


问:
How to pull certain information from excel spreadsheet?
I am extremely new to python and want to learn how to pull certain elements from a data sheet. For example:

How many attributes/categories the data has?

How many missing values the data has?

How many columns the data has?

The frequency of an element in a single column

I have gotten as far as printing the data but am wondering how I can compute the above values via while loops or for loops

```<code>file=open('9car.csv','r')

M=[]
lines=file.readlines()
for row in lines:
     value=row.strip()
     items=value.split()
     # print(items)
     print(value)
     # print(values)

for row in M:
     count=len(row)
     print(count)
</code>```

答:
For answering questions like these, pandas would be a better and convenient option.</p>

```<code>import pandas as pd
df = pd.read_csv('9car.csv')
1. df['col_name'].unique()
2. pd.isnull(df['col_name']).sum()
3. len(df.columns)
4. df['col_name'].value_count()
</code>```

Body:
I am extremely new to python and want to learn how to pull certain elements from a data sheet. For example:

How many attributes/categories the data has?

How many missing values the data has?

How many columns the data has?

The frequency of an element in a single column

I have gotten as far as printing the data but am wondering how I can compute the above values via while loops or for loops

file=open('9car.csv','r')

M=[]
lines=file.readlines()
for row in lines:
     value=row.strip()
     items=value.split()
     # print(items)
     print(value)
     # print(values)

for row in M:
     count=len(row)
     print(count)

Body:
For answering questions like these, pandas would be a better and convenient option.

import pandas as pd
df = pd.read_csv('9car.csv')
1. df['col_name'].unique()
2. pd.isnull(df['col_name']).sum()
3. len(df.columns)
4. df['col_name'].value_count()


问:
RegEx for match/replacing JavaScript comments (both multiline and inline)
I need to remove all JavaScript comments from a JavaScript source using the JavaScript RegExp object.

What I need is the pattern for the RegExp.

So far, I've found this:

```<code>compressed = compressed.replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, '');
</code>```

This pattern works OK for:

```<code>/* I'm a comment */
</code>```

or for:

```<code>/*
 * I'm a comment aswell
*/
</code>```

But doesn't seem to work for the inline:

```<code>// I'm an inline comment
</code>```

I'm not quite an expert for RegEx and it's patterns, so I need help.

Also, I' would like to have a RegEx pattern which would remove all those HTML-like comments.

```<code><!-- HTML Comment //--> or <!-- HTML Comment -->
</code>```

And also those conditional HTML comments, which can be found in various JavaScript sources.

Thanks.

答:
In plain simple JS regex, this:</p>

```<code>my_string_or_obj.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, ' ')
</code>```

Body:
I need to remove all JavaScript comments from a JavaScript source using the JavaScript RegExp object.

What I need is the pattern for the RegExp.

So far, I've found this:

compressed = compressed.replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, '');

This pattern works OK for:

/* I'm a comment */

or for:

/*
 * I'm a comment aswell
*/

But doesn't seem to work for the inline:

// I'm an inline comment

I'm not quite an expert for RegEx and it's patterns, so I need help.

Also, I' would like to have a RegEx pattern which would remove all those HTML-like comments.

 or

And also those conditional HTML comments, which can be found in various JavaScript sources.

Thanks.

Body:
In plain simple JS regex, this:

my_string_or_obj.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, ' ')

ContentLicense: CC BY-SA 4.0


问:
Flicker, orkut, picasa API for Flex? Need API?Please help?
I have to work on one new project, there we have to provide an option to download images from any website like, Orkut, picasa etc, so that the user, can view his/her pictures any time and his/her images are accessible any time, so i heard of APIs, that we developer can use.

i hope u r getting me, i saw tour de flex, there are few available API like for Flicker, they have ready made API, but i need to work on Facebook, Picasso, Photobucket, etc

please if any body of you having any solution on this, then plzz help me out,

Thanks in advance

答: You may try Picasa Flex AP for picasa.</p>

Body: You may try Picasa Flex AP for picasa.


问:
Replacing values in same column and same dataset in R
I have a dataset like this:

```<code>Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121
</code>```

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

```<code>ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"
</code>```

But the column still has a bunch of LS in there. Any ideas?

答:
With dplyr:

```<code>df <- tibble(Name = c("John", "Jack", "Job"), Material = c("LS", "Limestone", "LI"), Project = c(222, 111, 121))

df %>% mutate(Material = stringr::str_trim(Material)) %>%
        mutate(Material = case_when(
                              Material %in% c('LS', 'LI') ~ 'Limestone',
                              TRUE ~ Material
                              )
              )
</code>```

Body:
I have a dataset like this:

Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"

But the column still has a bunch of LS in there. Any ideas?

Body:
With dplyr:

df <- tibble(Name = c("John", "Jack", "Job"), Material = c("LS", "Limestone", "LI"), Project = c(222, 111, 121))

df %>% mutate(Material = stringr::str_trim(Material)) %>%
        mutate(Material = case_when(
                              Material %in% c('LS', 'LI') ~ 'Limestone',
                              TRUE ~ Material
                              )
              )


问:
how to change direction of TOC in aspose.word for C# .Net
I create a table of content by Aspose.Word but my document direction is right to left and i want to change direction to rtl.</p>

答:
Please use the following code example to create the table of content in right to left direction. Hope this helps you.

```<code>Document doc = new Document(MyDir + "in.docx");

// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.

builder.Font.LocaleIdBi = 1025;
builder.ParagraphFormat.Bidi = true;
builder.Font.NameBi = "Heading 1";
builder.Font.SizeBi = 10;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Bidi = true;

doc.Styles[StyleIdentifier.Toc1].ParagraphFormat.Bidi = true;
doc.Styles[StyleIdentifier.Toc1].Font.Bidi = true;

builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
builder.Writeln();

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("مرحبا هناك ما هو اسمك وماذا تفعل في هذا");

// Call the method below to update the TOC.
doc.UpdateFields();
doc.Save(MyDir + "output.docx");
</code>```

I work with Aspose as Developer Evangelist.

Body:
Please use the following code example to create the table of content in right to left direction. Hope this helps you.

Document doc = new Document(MyDir + "in.docx");

// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.

builder.Font.LocaleIdBi = 1025;
builder.ParagraphFormat.Bidi = true;
builder.Font.NameBi = "Heading 1";
builder.Font.SizeBi = 10;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Bidi = true;

doc.Styles[StyleIdentifier.Toc1].ParagraphFormat.Bidi = true;
doc.Styles[StyleIdentifier.Toc1].Font.Bidi = true;

builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
builder.Writeln();

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("مرحبا هناك ما هو اسمك وماذا تفعل في هذا");

// Call the method below to update the TOC.
doc.UpdateFields();
doc.Save(MyDir + "output.docx");

I work with Aspose as Developer Evangelist.


问:
PHP: How to iterate over array to retrieve incremental value (n, n+1, etc)
I have an array like this

```<code>$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
</code>```

And a index number

```<code>$index = 3;
</code>```

Is there a simple way to iterate over $data to get

```<code>$first = array(51729,8242,19610)
$second = array(49359,8124,18030)
$third = array(47548,8716,15698)
</code>```

Is array_chunk() and then foreach the chunks the way to go?

Edit: Here is how I made it with array_chunk()

```<code>$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
$index = 3;
$chunks = array_chunk($data, $index);
$first = array();
$second = array();
$third = array();
foreach($chunks as $out) {
    $first[] = $out[0];
    $second[] = $out[1];
    $third[] = $out[2];
}
</code>```

Edit 2: All of this is part of transforming a unidimensional array to multidimensional, naming will eventually be dynamic, based on values in array $labels. Index number is also going to change ($index is provided in original array).

答:
If you are looking to do this non-dynamically. i.e. it will always be named this way, you're looking to continuously iterate in this manner with little changing, then the following code will be sufficient.</p>

```<code>$i = 1;
foreach($data as $arr){
 switch($i){
  case 1:
   array_push($first, $arr);
   break;
  case 2:
   array_push($second, $arr);
   break;
  case 3:
   array_push($third, $arr);
   break;
 }

$i++;
if($i == 4){
$i = 1;
 }
}
</code>```

Body:
I have an array like this

$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);

And a index number

$index = 3;

Is there a simple way to iterate over $data to get

$first = array(51729,8242,19610)
$second = array(49359,8124,18030)
$third = array(47548,8716,15698)

Is array_chunk() and then foreach the chunks the way to go?

Edit: Here is how I made it with array_chunk()

$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
$index = 3;
$chunks = array_chunk($data, $index);
$first = array();
$second = array();
$third = array();
foreach($chunks as $out) {
    $first[] = $out[0];
    $second[] = $out[1];
    $third[] = $out[2];
}

Edit 2: All of this is part of transforming a unidimensional array to multidimensional, naming will eventually be dynamic, based on values in array $labels. Index number is also going to change ($index is provided in original array).

Body:
If you are looking to do this non-dynamically. i.e. it will always be named this way, you're looking to continuously iterate in this manner with little changing, then the following code will be sufficient.

$i = 1;
foreach($data as $arr){
 switch($i){
  case 1:
   array_push($first, $arr);
   break;
  case 2:
   array_push($second, $arr);
   break;
  case 3:
   array_push($third, $arr);
   break;
 }

$i++;
if($i == 4){
$i = 1;
 }
}