问:
Create and Plot spatial objects in R with lat, long & azimuth
Looking for some help..
I am trying to create and plot spatial objects in R based on lat, long & azimuth. Azimuth is the angle separation at a given lat, long. Expected output as shown in below image where the objects are filled with blue color:

Input data:

```<code>df <- data.frame(Latitude = c(32.897, 32.897, 32.897, 32.811, 32.811, 32.811),
                 Longitude = c(-97.04, -97.04, -97.04, -97.12, -97.12, -97.12),
                 Azimuth = c(0, 120, 240, 60, 200, 240),
                 Site = c("A", "A", "A", "B", "B", "B"),
                 Sector = c(1,2,3,1,2,3),
                 stringsAsFactors = F)
</code>```

答:
```<code>#Convert df into a spatial object:
library(sp)
coordinates(df)<-~Longitude+Latitude

#Simple plot:
plot(df, col="Blue")

#Plot with icons:
plot(df, col="Blue", pch=24)
plot(df, col="Blue", pch=25, add=TRUE)

#Plot on a map: (You need the associated projection)
proj4string(df) = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

library(mapview)
mapview(df)
</code>```

Body:
Looking for some help..
I am trying to create and plot spatial objects in R based on lat, long & azimuth. Azimuth is the angle separation at a given lat, long. Expected output as shown in below image where the objects are filled with blue color:

Input data:

df <- data.frame(Latitude = c(32.897, 32.897, 32.897, 32.811, 32.811, 32.811),
                 Longitude = c(-97.04, -97.04, -97.04, -97.12, -97.12, -97.12),
                 Azimuth = c(0, 120, 240, 60, 200, 240),
                 Site = c("A", "A", "A", "B", "B", "B"),
                 Sector = c(1,2,3,1,2,3),
                 stringsAsFactors = F)


来源: stackexchange

问:
Array Filter in Angular
i have json array get from http web api, i want to filter this array:

```<code>    [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}]
</code>```

i need to filter or select for get all where id_segmen=1.
this is my expectation :

```<code> [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
}]
</code>```

my current http.get is as below:

```<code>this.http.get<JuResponse>(environment.url + '/cps/' + year + '/' + month + '/' + kanwil + '/' + cabang).
   subscribe(data => {
       let filteredValues = data.filter((data) => value.id_segmen == 1);
       console.log(filteredValues);
});
</code>```

答:
You can use Array.filter

```<code>let filteredArray = this.myArray.filter(item => item.id_segment===1)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Array Filter in Angular

Body:
i have json array get from http web api, i want to filter this array:

    [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}]

i need to filter or select for get all where id_segmen=1.
this is my expectation :

 [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
}]

my current http.get is as below:

this.http.get<JuResponse>(environment.url + '/cps/' + year + '/' + month + '/' + kanwil + '/' + cabang).
   subscribe(data => {
       let filteredValues = data.filter((data) => value.id_segmen == 1);
       console.log(filteredValues);
});

Body:
You can use Array.filter

let filteredArray = this.myArray.filter(item => item.id_segment===1)


问:
wmic cpu get LoadPercentage always returns empty value
I'm use wmic command to get current CPU utilization, the command are:

```<code>wmic cpu get LoadPercentage /value
</code>```

It's works fine at first, but somehow it doesn't shows the LoadPercentage, but always returns with empty result like:

```<code>C:\Users\Administrator>wmic cpu get LoadPercentage /value

LoadPercentage=
</code>```

It's so weird and I'm pretty sure that the result don't match with the taskmgr.exe. I also tried this command without /value, the result is still the same.

I have copy a large file in my server, and the CPU usage in TaskManager and wmic is like:

no matter what value is in TaskManager, the wmic always return empty value.

答: I understand that this is an answer for a necro post. But as I can't see any correct answer here, the solution is lodctr /R . This command will reload counters. Must use a capital R, lower case 'r' returns an error. Remember Admin Privs as well.

Body:
I'm use wmic command to get current CPU utilization, the command are:

wmic cpu get LoadPercentage /value

It's works fine at first, but somehow it doesn't shows the LoadPercentage, but always returns with empty result like:

C:\Users\Administrator>wmic cpu get LoadPercentage /value

LoadPercentage=

It's so weird and I'm pretty sure that the result don't match with the taskmgr.exe. I also tried this command without /value, the result is still the same.

I have copy a large file in my server, and the CPU usage in TaskManager and wmic is like:

no matter what value is in TaskManager, the wmic always return empty value.


问:
Instrumenting java core classes
I need to add a variable in java.lang.string for some instrumentation purpose. Is it possible to do ? I am getting the following exception when i do:</p>

```<code>java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)
    at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:170)
    at com.javapapers.java.instrumentation.DurationAgent.premain(DurationAgent.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
</code>```

答:
Actually, the exception does already contain all relevant information. The exception’s type name java.lang.UnsupportedOperationException contains the term “unsupport operation” and its message does name the unsupported operation: “attempted to change the schema (add/remove fields)”.

In other words, adding or removing fields during a class redefinition is not supported by the HotSpot JVM, whether attempted on a core class or any other class. As the documentation states:

The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. These restrictions maybe be lifted in future versions.

For other classes, load time Instrumentation may help, changing the declared fields before its first definition in the runtime, however, for a crucial class like java.lang.String, which must be present before even Agents can be loaded, that is not an option.

The only possible way to change the String class is to prepend an alternative implementation to the bootstrap class path on JVM startup, however, I strongly discourage from altering the configuration in such a way. You can break the entire JVM too easily when playing with such a fundamental class, it’s even that, what happen to work with one JVM (version), may break the other (or next version)…

Title: Instrumenting java core classes

Body:
I need to add a variable in java.lang.string for some instrumentation purpose. Is it possible to do ? I am getting the following exception when i do:

java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)
    at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:170)
    at com.javapapers.java.instrumentation.DurationAgent.premain(DurationAgent.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)


问:
Highcharts: Column chart with pointIntervalUnit month causes incorrect spaces?
I want to create a column chart with no spaces and no overlapping between the columns based on a datetime x-axis.

```<code>Highcharts.chart('container', {
    chart: { type: 'column' },
    title: {
        text: 'Month columns'
    },
    xAxis: {
        type: 'datetime',
    },
    legend: {
        enabled: false
    },
    plotOptions: {
        column: {
            groupPadding: 0,
            pointPadding: 0,
            borderWidth: 0,
            grouping: false
        }
    },
    series: [{
        pointIntervalUnit: 'month',
        pointPadding: 0,
        groupPadding: 0,
        name: 'Test',
        negativeColor: 'rgb(223,83,83)',
        data: [{x: Date.UTC(2016,11), y:-1000},{x:Date.UTC(2017,0), y:-500}, {x:Date.UTC(2017,1), y: 500}, {x:Date.UTC(2017,2), y: 300}],
    }]
});
</code>```

The following fiddle shows the problem:
Spaces between columns.

The goal is that there are no spaces in between the columns and they don't overlap. I assume that the space is caused by the changing duration of a month e.g. 30 days, 31 days, 28 days, ... but i thought this is handled by the pointIntervalUnit: month option?

Any ideas on alternative series arrangements with the expected result are highly appreciated.

Many thanks for any help on this.

答:
The problem here is caused by the default pointRange value: https://api.highcharts.com/highcharts/plotOptions.column.pointRange

In this case it equals to 28 days - length of the shortest month - February 2017 (28 days).

There's no possibility in Highcharts to manipulate a single point using pointRange or  pointWidth (these options apply only to a series).

The easiest solution for this is simply to change the type of the x axis to 'linear' (default) and use categories.

Live demo: https://jsfiddle.net/kkulig/ua4a14vu/

Body:
I want to create a column chart with no spaces and no overlapping between the columns based on a datetime x-axis.

Highcharts.chart('container', {
    chart: { type: 'column' },
    title: {
        text: 'Month columns'
    },
    xAxis: {
        type: 'datetime',
    },
    legend: {
        enabled: false
    },
    plotOptions: {
        column: {
            groupPadding: 0,
            pointPadding: 0,
            borderWidth: 0,
            grouping: false
        }
    },
    series: [{
        pointIntervalUnit: 'month',
        pointPadding: 0,
        groupPadding: 0,
        name: 'Test',
        negativeColor: 'rgb(223,83,83)',
        data: [{x: Date.UTC(2016,11), y:-1000},{x:Date.UTC(2017,0), y:-500}, {x:Date.UTC(2017,1), y: 500}, {x:Date.UTC(2017,2), y: 300}],
    }]
});

The following fiddle shows the problem:
Spaces between columns.

The goal is that there are no spaces in between the columns and they don't overlap. I assume that the space is caused by the changing duration of a month e.g. 30 days, 31 days, 28 days, ... but i thought this is handled by the pointIntervalUnit: month option?

Any ideas on alternative series arrangements with the expected result are highly appreciated.

Many thanks for any help on this.


问:
How to take the exception thrown by a constructor using a ByteBuddy agent?
I'm trying to log every call, returned objects and exceptions thrown in methods and constructors using a ByteBuddy (v1.7.9) java agent, without iterfering with the normal functioning of the instrumented code.

My current instantiation of the agent is

```<code>new AgentBuilder.Default()
                .with(AgentBuilder.Listener.StreamWriting.toSystemOut())
                .type((typeDescription, classLoader, module, classBeingRedefined, protectionDomain) ->
                     matcher.matchesIncoming(typeDescription.getTypeName()))
                .transform((builder, typeDescription, classLoader, javaModule) -> builder
                        .visit(Advice.to(CustomAdvicer.class).on(ElementMatchers.any())))
                .installOn(inst);
</code>```

I have started with the simplest "advicer",

```<code>public class CustomAdvicer {
    @Advice.OnMethodEnter
    public static void enter(@Advice.Origin String origin) {
        System.out.println("Entering " + origin);
    }

    @Advice.OnMethodExit(onThrowable = Throwable.class)
    public static void exit(
        @Advice.Return(typing = Assigner.Typing.DYNAMIC) @RuntimeType Object value,
        @Advice.Origin String origin,
        @Advice.Thrown Throwable thrown) {
        System.out.println("Exiting " + origin);
    }
}
</code>```

However when I run the program I get an exception from bytebuddy:

```<code>[Byte Buddy] ERROR some.pack.Thrower [sun.misc.Launcher$AppClassLoader@18b4aac2, null, loaded=false]
java.lang.IllegalStateException: Cannot catch exception during constructor call for public some.pack.Thrower() throws java.lang.Exception
    at net.bytebuddy.asm.Advice.doWrap(Advice.java:515)
    at net.bytebuddy.asm.Advice.wrap(Advice.java:470)
    at net.bytebuddy.asm.AsmVisitorWrapper$ForDeclaredMethods$Entry.wrap(AsmVisitorWrapper.java:481)
    at net.bytebuddy.asm.AsmVisitorWrapper$ForDeclaredMethods$DispatchingVisitor.visitMethod(AsmVisitorWrapper.java:562)
    at net.bytebuddy.jar.asm.ClassVisitor.visitMethod(ClassVisitor.java:327)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining$RedefinitionClassVisitor.visitMethod(TypeWriter.java:3801)
    at net.bytebuddy.jar.asm.ClassReader.readMethod(ClassReader.java:1020)
    at net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:698)
    at net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:500)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining.create(TypeWriter.java:2941)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1633)
    at net.bytebuddy.dynamic.scaffold.inline.RebaseDynamicTypeBuilder.make(RebaseDynamicTypeBuilder.java:200)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$Transformation$Simple$Resolution.apply(AgentBuilder.java:8905)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.doTransform(AgentBuilder.java:9306)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:9269)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.access$1300(AgentBuilder.java:9047)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$LegacyVmDispatcher.run(AgentBuilder.java:9625)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$LegacyVmDispatcher.run(AgentBuilder.java:9575)
    at java.security.AccessController.doPrivileged(Native Method)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:9194)
    at sun.instrument.TransformerManager.transform(Unknown Source)
    at sun.instrument.InstrumentationImpl.transform(Unknown Source)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at Main.main(Main.java:23)
</code>```

So, what should I do in order to log the exceptions thrown inside constructors, bearing in mind that it must not interfere with the original code?

By the way, the Thrower class is a silly class I wrote to test this case:

```<code>package some.pack;

public class Thrower {
  public Thrower() throws Exception {
    throw new Exception("By courtesy of thrower! ;)");
  }
}
</code>```

答:
The problem is that a constructor has an implicit first instruction which is the invocation of another or a super constructor. Your Thrower class really looks like this:

```<code>public class Thrower {
  public Thrower() throws Exception {
    super();
    throw new Exception("By courtesy of thrower! ;)");
  }
}
</code>```

If you wanted to wrap the entire call in a try-catch block, this would yield this:

```<code>public class Thrower {
  public Thrower() throws Exception {
    try {
      super();
      throw new Exception("By courtesy of thrower! ;)");
    } catch (Exception e) {
      ...
    }
  }
}
</code>```

But this is not legal in the JVM and therefore, Byte Buddy does not allow it. There is neither a good way to exclude the super constructor call as this being the first call is only a Java language convention but byte code allows more arbitrary combinations. As you cannot know what language a class comes from, Byte Buddy does not try any tricks here and simply does not allow it.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to log every call, returned objects and exceptions thrown in methods and constructors using a ByteBuddy (v1.7.9) java agent, without iterfering with the normal functioning of the instrumented code.

My current instantiation of the agent is

new AgentBuilder.Default()
                .with(AgentBuilder.Listener.StreamWriting.toSystemOut())
                .type((typeDescription, classLoader, module, classBeingRedefined, protectionDomain) ->
                     matcher.matchesIncoming(typeDescription.getTypeName()))
                .transform((builder, typeDescription, classLoader, javaModule) -> builder
                        .visit(Advice.to(CustomAdvicer.class).on(ElementMatchers.any())))
                .installOn(inst);

I have started with the simplest "advicer",

public class CustomAdvicer {
    @Advice.OnMethodEnter
    public static void enter(@Advice.Origin String origin) {
        System.out.println("Entering " + origin);
    }

    @Advice.OnMethodExit(onThrowable = Throwable.class)
    public static void exit(
        @Advice.Return(typing = Assigner.Typing.DYNAMIC) @RuntimeType Object value,
        @Advice.Origin String origin,
        @Advice.Thrown Throwable thrown) {
        System.out.println("Exiting " + origin);
    }
}

However when I run the program I get an exception from bytebuddy:

[Byte Buddy] ERROR some.pack.Thrower [sun.misc.Launcher$AppClassLoader@18b4aac2, null, loaded=false]
java.lang.IllegalStateException: Cannot catch exception during constructor call for public some.pack.Thrower() throws java.lang.Exception
    at net.bytebuddy.asm.Advice.doWrap(Advice.java:515)
    at net.bytebuddy.asm.Advice.wrap(Advice.java:470)
    at net.bytebuddy.asm.AsmVisitorWrapper$ForDeclaredMethods$Entry.wrap(AsmVisitorWrapper.java:481)
    at net.bytebuddy.asm.AsmVisitorWrapper$ForDeclaredMethods$DispatchingVisitor.visitMethod(AsmVisitorWrapper.java:562)
    at net.bytebuddy.jar.asm.ClassVisitor.visitMethod(ClassVisitor.java:327)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining$RedefinitionClassVisitor.visitMethod(TypeWriter.java:3801)
    at net.bytebuddy.jar.asm.ClassReader.readMethod(ClassReader.java:1020)
    at net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:698)
    at net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:500)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining.create(TypeWriter.java:2941)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1633)
    at net.bytebuddy.dynamic.scaffold.inline.RebaseDynamicTypeBuilder.make(RebaseDynamicTypeBuilder.java:200)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$Transformation$Simple$Resolution.apply(AgentBuilder.java:8905)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.doTransform(AgentBuilder.java:9306)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:9269)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.access$1300(AgentBuilder.java:9047)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$LegacyVmDispatcher.run(AgentBuilder.java:9625)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$LegacyVmDispatcher.run(AgentBuilder.java:9575)
    at java.security.AccessController.doPrivileged(Native Method)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:9194)
    at sun.instrument.TransformerManager.transform(Unknown Source)
    at sun.instrument.InstrumentationImpl.transform(Unknown Source)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at Main.main(Main.java:23)

So, what should I do in order to log the exceptions thrown inside constructors, bearing in mind that it must not interfere with the original code?

By the way, the Thrower class is a silly class I wrote to test this case:

package some.pack;

public class Thrower {
  public Thrower() throws Exception {
    throw new Exception("By courtesy of thrower! ;)");
  }
}

Body:
The problem is that a constructor has an implicit first instruction which is the invocation of another or a super constructor. Your Thrower class really looks like this:

public class Thrower {
  public Thrower() throws Exception {
    super();
    throw new Exception("By courtesy of thrower! ;)");
  }
}

If you wanted to wrap the entire call in a try-catch block, this would yield this:

public class Thrower {
  public Thrower() throws Exception {
    try {
      super();
      throw new Exception("By courtesy of thrower! ;)");
    } catch (Exception e) {
      ...
    }
  }
}

But this is not legal in the JVM and therefore, Byte Buddy does not allow it. There is neither a good way to exclude the super constructor call as this being the first call is only a Java language convention but byte code allows more arbitrary combinations. As you cannot know what language a class comes from, Byte Buddy does not try any tricks here and simply does not allow it.


问:
Getting Akka.NET to connect to a remote addresses
All the demos I have found showing how to get started with remoting in Akka.NET demonstrate the simplest use case where the two actors are running on the same machine using localhost.

I am trying to get an Akka.NET actor to connect to a remote machine and have run into some difficulty.

The code is extremely simple:

Client Code:

```<code>var config = ConfigurationFactory.ParseString(@"
    akka {
        log-config-on-start = on
        stdout-loglevel = DEBUG
        loglevel = DEBUG
        actor {
            provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""

            debug {
                receive = on
                autoreceive = on
                lifecycle = on
                event-stream = on
                unhandled = on
            }

            deployment {
                /remoteactor {
                    router = round-robin-pool
                    nr-of-instances = 5
                    remote = ""akka.tcp://system2@xxx.australiasoutheast.cloudapp.azure.com:666""
                }
            }
        }
        remote {
            dot-netty.tcp {
                port = 0
                hostname = localhost
            }
        }
    }
");

using (var system = ActorSystem.Create("system1", config))
{
    Console.ReadLine();
}
</code>```

Server Code:

```<code>var config = ConfigurationFactory.ParseString(@"
akka {
    log-config-on-start = on
    stdout-loglevel = DEBUG
    loglevel = DEBUG
    actor {
        provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""

        debug {
            receive = on
            autoreceive = on
            lifecycle = on
            event-stream = on
            unhandled = on
        }
    }
    remote {
        dot-netty.tcp {
            transport-protocol = tcp
            port = 666
            hostname = ""10.0.0.4"" //This is the local IP address
        }
    }
}
");

using (ActorSystem.Create("system2", config))
{
    Console.ReadLine();
}
</code>```

I can successfully connect when I run the actor process on another machine on my local network but when I distribute the same simple example onto a cloud VM I receive the following error:

```<code>[ERROR][11/9/2017 3:58:45 PM][Thread 0008][[akka://system2/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2Fsystem1%40localhost%3A28456-1/endpointWriter#1657012126]] Dropping message [Akka.Remote.DaemonMsgCreate] for non-local recipient [[akka.tcp://system2@xxx.australiasoutheast.cloudapp.azure.com:666/remote]] arriving at [akka.tcp://system2@xxx.australiasoutheast.cloudapp.azure.com:666] inbound addresses [akka.tcp://system2@10.0.0.4:666]
Cause: Unknown
</code>```

I have also tried using "127.0.0.1" but that doesn't seem to work either locally or over the net.

Could anyone provide any input on what I might be doing wrong?

UPDATE:

I have tried to use the bind-hostname and bind-port options available in Akka.NET as this is supposed to get around the NAT issues I believe I am suffering. Unfortunately this doesn't seem to work either, I have tried various configuration options such as using the hostname and IP address as shown below:

```<code>remote {
    dot-netty.tcp {
        port = 666
        hostname = "13.73.xx.xx"

        bind-port = 666
        bind-hostname = "0.0.0.0"

    }
}
</code>```

The error message I receive when I try the above configuration is:

```<code>[ERROR][11/12/2017 5:19:58 AM][Thread 0003][Akka.Remote.Transport.DotNetty.TcpTransport] Failed to bind to 13.73.xx.xx:666; shutting down DotNetty transport.
Cause: System.AggregateException: One or more errors occurred. ---> System.Net.Sockets.SocketException: The requested address is not valid in its context
</code>```

答:
A few remarks:

In your server config have it bind to 0.0.0.0. (hostname = 0.0.0.0) This way the socket will bind to all local endpoints, in case your cloud hosted env uses multiple network endpoints.
Then use set the public-hostname = xxx.australiasoutheast.cloudapp.azure.com. This way the hostname for the server instance is the same as the remoting address you are using in your remoting url.

Do note that the public-hostname (and hostname, if you are not using public-hostname) must be DNS resolvable.

Body:
All the demos I have found showing how to get started with remoting in Akka.NET demonstrate the simplest use case where the two actors are running on the same machine using localhost.

I am trying to get an Akka.NET actor to connect to a remote machine and have run into some difficulty.

The code is extremely simple:

Client Code:

var config = ConfigurationFactory.ParseString(@"
    akka {
        log-config-on-start = on
        stdout-loglevel = DEBUG
        loglevel = DEBUG
        actor {
            provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""

            debug {
                receive = on
                autoreceive = on
                lifecycle = on
                event-stream = on
                unhandled = on
            }

            deployment {
                /remoteactor {
                    router = round-robin-pool
                    nr-of-instances = 5
                    remote = ""akka.tcp://system2@xxx.australiasoutheast.cloudapp.azure.com:666""
                }
            }
        }
        remote {
            dot-netty.tcp {
                port = 0
                hostname = localhost
            }
        }
    }
");

using (var system = ActorSystem.Create("system1", config))
{
    Console.ReadLine();
}

Server Code:

var config = ConfigurationFactory.ParseString(@"
akka {
    log-config-on-start = on
    stdout-loglevel = DEBUG
    loglevel = DEBUG
    actor {
        provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""

        debug {
            receive = on
            autoreceive = on
            lifecycle = on
            event-stream = on
            unhandled = on
        }
    }
    remote {
        dot-netty.tcp {
            transport-protocol = tcp
            port = 666
            hostname = ""10.0.0.4"" //This is the local IP address
        }
    }
}
");

using (ActorSystem.Create("system2", config))
{
    Console.ReadLine();
}

I can successfully connect when I run the actor process on another machine on my local network but when I distribute the same simple example onto a cloud VM I receive the following error:

[ERROR][11/9/2017 3:58:45 PM][Thread 0008][[akka://system2/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2Fsystem1%40localhost%3A28456-1/endpointWriter#1657012126]] Dropping message [Akka.Remote.DaemonMsgCreate] for non-local recipient [[akka.tcp://system2@xxx.australiasoutheast.cloudapp.azure.com:666/remote]] arriving at [akka.tcp://system2@xxx.australiasoutheast.cloudapp.azure.com:666] inbound addresses [akka.tcp://system2@10.0.0.4:666]
Cause: Unknown

I have also tried using "127.0.0.1" but that doesn't seem to work either locally or over the net.

Could anyone provide any input on what I might be doing wrong?

UPDATE:

I have tried to use the bind-hostname and bind-port options available in Akka.NET as this is supposed to get around the NAT issues I believe I am suffering. Unfortunately this doesn't seem to work either, I have tried various configuration options such as using the hostname and IP address as shown below:

remote {
    dot-netty.tcp {
        port = 666
        hostname = "13.73.xx.xx"

        bind-port = 666
        bind-hostname = "0.0.0.0"

    }
}

The error message I receive when I try the above configuration is:

[ERROR][11/12/2017 5:19:58 AM][Thread 0003][Akka.Remote.Transport.DotNetty.TcpTransport] Failed to bind to 13.73.xx.xx:666; shutting down DotNetty transport.
Cause: System.AggregateException: One or more errors occurred. ---> System.Net.Sockets.SocketException: The requested address is not valid in its context


问:
How to make gcc warn about passing wrong enum to a function
gcc doesn't seem to produce a warning with the following code. How can I get it to produce a warning?</p>

```<code>typedef enum
{
    REG8_A,
    REG8_B,
    REG8_C
}REG8;

typedef enum
{
    REG16_A,
    REG16_B,
    REG16_C
}REG16;

void function(REG8 reg8)
{

}

int main(void)
{
    function(REG16_A);    // Should warn about wrong enum
}
</code>```

答:
As others have pointed out, C does not differentiate between an enumerated type and the underlying integer type.  (Some compilers might include type-checking for enums or typedefs as extensions; YMMV.)

To get type-checking in C, you can use structs, but then you lose use of the built-in comparison operators and the ability to switch on a variable.  You might try something like this, though:

```<code>typedef struct {
    enum {
        reg8_val_A,
        reg8_val_B,
        reg8_val_C,
    } val;
} reg8;
#define reg8_A (reg8){.val = reg8_val_A}
#define reg8_B (reg8){.val = reg8_val_B}
#define reg8_C (reg8){.val = reg8_val_C}
…
bool
is_A_or_B(reg8 reg) {
    if reg.val == reg8_A.val    // one way to compare
        return true;
    switch (reg.val) {
        case reg8_val_B:        // the other way to compare; note that
            return true;        // “case reg8_B.val:” will *not* work
        case reg8_val_C:
            return false;
        default:
            fprintf(stderr, "bad reg value %d\n", reg.val);
            abort();
    }
}
</code>```

(Uses some C99 features.)

ContentLicense: CC BY-SA 2.5

Body:
gcc doesn't seem to produce a warning with the following code. How can I get it to produce a warning?

typedef enum
{
    REG8_A,
    REG8_B,
    REG8_C
}REG8;

typedef enum
{
    REG16_A,
    REG16_B,
    REG16_C
}REG16;

void function(REG8 reg8)
{

}

int main(void)
{
    function(REG16_A);    // Should warn about wrong enum
}

Body:
As others have pointed out, C does not differentiate between an enumerated type and the underlying integer type.  (Some compilers might include type-checking for enums or typedefs as extensions; YMMV.)

To get type-checking in C, you can use structs, but then you lose use of the built-in comparison operators and the ability to switch on a variable.  You might try something like this, though:

typedef struct {
    enum {
        reg8_val_A,
        reg8_val_B,
        reg8_val_C,
    } val;
} reg8;
#define reg8_A (reg8){.val = reg8_val_A}
#define reg8_B (reg8){.val = reg8_val_B}
#define reg8_C (reg8){.val = reg8_val_C}
…
bool
is_A_or_B(reg8 reg) {
    if reg.val == reg8_A.val    // one way to compare
        return true;
    switch (reg.val) {
        case reg8_val_B:        // the other way to compare; note that
            return true;        // “case reg8_B.val:” will *not* work
        case reg8_val_C:
            return false;
        default:
            fprintf(stderr, "bad reg value %d\n", reg.val);
            abort();
    }
}

(Uses some C99 features.)


问:
Match multiple words in any order via one regex
as stated in heading I want regex which will give me results in order based on my 'query'.

```<code>line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'**
</code>```

Example 1:

```<code>re.findall(r'FREQ="(.*?)"|VERSION="(.*?)"', line, re.MULTILINE)
</code>```

Output is:

```<code>[('', 'OTHER'), ('OFF', '')]
</code>```

And desired output I prefer is something like:

```<code>['OFF', 'OTHER']
</code>```

Example 2:

```<code>re.findall(r'VERSION="(.*?)"|FREQ="(.*?)"', line, re.MULTILINE)
</code>```

Output is the same:

```<code>[('', 'OTHER'), ('OFF', '')]
</code>```

And desired output I prefer is something like:

```<code>['OTHER', 'OFF']
</code>```

Any suggestion?

P.S.
Please don't ask me what I want to achieve and tell me that there is maybe better way, only if you have some question regarding this.

Thank you!

答:
You may leverage a non-capturing alternation group to match either VERSION or FREQ (optionally preceded with a word boundary, just check if it meets your requirements):

```<code>\b(?:VERSION|FREQ)="(.*?)"
</code>```

See the regex demo

Details

\b - a leading word boundary

(?:VERSION|FREQ) - either VERSION or FREQ

=" - a =" substring

(.*?) - Group 1 (the actual output of findall): any 0+ chars other than line break chars, as few as possible

" -  a double quote.

See the Python demo:

```<code>import re
line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'
print(re.findall(r'\b(?:VERSION|FREQ)="(.*?)"', line))
# => ['OTHER', 'OFF']
</code>```

A better idea, perhaps, is to capture key-value pairs and map them to a dictionary:

```<code>import re
line = 'VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'
results = re.findall(r'(VERSION|FREQ)="(.*?)"', line)
print(dict(results))
# => {'FREQ': 'OFF', 'VERSION': 'OTHER'}
</code>```

See the Python demo.

Body:
as stated in heading I want regex which will give me results in order based on my 'query'.

line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'**

Example 1:

re.findall(r'FREQ="(.*?)"|VERSION="(.*?)"', line, re.MULTILINE)

Output is:

[('', 'OTHER'), ('OFF', '')]

And desired output I prefer is something like:

['OFF', 'OTHER']

Example 2:

re.findall(r'VERSION="(.*?)"|FREQ="(.*?)"', line, re.MULTILINE)

Output is the same:

[('', 'OTHER'), ('OFF', '')]

And desired output I prefer is something like:

['OTHER', 'OFF']

Any suggestion?

P.S.
Please don't ask me what I want to achieve and tell me that there is maybe better way, only if you have some question regarding this.

Thank you!

Body:
You may leverage a non-capturing alternation group to match either VERSION or FREQ (optionally preceded with a word boundary, just check if it meets your requirements):

\b(?:VERSION|FREQ)="(.*?)"

See the regex demo

Details

\b - a leading word boundary

(?:VERSION|FREQ) - either VERSION or FREQ

=" - a =" substring

(.*?) - Group 1 (the actual output of findall): any 0+ chars other than line break chars, as few as possible

" -  a double quote.

See the Python demo:

import re
line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'
print(re.findall(r'\b(?:VERSION|FREQ)="(.*?)"', line))
# => ['OTHER', 'OFF']

A better idea, perhaps, is to capture key-value pairs and map them to a dictionary:

import re
line = 'VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'
results = re.findall(r'(VERSION|FREQ)="(.*?)"', line)
print(dict(results))
# => {'FREQ': 'OFF', 'VERSION': 'OTHER'}

See the Python demo.


问:
Pascal results window
I have written a programme which merges two 1D arrays containing names. I print the list of arr1, arr2 and arr3.

I am using Lazarus Free Pascal v. 1.0.14 . I was wondering if anyone knows how to break the results in the dos-like window because the list is so long that I can only see the last few names in the returned results. The rest go by too fast to read.

I know I can save the resuls to file and I also use the delay command, but would like to know if there is a way to somehow break the results or slow them down or even edit the output console?

I appreciate your help.

答:
This isn't really a programming question, because your console application should output the values without pause. Otherwise your program would become useless if you ever wanted it to run as part of another pipeline in an automated fashion.

Instead you need a tool that you wrap around your program to paginate the output if, and when, you so desire. Such tools are known as terminal pagers and the basic one that ships with Windows is called more. You execute your program and pipe the output to the more program. Like this:

```
C:\SomeDir>MyProject.exe <input_args> | more
```

Title: Pascal results window

Body:
This isn't really a programming question, because your console application should output the values without pause. Otherwise your program would become useless if you ever wanted it to run as part of another pipeline in an automated fashion.

Instead you need a tool that you wrap around your program to paginate the output if, and when, you so desire. Such tools are known as terminal pagers and the basic one that ships with Windows is called more. You execute your program and pipe the output to the more program. Like this:

C:\SomeDir>MyProject.exe <input_args> | more


问:
Deny public access to group in STASH/Bitbucket Server
In Stash/BitBucket Server, is it possible to, by default, deny access to all repos for a specific group/user?

We would then grant access to one or two repos to this person or group based on login status/permission assignment..

Our internal approach is:
- Many of our repos are public to those within our organization
- These repos should not be visible to external partners who closely work with us
- We want a close external partner to be able to see one or two repos.

We are using Atlassian Stash v2.12.1

Regards,
T

答:
From my point of view, you have to discard public access to all repositories and projects, and grant access thanks to an "my-organisation" group in project permissions.

Then you can register per user permissions for specific repositories external partner has to access to.


答:
Simply use the native javascript filter() method, like this way:

```<code>let filteredValues = result.filter((value) => value.id_segmen == 1);
</code>```

this way,
filteredValues will contain only your values with id_segmen == 1.

Title: Array Filter in Angular

Body:
Simply use the native javascript filter() method, like this way:

let filteredValues = result.filter((value) => value.id_segmen == 1);

this way,
filteredValues will contain only your values with id_segmen == 1.


答:
You can use

```<code>for (var i = 0; i < arrayData.length; i++) {
    if (arrayData[i].id_segmen == 1) {
        result.push(arrayData[i]);
    }
}
</code>```

Try this

var arrayData= [
{
 "bulan": "4",
 "tahun": "2017",
 "id_program": 4,
 "id_segmen": 1,
 "segmen": "ppu",
 "jumlah": 3953,
 "target": 900000
},
{
 "bulan": "4",
 "tahun": "2017",
 "id_program": 3,
 "id_segmen": 2,
 "segmen": "bpu",
 "jumlah": 45,
 "target": 500000
},
{
 "bulan": "4",
 "tahun": "2017",
 "id_program": 3,
 "id_segmen": 1,
 "segmen": "ppu",
 "jumlah": 8752,
 "target": 900000
}]
var result = [];
for (var i = 0; i < arrayData.length; i++) {
 if (arrayData[i].id_segmen == 1) {
  result.push(arrayData[i]);
 }
}
console.log(result)```

Title: Array Filter in Angular

Body:
You can use

for (var i = 0; i < arrayData.length; i++) {
    if (arrayData[i].id_segmen == 1) {
        result.push(arrayData[i]);
    }
}

Try this

var arrayData= [
{
 "bulan": "4",
 "tahun": "2017",
 "id_program": 4,
 "id_segmen": 1,
 "segmen": "ppu",
 "jumlah": 3953,
 "target": 900000
},
{
 "bulan": "4",
 "tahun": "2017",
 "id_program": 3,
 "id_segmen": 2,
 "segmen": "bpu",
 "jumlah": 45,
 "target": 500000
},
{
 "bulan": "4",
 "tahun": "2017",
 "id_program": 3,
 "id_segmen": 1,
 "segmen": "ppu",
 "jumlah": 8752,
 "target": 900000
}]
var result = [];
for (var i = 0; i < arrayData.length; i++) {
 if (arrayData[i].id_segmen == 1) {
  result.push(arrayData[i]);
 }
}
console.log(result)


答:
Check the below code, items is your JSON from WebAPI and fiteredItem is an array of objects which has id_segmen=1</p>

```<code>this.filteredItem= this.items.filter((item) => {
        return (item.id_segmen ===1);
      })
</code>```

Title: Array Filter in Angular

Body:
Check the below code, items is your JSON from WebAPI and fiteredItem is an array of objects which has id_segmen=1

this.filteredItem= this.items.filter((item) => {
        return (item.id_segmen ===1);
      })


问:
How does merge work within eclipse?
Perhaps I am looking in the wrong places, but can anyone explain how "Team >> Merge" works within Eclipse?  I ended up with instances of git comments interjecting into my code throughout the project, and would like to not have to delete my branch and rebuild.

Example:

```<code><<<<<<< HEAD
    static final void method(String input) {
=======
    static final void method(String input, int i) {
>>>>>>> master
</code>```

答:
Your git found a conflict there. You have now both version in your code HEAD and master. You should check which version you want to keep, and remove manually the the rest.

Just literally delete the <<<<<< HEAD stuff, till you only see static final void method(String input) {.
Since I'm working with Android, I didn't use Eclipse in years, but there should be a way to use a GUI for git, so you don't have to delete those lines manually.

Title: How does merge work within eclipse?

Body:
Perhaps I am looking in the wrong places, but can anyone explain how "Team >> Merge" works within Eclipse?  I ended up with instances of git comments interjecting into my code throughout the project, and would like to not have to delete my branch and rebuild.

Example:

<<<<<<>>>>>> master


问:
SAML Single Sign On Cannot Keep Session Cookie Jmeter
I successfully recorded a site that uses SAML Authentication Request and Single Sign On to Login. This site is using a proxy. So, I recorded it using a proxy.

When I played back the record, it successfully login but when I played back for the second times (I run after waiting for 5 seconds), it failed to login. If I checked, the difference is in the Cookie, however I already used HTTP Cookie Manager:

successfully login

failed login

If we can see the pictures above that the difference is the cookie.

So how to keep the session cookie?

答:
JMeter automatically checks cookies integrity, as per HTTP Cookie Manager documentation:

JMeter checks that received cookies are valid for the URL. This means that cross-domain cookies are not stored. If you have bugged behaviour or want Cross-Domain cookies to be used, define the JMeter property "CookieManager.check.cookies=false".

There are 2 ways of "defining" the aforementioned property:

Add the next line to user.properties file (located in "bin" folder of your JMeter installation)

```<code>CookieManager.check.cookies=false
</code>```

JMeter restart will be required to pick the property up

Override the property via -J command-line argument

```<code>jmeter -JCookieManager.check.cookies=false -n -t test.jmx -l result.jtl
</code>```

More information: HTTP Cookie Manager Advanced Usage - A Guide

Body:
JMeter automatically checks cookies integrity, as per HTTP Cookie Manager documentation:

JMeter checks that received cookies are valid for the URL. This means that cross-domain cookies are not stored. If you have bugged behaviour or want Cross-Domain cookies to be used, define the JMeter property "CookieManager.check.cookies=false".

There are 2 ways of "defining" the aforementioned property:

Add the next line to user.properties file (located in "bin" folder of your JMeter installation)

CookieManager.check.cookies=false

JMeter restart will be required to pick the property up

Override the property via -J command-line argument

jmeter -JCookieManager.check.cookies=false -n -t test.jmx -l result.jtl

More information: HTTP Cookie Manager Advanced Usage - A Guide


问:
AsyncTask <Map<String, List<Object>>
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

```<code>Map<String, List<Object>>
</code>```

I tried starting the asynctask like this:

```<code>public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>
</code>```

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

```<code>@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}
</code>```

and the on post execute like this:

```<code>@Override
public void onPostExecute(Map<String, List<Object>> map) {
}
</code>```

What is wrong with my syntax and how would I implement this correctly?

Thanks

答:
for the parameters of AsyncTask in simple terms :

```<code>extends AsyncTask<<Map<String, List<Object>>, Integer, Map<String, List<Object>>>{}
</code>```

1st is a parameter of doInBackGround method,

2nd is the parameter of onProgressUpdate method,

3rd is important, which is return type of doInBackGoround method, and a Post result to onPostExecute method.

so now your class looks like :

```<code>public class GetIndividualAlarmsFromDataBase extends AsyncTask<Map<String, List<Object>>, Integer, Map<String, List<Object>>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Map<String, List<Object>> doInBackground(Map<String, List<Object>>[] maps) {
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Map<String, List<Object>> maps) {
        super.onPostExecute(maps);
    }
}
</code>```

Title: AsyncTask <Map<String, List<Object>>

Body:
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

Map<String, List<Object>>

I tried starting the asynctask like this:

public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}

and the on post execute like this:

@Override
public void onPostExecute(Map<String, List<Object>> map) {
}

What is wrong with my syntax and how would I implement this correctly?

Thanks

Body:
for the parameters of AsyncTask in simple terms :

extends AsyncTask<<Map<String, List<Object>>, Integer, Map<String, List<Object>>>{}

1st is a parameter of doInBackGround method,

2nd is the parameter of onProgressUpdate method,

3rd is important, which is return type of doInBackGoround method, and a Post result to onPostExecute method.

so now your class looks like :

public class GetIndividualAlarmsFromDataBase extends AsyncTask<Map<String, List<Object>>, Integer, Map<String, List<Object>>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Map<String, List<Object>> doInBackground(Map<String, List<Object>>[] maps) {
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Map<String, List<Object>> maps) {
        super.onPostExecute(maps);
    }
}


问:
Enable button if the mentioned input boxed are filled using jquery?
HTML:

```<code><input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>
</code>```

This code displays two input boxes and one submit button.

jQuery:

```<code>$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});
</code>```

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

答:
So add checking for both elements and just check the val(). You don't need to access the length.

```<code>$(document).ready(function() {
   $('.sendButton').attr('disabled',true);

   const message = $('#message');
   const message1 = $('#message1');

   $("#message, #message1").on("change",function() {

      if(message.val() && message1.val()){
        $('.sendButton').attr('disabled', false);
      } else {
        $('.sendButton').attr('disabled', true);
      }

   });
});
</code>```

Body:
HTML:

<input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>

This code displays two input boxes and one submit button.

jQuery:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

Body:
So add checking for both elements and just check the val(). You don't need to access the length.

$(document).ready(function() {
   $('.sendButton').attr('disabled',true);

   const message = $('#message');
   const message1 = $('#message1');

   $("#message, #message1").on("change",function() {

      if(message.val() && message1.val()){
        $('.sendButton').attr('disabled', false);
      } else {
        $('.sendButton').attr('disabled', true);
      }

   });
});


问:
REST api monitoring (Progress Openedge)
Is there any monitoring tool for REST application(Progress Openedge) that can check:

whether the service is up and running or not

appserver is up and running

hit count and other information for each api resources

error logging

customized reporting(such as sending report in mail)

I saw RESTMAN Utility in the documentation but couldn't find the details as i expected/needed. Can it do the things mentioned above? If yes, how to implement and customize it?
(Progress version: 11.3)

答:
Mahesh

I had a quick look in the current online OpenEdge documentation (which is for 11.7) and found this - https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/asadm/using-the-restman-utility.html

There are links to the functions that seem to show what you are looking for.

I haven't used it myself, but it looks like most of the Progress monitoring tools, so the issue you may have is that it provides "all" of the information that you need, but in a format that you have to parse before you get to the specific details you need.

Hope that helps?

Title: REST api monitoring (Progress Openedge)


问:
onClickListener using Butterknife
onClickListener using Butterknife is bit confusing

Say, I have a Whatsapp button which onClick opens Whatsapp to share something. By conventional means, the code for onClickListener would be something like

```<code>ImageButton buttonWhatsapp = (ImageButton) findViewById(R.id.whatsapp);

buttonWhatsapp.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
optionsShareThis.whatsApp(ActivityWebView.this, ShareThisURL);
    }
});
</code>```

where, optionsShareThis is an object of OptionsShareThis class and whatsApp(Context context, String Url) is a method defined in this class.

I am confused with how to define onClick event using Butterknife. I tried using

@Bind(R.id.whatsapp) ImageButton ButtonWhatsapp; to bind the View

Then the below code for onClick event

```<code>@OnClick(R.id.whatsapp) void onClick() {
    optionsShareThis.whatsApp(this, ShareThisURL);
}
</code>```

Android Studio says the field ButtonWhatsapp and the method onClick() is never used. What's happening?

EDIT:  I have already added Butterknife.bind(this) inside onCreate(). Sorry, I didn't mention this earlier

答:
it's because you don't build project yet

@OnClick is annotation, that means the code is generated when you build your project

just Build -> Rebuild Project

Title: onClickListener using Butterknife

Body:
onClickListener using Butterknife is bit confusing

Say, I have a Whatsapp button which onClick opens Whatsapp to share something. By conventional means, the code for onClickListener would be something like

ImageButton buttonWhatsapp = (ImageButton) findViewById(R.id.whatsapp);

buttonWhatsapp.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
optionsShareThis.whatsApp(ActivityWebView.this, ShareThisURL);
    }
});

where, optionsShareThis is an object of OptionsShareThis class and whatsApp(Context context, String Url) is a method defined in this class.

I am confused with how to define onClick event using Butterknife. I tried using

@Bind(R.id.whatsapp) ImageButton ButtonWhatsapp; to bind the View

Then the below code for onClick event

@OnClick(R.id.whatsapp) void onClick() {
    optionsShareThis.whatsApp(this, ShareThisURL);
}

Android Studio says the field ButtonWhatsapp and the method onClick() is never used. What's happening?

EDIT:  I have already added Butterknife.bind(this) inside onCreate(). Sorry, I didn't mention this earlier


问:
gstreamer rtsp client connection refused error
I have installed Gstreamer on my i.MX6 board. I want to stream the camera connected using RTSP.

The following command displays the camera content on the LVDS screen:

```<code>gst-launch tvsrc ! Imxv4vl2sink
</code>```

Instead of displaying it on the screen, I want to send the content over network RTSP and display it on other device's display

I used the following command to start streaming which works without throwing any error

```<code>gst-launch-0.10 -vv imxv4l2src ! video/x-raw-yuv, framerate=30/1, width=1024
, height=768 ! vpuenc codec=avc ! rtph264pay ! udpsink host=127.0.0.1 port=5004
sync=false
</code>```

On the other device, I executed the following command:

```<code>gst-launch rtspsrc location=rtsp://<ip Address>:5004 name=source ! queue ! rtph264depay !
vpudec low-latency=true ! imxv4l2sink
</code>```

It fails with the following error:

```<code>gstrtspsrc.c(5685): gst_rtspsrc_retrieve_sdp (): /GstPipeline:pipeline0/GstRTSPSrc:source:
Failed to connect. (System error: Connection refused)
</code>```

I can ping from the other device to the streaming device.

What can be the issue?

答: You are sending RTP over UDP, but do not provide any RTSP protocol. So your receiver which tries to connect via RTSP will fail. You either need to use the GstRTSPServer class and implement some logic as an application on the sender side or receive your data via udpsrc. For the latter you still need a way to transmit SDP data (which usually is one thing an RTSP server does).

Body:
I have installed Gstreamer on my i.MX6 board. I want to stream the camera connected using RTSP.

The following command displays the camera content on the LVDS screen:

gst-launch tvsrc ! Imxv4vl2sink

Instead of displaying it on the screen, I want to send the content over network RTSP and display it on other device's display

I used the following command to start streaming which works without throwing any error

gst-launch-0.10 -vv imxv4l2src ! video/x-raw-yuv, framerate=30/1, width=1024
, height=768 ! vpuenc codec=avc ! rtph264pay ! udpsink host=127.0.0.1 port=5004
sync=false

On the other device, I executed the following command:

gst-launch rtspsrc location=rtsp://<ip Address>:5004 name=source ! queue ! rtph264depay !
vpudec low-latency=true ! imxv4l2sink

It fails with the following error:

gstrtspsrc.c(5685): gst_rtspsrc_retrieve_sdp (): /GstPipeline:pipeline0/GstRTSPSrc:source:
Failed to connect. (System error: Connection refused)

I can ping from the other device to the streaming device.

What can be the issue?


问:
ChangeTracker implementation with database first appraoch
Our company is new to using EF and I would appreciate any guidance/advise on our problem. In this project we are using EF 6, Visual Studio 2015, a database first approach and RESTful service(this is a RESTful API using JSON not a generic API, we only need the audit logging method to be generic). We need to implement auditing and are investigating using the ChangeTracker functionality. The idea is to make a generic method that can accept any entity. Here's what we have so far;

End of Shift API controller:

```<code>public class EndOfShiftsController : ApiController
{
    private iSuiteEntities db = new iSuiteEntities();
    // POST: api/EndOfShifts/post
    [Route("api/EndOfShift/post")]
    [ResponseType(typeof(EndOfShift))]
    public async Task<IHttpActionResult> PostEndOfShift_Post(EndOfShiftDto endOfShift)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        EndOfShift endofshift = new EndOfShift()
        {
            EndOfShiftID = endOfShift.EndOfShiftID,
            EndOfShiftDate = endOfShift.EndOfShiftDate,
            EquipmentID = endOfShift.EquipmentID,
            StartHours = endOfShift.StartHours,
            EndHours = endOfShift.EndHours,
            CreatedBy = endOfShift.CreatedBy,
            CreateDate = DateTime.Now,
            Active = true
        };

        try
        {
            if (!endOfShift.ToDelete)
            {
                if (EndOfShiftExists(endOfShift.EndOfShiftID))
                {
                    var update = db.EndOfShifts.Find(endOfShift.EndOfShiftID);
                    update.EndOfShiftDate = endofshift.EndOfShiftDate;
                    update.EquipmentID = endofshift.EquipmentID;
                    update.StartHours = endOfShift.StartHours;
                    update.EndHours = endOfShift.EndHours;
                    db.Entry(update).State = EntityState.Modified;

 //try calling the audit log method here/////////////////////////////////
                    AuditsController.GetAuditLogData(endofshift, endOfShift.EndOfShiftID, endOfShift.CreatedBy);
                    await db.SaveChangesAsync();
                }
                else
                {
                    db.EndOfShifts.Add(endofshift);
                    await db.SaveChangesAsync();
                }
            }
            else
            {
                EndOfShift delete = db.EndOfShifts.Find(endOfShift.EndOfShiftID);
                if (delete == null)
                {
                    return NotFound();
                }
                else
                {
                    delete.Active = false;
                    db.Entry(delete).State = EntityState.Modified;
                    await db.SaveChangesAsync();
                }
            }

            return Ok("Success");
        }
        catch(Exception ex)
        {
            return Ok(ex.Message);
        }
        //return CreatedAtRoute("DefaultApi", new { id = endOfShift.EndOfShiftID }, endOfShift);
    }
</code>```

Generic audit logging method something like this:

```<code>public class AuditsController : ApiController
{
    private static iSuiteEntities dbContext = new iSuiteEntities();
    private static iSuiteEntities db = new iSuiteEntities();

    //write Audit log
    public static async void GetAuditLogData<T>(T entity, int recID, int modByID) where T : new ()
    {
        try
        {
            var changeTrack = dbContext.ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);
            foreach (var entry in changeTrack)
            {
                if (entry.Entity != null)
                {
                    string entityName = string.Empty;
                    string state = string.Empty;
                    switch (entry.State)
                    {
                        case EntityState.Modified:
                            entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
                            state = entry.State.ToString();
                            foreach (string prop in entry.OriginalValues.PropertyNames)
                            {
                                object currentValue = entry.CurrentValues[prop];
                                object originalValue = entry.OriginalValues[prop];
                                if (!currentValue.Equals(originalValue))
                                {
                                    Audit auditEntry = new Audit()
                                    {
                                        recordID = recID,
                                        tableName = entityName,
                                        fieldName = prop,
                                        oldValue = Convert.ToString(originalValue),
                                        editReason = "Update",
                                        modifiedBy = modByID,
                                        modifiedDate = DateTime.Now
                                    };

                                    db.Audits.Add(auditEntry);
                                    await db.SaveChangesAsync();
                                }
                            }
                            break;
                            //data addition is not required to be logged/////
                        case EntityState.Deleted:
                            entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
                            state = entry.State.ToString();
                            foreach (string prop in entry.OriginalValues.PropertyNames)
                            {
                                Audit auditEntry = new Audit()
                                {
                                    recordID = recID,
                                    tableName = entityName,
                                    fieldName = prop,
                                    oldValue = Convert.ToString(entry.OriginalValues[prop]),
                                    editReason = "Delete",
                                    modifiedBy = modByID,
                                    modifiedDate = DateTime.Now
                                };

                                db.Audits.Add(auditEntry);
                                await db.SaveChangesAsync();
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //handle exception here....
        }
    }
</code>```

Is this a feasible option for us to pursue for our audit logging requirement? The code has not been tested, so I'm sure we need some pointers coding wise too. If this is not a viable option to achieve our goal, can you please recommend an option that can be implemented with the database first approach? Thanks in advance!!

答: After taking a different approach to what we were Googling, we came upon this link which gave us the solution to our problem. Leaving this here to hopefully save other developers some time :-)</p>

Body:
Our company is new to using EF and I would appreciate any guidance/advise on our problem. In this project we are using EF 6, Visual Studio 2015, a database first approach and RESTful service(this is a RESTful API using JSON not a generic API, we only need the audit logging method to be generic). We need to implement auditing and are investigating using the ChangeTracker functionality. The idea is to make a generic method that can accept any entity. Here's what we have so far;

End of Shift API controller:

public class EndOfShiftsController : ApiController
{
    private iSuiteEntities db = new iSuiteEntities();
    // POST: api/EndOfShifts/post
    [Route("api/EndOfShift/post")]
    [ResponseType(typeof(EndOfShift))]
    public async Task<IHttpActionResult> PostEndOfShift_Post(EndOfShiftDto endOfShift)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        EndOfShift endofshift = new EndOfShift()
        {
            EndOfShiftID = endOfShift.EndOfShiftID,
            EndOfShiftDate = endOfShift.EndOfShiftDate,
            EquipmentID = endOfShift.EquipmentID,
            StartHours = endOfShift.StartHours,
            EndHours = endOfShift.EndHours,
            CreatedBy = endOfShift.CreatedBy,
            CreateDate = DateTime.Now,
            Active = true
        };

        try
        {
            if (!endOfShift.ToDelete)
            {
                if (EndOfShiftExists(endOfShift.EndOfShiftID))
                {
                    var update = db.EndOfShifts.Find(endOfShift.EndOfShiftID);
                    update.EndOfShiftDate = endofshift.EndOfShiftDate;
                    update.EquipmentID = endofshift.EquipmentID;
                    update.StartHours = endOfShift.StartHours;
                    update.EndHours = endOfShift.EndHours;
                    db.Entry(update).State = EntityState.Modified;

 //try calling the audit log method here/////////////////////////////////
                    AuditsController.GetAuditLogData(endofshift, endOfShift.EndOfShiftID, endOfShift.CreatedBy);
                    await db.SaveChangesAsync();
                }
                else
                {
                    db.EndOfShifts.Add(endofshift);
                    await db.SaveChangesAsync();
                }
            }
            else
            {
                EndOfShift delete = db.EndOfShifts.Find(endOfShift.EndOfShiftID);
                if (delete == null)
                {
                    return NotFound();
                }
                else
                {
                    delete.Active = false;
                    db.Entry(delete).State = EntityState.Modified;
                    await db.SaveChangesAsync();
                }
            }

            return Ok("Success");
        }
        catch(Exception ex)
        {
            return Ok(ex.Message);
        }
        //return CreatedAtRoute("DefaultApi", new { id = endOfShift.EndOfShiftID }, endOfShift);
    }

Generic audit logging method something like this:

public class AuditsController : ApiController
{
    private static iSuiteEntities dbContext = new iSuiteEntities();
    private static iSuiteEntities db = new iSuiteEntities();

    //write Audit log
    public static async void GetAuditLogData<T>(T entity, int recID, int modByID) where T : new ()
    {
        try
        {
            var changeTrack = dbContext.ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);
            foreach (var entry in changeTrack)
            {
                if (entry.Entity != null)
                {
                    string entityName = string.Empty;
                    string state = string.Empty;
                    switch (entry.State)
                    {
                        case EntityState.Modified:
                            entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
                            state = entry.State.ToString();
                            foreach (string prop in entry.OriginalValues.PropertyNames)
                            {
                                object currentValue = entry.CurrentValues[prop];
                                object originalValue = entry.OriginalValues[prop];
                                if (!currentValue.Equals(originalValue))
                                {
                                    Audit auditEntry = new Audit()
                                    {
                                        recordID = recID,
                                        tableName = entityName,
                                        fieldName = prop,
                                        oldValue = Convert.ToString(originalValue),
                                        editReason = "Update",
                                        modifiedBy = modByID,
                                        modifiedDate = DateTime.Now
                                    };

                                    db.Audits.Add(auditEntry);
                                    await db.SaveChangesAsync();
                                }
                            }
                            break;
                            //data addition is not required to be logged/////
                        case EntityState.Deleted:
                            entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
                            state = entry.State.ToString();
                            foreach (string prop in entry.OriginalValues.PropertyNames)
                            {
                                Audit auditEntry = new Audit()
                                {
                                    recordID = recID,
                                    tableName = entityName,
                                    fieldName = prop,
                                    oldValue = Convert.ToString(entry.OriginalValues[prop]),
                                    editReason = "Delete",
                                    modifiedBy = modByID,
                                    modifiedDate = DateTime.Now
                                };

                                db.Audits.Add(auditEntry);
                                await db.SaveChangesAsync();
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //handle exception here....
        }
    }

Is this a feasible option for us to pursue for our audit logging requirement? The code has not been tested, so I'm sure we need some pointers coding wise too. If this is not a viable option to achieve our goal, can you please recommend an option that can be implemented with the database first approach? Thanks in advance!!


问:
How to Import a Class From Android Source While Developing an Android Application
I want to use a java class from android/frameworks/base/.... How can I import the class to my project in Eclipse? </p>

答:
(cross-posted from android-developers)

The Settings app is part of the firmware. It has the ability to use classes that are not part of the Android SDK.

If your "application about display settings" is an SDK application, you cannot use HdmiService.

If your "application about display settings" is part of the firmware, more relevant support lists can be found here:

http://source.android.com/community/index.html


问:
Deploying an angular application in hyperledger-composer
I have my composer-rest-server running on port 3000 and now I try to generate an angular application with yo hyperledger-composer following the tutorial.

Steps creating the webapp:

After I do npm start and it seems that the webapp es correctly created because I am able to reach it from the localhost with curl localhost:4200 but when I try to reach it from another host I get nothing.

Both hosts are connected because I can reach the composer server running on port 3000.

答:
you need to change your Angular app's configuration info (for the install) - it is based on your currently configured IP address, that you want to access from 'remote':

1) Change your Angular skeleton app - eg. for application named my-app - its  the file my-app/src/app/configuration.ts (where my-app is the generated app dir). For the network interface/resolvable host you chose, change the property:

public ApiIP: string = "localhost";

to be your IP or resolvable host.

2) After building, you can change it as you wish - specifically where it says ng serve --host 0.0.0.0 to ng serve --host {MY_IP} in your package.json(leave the rest in!)- see example below:

```<code>    "start": "concurrently \"ng serve --host 10.0.0.1\" \"npm run my-app\"",
</code>```

Body:
you need to change your Angular app's configuration info (for the install) - it is based on your currently configured IP address, that you want to access from 'remote':

1) Change your Angular skeleton app - eg. for application named my-app - its  the file my-app/src/app/configuration.ts (where my-app is the generated app dir). For the network interface/resolvable host you chose, change the property:

public ApiIP: string = "localhost";

to be your IP or resolvable host.

2) After building, you can change it as you wish - specifically where it says ng serve --host 0.0.0.0 to ng serve --host {MY_IP} in your package.json(leave the rest in!)- see example below:

    "start": "concurrently \"ng serve --host 10.0.0.1\" \"npm run my-app\"",


问:
Know the nature of a URL before GETting it
Is it possible to know the nature of a URL before GETting it ?

I have one URL in particular that ends with m3u but is not a simple file I can download. This is actually a radio stream. As I expect a (finite) file, the GET method never ends. The timeout options does not works in this case (normal).

```<code>const options = {timeout: 5000};
return HTTP.call('GET', "http://av.rasset.ie/av/live/radio/junior.m3u", options);
</code>```

The safe solution should be to ask for the type of the response before actually getting the file.
How can I do that?

Thanks,
Mickael.

答:
Even if in this particular case, running HEAD runs into an HTTP Parse Error, while I know the stream is OK (if someone can still explains me why, I would be grateful), I think Opal gave the general solution:

You can run a HEAD request first

Body:
Is it possible to know the nature of a URL before GETting it ?

I have one URL in particular that ends with m3u but is not a simple file I can download. This is actually a radio stream. As I expect a (finite) file, the GET method never ends. The timeout options does not works in this case (normal).

const options = {timeout: 5000};
return HTTP.call('GET', "http://av.rasset.ie/av/live/radio/junior.m3u", options);

The safe solution should be to ask for the type of the response before actually getting the file.
How can I do that?

Thanks,
Mickael.


问:
can't install ceph on fedora21
I used 3 fedora21 to install ceph, I tried with

```<code>ceph-deploy install serverc serverd servere
</code>```

but got:

```<code>[ceph_deploy][ERROR ] RuntimeError: Failed to execute command: rpm -Uvh --replacepkgs --force --quiet http://ceph.com/rpm-hammer/fc21/noarch/ceph-release-1-0.fc21.noarch.rpm
</code>```

It seems that the http://ceph.com/rpm-hammer/fc21/noarch/ceph-release-1-0.fc21.noarch.rpm no longer available.

How can I fix this?

thanks

答:
I met the same problem as you, it's a bug of ceph-deploy, the url is wrong and the right url is download.ceph.com rather than ceph.com.
The best way to fix it is to download a new version ceph-deploy. You can use pip
 to install ceph-deploy 1.5.39 like this:

pip install ceph-deploy

Title: can't install ceph on fedora21

Body:
I used 3 fedora21 to install ceph, I tried with

ceph-deploy install serverc serverd servere

but got:

[ceph_deploy][ERROR ] RuntimeError: Failed to execute command: rpm -Uvh --replacepkgs --force --quiet http://ceph.com/rpm-hammer/fc21/noarch/ceph-release-1-0.fc21.noarch.rpm

It seems that the http://ceph.com/rpm-hammer/fc21/noarch/ceph-release-1-0.fc21.noarch.rpm no longer available.

How can I fix this?

thanks


问:
Why doesn't the first navigationcontroller in my storyboard have an effect on the tableviewcontroller?
My Storyboard is setup as:

```<code>                                                    UIViewCont
                                                   /
NavigationController -> UIViewContr -> UIViewContr ----- UIView Contr
                                                  \
                                                   NavCont
                                                     \
                                                    TableViewController
</code>```

The last three controllers (2 x UIView and 1 x TableView) use "show" segues from three different buttons. And the TableView controller is embedded in the NavCont.

Because the first controller is a NavController every UIViewController has a back button except the TableViewController.

I've been reading up about it but can't figure out why. Other than each Navigation controller is it's own stack and kind of starts again so you can't just navigate back from a 2nd or 3rd navigation controller. But not sure.

Thanks.

答:
Using a navigation controller resets the navigation stack tracking, so your table view does not have a back button because it is effectively a new root. If you create a view controller that the table view segues to, it will have a back button because it is part of the (inner) navigation chain and not the root.

It is not apparent from your example what you are trying to do or why you have the inner navigation controller instead of just relying on the original navigation stack. There is one option you can try. The root view of a navigation stack should have the navigation bar, and you can drag bar button items onto it, allowing you to unwind back to the previous state.

Body:
My Storyboard is setup as:

                                                    UIViewCont
                                                   /
NavigationController -> UIViewContr -> UIViewContr ----- UIView Contr
                                                  \
                                                   NavCont
                                                     \
                                                    TableViewController

The last three controllers (2 x UIView and 1 x TableView) use "show" segues from three different buttons. And the TableView controller is embedded in the NavCont.

Because the first controller is a NavController every UIViewController has a back button except the TableViewController.

I've been reading up about it but can't figure out why. Other than each Navigation controller is it's own stack and kind of starts again so you can't just navigate back from a 2nd or 3rd navigation controller. But not sure.

Thanks.


问:
zen-coding.vim not working for me (pathogen)
So, I've just installed the zen-coding.vim plugin and expansions aren't  happening.  The plugin is there if I do scriptnames, and :verbose map  shows the ZenCoding mappings.  However, if I edit an html file (or set ft=html) and type

h1#title

Nothing happens.  I am sure my .vimrc is hosed, but I am a bit new to the vim world so I am struggling finding out what I've messed up.  My vim setup is here.  I am on Mac OSX and I am using pathogen to bundle my plugins.

Anyone have any suggestions?

Thanks,
Glenn

Output of :set rtp

runtimepath=~/.vim,~/.vim/bundle/IndexedSearch,~/.vim/bundle/gist,~/.vim/bundle/jquery,~/.vim/bundle/nerdtree,~/.
vim/bundle/snipmate.vim,~/.vim/bundle/textile.vim,~/.vim/bundle/vim-align,~/.vim/bundle/vim-cucumber,~/.vim/bundle/
vim-fugitive,~/.vim/bundle/vim-git,~/.vim/bundle/vim-haml,~/.vim/bundle/vim-markdown,~/.vim/bundle/vim-rails,~/.vim
/bundle/vim-repeat,~/.vim/bundle/vim-ruby,~/.vim/bundle/vim-ruby-debugger,~/.vim/bundle/vim-shoulda,~/.vim/bundle/v
im-supertab,~/.vim/bundle/vim-surround,~/.vim/bundle/vim-tcomment,~/.vim/bundle/vim-vividchalk,~/.vim/bundle/zencoding-vim,/Applications/MacVim.app/Contents/Resources/vim/vimfiles,/Applications/MacVim.app/Contents/Resources/vim/ru
ntime,/Applications/MacVim.app/Contents/Resources/vim/vimfiles/after,~/.vim/bundle/snipmate.vim/after,~/.vim/after

答:
It seems that Pathogen doesn't explicitly include the "after" directories found within plugins that you place in your "bundle" directory. What this means is that plugins such as zen-coding and snipMate fail to run their initialization/cleanup/key binding routines.

Apparently these plugins have worked fine for other folks in other environments, but for me in Windows, snipMate wouldn't work because the final snippet loading command in the "after" directory was not sourced.

I fixed this in pathogen.vim by amending the pathogen#runtime_append_all_bundles() function to explicitly append all "after" directories found within bundle directories.

Here is a patch for pathogen.vim version 1.2:

```<code>121c121,125
<       let list +=  [dir] + pathogen#glob_directories(dir.sep.name.sep.'*[^~]')
---
>       let subdirs = pathogen#glob_directories(dir.sep.name.sep.'*[^~]')
>       let list += [dir]
>       for subdir in subdirs
>         let list += [subdir] + pathogen#glob_directories(subdir.sep.'*after*')
>       endfor
</code>```

BIG EDIT: After coming across this closed issue on the Pathogen github site, I discovered that the root cause was not that the "after" directories needed to be added explicitly, but that they were not being added because of a backslash escaping issue on win32 systems in the substitute() command.

Here is a much more concise patch, and in unified format this time, sorry...

```<code>@@ -116,7 +116,8 @@
   let list = []
   for dir in pathogen#split(&rtp)
     if dir =~# '\<after$'
-      let list +=  pathogen#glob_directories(substitute(dir,'after$',name.sep.'*[^~]'.sep.'after','')) + [dir]
+      let replacement = substitute(name.sep.'*[^~]'.sep.'after', '\\', '\\\\', 'g')
+      let list +=  pathogen#glob_directories(substitute(dir,'after$',replacement,'')) + [dir]
     else
       let list +=  [dir] + pathogen#glob_directories(dir.sep.name.sep.'*[^~]')
     endif
</code>```

The reporter of the github issue said that they sent Tim a pull request, and Tim said he accepted it, but the described change isn't in the current version of the code, so I thought I would do what I could to provide my solution here.

This patch escapes any backslashes in the glob. There shouldn't be any backslashes in any of the runtime path items on non-win32 systems in the first place, or if there are it is because +shellslash is set in vim and this escaping is probably required.

I'm leaving the old solution up there for reference.

Body:
It seems that Pathogen doesn't explicitly include the "after" directories found within plugins that you place in your "bundle" directory. What this means is that plugins such as zen-coding and snipMate fail to run their initialization/cleanup/key binding routines.

Apparently these plugins have worked fine for other folks in other environments, but for me in Windows, snipMate wouldn't work because the final snippet loading command in the "after" directory was not sourced.

I fixed this in pathogen.vim by amending the pathogen#runtime_append_all_bundles() function to explicitly append all "after" directories found within bundle directories.

Here is a patch for pathogen.vim version 1.2:

121c121,125
<       let list +=  [dir] + pathogen#glob_directories(dir.sep.name.sep.'*[^~]')
---
>       let subdirs = pathogen#glob_directories(dir.sep.name.sep.'*[^~]')
>       let list += [dir]
>       for subdir in subdirs
>         let list += [subdir] + pathogen#glob_directories(subdir.sep.'*after*')
>       endfor

BIG EDIT: After coming across this closed issue on the Pathogen github site, I discovered that the root cause was not that the "after" directories needed to be added explicitly, but that they were not being added because of a backslash escaping issue on win32 systems in the substitute() command.

Here is a much more concise patch, and in unified format this time, sorry...

@@ -116,7 +116,8 @@
   let list = []
   for dir in pathogen#split(&rtp)
     if dir =~# '\<after$'
-      let list +=  pathogen#glob_directories(substitute(dir,'after$',name.sep.'*[^~]'.sep.'after','')) + [dir]
+      let replacement = substitute(name.sep.'*[^~]'.sep.'after', '\\', '\\\\', 'g')
+      let list +=  pathogen#glob_directories(substitute(dir,'after$',replacement,'')) + [dir]
     else
       let list +=  [dir] + pathogen#glob_directories(dir.sep.name.sep.'*[^~]')
     endif

The reporter of the github issue said that they sent Tim a pull request, and Tim said he accepted it, but the described change isn't in the current version of the code, so I thought I would do what I could to provide my solution here.

This patch escapes any backslashes in the glob. There shouldn't be any backslashes in any of the runtime path items on non-win32 systems in the first place, or if there are it is because +shellslash is set in vim and this escaping is probably required.

I'm leaving the old solution up there for reference.


问:
Retrofit 2.0 - How to get response body for 400 Bad Request error?
So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.

```<code>{
    "userMessage": "Blah",
    "internalMessage": "Bad Request blah blah",
    "errorCode": 1
}
</code>```

I call it by

```<code>Call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        //AA
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //BB
    }
}
</code>```

However the problem is that once I get the response, onFailure() is invoke so that //BB is called. Here, I have no way to access the JSON response.
When I log the api request and response, it doesn't show JSON response at all. And Throwable t is IOException. However, strangely, when I make the same call on Postman, it does return the expected JSON response with 400 error code.

So my question is how can I get the json response when I get 400 Bad Request error? Should I add something to okhttpclient?

Thanks

答:
This is how you can handle the response message
I am handling for error 500 you can add as much you want</p>

```<code>                switch (response.code()) {
                    case HttpURLConnection.HTTP_OK:
                        break;
                    case HttpURLConnection.HTTP_UNAUTHORIZED:
                        callback.onUnAuthentic();
                        break;
                    case HttpURLConnection.HTTP_INTERNAL_ERROR:
                        try {
                            String errorResponse = response.errorBody().string();
                            JSONObject object = new JSONObject(errorResponse);
                            String message = "Error";
                            if (object.has("Message"))
                                message = String.valueOf(object.get("Message"));
                            callback.onError(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
                    default:
                        callback.onNetworkError();
                        break;
                }
</code>```

Body:
So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.

{
    "userMessage": "Blah",
    "internalMessage": "Bad Request blah blah",
    "errorCode": 1
}

I call it by

Call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        //AA
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //BB
    }
}

However the problem is that once I get the response, onFailure() is invoke so that //BB is called. Here, I have no way to access the JSON response.
When I log the api request and response, it doesn't show JSON response at all. And Throwable t is IOException. However, strangely, when I make the same call on Postman, it does return the expected JSON response with 400 error code.

So my question is how can I get the json response when I get 400 Bad Request error? Should I add something to okhttpclient?

Thanks

Body:
This is how you can handle the response message
I am handling for error 500 you can add as much you want

                switch (response.code()) {
                    case HttpURLConnection.HTTP_OK:
                        break;
                    case HttpURLConnection.HTTP_UNAUTHORIZED:
                        callback.onUnAuthentic();
                        break;
                    case HttpURLConnection.HTTP_INTERNAL_ERROR:
                        try {
                            String errorResponse = response.errorBody().string();
                            JSONObject object = new JSONObject(errorResponse);
                            String message = "Error";
                            if (object.has("Message"))
                                message = String.valueOf(object.get("Message"));
                            callback.onError(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
                    default:
                        callback.onNetworkError();
                        break;
                }


问:
Authenticating a Today Widget for API access
I need to add a Today Widget/extension to an existing iOS app, which requires the user to sign in via a WKWebView.

As the extension only communicates with Apple frameworks or via openURL() back to the main app, how would I best share the authentication token stored in the main app with the Today Widget/extension, so that it can make authenticated API calls?

Can this be done with a shared keychain? Or is there another secure alternative?

It is not feasible to have the user sign in again in the Today extension UI.

答: Use a Shared Keychain Group to store the token, as described at 14m00s in this WWDC video.</p>