问:
Vertically centre variable-height divs within fullscreen wrapper
The wrapper is 1170px wide - variable/full-screen height
Child divs are % width - variable in height (though i've specified px in the jsfiddle)

I've used the table(parent)/table-cell(child) method and that doesn't work.
Margin 0 Auto also doesn't seem to do anything - I'm not sure if it has anything to do with the relative position attribute of the child divs...

https://jsfiddle.net/x3cm32my/

```<code>.wrap {
  background: grey;
  margin-left: auto;
  margin-right: auto;
  width: 1170px;
  min-height: 100vh;
  vertical-align: middle;
  text-align: left;
  display: table;
}

.mod-left {
  background: blue;
  margin:0 auto;
  width: 30%;
  height: 100px;
  float: left;
  vertical-align: middle;
  position: relative;
  display: table-cell;
}

.mod-right {
  background: green;
  margin:0 auto;
  width: 65%;
  float: right;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 150px;
  position: relative;
}
</code>```

Would appreciate any tips!

答:
you can also use padding at .wrap to make your child in center of their parent.

for example

padding: 40vh 0;

Body:
The wrapper is 1170px wide - variable/full-screen height
Child divs are % width - variable in height (though i've specified px in the jsfiddle)

I've used the table(parent)/table-cell(child) method and that doesn't work.
Margin 0 Auto also doesn't seem to do anything - I'm not sure if it has anything to do with the relative position attribute of the child divs...

https://jsfiddle.net/x3cm32my/

.wrap {
  background: grey;
  margin-left: auto;
  margin-right: auto;
  width: 1170px;
  min-height: 100vh;
  vertical-align: middle;
  text-align: left;
  display: table;
}

.mod-left {
  background: blue;
  margin:0 auto;
  width: 30%;
  height: 100px;
  float: left;
  vertical-align: middle;
  position: relative;
  display: table-cell;
}

.mod-right {
  background: green;
  margin:0 auto;
  width: 65%;
  float: right;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 150px;
  position: relative;
}

Would appreciate any tips!


来源: stackexchange

问:
Ingress responding with 'default backend - 404' when using GKE
Using the latest Kubernetes version in GCP (1.6.4), I have the following Ingress definition:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: myproject
  namespace: default
  annotations:
    ingress.kubernetes.io/rewrite-target: /
    kubernetes.io/ingress.class: "gce"
spec:
  rules:
  - host: staging.myproject.io
    http:
      paths:
      - path: /poller
        backend:
          serviceName: poller
          servicePort: 8080
</code>```

Here is my service and deployment:

```<code>apiVersion: v1
kind: Service
metadata:
  name: poller
  labels:
    app: poller
    tier: backend
    role: service
spec:
  type: NodePort
  selector:
    app: poller
    tier: backend
    role: service
  ports:
  - port: 8080
    targetPort: 8080
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: poller
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: poller
        tier: backend
        role: service
    spec:
      containers:
      - name: poller
        image: gcr.io/myproject-1364/poller:latest
        imagePullPolicy: Always
        env:
        - name: SPRING_PROFILES_ACTIVE
          value: staging
        - name: GET_HOSTS_FROM
          value: dns
        ports:
        - containerPort: 8080
</code>```

In my /etc/hosts I have a line like:

```<code>35.190.37.148 staging.myproject.io
</code>```

However, I get default backend - 404 when curling any endpoint on staging.myproject.io:

```<code>$ curl staging.myproject.io/poller/cache/status
default backend - 404
</code>```

I have the exact same configuration working locally inside Minikube, with the only difference being the domain (dev.myproject.io), and that works like a charm.

I have read and tried pretty much everything that I could find, including stuff from here and here and here, but maybe I'm just missing something... any ideas?

答:
It does take 5-10 minutes for an Ingress to actually become usable in GKE. In the meanwhile, you can see responses with status codes 404, 502 and 500.

There is an ingress tutorial here: https://cloud.google.com/container-engine/docs/tutorials/http-balancer I recommend following it. Based on what you pasted, I can say the following:

You use service.Type=NodePort, which is correct.

I am not sure about the ingress.kubernetes.io/rewrite-target annotation, maybe that's the issue.

Make sure your application responds 200 OK to GET / request.

Also I realize you curl http://<ip>/ but your Ingress spec only handles /poller endpoint. So it's normal you get default backend - 404 response while querying /. You didn't configure any backends for / path in your Ingress spec.

ContentLicense: CC BY-SA 3.0

Body:
Using the latest Kubernetes version in GCP (1.6.4), I have the following Ingress definition:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: myproject
  namespace: default
  annotations:
    ingress.kubernetes.io/rewrite-target: /
    kubernetes.io/ingress.class: "gce"
spec:
  rules:
  - host: staging.myproject.io
    http:
      paths:
      - path: /poller
        backend:
          serviceName: poller
          servicePort: 8080

Here is my service and deployment:

apiVersion: v1
kind: Service
metadata:
  name: poller
  labels:
    app: poller
    tier: backend
    role: service
spec:
  type: NodePort
  selector:
    app: poller
    tier: backend
    role: service
  ports:
  - port: 8080
    targetPort: 8080
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: poller
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: poller
        tier: backend
        role: service
    spec:
      containers:
      - name: poller
        image: gcr.io/myproject-1364/poller:latest
        imagePullPolicy: Always
        env:
        - name: SPRING_PROFILES_ACTIVE
          value: staging
        - name: GET_HOSTS_FROM
          value: dns
        ports:
        - containerPort: 8080

In my /etc/hosts I have a line like:

35.190.37.148 staging.myproject.io

However, I get default backend - 404 when curling any endpoint on staging.myproject.io:

$ curl staging.myproject.io/poller/cache/status
default backend - 404

I have the exact same configuration working locally inside Minikube, with the only difference being the domain (dev.myproject.io), and that works like a charm.

I have read and tried pretty much everything that I could find, including stuff from here and here and here, but maybe I'm just missing something... any ideas?


问:
How to make android unit test for notifications?
I have the class handleFirebaseMessages . It contains the function onMessageReceived() . This function is in charge of receiving data and creating notifications. onMessageReceived() receives data in a RemoteMessages object. I am trying to write a test for this function. But I've not got it completely.

HandleFirebaseMessages

```<code>public class HandleFirebaseMessages extends FirebaseMessagingService {
@Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
   final Map<String, String> data = remoteMessage.getData();
    //create notifications using NotificationCompat.Builder
    }
 }
</code>```

I've been able to write a part of the test code. How do I complete this?

```<code>@Test
public  void testHandleFirebaseMessages() throws  Exception {

    Map<String,String> data=new HashMap<String,String>();
    data.put("id","4422");
    data.put("type", "1");
    data.put("imageUrl" , "https://image.freepik.com/free-vector/android-boot-logo_634639.jpg");
    data.put("smallTitle" , "DoJMA v2");
    data.put("smallSubTitle", "Update now from Google Play Store");
    data.put("ticker" , "New update for DoJMA");
    data.put("contentInfo" , "");
    data.put("link" , "https://photo2.tinhte.vn/data/avatars/l/1885/1885712.jpg?1402763583");
    data.put("className" , "HomeActivity");
    data.put("page" , "2");
    data.put("bigTitle" , "DoJMA Android app version 2 released!");
    data.put("bigSubTitle" , "Hi folks! New DoJMA update is here! Major redesigning and improvements! This app was made by the Mobile App Club.They work really hard man...and get good products");
    data.put("bigSummaryText" , "Update now");

    RemoteMessage message = new RemoteMessage.Builder("1")
            .setMessageId("1")
            .setData(data)
            .build();
    (new HandleFirebaseMessages()).onMessageReceived(message);

    //WHat now?
}
</code>```

答:
You test this by wrapping the Notifications API to make it testable. First you will need a way of passing in mocked dependencies to the constructor of your wrapper. You can write something like this:

```<code>class NotificationBuilderProvider {

    //TODO: implement Provider<NotificationCompat.Builder> if you are using JSR-330 annotations

    private Context context;

    NotificationBuilderProvider(Context context) {
        this.context = context;
    }

    @Override
    public NotificationCompat.Builder get() {
        return new NotificationCompat.Builder(context);
    }

}
</code>```

Now you can write a wrapper like this:

```<code>class NotificationsWrapper {

    private final NotificationBuilderProvider notificationBuilderProvider;
    private final NotificationManager notificationManager;

    NotficiationsWrapper(NotificationBuilderProvider notificationBuilderProvider, NotificationManager notificationManager) {
        this.notificationBuilderProvider = notificationBuilderProvider;
        this.notificationManager = notificationManager;
    }

    public void postNotification(Map<String, String> data) {
        Notification notification = notificationBuilderProvider.get()
            .setContentTitle(data.get("Title"))
            //etc
            .build();
        notificationManager.notify(ID, notification);
    }
}
</code>```

Now you can write a unit test for your NotificationWrapper which is easier to testing than testing the heavyweight service:

```<code>//mocks
NotificationBuilderProvider mockNotificationBuilderProvider;
NotificationBuilder mockNotificationBuilder;
NotificationManager mockNotificationManager;

//system under test
NotificationWrapper notificationWrapper;

@Before
public void setUp() {
     mockNotificationBuilderProvider = Mockito.mock(NotificationBuilderProvider.class);
     mockNotificationBuilder = Mockito.mock(NotificationCompat.Builder.class, RETURNS_SELF);
     mockNotifyManager = Mockito.mock(NotificationManager.class);
}

@Test
public void givenTitleInData_whenPost_thenNotificationHasContentTitle() {
     //arrange
     Map<String, String> data = new HashMap<>();
     data.put("Title", "MyTitle");

     //act
     notificationsWrapper.postNotification(data);

     //assert
     verify(notificationBuilder).setContentTitle(eq("Title"));
}
</code>```

If this all seems a little complicated, it's better to start with writing unit tests for simple classes until you are comfortable with the concepts of unit testing and mocking. Then you can move up to testing more complex classes. The Mockito documentation is a great place to start to learn about mocking and unit testing. Good luck!

Body:
I have the class handleFirebaseMessages . It contains the function onMessageReceived() . This function is in charge of receiving data and creating notifications. onMessageReceived() receives data in a RemoteMessages object. I am trying to write a test for this function. But I've not got it completely.

HandleFirebaseMessages

public class HandleFirebaseMessages extends FirebaseMessagingService {
@Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
   final Map<String, String> data = remoteMessage.getData();
    //create notifications using NotificationCompat.Builder
    }
 }

I've been able to write a part of the test code. How do I complete this?

@Test
public  void testHandleFirebaseMessages() throws  Exception {

    Map<String,String> data=new HashMap<String,String>();
    data.put("id","4422");
    data.put("type", "1");
    data.put("imageUrl" , "https://image.freepik.com/free-vector/android-boot-logo_634639.jpg");
    data.put("smallTitle" , "DoJMA v2");
    data.put("smallSubTitle", "Update now from Google Play Store");
    data.put("ticker" , "New update for DoJMA");
    data.put("contentInfo" , "");
    data.put("link" , "https://photo2.tinhte.vn/data/avatars/l/1885/1885712.jpg?1402763583");
    data.put("className" , "HomeActivity");
    data.put("page" , "2");
    data.put("bigTitle" , "DoJMA Android app version 2 released!");
    data.put("bigSubTitle" , "Hi folks! New DoJMA update is here! Major redesigning and improvements! This app was made by the Mobile App Club.They work really hard man...and get good products");
    data.put("bigSummaryText" , "Update now");

    RemoteMessage message = new RemoteMessage.Builder("1")
            .setMessageId("1")
            .setData(data)
            .build();
    (new HandleFirebaseMessages()).onMessageReceived(message);

    //WHat now?
}

Body:
You test this by wrapping the Notifications API to make it testable. First you will need a way of passing in mocked dependencies to the constructor of your wrapper. You can write something like this:

class NotificationBuilderProvider {

    //TODO: implement Provider<NotificationCompat.Builder> if you are using JSR-330 annotations

    private Context context;

    NotificationBuilderProvider(Context context) {
        this.context = context;
    }

    @Override
    public NotificationCompat.Builder get() {
        return new NotificationCompat.Builder(context);
    }

}

Now you can write a wrapper like this:

class NotificationsWrapper {

    private final NotificationBuilderProvider notificationBuilderProvider;
    private final NotificationManager notificationManager;

    NotficiationsWrapper(NotificationBuilderProvider notificationBuilderProvider, NotificationManager notificationManager) {
        this.notificationBuilderProvider = notificationBuilderProvider;
        this.notificationManager = notificationManager;
    }

    public void postNotification(Map<String, String> data) {
        Notification notification = notificationBuilderProvider.get()
            .setContentTitle(data.get("Title"))
            //etc
            .build();
        notificationManager.notify(ID, notification);
    }
}

Now you can write a unit test for your NotificationWrapper which is easier to testing than testing the heavyweight service:

//mocks
NotificationBuilderProvider mockNotificationBuilderProvider;
NotificationBuilder mockNotificationBuilder;
NotificationManager mockNotificationManager;

//system under test
NotificationWrapper notificationWrapper;

@Before
public void setUp() {
     mockNotificationBuilderProvider = Mockito.mock(NotificationBuilderProvider.class);
     mockNotificationBuilder = Mockito.mock(NotificationCompat.Builder.class, RETURNS_SELF);
     mockNotifyManager = Mockito.mock(NotificationManager.class);
}

@Test
public void givenTitleInData_whenPost_thenNotificationHasContentTitle() {
     //arrange
     Map<String, String> data = new HashMap<>();
     data.put("Title", "MyTitle");

     //act
     notificationsWrapper.postNotification(data);

     //assert
     verify(notificationBuilder).setContentTitle(eq("Title"));
}

If this all seems a little complicated, it's better to start with writing unit tests for simple classes until you are comfortable with the concepts of unit testing and mocking. Then you can move up to testing more complex classes. The Mockito documentation is a great place to start to learn about mocking and unit testing. Good luck!


问:
Critiquing my first python script, looking for advise
Looking for all of the errors in my code, I'm positive there are quite a few, I was wondering if someone  could point them out and possibly quickly explain how I could fix them..    </p>

```<code>import time
import re

cls=("\n" * 50)

fname=input("Please enter your first name:: ")
lname=input("Please enter your last name:: ")

while True:
    age= str (input("Please enter your age:: "))
    if re.search('[0-9]', age):
        break

while True:

    print("Welcome to python ",fname," ",lname,", your current age is ",age, sep="", end="")
    print(", This string should not break")

    addageyorn=input("Would you like to add X amount of years to your age, y or n:: ")

    if addageyorn==("y"):
        addage=input("How many years do you want to add to your age:: ")
        print("OK, so you want to add ",addage," years to your current age of ",age, sep="", end="")
        exeaddage = int(age) + int(addage)
        computed = str(exeaddage)
        print(", In ",addage," years you will be ",computed," years old, thanks for signing in.", sep="")
        time.sleep(5)
        exit()

    if addageyorn==("n"):
        print("Thanks for signing in")
        time.sleep(5)
        exit()

    elif addageyorn!=("y", "n"):
        print("Invalid Input")
</code>```

答:
i am not much sure about this,you need + operator to concatinate variables

```<code>import time
import re

cls=("\n" * 50)

fname=input("Please enter your first name:: ")
lname=input("Please enter your last name:: ")

while True:
    age= str (input("Please enter your age:: "))
    if re.search('[0-9]', age):
        break

while True:

    print("Welcome to python "+fname," "+lname+", your current age is "+age)
    print(", This string should not break")

    addageyorn=input("Would you like to add X amount of years to your age, y or n:: ")

    if addageyorn==("y"):
        addage=input("How many years do you want to add to your age:: ")
        print("OK, so you want to add "+addage+" years to your current age of "+age)
        exeaddage = int(age) + int(addage)
        computed = str(exeaddage)
        print(", In "+addage+" years you will be ",computed," years old, thanks for signing in.")
        time.sleep(5)
        exit()

    if addageyorn==("n"):
        print("Thanks for signing in")
        time.sleep(5)
        exit()

    elif addageyorn!=("y", "n"):
        print("Invalid Input")
</code>```

Body:
Looking for all of the errors in my code, I'm positive there are quite a few, I was wondering if someone  could point them out and possibly quickly explain how I could fix them..

import time
import re

cls=("\n" * 50)

fname=input("Please enter your first name:: ")
lname=input("Please enter your last name:: ")

while True:
    age= str (input("Please enter your age:: "))
    if re.search('[0-9]', age):
        break

while True:

    print("Welcome to python ",fname," ",lname,", your current age is ",age, sep="", end="")
    print(", This string should not break")

    addageyorn=input("Would you like to add X amount of years to your age, y or n:: ")

    if addageyorn==("y"):
        addage=input("How many years do you want to add to your age:: ")
        print("OK, so you want to add ",addage," years to your current age of ",age, sep="", end="")
        exeaddage = int(age) + int(addage)
        computed = str(exeaddage)
        print(", In ",addage," years you will be ",computed," years old, thanks for signing in.", sep="")
        time.sleep(5)
        exit()

    if addageyorn==("n"):
        print("Thanks for signing in")
        time.sleep(5)
        exit()

    elif addageyorn!=("y", "n"):
        print("Invalid Input")

Body:
i am not much sure about this,you need + operator to concatinate variables

import time
import re

cls=("\n" * 50)

fname=input("Please enter your first name:: ")
lname=input("Please enter your last name:: ")

while True:
    age= str (input("Please enter your age:: "))
    if re.search('[0-9]', age):
        break

while True:

    print("Welcome to python "+fname," "+lname+", your current age is "+age)
    print(", This string should not break")

    addageyorn=input("Would you like to add X amount of years to your age, y or n:: ")

    if addageyorn==("y"):
        addage=input("How many years do you want to add to your age:: ")
        print("OK, so you want to add "+addage+" years to your current age of "+age)
        exeaddage = int(age) + int(addage)
        computed = str(exeaddage)
        print(", In "+addage+" years you will be ",computed," years old, thanks for signing in.")
        time.sleep(5)
        exit()

    if addageyorn==("n"):
        print("Thanks for signing in")
        time.sleep(5)
        exit()

    elif addageyorn!=("y", "n"):
        print("Invalid Input")


问:
Wangle: /usr/local/lib/libfolly.so: undefined reference to boost::re_detail_106000
While installing Wangle, I encountered the following problem. I have already installed Boost, and I don't know why.

```<code>[ 65%] Built target wangle
Linking CXX executable bin/AcceptorTest
/usr/bin/ld: warning: libboost_filesystem.so.1.54.0, needed by /usr/local/lib/libfolly.so, may conflict with libboost_filesystem.so.1.61.0
/usr/bin/ld: warning: libboost_system.so.1.54.0, needed by /usr/local/lib/libfolly.so, may conflict with libboost_system.so.1.61.0
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::perl_matcher<char const*, std::allocator<boost::sub_match<char const*> >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::get_mem_block()'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::cpp_regex_traits_implementation<char>::transform_primary(char const*, char const*) const'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::verify_options(unsigned int, boost::regex_constants::_match_flags)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::get_default_error_string(boost::regex_constants::error_type)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::string>, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::string> > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::put_mem_block(void*)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::raise_runtime_error(std::runtime_error const&)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::cpp_regex_traits_implementation<char>::transform(char const*, char const*) const'
collect2: error: ld returned 1 exit status

make[2]: *** [bin/AcceptorTest] Error 1

make[1]: *** [CMakeFiles/AcceptorTest.dir/all] Error 2

make: *** [all] Error 2
</code>```

答:
Using clang instead of gcc, removing the atomic check in the CMakeList.txt and disabling tests made wangle build for me on Arch.

It currently won't build with GCC 7 (Issue) and GCC 5 threw a similar issue to yours for me.

CC=clang CXX=clang cmake . -DBUILD_TEST=0

(code above does not include the atomic check you need to remove in the CMakeList.txt yourself! Just search for atomic.)

Body:
While installing Wangle, I encountered the following problem. I have already installed Boost, and I don't know why.

[ 65%] Built target wangle
Linking CXX executable bin/AcceptorTest
/usr/bin/ld: warning: libboost_filesystem.so.1.54.0, needed by /usr/local/lib/libfolly.so, may conflict with libboost_filesystem.so.1.61.0
/usr/bin/ld: warning: libboost_system.so.1.54.0, needed by /usr/local/lib/libfolly.so, may conflict with libboost_system.so.1.61.0
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::perl_matcher<char const*, std::allocator<boost::sub_match<char const*> >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::get_mem_block()'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::cpp_regex_traits_implementation<char>::transform_primary(char const*, char const*) const'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::verify_options(unsigned int, boost::regex_constants::_match_flags)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::get_default_error_string(boost::regex_constants::error_type)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::string>, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::string> > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::put_mem_block(void*)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::raise_runtime_error(std::runtime_error const&)'
/usr/local/lib/libfolly.so: undefined reference to `boost::re_detail_106000::cpp_regex_traits_implementation<char>::transform(char const*, char const*) const'
collect2: error: ld returned 1 exit status

make[2]: *** [bin/AcceptorTest] Error 1

make[1]: *** [CMakeFiles/AcceptorTest.dir/all] Error 2

make: *** [all] Error 2


问:
pulling a random item from multiple arrays
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

```<code>var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}
</code>```

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

答:
You can use the window object.</p>

```<code>var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(window["f"+i][randomPrompt]);
}
</code>```

Body:
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

Body:
You can use the window object.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(window["f"+i][randomPrompt]);
}


问:
Where to store AES key at device end in android application development
When i develop any android application which is having the AES implementation and key should be common which is being used in server side as well as mobile side(client). So please suggest/ Guide me where should i store my key in device so that it will totally safe.
Should i store that key in SQLite database ?
or Should i make that key as string in code ?</p>

答:
Totally safe?  Nowhere.

What threat vector are you trying to protect yourself against?  If you're worried about just external attackers, downloading a key from the server and using it only in RAM or storing it in the keychain is sufficient.

If you're worried about the user/device owner-  well, nothing stops him from just putting on a custom ROM that logs all calls to the keychain functions.  Or that logs all data sent from the device.  To even start to make that safe you'd need to use your own copy of libssl, your own http libraries (that do the encryption yourself), and never write it anywhere (request it from the server each time).  And even then its not safe against anyone willing to do reverse engineering and figure out where in memory the key is saved.

If you really want to keep data safe-  don't send it to the client.


问:
How to create a java package that lives outside the android project
My android project is called MyPlaces. I want to create a library (package) with commomTools classes that LIVES outside the MyPlaces directory; however, every time I open MyPlaces project and create a new module, Android Studio creates a directory INSIDE MyPlaces called commontools. I want to create this commonTools directory outside, as it is shown in the screenshot and I prefer it not to be an android project.

I just want to be able to import the classes from the package from different Android Applications.

How can I do that?

Thank you for your help.

答:
Create a new project and and a module which is library.

Then you can use jitpack.io to import it from Gradle.

Good luck

Emre


问:
how to execute docker diff command using kubernetes
I am using docker diff in my application in order to find all changed files in a container. Now, my application manages containers through Kubernetes and don't have a direct access to them. I found Kubernetes implementations for several docker commands (like kubectl logs), bit docker diff is missed.

Is there a way to execute docker diff for a pod  through Kubernetes?

Many thanks

答:
Kubernetes (kubectl) does not offer an equivalent command. Ideally you should not be using this command at all outside your local development environment (which is docker)

The best practice is to start containers with readonly root filesystem, so that you avoid storing any important state in containers. Kubernetes can kill and restart your pod in another node as a new container, so you should not care about the docker diff that happens on the container.


问:
print " ".join(tsOutput) ^ SyntaxError: invalid syntax
i am getting error in

print "".join(tsOutput)

is it due to syntax are different in python 2.x and 3.x versions?

答:
print("".join(tsOutput)) try this.

go through this site to learn more about python


问:
Change date format dot instead of slash in Date Range Picker
is it possible to change the date format from 02/03/2017 to 02.03.2017
dot instead of slash ?
please advice

link to jquery plugin daterangepicker.com

答:
Use the following code to change the Date format</p>

```<code>$('input[name="daterange"]').daterangepicker({
        locale: {
            format: 'MM.DD.YYYY h:mm A'
        }
    });
</code>```

Body:
Use the following code to change the Date format

$('input[name="daterange"]').daterangepicker({
        locale: {
            format: 'MM.DD.YYYY h:mm A'
        }
    });


问:
How to make UWP apps compatible with windows 8.1
I have installed Visual studio 2017 and Visual studio 2015.

Using visual studio 2015 I am able to create Xamarin.winphone projects and I am able to run this app on windows 8,8.1,10

Using visual studio 2017 I am able to create Xamarin.uwp projects and while Creating it I would like to support windows 8 as well .. but in minimum version I am not able to find it

答:
UWP is Windows 10 only, so the lowest target is the first Windows 10 Build 10240

The Universal Windows Platform (UWP) is the app platform for Windows
  10. You can develop apps for UWP with just one API set, one app package, and one store to reach all Windows 10 devices – PC, tablet,
  phone, Xbox, HoloLens, Surface Hub and more.


问:
update property value of array of object using es6
```<code>function posts(state = [], action) {
    switch(action.type){
        case 'INCREMENT_LIKES':
            const i = action.index
            return [
                ...state.slice(0,i),
                {...state[i], likes: state[i].likes + 1},
                ...state.slice(i + 1),
            ]
        default:
            return state
    }
}

export default posts
</code>```

Above code worked but for me it's not so elegant, it look super confusing and not so flexible. What if my id is in number, I can't do slice(i + 1), anymore. I can use map with object assign to solve it but I'm looking for more alternative to do update property value of array of object using es6

答:
An alternative would be to make use of update from npm package immutability-helper which is every easy to handle and understand even in case of deep nested states and

```<code>import update from `immutability-helper`

function posts(state = [], action) {
    switch(action.type){
        case 'INCREMENT_LIKES':
            const i = action.index
            return update(state, {
                 [i]: {
                      likes: {
                            $set: state[i].likes + 1
                      }
                 }
            })

        default:
            return state
    }
}

export default posts
</code>```

Body:
function posts(state = [], action) {
    switch(action.type){
        case 'INCREMENT_LIKES':
            const i = action.index
            return [
                ...state.slice(0,i),
                {...state[i], likes: state[i].likes + 1},
                ...state.slice(i + 1),
            ]
        default:
            return state
    }
}

export default posts

Above code worked but for me it's not so elegant, it look super confusing and not so flexible. What if my id is in number, I can't do slice(i + 1), anymore. I can use map with object assign to solve it but I'm looking for more alternative to do update property value of array of object using es6

Body:
An alternative would be to make use of update from npm package immutability-helper which is every easy to handle and understand even in case of deep nested states and

import update from `immutability-helper`

function posts(state = [], action) {
    switch(action.type){
        case 'INCREMENT_LIKES':
            const i = action.index
            return update(state, {
                 [i]: {
                      likes: {
                            $set: state[i].likes + 1
                      }
                 }
            })

        default:
            return state
    }
}

export default posts


问:
Intellij-idea Debugger disconnected when debugging maven test
I have followed this link to debug maven test via Intellij Idea : http://www.grygoriy.com/2012/01/how-to-debug-tests-maven-test-via.html

When reaching the third step and starting debugging, It's connected but quickly disconnected and isn't stopped in breakpoints. I had in Intellij :

Connected to the target VM, address: 'localhost:5005', transport: 'socket'

Disconnected from the target VM, address: 'localhost:5005', transport: 'socket'

Any idea ?

答:
The only thing that prevents Idea from debugging Maven's goals is forking.

Plugins such surefire and spring-boot are using forking by default.

So, when you start debuging maven goal from IDEA it connects to maven, but process that you are really want to debug distincts from maven process, so it doesn't connected.

To prevent such behavior in surefire plugin you should read this article: http://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html

In short:

If you use old surefire:

```<code><configuration>
    <forkMode>never</forkMode>
</configuration>
</code>```

In new surefire:

```<code><configuration>
    <forkCount>0</forkCount>
</configuration>
</code>```

But it's not much clear:

in case of CI (i wish you are using CI tools) you are not have prevent forking while it's much slow

if you ship your project to others - they will not be happy if some of modules behave in not default way

So if you want to please CI, IDEA, co-developers and yourself you should provide more smart way to allow debugging you build.

My suggestion:

default behavior is forked because build process is very often thing, while debugging it - is exception

debugger behavior is isolated with simple to use "switch on"

My variant:

```<code><properties>
    <test.forkCount>1</test.forkCount>
</properties>
<profiles>
      <profile>
            <id>debug</id>
             <properties>
                     <test.forkCount>0</test.forkCount>
             </properties>
        </profile>
 </profiles>
 <build>
      <plugins>
           <plugin>
                <!-- surefire -->
                <configuration>
                    <forkCount>${test.forkCount}</forkCount>
                </configuration>
            </plugin>
        </plugins>
</build>
</code>```

So, in IDEA you just require to create named Run configuration with goal test and include debug to profile list.

But in other contexts - maven behaves still by default.

Where is addition profit - you can incapsulate whole debug behavior in single profile.

For example in my real project debug profile:

swith off forking on spring-boot:run

switch off JaCoCo coverage (it requires forking on surefire)

keep building Docker images locally but prevents pushing to registry

keep full packaging process but prevents publication to nexus

redirects SOAP UI functional tests to specital URL for local debugging

redirects DBCONFIG to docker-based Postgres that is "always empty"

downgrades loglevel for log4j to DEBUG

So if I use mvn <any> -P debug i'm sure that my environment and process is really debug

But if i ran mvn deploy on CI - i will get full stack of my building process.

Body:
The only thing that prevents Idea from debugging Maven's goals is forking.

Plugins such surefire and spring-boot are using forking by default.

So, when you start debuging maven goal from IDEA it connects to maven, but process that you are really want to debug distincts from maven process, so it doesn't connected.

To prevent such behavior in surefire plugin you should read this article: http://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html

In short:

If you use old surefire:

<configuration>
    <forkMode>never</forkMode>
</configuration>

In new surefire:

<configuration>
    <forkCount>0</forkCount>
</configuration>

But it's not much clear:

in case of CI (i wish you are using CI tools) you are not have prevent forking while it's much slow

if you ship your project to others - they will not be happy if some of modules behave in not default way

So if you want to please CI, IDEA, co-developers and yourself you should provide more smart way to allow debugging you build.

My suggestion:

default behavior is forked because build process is very often thing, while debugging it - is exception

debugger behavior is isolated with simple to use "switch on"

My variant:

<properties>
    <test.forkCount>1</test.forkCount>
</properties>
<profiles>
      <profile>
            <id>debug</id>
             <properties>
                     <test.forkCount>0</test.forkCount>
             </properties>
        </profile>
 </profiles>
 <build>
      <plugins>
           <plugin>
                <!-- surefire -->
                <configuration>
                    <forkCount>${test.forkCount}</forkCount>
                </configuration>
            </plugin>
        </plugins>
</build>

So, in IDEA you just require to create named Run configuration with goal test and include debug to profile list.

But in other contexts - maven behaves still by default.

Where is addition profit - you can incapsulate whole debug behavior in single profile.

For example in my real project debug profile:

swith off forking on spring-boot:run

switch off JaCoCo coverage (it requires forking on surefire)

keep building Docker images locally but prevents pushing to registry

keep full packaging process but prevents publication to nexus

redirects SOAP UI functional tests to specital URL for local debugging

redirects DBCONFIG to docker-based Postgres that is "always empty"

downgrades loglevel for log4j to DEBUG

So if I use mvn <any> -P debug i'm sure that my environment and process is really debug

But if i ran mvn deploy on CI - i will get full stack of my building process.


问:
Difference between Testng class and normal Java class
What is the difference between Testng Class and a normal Java class. While creating an Automation suite in Selenium should we use Testng class or normal java class in Eclipse.</p>

答:
Testng Class and a normal Java class

TestNG Class: TestNg class is nothing but any normal class with TestNG annotation and Annotation is a tag that represents the metadata which gives the addition information about class, methods and interface.

To know more about annotation Please refer this https://docs.oracle.com/javase/tutorial/java/annotations/

While creating Automation suite we use either JUNIT or TestNG. JUNIT or TestNG are testing framework. They have their own set of libraries and annotations which is useful to run our automation suite. JUNIT or TestNG makes easy to run automation suite or generate reports of build run. They provide the feature to setup or cleanup activity using Before and After annotation which is require in almost every autoamtion suite.

TestNG also provide us flexibility to execute our automation script based on our requirement like we can group of test cases, we can include or exclude methods, parallel execution of test methods and many more.

Please refer this to know more about TestNG.
  http://testng.org/doc/documentation-main.html

I hope this will help.


问:
Java 8 stream: sum of units of same items
Is there a concise way to sum the units of the same type of items in a list with Java 8 streams? For example, suppose I have a list of three items:

```<code>{id: 10, units: 1}
{id: 20, units: 2}
{id: 10, units: 1}
</code>```

I like a summary stream like:

```<code>{id: 10, units 2}
{id: 20, units 2}
</code>```

which sums the units of items of the same id. Any ideas?

Here's Federico's solution (with Lombok):

```<code>import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class So44348207 {

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
            new Item(10,1), new Item(20,2), new Item(10, 1)
        );

        Map<Long, Integer> results = items.stream().collect(
            Collectors.toMap(
                Item::getId,
                Item::getUnits,
                Integer::sum
                )
            );

        results.forEach( (k,v) -> System.out.println(
            String.format("{id: %d, units: %d}", k,v))
        );
    }

    @Data
    @AllArgsContructor
    public static class Item {
        Long id;
        Integer units;
    }
}
</code>```

which correctly produces:

```<code>java So44348207
{id: 20, units: 2}
{id: 10, units: 2}
</code>```

答:
Here is another simple solution by StreamEx</p>

```<code>StreamEx.of(items).toMap(Item::getId, Item::getUnits, Integer::sum);
</code>```

Body:
Is there a concise way to sum the units of the same type of items in a list with Java 8 streams? For example, suppose I have a list of three items:

{id: 10, units: 1}
{id: 20, units: 2}
{id: 10, units: 1}

I like a summary stream like:

{id: 10, units 2}
{id: 20, units 2}

which sums the units of items of the same id. Any ideas?

Here's Federico's solution (with Lombok):

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class So44348207 {

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
            new Item(10,1), new Item(20,2), new Item(10, 1)
        );

        Map<Long, Integer> results = items.stream().collect(
            Collectors.toMap(
                Item::getId,
                Item::getUnits,
                Integer::sum
                )
            );

        results.forEach( (k,v) -> System.out.println(
            String.format("{id: %d, units: %d}", k,v))
        );
    }

    @Data
    @AllArgsContructor
    public static class Item {
        Long id;
        Integer units;
    }
}

which correctly produces:

java So44348207
{id: 20, units: 2}
{id: 10, units: 2}

Body:
Here is another simple solution by StreamEx

StreamEx.of(items).toMap(Item::getId, Item::getUnits, Integer::sum);


问:
Tutorials on PyObjC
I would like to know if there are any tutorial websites for learning PyObjC apart from the home page of the project itself. I'm enthusiastic about being able to use python to develop native code and be productive without learning how to program in some of the other more traditional compiled languages. Anywhere I could get a screencast or good beginner tuts would be excellent.</p>

答:
You could start with Will Larson's stuff.  You could read the Apple docs and do the temperature conversion thingie.  You could do what I did and get Hillegass's book and then do the examples using PyObjC.  You could read my stuff.  I have lots of simple examples, but I'm just an amateur.  You don't need to worry about Objective-C yet, but if you stick with it, you probably will.

And you really must learn that case matters.

ContentLicense: CC BY-SA 2.5

Title: Tutorials on PyObjC


问:
PHP array to JavaScript array using json_encode()
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

```<code>$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });
</code>```

PHP code:

```<code><?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct
    //username and password
    $username = trim($_POST["user"]);

   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}
</code>```

答:
You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:

```<code>header('Content-Type: application/json');
echo json_encode($customer_array);
</code>```

Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).

Body:
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });

PHP code:

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct
    //username and password
    $username = trim($_POST["user"]);

   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}

Body:
You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:

header('Content-Type: application/json');
echo json_encode($customer_array);

Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).


问:
RSPec: Fix "warning: already initialized constant" for memoized class under test
I keep seeing these warnings when running this basic test suite:

```<code>spec/example_spec.rb:6: warning: already initialized constant DB_ID
spec/example_spec.rb:6: warning: previous definition of DB_ID was here
spec/example_spec.rb:8: warning: already initialized constant FIELDS
spec/example_spec.rb:8: warning: previous definition of FIELDS was here
</code>```

Here's an example test:

```<code>require_relative 'spec_helper'

RSpec.describe MyModule::BaseClass do
  let(:example_class) do
    Class.new(described_class) do
      DB_ID = 'example'

      FIELDS = {
        a: 2,
        b: 4,
        c: 6
      }

      def foo
        'foo'
      end

      def bar
        'bar'
      end
    end
  end

  subject { example_class.new }

  it 'does foo' do
    expect(subject.foo).to eq('foo')
  end

  it 'does bar' do
    expect(subject.bar).to eq('bar')
  end
end
</code>```

The warnings are triggered anytime I use subject.

My understanding is that let defines a memoized helper method so that the example_class is only evaluated once on first reference.

If that's true, why am I receiving these warnings?

答:
When you use Class.new you are creating an anonymous (unnamed) class.

When constant is defined ruby needs to resolve the namespace for which the constant is defined.

Unlike in a module or a class the namespace within the anonymous class is empty.

```<code>class A
  p Module.nesting # => [A]
  B = 1
end
B    #=> NameError: uninitialized constant B
A::B #=> 1

Class.new(A) do
  p Module.nesting # => []
  C = 1
end
C #=> 1
</code>```

Since there is no explicit namespace where to put these constant, they end up getting defined "globally" in Object class.

You can try this yourself with following example (run it with --order defined):

```<code>require_relative 'spec_helper'

class Base
end

RSpec.describe Base do
  context 'creating an anonymous class with a constant' do
    let(:example_class) do
      Class.new(described_class) do
        DB_ID = 'example'

        def foo
          'foo'
        end
      end
    end

    it 'does foo' do
      expect(example_class.new.foo).to eq('foo')
    end
  end

  context 'the constant is on Object' do
    it 'does bar' do
      expect(DB_ID).to eq('example')
    end
  end
end
</code>```

It boils down to how ruby constant lookup works. Here is a nice post about it https://cirw.in/blog/constant-lookup.html.

Body:
I keep seeing these warnings when running this basic test suite:

spec/example_spec.rb:6: warning: already initialized constant DB_ID
spec/example_spec.rb:6: warning: previous definition of DB_ID was here
spec/example_spec.rb:8: warning: already initialized constant FIELDS
spec/example_spec.rb:8: warning: previous definition of FIELDS was here

Here's an example test:

require_relative 'spec_helper'

RSpec.describe MyModule::BaseClass do
  let(:example_class) do
    Class.new(described_class) do
      DB_ID = 'example'

      FIELDS = {
        a: 2,
        b: 4,
        c: 6
      }

      def foo
        'foo'
      end

      def bar
        'bar'
      end
    end
  end

  subject { example_class.new }

  it 'does foo' do
    expect(subject.foo).to eq('foo')
  end

  it 'does bar' do
    expect(subject.bar).to eq('bar')
  end
end

The warnings are triggered anytime I use subject.

My understanding is that let defines a memoized helper method so that the example_class is only evaluated once on first reference.

If that's true, why am I receiving these warnings?

Body:
When you use Class.new you are creating an anonymous (unnamed) class.

When constant is defined ruby needs to resolve the namespace for which the constant is defined.

Unlike in a module or a class the namespace within the anonymous class is empty.

class A
  p Module.nesting # => [A]
  B = 1
end
B    #=> NameError: uninitialized constant B
A::B #=> 1

Class.new(A) do
  p Module.nesting # => []
  C = 1
end
C #=> 1

Since there is no explicit namespace where to put these constant, they end up getting defined "globally" in Object class.

You can try this yourself with following example (run it with --order defined):

require_relative 'spec_helper'

class Base
end

RSpec.describe Base do
  context 'creating an anonymous class with a constant' do
    let(:example_class) do
      Class.new(described_class) do
        DB_ID = 'example'

        def foo
          'foo'
        end
      end
    end

    it 'does foo' do
      expect(example_class.new.foo).to eq('foo')
    end
  end

  context 'the constant is on Object' do
    it 'does bar' do
      expect(DB_ID).to eq('example')
    end
  end
end

It boils down to how ruby constant lookup works. Here is a nice post about it https://cirw.in/blog/constant-lookup.html.


问:
Erroneous example in official Python tutorial (Chapter 9.10)?
I copied the following example from Python 3.6.1 Documentation, Chapter 9.10 into Jupyter Notebook (Python version 3.6.1):

```<code>xvec = [10, 20, 30]

yvec = [7, 5, 3]

sum(x*y for x,y in zip(xvec, yvec))         # dot product
</code>```

While the official documentation says that it would print 260, I got the following error in Notebook:

```<code>----> 4 sum(x*y for x,y in zip(xvec, yvec))
TypeError: 'int' object is not callable
</code>```

This is definitely not just a question on 'int object is not callable', but more on the palpable error in what is considered to be the gospel for Python.

答:
The code should work as long as you didn't overwrite zip or sum:

```<code>>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))
260
</code>```

Make sure that you didn't overwrite them:

```<code>>>> sum = 0  # <--- overwrite
>>> sum(x*y for x,y in zip(xvec, yvec))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
</code>```

Body:
I copied the following example from Python 3.6.1 Documentation, Chapter 9.10 into Jupyter Notebook (Python version 3.6.1):

xvec = [10, 20, 30]

yvec = [7, 5, 3]

sum(x*y for x,y in zip(xvec, yvec))         # dot product

While the official documentation says that it would print 260, I got the following error in Notebook:

----> 4 sum(x*y for x,y in zip(xvec, yvec))
TypeError: 'int' object is not callable

This is definitely not just a question on 'int object is not callable', but more on the palpable error in what is considered to be the gospel for Python.

Body:
The code should work as long as you didn't overwrite zip or sum:

>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))
260

Make sure that you didn't overwrite them:

>>> sum = 0  # <--- overwrite
>>> sum(x*y for x,y in zip(xvec, yvec))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable


问:
Laravel Echo never recieving event
For whatever reason, I cannot receive any data on my client side from laravel echo. I am using laravel-echo-server (socket.io), redis broadcaster, and redis queues. As far as I can tell, they are all functional. I'll take you through how I set it up for testing. First I created a UserCreated event:

```<code>class UserCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return new Channel('user-created');
    }

    public function broadcastAs()
    {
        return 'user.created';
    }
}
</code>```

Then, to test this event, I created a CreateUser command:

```<code>class CreateUser extends Command
{
    protected $signature = 'create:user {username}';

    protected $description = 'Create a new user!';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $user = \Chatter\User::create([
            'name' => $this->argument('username'),
            'email' => uniqid() . '@gmail.com',
            'password' => bcrypt('secret')
        ]);
        event(new \Chatter\Events\UserCreated($user));
    }
}
</code>```

Finally, here is my laravel-echo-server.json:

```<code>{
    "authEndpoint": "/broadcasting/auth",
    "authHost": "chatter.dev",
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "localhost"
        }
    },
    "port": 6001,
    "protocol": "http",
    "sslCertPath": "",
    "sslKeyPath": "",
    "socketio": {}
}
</code>```

Next I ran php artisan queue:listen, and laravel-echo-server start. They both ran without error.
To make sure that the server worked, I did php artisan create:user Bob123.
It was successful. The queue returned this (in console):

```<code>[2017-06-01 01:28:27] Processing: Chatter\Events\UserCreated
[2017-06-01 01:28:27] Processed:  Chatter\Events\UserCreated
</code>```

And the laravel-echo-server returned this (in console):

```<code>CHANNEL user-created
</code>```

So, to get the data I sent with the user, I created a Vue component, with a echo listener in the mounted function. Here's my component:

```<code><template>
    <div class="container">
        <div class="row">

        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.');
            window.Echo.channel('user-created')
                .listen('.user.created', (data) => {
                    console.log(data);
                });
        },

        data(){
            return {
                messages: []
            }
        }
     }
</script>
</code>```

When I refreshed my webpage, Component mounted was logged to the console so I'm certain that it loaded. But, for whatever reason, when I send the CreateUser command, the data is not logged into the browsers console.

Here is everything that you might point out:

I changed my broadcast driver to redis in my .env

```<code>BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
</code>```

I also uncommented the BroadcastingServiceProvider in the app.php config.

I can't think of anything else right now that you might point out that I have done, but if I remember any others I will update the question.

Thanks for any help.

Note: I'm not familiar with Redis, so currently I'm leaning towards that being my problem. Simply adding predis\predis as a dependency simply doesn't feel like that's all I have to do. Hopefully this note helps.

Edit:

As suggested, I tried running redis-server before I ran laravel-echo-server. This is what was returned in the console:

```<code>vagrant@homestead:~/Code/Chatter$ redis-server
16342:C 01 Jun 05:45:38.066 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
16342:M 01 Jun 05:45:38.067 * Increased maximum number of open files to 10032 (it was originally set to 1024).
16342:M 01 Jun 05:45:38.067 # Creating Server TCP listening socket *:6379: bind: Address already in use
</code>```

I assume this means that the redis server was running, so I guess homestead starts it automatically by default.

Github Repository:

Sorry this took so long, I was very busy personally. Here is the link to the github repository for this project. If there are any questions about the repository just let me know.

https://github.com/Dastur1970/laravel-echo-test

Edit 2:

Just in case anyone needs it, here is my the code I used to create my Echo instance.

```<code>window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
    // auth: {
    //     headers: {
    //         'Authorization': 'bf242984230eb684 1076b91e572e5bbcc81a852471364c49'
    //     }
    // },
    // key: '1076b91e572e5bbcc81a852471364c497',
    // csrfToken: token.content
});
</code>```

Commented out some of the stuff that I was testing with. Was not sure if I would need the again so I just left them commented. Let me know if any of the commented code may actually be helpful.

答:
Okay, let's find the possible parts where you error could be:

This is the queue that the server is running through

Event

Listener

Redis

Laravel-echo-Server

Client

[2017-06-01 01:28:27] Processed:  Chatter\Events\UserCreated

the event was successfully handled by the listener (step 2)

CHANNEL user-created

The event was written to the database and the laravel-echo-server got it (step 4)

Normally the laravel-echo-server prints a message when a new user joins a channel. I see none of those messages in your code so the connection between the laravel-echo-server and the client could be the problem. Also, I don't see any code where you create the Echo object on the client with Javascript.

Title: Laravel Echo never recieving event

Body:
For whatever reason, I cannot receive any data on my client side from laravel echo. I am using laravel-echo-server (socket.io), redis broadcaster, and redis queues. As far as I can tell, they are all functional. I'll take you through how I set it up for testing. First I created a UserCreated event:

class UserCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return new Channel('user-created');
    }

    public function broadcastAs()
    {
        return 'user.created';
    }
}

Then, to test this event, I created a CreateUser command:

class CreateUser extends Command
{
    protected $signature = 'create:user {username}';

    protected $description = 'Create a new user!';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $user = \Chatter\User::create([
            'name' => $this->argument('username'),
            'email' => uniqid() . '@gmail.com',
            'password' => bcrypt('secret')
        ]);
        event(new \Chatter\Events\UserCreated($user));
    }
}

Finally, here is my laravel-echo-server.json:

{
    "authEndpoint": "/broadcasting/auth",
    "authHost": "chatter.dev",
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "localhost"
        }
    },
    "port": 6001,
    "protocol": "http",
    "sslCertPath": "",
    "sslKeyPath": "",
    "socketio": {}
}

Next I ran php artisan queue:listen, and laravel-echo-server start. They both ran without error.
To make sure that the server worked, I did php artisan create:user Bob123.
It was successful. The queue returned this (in console):

[2017-06-01 01:28:27] Processing: Chatter\Events\UserCreated
[2017-06-01 01:28:27] Processed:  Chatter\Events\UserCreated

And the laravel-echo-server returned this (in console):

CHANNEL user-created

So, to get the data I sent with the user, I created a Vue component, with a echo listener in the mounted function. Here's my component:

<template>

</template>

When I refreshed my webpage, Component mounted was logged to the console so I'm certain that it loaded. But, for whatever reason, when I send the CreateUser command, the data is not logged into the browsers console.

Here is everything that you might point out:

I changed my broadcast driver to redis in my .env

BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

I also uncommented the BroadcastingServiceProvider in the app.php config.

I can't think of anything else right now that you might point out that I have done, but if I remember any others I will update the question.

Thanks for any help.

Note: I'm not familiar with Redis, so currently I'm leaning towards that being my problem. Simply adding predis\predis as a dependency simply doesn't feel like that's all I have to do. Hopefully this note helps.

Edit:

As suggested, I tried running redis-server before I ran laravel-echo-server. This is what was returned in the console:

vagrant@homestead:~/Code/Chatter$ redis-server
16342:C 01 Jun 05:45:38.066 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
16342:M 01 Jun 05:45:38.067 * Increased maximum number of open files to 10032 (it was originally set to 1024).
16342:M 01 Jun 05:45:38.067 # Creating Server TCP listening socket *:6379: bind: Address already in use

I assume this means that the redis server was running, so I guess homestead starts it automatically by default.

Github Repository:

Sorry this took so long, I was very busy personally. Here is the link to the github repository for this project. If there are any questions about the repository just let me know.

https://github.com/Dastur1970/laravel-echo-test

Edit 2:

Just in case anyone needs it, here is my the code I used to create my Echo instance.

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
    // auth: {
    //     headers: {
    //         'Authorization': 'bf242984230eb684 1076b91e572e5bbcc81a852471364c49'
    //     }
    // },
    // key: '1076b91e572e5bbcc81a852471364c497',
    // csrfToken: token.content
});

Commented out some of the stuff that I was testing with. Was not sure if I would need the again so I just left them commented. Let me know if any of the commented code may actually be helpful.


问:
Reusing host GOOGLE_APPLICATION_CREDENTIALS in pods
Is there a way to inherit host environmental variables in the GKE pods?

I am specifically interested in GOOGLE_APPLICATION_CREDENTIALS - container performs some internal project services and it would be great if I could reuse Compute Engine default Service Account as opposed to define a custom one.

答:
Where are you planning to inherit environment variables from?

By default, if you give your container cluster enough privileges (i.e. the  --scopes argument in gcloud container clusters create), containers will be able to use GCE machine’s IAM role and will be able to use the services listed in --scopes.

If you use --scopes, you don't need to specify any GOOGLE_APPLICATION_CREDENTIALS, most Google Cloud client libraries will automatically use GCE instance’s identity to make requests.


问:
How to plot parallel coordinates with multiple categorical variables in R
I am facing a difficulty while plotting a parallel coordinates plot using the ggparcoord from the GGally package. As there are two categorical variables, what I want to show in the visualisation is like the image below. I've found that in ggparcoord, groupColumn is only allowed to a single variable to group (colour) by, and surely I can use showPoints to mark the values on the axes, but i also need to vary the shape of these markers according to the categorical variables. Is there other package that can help me to realise my idea?

Any response will be appreciated! Thanks!

答:
It's not that difficult to roll your own parallel coordinates plot in ggplot2, which will give you the flexibility to customize the aesthetics. Below is an illustration using the built-in diamonds data frame.

To get parallel coordinates, you need to add an ID column so you can identify each row of the data frame, which we'll use as a group aesthetic in ggplot. You also need to scale the numeric values so that they'll all be on the same vertical scale when we plot them. Then you need to take all the columns that you want on the x-axis and reshape them to "long" format. We do all that on the fly below with the tidyverse/dplyr pipe operator.

Even after limiting the number of category combinations, the lines are probably too intertwined for this plot to be easily interpretable, so consider this merely a "proof of concept". Hopefully, you can create something more useful with your data. I've used colour (for the lines) and fill (for the points) aesthetics below. You can use shape or linetype instead, depending on your needs.

```<code>library(tidyverse)
theme_set(theme_classic())

# Get 20 random rows from the diamonds data frame after limiting
#  to two levels each of cut and color
set.seed(2)
ds = diamonds %>%
  filter(color %in% c("D","J"), cut %in% c("Good", "Premium")) %>%
  sample_n(20)

ggplot(ds %>%
         mutate(ID = 1:n()) %>%             # Add ID for each row
         mutate_if(is.numeric, scale) %>%   # Scale numeric columns
         gather(key, value, c(1,5:10)),     # Reshape to "long" format
       aes(key, value, group=ID, colour=color, fill=cut)) +
  geom_line() +
  geom_point(size=2, shape=21, colour="grey50") +
  scale_fill_manual(values=c("black","white"))
</code>```

I haven't used ggparcoords before, but the only option that seemed straightforward (at least on my first try with the function) was to paste together two columns of data. Below is an example. Even with just four category combinations, the plot is confusing, but maybe it will be interpretable if there are strong patterns in your data:

```<code>library(GGally)

ds$group = with(ds, paste(cut, color, sep="-"))

ggparcoord(ds, columns=c(1, 5:10), groupColumn=11) +
  theme(panel.grid.major.x=element_line(colour="grey70"))
</code>```

Body:
It's not that difficult to roll your own parallel coordinates plot in ggplot2, which will give you the flexibility to customize the aesthetics. Below is an illustration using the built-in diamonds data frame.

To get parallel coordinates, you need to add an ID column so you can identify each row of the data frame, which we'll use as a group aesthetic in ggplot. You also need to scale the numeric values so that they'll all be on the same vertical scale when we plot them. Then you need to take all the columns that you want on the x-axis and reshape them to "long" format. We do all that on the fly below with the tidyverse/dplyr pipe operator.

Even after limiting the number of category combinations, the lines are probably too intertwined for this plot to be easily interpretable, so consider this merely a "proof of concept". Hopefully, you can create something more useful with your data. I've used colour (for the lines) and fill (for the points) aesthetics below. You can use shape or linetype instead, depending on your needs.

library(tidyverse)
theme_set(theme_classic())

# Get 20 random rows from the diamonds data frame after limiting
#  to two levels each of cut and color
set.seed(2)
ds = diamonds %>%
  filter(color %in% c("D","J"), cut %in% c("Good", "Premium")) %>%
  sample_n(20)

ggplot(ds %>%
         mutate(ID = 1:n()) %>%             # Add ID for each row
         mutate_if(is.numeric, scale) %>%   # Scale numeric columns
         gather(key, value, c(1,5:10)),     # Reshape to "long" format
       aes(key, value, group=ID, colour=color, fill=cut)) +
  geom_line() +
  geom_point(size=2, shape=21, colour="grey50") +
  scale_fill_manual(values=c("black","white"))

I haven't used ggparcoords before, but the only option that seemed straightforward (at least on my first try with the function) was to paste together two columns of data. Below is an example. Even with just four category combinations, the plot is confusing, but maybe it will be interpretable if there are strong patterns in your data:

library(GGally)

ds$group = with(ds, paste(cut, color, sep="-"))

ggparcoord(ds, columns=c(1, 5:10), groupColumn=11) +
  theme(panel.grid.major.x=element_line(colour="grey70"))


问:
how to use VB.NET 2015 or 2017 on an Azure Windows Server 2012 VM to programmatically send a message to the 10-digit mobile number of an SMS device
Given the 10-digit mobile# of, say, an iPhone, how can .NET send a message (<= 160 chars) to arrive as a text message at the device (iPhone or Android)?

If I knew the mobile# ranges of each carrier's domain, then I could email via SMTP to:
<10-digit#>@
But I haven't found any table of carrier domains vs. mobile#.

答: direct sms from c# isn't something you'll be able to code, you'll need to have connections to the telcom networks, which is not something you'll be able to get without some hardcore company resources and negotiations behind you. unless you use a 3rd party api, tropo is one that i use, there's a few more out there that provide the similar api's</p>


问:
Do I have to use a signal handler for a Posix timer?
I want to start a timer and have a function called when it expires.

Googling finds lots of examples, including the example in the manual, all of which use sigaction() to set a signal handler.

However, @Patryk says in this question that we can just

```<code>void cbf(union sigval);
struct sigevent sev;
timer_t timer;

sev.sigev_notify = SIGEV_THREAD;
sev.sigev_notify_function = cbf; //this function will be called when timer expires
sev.sigev_value.sival_ptr = (void*) arg;//this argument will be passed to cbf
timer_create(CLOCK_MONOTONIC, &sev, &timer);
</code>```

which is shorter, simpler, cleaner, more maintainable ...

What gives? Is this correct? Is it just a wrapper for sigaction()? Why do the examples explicitly set a signal handler?

Also, if I start a timer either by this method, or by timer_settime and a signal handler, will cancelling the timer casue the system to remove the association between that timer and the callback, or do I have to do that explicitly?

[Update]  You can choose either signals or the method I show in my answer below (or both, but that seems silly). It is a matter of taste. Singals might offer a little more fucntionality, at the cost of complciation.

If all you want to do is start a timer and be notified when it expires, the method in my answer is simplest.

答:
Michael Kerrisk has a detailed example in his "The Linux Programming Interface" book:

```<code>/* ptmr_sigev_thread.c

   This program demonstrates the use of threads as the notification mechanism
   for expirations of a POSIX timer. Each of the program's command-line
   arguments specifies the initial value and interval for a POSIX timer. The
   format of these arguments is defined by the function itimerspecFromStr().

   The program creates and arms one timer for each command-line argument.
   The timer notification method is specified as SIGEV_THREAD, causing the
   timer notifications to be delivered via a thread that invokes threadFunc()
   as its start function. The threadFunc() function displays information
   about the timer expiration, increments a global counter of timer expirations,
   and signals a condition variable to indicate that the counter has changed.
   In the main thread, a loop waits on the condition variable, and each time
   the condition variable is signaled, the main thread prints the value of the
   global variable that counts timer expirations.

   Kernel support for Linux timers is provided since Linux 2.6. On older
   systems, an incomplete user-space implementation of POSIX timers
   was provided in glibc.
*/
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include "curr_time.h"              /* Declares currTime() */
#include "tlpi_hdr.h"
#include "itimerspec_from_str.h"    /* Declares itimerspecFromStr() */

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static int expireCnt = 0;           /* Number of expirations of all timers */
static void                         /* Thread notification function */
threadFunc(union sigval sv)
{
    timer_t *tidptr;
    int s;

    tidptr = sv.sival_ptr;

    printf("[%s] Thread notify\n", currTime("%T"));
    printf("    timer ID=%ld\n", (long) *tidptr);
    printf("    timer_getoverrun()=%d\n", timer_getoverrun(*tidptr));

    /* Increment counter variable shared with main thread and signal
       condition variable to notify main thread of the change. */

    s = pthread_mutex_lock(&mtx);
    if (s != 0)
        errExitEN(s, "pthread_mutex_lock");

    expireCnt += 1 + timer_getoverrun(*tidptr);

    s = pthread_mutex_unlock(&mtx);
    if (s != 0)
        errExitEN(s, "pthread_mutex_unlock");

    s = pthread_cond_signal(&cond);
    if (s != 0)
        errExitEN(s, "pthread_cond_signal");
}
int
main(int argc, char *argv[])
{
    struct sigevent sev;
    struct itimerspec ts;
    timer_t *tidlist;
    int s, j;

    if (argc < 2)
        usageErr("%s secs[/nsecs][:int-secs[/int-nsecs]]...\n", argv[0]);

    tidlist = calloc(argc - 1, sizeof(timer_t));
    if (tidlist == NULL)
        errExit("malloc");

    sev.sigev_notify = SIGEV_THREAD;            /* Notify via thread */
    sev.sigev_notify_function = threadFunc;     /* Thread start function */
    sev.sigev_notify_attributes = NULL;
            /* Could be pointer to pthread_attr_t structure */

    /* Create and start one timer for each command-line argument */

    for (j = 0; j < argc - 1; j++) {
        itimerspecFromStr(argv[j + 1], &ts);

        sev.sigev_value.sival_ptr = &tidlist[j];
                /* Passed as argument to threadFunc() */

        if (timer_create(CLOCK_REALTIME, &sev, &tidlist[j]) == -1)
            errExit("timer_create");
        printf("Timer ID: %ld (%s)\n", (long) tidlist[j], argv[j + 1]);

        if (timer_settime(tidlist[j], 0, &ts, NULL) == -1)
            errExit("timer_settime");
    }

    /* The main thread waits on a condition variable that is signaled
       on each invocation of the thread notification function. We
       print a message so that the user can see that this occurred. */

    s = pthread_mutex_lock(&mtx);
    if (s != 0)
        errExitEN(s, "pthread_mutex_lock");

    for (;;) {
        s = pthread_cond_wait(&cond, &mtx);
        if (s != 0)
            errExitEN(s, "pthread_cond_wait");
        printf("main(): expireCnt = %d\n", expireCnt);
    }
}
</code>```

Taken from online source code.

Also read the Chapter 23 of the book, this code is explained in great detail there.

To test the code above, one would enter

```<code>$ ./ptmr_sigev_thread 5:5 10:10
</code>```

This will set two timers: one with initial expiry of 5 seconds and an interval with 5 seconds, and the other with 10 respectively.

The definitions for helper functions can be found by following the link on the book's source code above.

ContentLicense: CC BY-SA 4.0

Body:
I want to start a timer and have a function called when it expires.

Googling finds lots of examples, including the example in the manual, all of which use sigaction() to set a signal handler.

However, @Patryk says in this question that we can just

void cbf(union sigval);
struct sigevent sev;
timer_t timer;

sev.sigev_notify = SIGEV_THREAD;
sev.sigev_notify_function = cbf; //this function will be called when timer expires
sev.sigev_value.sival_ptr = (void*) arg;//this argument will be passed to cbf
timer_create(CLOCK_MONOTONIC, &sev, &timer);

which is shorter, simpler, cleaner, more maintainable ...

What gives? Is this correct? Is it just a wrapper for sigaction()? Why do the examples explicitly set a signal handler?

Also, if I start a timer either by this method, or by timer_settime and a signal handler, will cancelling the timer casue the system to remove the association between that timer and the callback, or do I have to do that explicitly?

[Update]  You can choose either signals or the method I show in my answer below (or both, but that seems silly). It is a matter of taste. Singals might offer a little more fucntionality, at the cost of complciation.

If all you want to do is start a timer and be notified when it expires, the method in my answer is simplest.

Body:
Michael Kerrisk has a detailed example in his "The Linux Programming Interface" book:

/* ptmr_sigev_thread.c

   This program demonstrates the use of threads as the notification mechanism
   for expirations of a POSIX timer. Each of the program's command-line
   arguments specifies the initial value and interval for a POSIX timer. The
   format of these arguments is defined by the function itimerspecFromStr().

   The program creates and arms one timer for each command-line argument.
   The timer notification method is specified as SIGEV_THREAD, causing the
   timer notifications to be delivered via a thread that invokes threadFunc()
   as its start function. The threadFunc() function displays information
   about the timer expiration, increments a global counter of timer expirations,
   and signals a condition variable to indicate that the counter has changed.
   In the main thread, a loop waits on the condition variable, and each time
   the condition variable is signaled, the main thread prints the value of the
   global variable that counts timer expirations.

   Kernel support for Linux timers is provided since Linux 2.6. On older
   systems, an incomplete user-space implementation of POSIX timers
   was provided in glibc.
*/
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include "curr_time.h"              /* Declares currTime() */
#include "tlpi_hdr.h"
#include "itimerspec_from_str.h"    /* Declares itimerspecFromStr() */

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static int expireCnt = 0;           /* Number of expirations of all timers */
static void                         /* Thread notification function */
threadFunc(union sigval sv)
{
    timer_t *tidptr;
    int s;

    tidptr = sv.sival_ptr;

    printf("[%s] Thread notify\n", currTime("%T"));
    printf("    timer ID=%ld\n", (long) *tidptr);
    printf("    timer_getoverrun()=%d\n", timer_getoverrun(*tidptr));

    /* Increment counter variable shared with main thread and signal
       condition variable to notify main thread of the change. */

    s = pthread_mutex_lock(&mtx);
    if (s != 0)
        errExitEN(s, "pthread_mutex_lock");

    expireCnt += 1 + timer_getoverrun(*tidptr);

    s = pthread_mutex_unlock(&mtx);
    if (s != 0)
        errExitEN(s, "pthread_mutex_unlock");

    s = pthread_cond_signal(&cond);
    if (s != 0)
        errExitEN(s, "pthread_cond_signal");
}
int
main(int argc, char *argv[])
{
    struct sigevent sev;
    struct itimerspec ts;
    timer_t *tidlist;
    int s, j;

    if (argc < 2)
        usageErr("%s secs[/nsecs][:int-secs[/int-nsecs]]...\n", argv[0]);

    tidlist = calloc(argc - 1, sizeof(timer_t));
    if (tidlist == NULL)
        errExit("malloc");

    sev.sigev_notify = SIGEV_THREAD;            /* Notify via thread */
    sev.sigev_notify_function = threadFunc;     /* Thread start function */
    sev.sigev_notify_attributes = NULL;
            /* Could be pointer to pthread_attr_t structure */

    /* Create and start one timer for each command-line argument */

    for (j = 0; j < argc - 1; j++) {
        itimerspecFromStr(argv[j + 1], &ts);

        sev.sigev_value.sival_ptr = &tidlist[j];
                /* Passed as argument to threadFunc() */

        if (timer_create(CLOCK_REALTIME, &sev, &tidlist[j]) == -1)
            errExit("timer_create");
        printf("Timer ID: %ld (%s)\n", (long) tidlist[j], argv[j + 1]);

        if (timer_settime(tidlist[j], 0, &ts, NULL) == -1)
            errExit("timer_settime");
    }

    /* The main thread waits on a condition variable that is signaled
       on each invocation of the thread notification function. We
       print a message so that the user can see that this occurred. */

    s = pthread_mutex_lock(&mtx);
    if (s != 0)
        errExitEN(s, "pthread_mutex_lock");

    for (;;) {
        s = pthread_cond_wait(&cond, &mtx);
        if (s != 0)
            errExitEN(s, "pthread_cond_wait");
        printf("main(): expireCnt = %d\n", expireCnt);
    }
}

Taken from online source code.

Also read the Chapter 23 of the book, this code is explained in great detail there.

To test the code above, one would enter

$ ./ptmr_sigev_thread 5:5 10:10

This will set two timers: one with initial expiry of 5 seconds and an interval with 5 seconds, and the other with 10 respectively.

The definitions for helper functions can be found by following the link on the book's source code above.


问:
Artifactory user update removes admin
Consider the following POST to the Artifactory REST API:

```<code>curl -f -u admin:password \
     -X POST \
     -H 'Content-Type: application/json; charset=UTF-8' \
     -d '{ "groups": ["oldgroup", "newgroup"] }' \
     http://localhost/artifactory/api/security/users/targetuser
</code>```

This request does ensure that the user is a member of both the "oldgroup" and the "newgroup" but additionally it removes admin privileges from the user (if they had it): Ex. { "admin": true } changes to { "admin": false } after the update.

It would appear that one would need to additionally pass { "admin": true } if the user was an admin originally in order to avoid this strange side effect of the update:

```<code>curl -f -u admin:password \
     -X POST \
     -H 'Content-Type: application/json; charset=UTF-8' \
     -d '{ "admin": true, "groups": ["oldgroup", "newgroup"] }' \
     http://localhost/artifactory/api/security/users/targetuser
</code>```

This does not seem to be implemented as a true update. Is this a bug? Am I missing something?

Additionally, I was wondering if this had to do with the 'Content-Type' header I was originally passing as I was using the full application/vnd.org.jfrog.artifactory.security.User+json but a change to just application/json has the same result.

I could see if I was using the PUT method to Create or Replace a user but this is the POST request and doesn't seem to be working as I expect it to.

Artifactory REST API Documentation and my research:

Method: Update User

Object: application/vnd.org.jfrog.artifactory.security.User+json

Similar unanswered post from the old Jfrog forums: thread

答: As Artifactory, upon getting the update REST API command, can't tell which params you intended to change, for example in your case change the groups, it will take your input and apply it to the user. That means that the value of Admin will be set to false as this is the default value to that field. In case that you wish to save the existing configuration for the user, I would suggest doing a get request for the user details > saving it to a JSON file > edit it to the desired values > post it to Artifactory. That way you won't change the values that you intend to keep. </p>

Title: Artifactory user update removes admin

Body:
Consider the following POST to the Artifactory REST API:

curl -f -u admin:password \
     -X POST \
     -H 'Content-Type: application/json; charset=UTF-8' \
     -d '{ "groups": ["oldgroup", "newgroup"] }' \
     http://localhost/artifactory/api/security/users/targetuser

This request does ensure that the user is a member of both the "oldgroup" and the "newgroup" but additionally it removes admin privileges from the user (if they had it): Ex. { "admin": true } changes to { "admin": false } after the update.

It would appear that one would need to additionally pass { "admin": true } if the user was an admin originally in order to avoid this strange side effect of the update:

curl -f -u admin:password \
     -X POST \
     -H 'Content-Type: application/json; charset=UTF-8' \
     -d '{ "admin": true, "groups": ["oldgroup", "newgroup"] }' \
     http://localhost/artifactory/api/security/users/targetuser

This does not seem to be implemented as a true update. Is this a bug? Am I missing something?

Additionally, I was wondering if this had to do with the 'Content-Type' header I was originally passing as I was using the full application/vnd.org.jfrog.artifactory.security.User+json but a change to just application/json has the same result.

I could see if I was using the PUT method to Create or Replace a user but this is the POST request and doesn't seem to be working as I expect it to.

Artifactory REST API Documentation and my research:

Method: Update User

Object: application/vnd.org.jfrog.artifactory.security.User+json

Similar unanswered post from the old Jfrog forums: thread


问:
Print Out of Paper Cannot Fully Print

I have trouble to print the last column "Potensi", this text in this column cannot fully print, How can i fix the code? I use PHP. Thanks

答:
The problem is not with PHP, it's a front-end problem. Also you may need to use @media rule. so you can style your page in the printing mode.

For example you may reduce the font-size or reduce the padding of the page or anything else.

Title: Print Out of Paper Cannot Fully Print


问:
Chef: Do something when a service is started
I'm facing up with solving a tipical problem a newbie finds 5 minutes having started with chef.

Concretly:

I want a service starts.

When it is started do something (execute a command, create a file,...)

Currently, I'm solving that using this:

```<code>service 'mongod' do
  action :start
end

execute "Add Mongo Users" do
  command "mongo #{host}:#{port} /tmp/mongo.setup.users.js"
  retries 5 #times
  retry_delay 10 #seconds
end
</code>```

It's not an elegant way to make it works I believe.

My question is: Is there any way to solve it using notifications and subscription. I've already took a look on documentation but I don't quite figure out how to get it.

答:
It is as easy as:

```<code>execute 'foo' do
  cmd 'bar'
  subscribes :run, 'service[mongod]', :immediate # or :delayed
end
</code>```

In general, the way notifies and subscribes is:

```<code>subscribes|notify, 'resource_type[resource_name]', :timer
</code>```

Also, as @coderanger stated, I would be really careful with that javascript not being idempotent (This mean here, that it creates over and over the users in this case, even if they already exist).

Personally I think it would be more elegant writing your own library for this, there is a MongoDB driver for Ruby that you can use to Create/Remove/Edit users, indexes, documents... while keeping it all clean and maintained inside your ruby Chef code, being (in my opinion) something more similar to the concept of "infrastructure as code".

Body:
I'm facing up with solving a tipical problem a newbie finds 5 minutes having started with chef.

Concretly:

I want a service starts.

When it is started do something (execute a command, create a file,...)

Currently, I'm solving that using this:

service 'mongod' do
  action :start
end

execute "Add Mongo Users" do
  command "mongo #{host}:#{port} /tmp/mongo.setup.users.js"
  retries 5 #times
  retry_delay 10 #seconds
end

It's not an elegant way to make it works I believe.

My question is: Is there any way to solve it using notifications and subscription. I've already took a look on documentation but I don't quite figure out how to get it.

Body:
It is as easy as:

execute 'foo' do
  cmd 'bar'
  subscribes :run, 'service[mongod]', :immediate # or :delayed
end

In general, the way notifies and subscribes is:

subscribes|notify, 'resource_type[resource_name]', :timer

Also, as @coderanger stated, I would be really careful with that javascript not being idempotent (This mean here, that it creates over and over the users in this case, even if they already exist).

Personally I think it would be more elegant writing your own library for this, there is a MongoDB driver for Ruby that you can use to Create/Remove/Edit users, indexes, documents... while keeping it all clean and maintained inside your ruby Chef code, being (in my opinion) something more similar to the concept of "infrastructure as code".