问:
Is it relevant to have a single inline function alone in a C file?
I am seeing this example where I have a crc32.c file which contains:

```<code>inline int32_t crc32_compute(int32_t *buffer, size_t size) {
   ...
}
</code>```

In the header file I find:

```<code>extern inline int32_t crc32_compute(int32_t *buffer, size_t size);
</code>```

To me the inline keyword has no effect because the function should be declared on the header file not on the C file. Is it that correct?

答:
You are correct, whoever wrote this code put things the wrong way around. The header file should contain inline function, along with its full definition, while the .c file should contain extern inline declaration, without a definition:

Header:

```<code>inline int32_t crc32_compute(int32_t *buffer, size_t size) {
   ...
}
</code>```

C file:

```<code>extern inline int32_t crc32_compute(int32_t *buffer, size_t size);
</code>```

The header will allow the function code to be inlined; the .c file will instruct the compiler to emit an externally visible symbol for it.

Body:
I am seeing this example where I have a crc32.c file which contains:

inline int32_t crc32_compute(int32_t *buffer, size_t size) {
   ...
}

In the header file I find:

extern inline int32_t crc32_compute(int32_t *buffer, size_t size);

To me the inline keyword has no effect because the function should be declared on the header file not on the C file. Is it that correct?

Body:
You are correct, whoever wrote this code put things the wrong way around. The header file should contain inline function, along with its full definition, while the .c file should contain extern inline declaration, without a definition:

Header:

inline int32_t crc32_compute(int32_t *buffer, size_t size) {
   ...
}

C file:

extern inline int32_t crc32_compute(int32_t *buffer, size_t size);

The header will allow the function code to be inlined; the .c file will instruct the compiler to emit an externally visible symbol for it.


来源: stackexchange

问:
Text on the top not center in the button
I have button with text on top

Here is code

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <button class="settings-button-new"><span>Home</span></button></code>```

It on the top, but not centered as you can see.

I try to use text-align: center; but seems it not works.

How can i center it in button?

Thank's for help

答: can you change span to div , text-align:center will then work fine</p>

ContentLicense: CC BY-SA 3.0

Body:
I have button with text on top

Here is code

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left:0;
}

 <button class="settings-button-new">Home</button>

It on the top, but not centered as you can see.

I try to use text-align: center; but seems it not works.

How can i center it in button?

Thank's for help


问:
Can't accept license agreement Android SDK Platform 24
I'm getting the following error when trying to install an android platform on a Cordova project. I've been following this guide: https://cordova.apache.org/docs/en/latest/guide/cli/

Error occurs when executing the following: $ cordova platform add android --save

A problem occurred configuring root project 'android'.
  You have not accepted the license agreements of the following SDK components:   [Android SDK Platform 24].

I've searched all over for ways to accept the license agreement of Android SDK Platform 24, but no real luck.

Thank you ahead of time.

答: It needs a latest stable sdk-platform installed. I installed SDK-Platform from API 25. It fixed my problem.


问:
How to use Django 1.8.5 ORM without creating a django project?
I've used Django ORM for one of my web-app and I'm very much comfortable with it. Now I've a new requirement which needs the database but nothing else that Django offers. I don't want to invest more time in learning another ORM like SQLAlchemy.

I think I can still do:

```<code>from django.db import models
</code>```

and create models, but then without manage.py how would I do migration and syncing?

答:
Django 1.11 documentation on how the applications are loaded

For latest django version project structure would be-

```<code>|--myproject
|--main.py
|--manage.py
|--myapp
|   |--models.py
|   |--views.py
|   |--admin.py
|   |--apps.py
|   |--__init__.py
|   |--migrations
|--myproject
|   |--settings.py
|   |--urls.py
|   |--wsgi.py
|   |--__init__.py
</code>```

You would still need manage.py to run migrations, main.py is your standalone script

```<code># main.py
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
django.setup()
from myapp.models import MyModel
print(MyModel.objects.all()[0])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've used Django ORM for one of my web-app and I'm very much comfortable with it. Now I've a new requirement which needs the database but nothing else that Django offers. I don't want to invest more time in learning another ORM like SQLAlchemy.

I think I can still do:

from django.db import models

and create models, but then without manage.py how would I do migration and syncing?

Body:
Django 1.11 documentation on how the applications are loaded

For latest django version project structure would be-

|--myproject
|--main.py
|--manage.py
|--myapp
|   |--models.py
|   |--views.py
|   |--admin.py
|   |--apps.py
|   |--__init__.py
|   |--migrations
|--myproject
|   |--settings.py
|   |--urls.py
|   |--wsgi.py
|   |--__init__.py

You would still need manage.py to run migrations, main.py is your standalone script

# main.py
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
django.setup()
from myapp.models import MyModel
print(MyModel.objects.all()[0])


问:
JAX-RS POST Message unable to convert from Application/JSON to POJO
```<code>@Path("/{tableId}/order")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON )
    public String giveOrder(List<ItemOrder> itemOrderList, @PathParam("tableID") int tableId){
Customer currentCustomer = restaurant.getTables().get(tableId).getCurrentCustomer();
for (int i = 0; i<itemOrderList.size(); i++){
            currentCustomer.giveOrder(itemOrderList.get(i));
        }

String retStr = "Thank you " + currentCustomer.getCustomerName() + ". Your food will be served soon";
return retStr;
}
</code>```

Class ItemOrder:

```<code>@XmlRootElement
public class ItemOrder {
    private Item mItem;
    private int mNumberOfPlates;

    public ItemOrder(){
        mItem = null;
        mNumberOfPlates = 0;
    }
    public ItemOrder(Item item, int numberOfPlates){
        mItem = item;
        mNumberOfPlates = numberOfPlates;
    }

    public Item getItem() {
        return mItem;
    }
    public void setItem(Item mItem) {
        this.mItem = mItem;
    }
    public int getNumberOfPlates() {
        return mNumberOfPlates;
    }
    public void setNumberOfPlates(int mNumberOfPlates) {
        this.mNumberOfPlates = mNumberOfPlates;
    }
}
</code>```

Class Item:

```<code>@XmlRootElement
public class Item {
    private int mItemId;
    private String mName;
    private float mPrice;

    public Item(){

    }

    public Item(int id, String name, float price){
        mItemId = id;
        mName = name;
        mPrice = price;
    }
    public int getItemId() {
        return mItemId;
    }
    public void setItemId(int mItemId) {
        this.mItemId = mItemId;
    }
    public String getItemName() {
        return mName;
    }
    public void setItemName(String mName) {
        this.mName = mName;
    }
    public float getItemPrice() {
        return mPrice;
    }
    public void setItemPrice(float mPrice) {
        this.mPrice = mPrice;
    }
}
</code>```

JSON Post Body:

```<code>{"itemOrderList":[
{"item":{"itemId":11,"itemName":"Tea","itemPrice":10.0},"numberOfPlates":5},
{"item":{"itemId":22,"itemName":"Coffee","itemPrice":20.0},"numberOfPlates":5},
{"item":{"itemId":33,"itemName":"Bread","itemPrice":30.0},"numberOfPlates":5}
    ]
}
</code>```

With the above setup of JaxRS POST message, i am always getting argument type mismatch error as follows:

```<code>SEVERE: Servlet.service() for servlet [com.somitsolutions.training.java.restaurant1.App] in context with path [/restaurant1] threw exception [javax.ws.rs.ProcessingException: Resource Java method invocation error.] with root cause
java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:143)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:160)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:203)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:97)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:303)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:399)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I am really clueless what to do. I have even written a MessageBodyReader for the ItemOrder class as follows. Nothing is working out.

```<code>@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class ItemOrderMessageBodyReader implements MessageBodyReader<ItemOrder>{

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        // TODO Auto-generated method stub
        return ItemOrder.class.isAssignableFrom(type);
        //return false;
    }

    @Override
    public ItemOrder readFrom(Class<ItemOrder> arg0, Type arg1,
            Annotation[] arg2, MediaType arg3,
            MultivaluedMap<String, String> arg4, InputStream arg5)
            throws IOException, WebApplicationException {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(ItemOrder.class);
            return (ItemOrder) jaxbContext.createUnmarshaller().unmarshal(arg5);
        } catch (JAXBException e) {
            throw new ProcessingException("Error deserializing user.", e);
        }
    }

}
</code>```

答:
Yeah i know sometimes i behave so stupid. The JSON payload for the POST method should be</p>

```<code>[
    {
        "item": {
            "itemId": 11,
            "itemName": "Tea",
            "itemPrice": 10
        },
        "numberOfPlates": 5
    },
    {
        "item": {
            "itemId": 22,
            "itemName": "Coffee",
            "itemPrice": 20
        },
        "numberOfPlates": 5
    },
    {
        "item": {
            "itemId": 33,
            "itemName": "Bread",
            "itemPrice": 30
        },
        "numberOfPlates": 5
    }
]
</code>```

Body:
@Path("/{tableId}/order")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON )
    public String giveOrder(List<ItemOrder> itemOrderList, @PathParam("tableID") int tableId){
Customer currentCustomer = restaurant.getTables().get(tableId).getCurrentCustomer();
for (int i = 0; i<itemOrderList.size(); i++){
            currentCustomer.giveOrder(itemOrderList.get(i));
        }

String retStr = "Thank you " + currentCustomer.getCustomerName() + ". Your food will be served soon";
return retStr;
}

Class ItemOrder:

@XmlRootElement
public class ItemOrder {
    private Item mItem;
    private int mNumberOfPlates;

    public ItemOrder(){
        mItem = null;
        mNumberOfPlates = 0;
    }
    public ItemOrder(Item item, int numberOfPlates){
        mItem = item;
        mNumberOfPlates = numberOfPlates;
    }

    public Item getItem() {
        return mItem;
    }
    public void setItem(Item mItem) {
        this.mItem = mItem;
    }
    public int getNumberOfPlates() {
        return mNumberOfPlates;
    }
    public void setNumberOfPlates(int mNumberOfPlates) {
        this.mNumberOfPlates = mNumberOfPlates;
    }
}

Class Item:

@XmlRootElement
public class Item {
    private int mItemId;
    private String mName;
    private float mPrice;

    public Item(){

    }

    public Item(int id, String name, float price){
        mItemId = id;
        mName = name;
        mPrice = price;
    }
    public int getItemId() {
        return mItemId;
    }
    public void setItemId(int mItemId) {
        this.mItemId = mItemId;
    }
    public String getItemName() {
        return mName;
    }
    public void setItemName(String mName) {
        this.mName = mName;
    }
    public float getItemPrice() {
        return mPrice;
    }
    public void setItemPrice(float mPrice) {
        this.mPrice = mPrice;
    }
}

JSON Post Body:

{"itemOrderList":[
{"item":{"itemId":11,"itemName":"Tea","itemPrice":10.0},"numberOfPlates":5},
{"item":{"itemId":22,"itemName":"Coffee","itemPrice":20.0},"numberOfPlates":5},
{"item":{"itemId":33,"itemName":"Bread","itemPrice":30.0},"numberOfPlates":5}
    ]
}

With the above setup of JaxRS POST message, i am always getting argument type mismatch error as follows:

SEVERE: Servlet.service() for servlet [com.somitsolutions.training.java.restaurant1.App] in context with path [/restaurant1] threw exception [javax.ws.rs.ProcessingException: Resource Java method invocation error.] with root cause
java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:143)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:160)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:203)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:97)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:303)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:399)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

I am really clueless what to do. I have even written a MessageBodyReader for the ItemOrder class as follows. Nothing is working out.

@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class ItemOrderMessageBodyReader implements MessageBodyReader<ItemOrder>{

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        // TODO Auto-generated method stub
        return ItemOrder.class.isAssignableFrom(type);
        //return false;
    }

    @Override
    public ItemOrder readFrom(Class<ItemOrder> arg0, Type arg1,
            Annotation[] arg2, MediaType arg3,
            MultivaluedMap<String, String> arg4, InputStream arg5)
            throws IOException, WebApplicationException {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(ItemOrder.class);
            return (ItemOrder) jaxbContext.createUnmarshaller().unmarshal(arg5);
        } catch (JAXBException e) {
            throw new ProcessingException("Error deserializing user.", e);
        }
    }

}

Body:
Yeah i know sometimes i behave so stupid. The JSON payload for the POST method should be

[
    {
        "item": {
            "itemId": 11,
            "itemName": "Tea",
            "itemPrice": 10
        },
        "numberOfPlates": 5
    },
    {
        "item": {
            "itemId": 22,
            "itemName": "Coffee",
            "itemPrice": 20
        },
        "numberOfPlates": 5
    },
    {
        "item": {
            "itemId": 33,
            "itemName": "Bread",
            "itemPrice": 30
        },
        "numberOfPlates": 5
    }
]


答:
You can remove vertical aligning text using without absolute positioning: you can use vertical-align and pseudoelement for this. Source answer for this technique.

Also

You don't need absolute position in this case (and text-align: center).

I would recommend you to delete vendor prefixed properties because they are for very old browsers

linear-gradient will work for background, not background-image property

Demo:

/* styles to align button's text at the top */
.settings-button-new:after {
  content: "";
  display: inline-block;
  vertical-align: top;
  height: inherit;
}

/* styles to align button's text at the top */
.settings-button-new span {
  vertical-align: top;
  display: inline-block;
}

/* Cleaned up button styles */
.settings-button-new {
  width: 150px;
  height: 150px;
  text-decoration: none;
  margin-left: 20px;
  margin-bottom: 20px;
  border: solid 4px #d3dbde;
  border-radius: 13px;
  font: 15px Arial, Helvetica, sans-serif;
  color: #1c559b;
  background: #fff linear-gradient(top, #fff 0%, #fcfcfc 100%);
  box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="settings-button-new">
  <span>Home</span>
</button></code>```

Title: Text on the top not center in the button

Body:
You can remove vertical aligning text using without absolute positioning: you can use vertical-align and pseudoelement for this. Source answer for this technique.

Also

You don't need absolute position in this case (and text-align: center).

I would recommend you to delete vendor prefixed properties because they are for very old browsers

linear-gradient will work for background, not background-image property

Demo:

/* styles to align button's text at the top */
.settings-button-new:after {
  content: "";
  display: inline-block;
  vertical-align: top;
  height: inherit;
}

/* styles to align button's text at the top */
.settings-button-new span {
  vertical-align: top;
  display: inline-block;
}

/* Cleaned up button styles */
.settings-button-new {
  width: 150px;
  height: 150px;
  text-decoration: none;
  margin-left: 20px;
  margin-bottom: 20px;
  border: solid 4px #d3dbde;
  border-radius: 13px;
  font: 15px Arial, Helvetica, sans-serif;
  color: #1c559b;
  background: #fff linear-gradient(top, #fff 0%, #fcfcfc 100%);
  box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #fff;
}

<button class="settings-button-new">
  <span>Home</span>
</button>


问:
How to replace a String which has escape sequence inside a File using Perl?
how to replace a String inside a File using perl ?

```<code>perl -pi -e 's/Arun/Brun/g' *
</code>```

this worked fine for me

but when i tried to change class/students/a to class1/students1/B it throws error how to solve this problem ..i tried adding back slash (\) before every (/) but it didn't help

```<code>perl -pi -e 's/class/students/a/class1/students1/B/g' *
</code>```

答:
Try perl -pi -e 's{class/students/a}{class1/students1/B}g' *

From perldoc perlop:

Any non-whitespace delimiter may
  replace the slashes. Add space after
  the s when using a character allowed
  in identifiers. (...) If the
  PATTERN is delimited by bracketing
  quotes, the REPLACEMENT has its own
  pair of quotes, which may or may not
  be bracketing quotes, e.g.,
  s(foo)(bar) or s/bar/.

ContentLicense: CC BY-SA 2.5

Body:
how to replace a String inside a File using perl ?

perl -pi -e 's/Arun/Brun/g' *

this worked fine for me

but when i tried to change class/students/a to class1/students1/B it throws error how to solve this problem ..i tried adding back slash (\) before every (/) but it didn't help

perl -pi -e 's/class/students/a/class1/students1/B/g' *


问:
How to get launcher activity / intent without using package manager (for self package)
I have a base code which is shared between 3 different packages.

I want to get the launcher activity for the current package, this is what I do today :

```<code>PackageManager pm = context.getPackageManager();
intent = pm.getLaunchIntentForPackage(context.getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
flag = PendingIntent.FLAG_UPDATE_CURRENT;
return PendingIntent.getActivity(context, 0, intent, flag);
</code>```

But I received a crash report for Caused by java.lang.RuntimeException: Package manager has died

The used context belongs to a service which should be running, but as we all know, it can always stop due to system requirements.

I know I can catch the exception but then the launch intent will be missing.

I was hoping there is a less resource requiring method for getting the launch intent for the self package.

P.S.
Another solution is having a some kind of a singletone initialized with the main activity by each package, but since the packageName is known on runtime, I want to think I can avoid implementing this.

答:
I can try to use a broadcast receivers that can catch events between packages.
So, you can send, store any data you want without killed events.</p>

Body:
I have a base code which is shared between 3 different packages.

I want to get the launcher activity for the current package, this is what I do today :

PackageManager pm = context.getPackageManager();
intent = pm.getLaunchIntentForPackage(context.getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
flag = PendingIntent.FLAG_UPDATE_CURRENT;
return PendingIntent.getActivity(context, 0, intent, flag);

But I received a crash report for Caused by java.lang.RuntimeException: Package manager has died

The used context belongs to a service which should be running, but as we all know, it can always stop due to system requirements.

I know I can catch the exception but then the launch intent will be missing.

I was hoping there is a less resource requiring method for getting the launch intent for the self package.

P.S.
Another solution is having a some kind of a singletone initialized with the main activity by each package, but since the packageName is known on runtime, I want to think I can avoid implementing this.


问:
WARNING Illegal string offset 'file' on line number 19
simple array giving error.

WARNING Illegal string offset 'file' on line number 19

any help will be great

```<code><?php
  //    $someffdd is output of print_r

$someffdd="Array
(
    [file] => Array
        (
            [name] => 2Pcs-font-b-Mini-b-font-font-b-Couple-b-font-Lover-Animal-DIY-Resin-Fairy-32-185x215.jpg
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpwhglrk
            [error] => 0
            [size] => 8713
        )

)";

            foreach((array) $someffdd as $value ) {

    $jkgkgff=$value['file'];

echo $jkgkgff;
}

?>
</code>```

tried all sort of combination but nothing is error free . i want to output name value

答:
You cannot parse the output of print_r() (or var_dump()) back into an array in PHP. So (array)$someffdd will fail, and you'll be looping through a string (i.e. $value will be 'A' the first time, then 'r', then another 'r', then 'a' and so on, until it reaches the final ')').

If you cannot change the source of your $someffdd to something PHP can parse using json_encode(), serialize() or var_export(), you can either use regular expressions to match the name section of the string, or use some strpos()/substr() wizardry:

```<code>$matches = [];
preg_match("/\[name\] => (.*)\n/", $someffdd, $matches);
$name = $matches[1];

$position = strpos($someffdd, '[name] => ') + 10;
$section = substr($someffdd, $position);
$eol = strpos($section, "\n");
$name = substr($section, 0, $eol);
</code>```

Body:
simple array giving error.

WARNING Illegal string offset 'file' on line number 19

any help will be great

<?php
  //    $someffdd is output of print_r

$someffdd="Array
(
    [file] => Array
        (
            [name] => 2Pcs-font-b-Mini-b-font-font-b-Couple-b-font-Lover-Animal-DIY-Resin-Fairy-32-185x215.jpg
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpwhglrk
            [error] => 0
            [size] => 8713
        )

)";

            foreach((array) $someffdd as $value ) {

    $jkgkgff=$value['file'];

echo $jkgkgff;
}

?>

tried all sort of combination but nothing is error free . i want to output name value

Body:
You cannot parse the output of print_r() (or var_dump()) back into an array in PHP. So (array)$someffdd will fail, and you'll be looping through a string (i.e. $value will be 'A' the first time, then 'r', then another 'r', then 'a' and so on, until it reaches the final ')').

If you cannot change the source of your $someffdd to something PHP can parse using json_encode(), serialize() or var_export(), you can either use regular expressions to match the name section of the string, or use some strpos()/substr() wizardry:

$matches = [];
preg_match("/\[name\] => (.*)\n/", $someffdd, $matches);
$name = $matches[1];

$position = strpos($someffdd, '[name] => ') + 10;
$section = substr($someffdd, $position);
$eol = strpos($section, "\n");
$name = substr($section, 0, $eol);


问:
PHP Excel save only one sheet as pdf
i'm using phpoffice/phpexcel an have a problem.

I have a excel file with 9 sheets

I open 6 of this 9 sheets ($objReader->setLoadSheetsOnly([...])) do set some values and calculate

I save this new excel file with 6 sheets

Info: one of the 6 steets is a overview site which have some references to the other sheets

I there any method to save only the overview sheet as PDF?

My Lines:

```<code>require_once dirname(__FILE__) . '/PHPExcel/IOFactory.php';

if (!file_exists("orginal.xls")) {
    exit("Please create orginal.xls first." . EOL);
}

PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory);

echo date('H:i:s') , " Load from Excel2007 file" , EOL;

$objReader = PHPExcel_IOFactory::createReader('Excel5');

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("orginal.xls");

$objPHPExcel->setActiveSheetIndexByName('Dateneingabe');
$objPHPExcel->getActiveSheet()->SetCellValue('D102', '220');
$objPHPExcel->getActiveSheet()->SetCellValue('F102', '220');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->setPreCalculateFormulas(false);
$objWriter->setOffice2003Compatibility(true);
$objWriter->save(str_replace('.php', '.xls', __FILE__));

 //SAVE AS PDF

$objReader = PHPExcel_IOFactory::createReader('Excel2007');

$objReader->setReadDataOnly(true);

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("index.xls");

$objPHPExcel->setActiveSheetIndexByName('Offerte');

$rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;

$rendererLibrary = dirname(__FILE__).'/dompdf/dompdf/';

PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibrary);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');

$objWriter->setPreCalculateFormulas(false);

$objWriter->save(str_replace('.php', '.pdf', __FILE__));
</code>```

答:
By default, the HTML and PDF Writers (the PDF Writer uses output from the HTML Writer that it converts to PDF using any of the supported PDF Writer libraries) will only create a single sheet output.

However, these Writers allow you to select which sheet to write using the setSheetIndex() method, so you could write out files for each individual worksheet in turn, and then "stitch" them all together using any of the PDF stitching tools that exist... or there is also a writeAllSheets() method.

Title: PHP Excel save only one sheet as pdf

Body:
i'm using phpoffice/phpexcel an have a problem.

I have a excel file with 9 sheets

I open 6 of this 9 sheets ($objReader->setLoadSheetsOnly([...])) do set some values and calculate

I save this new excel file with 6 sheets

Info: one of the 6 steets is a overview site which have some references to the other sheets

I there any method to save only the overview sheet as PDF?

My Lines:

require_once dirname(__FILE__) . '/PHPExcel/IOFactory.php';

if (!file_exists("orginal.xls")) {
    exit("Please create orginal.xls first." . EOL);
}

PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory);

echo date('H:i:s') , " Load from Excel2007 file" , EOL;

$objReader = PHPExcel_IOFactory::createReader('Excel5');

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("orginal.xls");

$objPHPExcel->setActiveSheetIndexByName('Dateneingabe');
$objPHPExcel->getActiveSheet()->SetCellValue('D102', '220');
$objPHPExcel->getActiveSheet()->SetCellValue('F102', '220');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->setPreCalculateFormulas(false);
$objWriter->setOffice2003Compatibility(true);
$objWriter->save(str_replace('.php', '.xls', __FILE__));

 //SAVE AS PDF

$objReader = PHPExcel_IOFactory::createReader('Excel2007');

$objReader->setReadDataOnly(true);

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("index.xls");

$objPHPExcel->setActiveSheetIndexByName('Offerte');

$rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;

$rendererLibrary = dirname(__FILE__).'/dompdf/dompdf/';

PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibrary);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');

$objWriter->setPreCalculateFormulas(false);

$objWriter->save(str_replace('.php', '.pdf', __FILE__));


问:
What does this php code means
Hello I am new to PHP and I don't know exactaly what does this code means

```<code>$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});
</code>```

The only thing that I need to know is what does ${$de} mean?

答:
It's a variable variable, one of the most intriguing part of the php implementation.

Sometimes usefull, always confusing:

```<code>$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
....
</code>```

Title: What does this php code means

Body:
Hello I am new to PHP and I don't know exactaly what does this code means

$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});

The only thing that I need to know is what does ${$de} mean?

Body:
It's a variable variable, one of the most intriguing part of the php implementation.

Sometimes usefull, always confusing:

$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
....


问:
Rxandroid What's the difference between SubscribeOn and ObserveOn
I am just learning Rx-java and Rxandroid2 and I am just confused what is the major difference between in SubscribeOn and ObserveOn.</p>

答:
SubscribeOn specify the Scheduler on which an Observable will operate.
ObserveOn specify the Scheduler on which an observer will observe this Observable.

So basically SubscribeOn is mostly subscribed (executed) on a background thread ( you do not want to block the UI thread while waiting for the observable) and also in ObserveOn you want to observe the result on a main thread...

If you are familiar with AsyncTask then SubscribeOn is similar to doInBackground method and ObserveOn to onPostExecute...


问:
Pass an object to a function or sub procedure
I am trying to pass and excel work book off to a sub procedure with out having to open and close it again.

I tried this

```<code>Dim ExcelApp As New Excel.Application
Dim ws As Object

Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....
</code>```

The function opens to this

```<code>Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
'    Dim ExcelApp As New Excel.Application
'    DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
'    Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
    If Cell.Text <> "" Then
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True
Exit Function
</code>```

But I guess I'm not passing the Excel object properly. How are applications objects passed to sub with out close and reopening.

答:
Try the code below, explanation inside the code's comments:</p>

```<code>Option Explicit

Dim ExcelApp As New Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim FileDir As String

'======================================================================
Public Function cert()  '<-- NOT SURE why this is a Function and not a Sub ?

' set the workbook object
Set wb = ExcelApp.Workbooks.Open(FileDir)
Set wb = Workbooks.Open(FileDir) ' <-- why not use this if this is inside Excel VBA ?

' set the worksheet object
Set ws = wb.Sheets(1)
If CheckForMutipleUIC(ws) = True Then ' pass the worksheet object to the Function
    '....

End If

End Function

'======================================================================
Public Function CheckForMutipleUIC(ByVal ws As Worksheet) As Boolean

Dim Cell As Range
Dim UICCheck

UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").Cells
'    If Cell.Text <> "" Then
    If Cell.Value2 <> "" Then ' <-- use Value 2 instead of Text
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True

End Function
</code>```

Body:
I am trying to pass and excel work book off to a sub procedure with out having to open and close it again.

I tried this

Dim ExcelApp As New Excel.Application
Dim ws As Object

Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....

The function opens to this

Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
'    Dim ExcelApp As New Excel.Application
'    DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
'    Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
    If Cell.Text <> "" Then
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True
Exit Function

But I guess I'm not passing the Excel object properly. How are applications objects passed to sub with out close and reopening.

Body:
Try the code below, explanation inside the code's comments:

Option Explicit

Dim ExcelApp As New Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim FileDir As String

'======================================================================
Public Function cert()  '<-- NOT SURE why this is a Function and not a Sub ?

' set the workbook object
Set wb = ExcelApp.Workbooks.Open(FileDir)
Set wb = Workbooks.Open(FileDir) ' <-- why not use this if this is inside Excel VBA ?

' set the worksheet object
Set ws = wb.Sheets(1)
If CheckForMutipleUIC(ws) = True Then ' pass the worksheet object to the Function
    '....

End If

End Function

'======================================================================
Public Function CheckForMutipleUIC(ByVal ws As Worksheet) As Boolean

Dim Cell As Range
Dim UICCheck

UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").Cells
'    If Cell.Text <> "" Then
    If Cell.Value2 <> "" Then ' <-- use Value 2 instead of Text
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True

End Function


问:
iOS AutoLayout - get frame size width
I am developing using iOS 6 auto layout

I would like to log a message displaying the frame width of the view.

I can see the textView on the screen.

But I get the width and height as zero, am I missing something ?

```<code>NSLog(@"textView    = %p", self.textView);
NSLog(@"height      = %f", self.textView.frame.size.height);
NSLog(@"width       = %f", self.textView.frame.size.width);

textView    = 0x882de00
height      = 0.000000
width       = 0.000000
</code>```

答:
You can only find out the size after the first layout pass. Or Just call below method then after you got actual width of you view.</p>

```<code>[yourView layoutIfNeeded];
</code>```

Title: iOS AutoLayout - get frame size width

Body:
I am developing using iOS 6 auto layout

I would like to log a message displaying the frame width of the view.

I can see the textView on the screen.

But I get the width and height as zero, am I missing something ?

NSLog(@"textView    = %p", self.textView);
NSLog(@"height      = %f", self.textView.frame.size.height);
NSLog(@"width       = %f", self.textView.frame.size.width);

textView    = 0x882de00
height      = 0.000000
width       = 0.000000

Body:
You can only find out the size after the first layout pass. Or Just call below method then after you got actual width of you view.

[yourView layoutIfNeeded];


问:
How to read dynamic json in request using nodejs
I am getting json like this in post in nodejs:

```<code>{
   "action":"4",
   "enter":{
      "login":"loginname"
   },
   "data_1":{
      "order":"0",
      "time":"19:12:10 2017-07-05",
      "message":"Loop 0",
      "type":"test_type"
   },
   "data_2":{
      "order":"1",
      "time":"19:12:11 2017-07-05",
      "message":"Loop 1",
      "type":"test_type"
   },
   "data_3":{
      "order":"2",
      "time":"19:12:11 2017-07-05",
      "message":"Loop 2",
      "type":"test_type"
   }
}
</code>```

There is a data node, how can I iterate (DYNAMIC) over all data nodes and print message?

Thank you for your help.

答:
Here you go with the solution https://jsfiddle.net/6gze9occ/</p>

```<code>var data = {
  "action":"4",
  "enter":{
  "login":"loginname"
 },
 "data_1":{
  "order":"0",
  "time":"19:12:10 2017-07-05",
  "message":"Loop 0",
  "type":"test_type"
 },
 "data_2":{
  "order":"1",
  "time":"19:12:11 2017-07-05",
  "message":"Loop 1",
  "type":"test_type"
 },
 "data_3":{
  "order":"2",
  "time":"19:12:11 2017-07-05",
  "message":"Loop 2",
  "type":"test_type"
 }
};

var keys = Object.keys(data);

for(var i=0; i<keys.length; i++){
   if(typeof data[keys[i]]["message"] !== 'undefined')
       console.log(data[keys[i]]["message"]);
}
</code>```

Body:
I am getting json like this in post in nodejs:

{
   "action":"4",
   "enter":{
      "login":"loginname"
   },
   "data_1":{
      "order":"0",
      "time":"19:12:10 2017-07-05",
      "message":"Loop 0",
      "type":"test_type"
   },
   "data_2":{
      "order":"1",
      "time":"19:12:11 2017-07-05",
      "message":"Loop 1",
      "type":"test_type"
   },
   "data_3":{
      "order":"2",
      "time":"19:12:11 2017-07-05",
      "message":"Loop 2",
      "type":"test_type"
   }
}

There is a data node, how can I iterate (DYNAMIC) over all data nodes and print message?

Thank you for your help.

Body:
Here you go with the solution https://jsfiddle.net/6gze9occ/

var data = {
  "action":"4",
  "enter":{
  "login":"loginname"
 },
 "data_1":{
  "order":"0",
  "time":"19:12:10 2017-07-05",
  "message":"Loop 0",
  "type":"test_type"
 },
 "data_2":{
  "order":"1",
  "time":"19:12:11 2017-07-05",
  "message":"Loop 1",
  "type":"test_type"
 },
 "data_3":{
  "order":"2",
  "time":"19:12:11 2017-07-05",
  "message":"Loop 2",
  "type":"test_type"
 }
};

var keys = Object.keys(data);

for(var i=0; i<keys.length; i++){
   if(typeof data[keys[i]]["message"] !== 'undefined')
       console.log(data[keys[i]]["message"]);
}


问:
Test @Valid annotation with SpringMVC Maven
I am working on the chapter 5 example of the book Spring in Action 4. When I am running the Test classes I found one of the @Valid test is not working, it appears as if the validation never occured(returned status code of 302 and view's name is "/spitter/null"). However, it works fine when I run it in Tomcat.

The validatioon jars(hibernate-validator and its dependencies) are loaded with Maven.

The whole project is on github.

Any ideas?

test code snippet:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={RootConfig.class, WebConfig.class})
public class SpitterControllerTest {
    @Test
    public void shouldFailValidationWithNoData() throws Exception {
        SpitterRepository mockRepository = mock(SpitterRepository.class);
        SpitterController controller = new SpitterController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller).build();

        mockMvc.perform(post("/spitter/register"))
            .andExpect(status().isOk())
            .andExpect(view().name("registerForm"))
            .andExpect(model().errorCount(5))
            .andExpect(model().attributeHasFieldErrors(
                "spitter", "firstName", "lastName", "username", "password", "email"));
    }
}
</code>```

SpitterController snippet:

```<code>  @RequestMapping(value="/register", method=POST)
  public String processRegistration(
      @Valid Spitter spitter,
      Errors errors) {
    if (errors.hasErrors()) {
      return "registerForm";
    }

    spitterRepository.save(spitter);
    return "redirect:/spitter/" + spitter.getUsername();
  }
</code>```

Spitter snippet:

```<code>@NotNull
  @Size(min=5, max=16)
  private String username;

  @NotNull
  @Size(min=5, max=25)
  private String password;

  @NotNull
  @Size(min=2, max=30)
  private String firstName;

  @NotNull
  @Size(min=2, max=30)
  private String lastName;

  @NotNull
  @Email
  private String email;
</code>```

Thanks a lot!

答:
Mark your SpitterController with @Validated

```<code>import org.springframework.validation.annotation.Validated;

@Controller
@Validated
@RequestMapping("/spitter")
public class SpitterController {
</code>```

@Autowired the SpitterController and create MethodValidationPostProcessor bean which delegates to a JSR-303 provider for performing method-level validation on annotated methods, as follows:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { RootConfig.class, WebConfig.class,
        SpitterControllerTest.Config.class })
public class SpitterControllerTest {

    @Autowired
    private SpitterController spitterController;

    @Configuration
    public static class Config {
        @Bean
        public MethodValidationPostProcessor methodValidationPostProcessor() {
            return new MethodValidationPostProcessor();
        }
    }

    @Test
    public void shouldFailValidationWithNoData() throws Exception {
    }

}
</code>```

Body:
I am working on the chapter 5 example of the book Spring in Action 4. When I am running the Test classes I found one of the @Valid test is not working, it appears as if the validation never occured(returned status code of 302 and view's name is "/spitter/null"). However, it works fine when I run it in Tomcat.

The validatioon jars(hibernate-validator and its dependencies) are loaded with Maven.

The whole project is on github.

Any ideas?

test code snippet:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={RootConfig.class, WebConfig.class})
public class SpitterControllerTest {
    @Test
    public void shouldFailValidationWithNoData() throws Exception {
        SpitterRepository mockRepository = mock(SpitterRepository.class);
        SpitterController controller = new SpitterController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller).build();

        mockMvc.perform(post("/spitter/register"))
            .andExpect(status().isOk())
            .andExpect(view().name("registerForm"))
            .andExpect(model().errorCount(5))
            .andExpect(model().attributeHasFieldErrors(
                "spitter", "firstName", "lastName", "username", "password", "email"));
    }
}

SpitterController snippet:

  @RequestMapping(value="/register", method=POST)
  public String processRegistration(
      @Valid Spitter spitter,
      Errors errors) {
    if (errors.hasErrors()) {
      return "registerForm";
    }

    spitterRepository.save(spitter);
    return "redirect:/spitter/" + spitter.getUsername();
  }

Spitter snippet:

@NotNull
  @Size(min=5, max=16)
  private String username;

  @NotNull
  @Size(min=5, max=25)
  private String password;

  @NotNull
  @Size(min=2, max=30)
  private String firstName;

  @NotNull
  @Size(min=2, max=30)
  private String lastName;

  @NotNull
  @Email
  private String email;

Thanks a lot!

Body:
Mark your SpitterController with @Validated

import org.springframework.validation.annotation.Validated;

@Controller
@Validated
@RequestMapping("/spitter")
public class SpitterController {

@Autowired the SpitterController and create MethodValidationPostProcessor bean which delegates to a JSR-303 provider for performing method-level validation on annotated methods, as follows:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { RootConfig.class, WebConfig.class,
        SpitterControllerTest.Config.class })
public class SpitterControllerTest {

    @Autowired
    private SpitterController spitterController;

    @Configuration
    public static class Config {
        @Bean
        public MethodValidationPostProcessor methodValidationPostProcessor() {
            return new MethodValidationPostProcessor();
        }
    }

    @Test
    public void shouldFailValidationWithNoData() throws Exception {
    }

}


问:
Image not displayed from static
I am using a csv file to display an image on my django template. The csv file is like

```<code>id | Name  | image
-- | ----- | --------------------
 1 | wine1 | images\download1.jpg
</code>```

i have kept the image in the static file

my  wine_list.html is as

```<code>{% for wine in wine_list %}
    <div>
        <h4><a href="{% url 'reviews:wine_detail' wine.id %}">
        {{ wine.name}}</a><br>
        {% if wine.description != "nan" %}
        <h4>{{ wine.description }}</h4>
        {% else %}
        <h1> No Description available
        {% endif %}
        <h3>'{{ wine.images.url }}'</h3>
        <br>
        <a>  <img src="{% static '{{ wine.images.url }}' %}" height="200"></a>
</code>```

the name and description shows fine, and the

wine.images.url

prints

images/download.jpg

shouldn't the image be printed ?

my image folder is in my static, when i print it like this

```<code><a>  <img src="{% static 'images/download.jpg' %}" height="200"></a>
</code>```

it does display the image.

答:
The provided answer doesn't work for me, but this does:</p>

```<code>src="{{ wine.image.url }}"
</code>```

Title: Image not displayed from static

Body:
I am using a csv file to display an image on my django template. The csv file is like

id | Name  | image
-- | ----- | --------------------
 1 | wine1 | images\download1.jpg

i have kept the image in the static file

my  wine_list.html is as

{% for wine in wine_list %}

        {{ wine.name}}

        {% if wine.description != "nan" %}

{{ wine.description }}

        {% else %}

 No Description available
        {% endif %}

'{{ wine.images.url }}'

the name and description shows fine, and the

wine.images.url

prints

images/download.jpg

shouldn't the image be printed ?

my image folder is in my static, when i print it like this

it does display the image.

Body:
The provided answer doesn't work for me, but this does:

src="{{ wine.image.url }}"


问:
Clear all input inside a modal
I have a modal where I can input some data to create and also to update the selected data. What I want to is, whenever the modal closes, it will clear the textbox and set the dropdown to its default display.

I have tried this http://jsfiddle.net/5LCSU/ applying to my project but it doesn't work and there is no error too.

Here is my moda/view:

```<code><div id="productModal" class="modal fade">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Prescription<label id="title"></label></h4>
        </div>
        <div class="modal-body">
            <div class="form-horizontal">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <div class="form-group">
                    @Html.Label("Name", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @ViewBag.name
                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Complaint", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @ViewBag.complaint
                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Medicine", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("MedcineID", null, "--Select Medicine--", htmlAttributes: new { @class = "form-control" })

                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Quantity", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })

                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Frequency", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.Frequency, frequency, "-- Frequency --", htmlAttributes: new { @class = "form-control" })

                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.Remarks, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Remarks, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" id="btn-add" class="btn btn-primary">Add to list</button>
            <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Cancel</button>
        </div>
    </div>
</div>
</code>```

Here is my js:

```<code>$(document).ready(function () {
    //create
    $('#btn-add').click(function () {
        var assessmentID = $('#assessmentID').val();
        var medicineID = $('#MedcineID').val();
        var qty = $('#Quantity').val();
        var freq = $('#Frequency').val();
        var remarks = $('#Remarks').val();
        var data = {
            'assessmentID': assessmentID,
            'medicineID': medicineID,
            'qty': qty,
            'freq': freq,
            'remarks': remarks
        }

        if (medicineID == '') { // check if medicine is null
            alert('Please specify a valid medicine');
        }
        else { //check if duplicate
            $.ajax({//check via controller
                type: "POST",
                dataType: "Json",
                data: data,
                url: '/Prescriptions/CheckData/',
                success: function (f) {
                    if (f == 'Fail') {
                        alert('Specified medicine has already been added');
                    }
                    else {
                        if (qty < 1) {
                            alert('Please specify a valid quantity');
                        }
                        else {
                            if (freq == '') {
                                alert('Please specify a valid frequency');
                            }
                            else {
                                $.ajax({
                                    type: "POST",
                                    dataType: "Json",
                                    data: data,
                                    url: '/Prescriptions/Add/',
                                    success: function (f) {
                                        $('#tbl-prescription').load('/Prescriptions/_PrescriptionList/?assessmentID=' + assessmentID);
                                    }
                                })
                            }
                        }
                    }
                }
            })
        }
    })
});

// clears modal
$('#productModal').on('hidden.bs.modal', function (e) {
    $(this)
      .find("input,textarea,select")
         .val('')
         .end()
})
</code>```

答:
```<code>// clears modal
$('#productModal').on('hidden.bs.modal', function (e) {
     $(":input").val('');
     $("select").change();
})
</code>```

Title: Clear all input inside a modal

Body:
I have a modal where I can input some data to create and also to update the selected data. What I want to is, whenever the modal closes, it will clear the textbox and set the dropdown to its default display.

I have tried this http://jsfiddle.net/5LCSU/ applying to my project but it doesn't work and there is no error too.

Here is my moda/view:

            <button type="button" class="close" data-dismiss="modal">×</button>

Prescription

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.Label("Name", new { @class = "control-label col-md-2" })

                        @ViewBag.name

                    @Html.Label("Complaint", new { @class = "control-label col-md-2" })

                        @ViewBag.complaint

                    @Html.Label("Medicine", htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.DropDownList("MedcineID", null, "--Select Medicine--", htmlAttributes: new { @class = "form-control" })

                    @Html.Label("Quantity", htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.Label("Frequency", htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.DropDownListFor(model => model.Frequency, frequency, "-- Frequency --", htmlAttributes: new { @class = "form-control" })

                    @Html.LabelFor(model => model.Remarks, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Remarks, "", new { @class = "text-danger" })

            <button type="submit" id="btn-add" class="btn btn-primary">Add to list</button>
            <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Cancel</button>

Here is my js:

$(document).ready(function () {
    //create
    $('#btn-add').click(function () {
        var assessmentID = $('#assessmentID').val();
        var medicineID = $('#MedcineID').val();
        var qty = $('#Quantity').val();
        var freq = $('#Frequency').val();
        var remarks = $('#Remarks').val();
        var data = {
            'assessmentID': assessmentID,
            'medicineID': medicineID,
            'qty': qty,
            'freq': freq,
            'remarks': remarks
        }

        if (medicineID == '') { // check if medicine is null
            alert('Please specify a valid medicine');
        }
        else { //check if duplicate
            $.ajax({//check via controller
                type: "POST",
                dataType: "Json",
                data: data,
                url: '/Prescriptions/CheckData/',
                success: function (f) {
                    if (f == 'Fail') {
                        alert('Specified medicine has already been added');
                    }
                    else {
                        if (qty < 1) {
                            alert('Please specify a valid quantity');
                        }
                        else {
                            if (freq == '') {
                                alert('Please specify a valid frequency');
                            }
                            else {
                                $.ajax({
                                    type: "POST",
                                    dataType: "Json",
                                    data: data,
                                    url: '/Prescriptions/Add/',
                                    success: function (f) {
                                        $('#tbl-prescription').load('/Prescriptions/_PrescriptionList/?assessmentID=' + assessmentID);
                                    }
                                })
                            }
                        }
                    }
                }
            })
        }
    })
});

// clears modal
$('#productModal').on('hidden.bs.modal', function (e) {
    $(this)
      .find("input,textarea,select")
         .val('')
         .end()
})


答:
remove the poistion .and simply add margin:auto

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    margin:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="settings-button-new"><span>Home</span></button></code>```

Body:
I have button with text on top

Here is code

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left:0;
}

 <button class="settings-button-new">Home</button>

It on the top, but not centered as you can see.

I try to use text-align: center; but seems it not works.

How can i center it in button?

Thank's for help

Body:
remove the poistion .and simply add margin:auto

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    margin:auto;
}

<button class="settings-button-new"><span>Home</span></button>


问:
SQL: Sum two columns as 'Name' and use that name in where
MySQL:

I'm trying to Sum two columns in my database and return that results. I have that bit working.

```<code>SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats GROUP BY Id
</code>```

Now I have the two columns totalling together i want to be able to use 'TotalMoney' in a where clause?

```<code>SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats
WHERE TotalMoney BETWEEN 100000 AND 1000000
GROUP BY Id
</code>```

I'm getting a error saying TotalMoney does not exist but I have declared it.

答:
```<code>SELECT Id, SUM(Money) + SUM(Bank) AS TotalMoney FROM Players_Stats
GROUP BY Id HAVING SUM(Money) + SUM(Bank) BETWEEN 100000 AND 1000000
</code>```

or:

```<code>SELECT ID,TotalMoney FROM
(
SELECT Id, SUM(Money) + SUM(Bank) AS TotalMoney FROM Players_Stats
    GROUP BY Id
)Z WHERE Z.TotalMoney  BETWEEN 100000 AND 1000000
</code>```

Try above query.

Body:
MySQL:

I'm trying to Sum two columns in my database and return that results. I have that bit working.

SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats GROUP BY Id

Now I have the two columns totalling together i want to be able to use 'TotalMoney' in a where clause?

SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats
WHERE TotalMoney BETWEEN 100000 AND 1000000
GROUP BY Id

I'm getting a error saying TotalMoney does not exist but I have declared it.

Body:
SELECT Id, SUM(Money) + SUM(Bank) AS TotalMoney FROM Players_Stats
GROUP BY Id HAVING SUM(Money) + SUM(Bank) BETWEEN 100000 AND 1000000

or:

SELECT ID,TotalMoney FROM
(
SELECT Id, SUM(Money) + SUM(Bank) AS TotalMoney FROM Players_Stats
    GROUP BY Id
)Z WHERE Z.TotalMoney  BETWEEN 100000 AND 1000000

Try above query.


问:
I want to make an auto upgradable calendar like the Facebook calendar to add to my Google calendar
My goal is simple: I want to make a calendar that takes information from my account with my local library (book name and due date) and add it to my Google calendar but I want it so that whenever my account is updated (I borrow a new book) the information is also updated on the calendar. The only thing is that I have zero clue where to begin, and what languages to use, and what to do exactly. If anyone can lay out the steps for me with some detail I will be really grateful. Also, I'm not sure whether this qualifies as a programming question since I'm asking what to do rather than how to do it, so treat it as is appropriate.</p>

答:
I would suggest you to accomplish your task using means Google already provides instead of writing a local script which would probably require more of maintaining and synchronization among devices.
The one possible approach would be to synchronize your local folder with Google drive and write a google script which would update your calendar based on Google Drive changes.
The example of the script which tracks modification dates of files in one's drive is here: https://ctrlq.org/code/19921-monitor-drive-files-google-script</p>


问:
Merging objects within an array and keeping the highest value for identical properties
I have this array and I would like to merge the objects within it.

```<code>[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]
</code>```

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }```

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.

答:
Use Array#reduce to convert the array to an object, and iterate the keys of each object in the array using Array#forEach.

Note: I've updated your test case to have higher values before lower values, to better demonstrate the solution.

const arr = [null, null, {"1":0},{"2":3},{"5": 25},{"3":1},{"2":2},{"5":1},{"1":-5}];

const result = arr.reduce((r, o) => {
  if(!typeof(o) === 'object' || o === null) {
    return r;
  }

  Object.keys(o) // iterate the keys
    .forEach((key) => r[key] = r[key] !== undefined ? Math.max(r[key], o[key]) : o[key]); // get the greatest value

  return r;
}, {});

console.log(result);```

Body:
I have this array and I would like to merge the objects within it.

[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.


问:
Unable to run Python code
I have installed Python 3.5 in the directory c:\users\rshukla\desktop\python\python35

I have downloaded a simple Python code that I have saved in Atom.io also in the same folder c:\users\rshukla\desktop\python\happy_hour.py
And I am trying to it run through Powershell

```<code>import random

bars = ["Shoolbred's",
    "The Wren",
    "The Scratcher",
    "ACME",
    "Blind Barber"]

people = ["Mattan",
      "Chris",
      "Pooje",
      "that person you forgot to text back",
      "Kanye West",
      "Samuel L. Jackson"]

random_bar = random.choice(bars)
random_person_1 = random.choice(people)
random_person_2 = ramndon.choice(people)

print(f"How about you go to {random_bar} with {random_person_1} and {random_person_2}")
</code>```

When I try running this in Powershell, I get the output below - what am I doing    wrong?

```<code>PS C:\Users\rshukla\desktop\python> python happy_hour.py
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python happy_hour.py
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
you have to put python in path. see this How to add to the pythonpath in windows 7?

but i think this kind of format string is new in python 3.6 and not available in python 3.5

Title: Unable to run Python code

Body:
I have installed Python 3.5 in the directory c:\users\rshukla\desktop\python\python35

I have downloaded a simple Python code that I have saved in Atom.io also in the same folder c:\users\rshukla\desktop\python\happy_hour.py
And I am trying to it run through Powershell

import random

bars = ["Shoolbred's",
    "The Wren",
    "The Scratcher",
    "ACME",
    "Blind Barber"]

people = ["Mattan",
      "Chris",
      "Pooje",
      "that person you forgot to text back",
      "Kanye West",
      "Samuel L. Jackson"]

random_bar = random.choice(bars)
random_person_1 = random.choice(people)
random_person_2 = ramndon.choice(people)

print(f"How about you go to {random_bar} with {random_person_1} and {random_person_2}")

When I try running this in Powershell, I get the output below - what am I doing    wrong?

PS C:\Users\rshukla\desktop\python> python happy_hour.py
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python happy_hour.py
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


问:
How do I change the exported name decoration for __stdcall in VC++?
This is how I have my export function declared at the moment:

```<code>extern "C" __declspec(dllexport)
Iexport_class* __stdcall GetExported_Class();
</code>```

When VS2008 compiled the source for this, the dll produced contains this under its export table:

```<code>_GetExported_Class@0
</code>```

For compatibility with other compilers I need the above decoration to look like this instead:

```<code>GetExported_Class
</code>```

Changing the calling convention to __cdecl will decorate it to the way I want but the convention would be wrong so I can't use that. I need it to be decorated the way __cdecl looks but uses __stdcall instead.

Is there anyway to do this without using a .def file? Is there a switch or an option I can pass to the link.exe linker that can make it decorate the export name to the way I want?

Thanks

答: No. All __stdcall names are decorated this way. I'm amazed that you have some other compiler that won't expect __stdcall exports to be decorated like this. Overriding the linker with .def is pretty much all you can do- unless you want to alter the PE file after production.</p>

Body:
This is how I have my export function declared at the moment:

extern "C" __declspec(dllexport)
Iexport_class* __stdcall GetExported_Class();

When VS2008 compiled the source for this, the dll produced contains this under its export table:

_GetExported_Class@0

For compatibility with other compilers I need the above decoration to look like this instead:

GetExported_Class

Changing the calling convention to __cdecl will decorate it to the way I want but the convention would be wrong so I can't use that. I need it to be decorated the way __cdecl looks but uses __stdcall instead.

Is there anyway to do this without using a .def file? Is there a switch or an option I can pass to the link.exe linker that can make it decorate the export name to the way I want?

Thanks


问:
ServerResponse 404 while uploading image to server
I want to upload Image to Perticular Url(www.myUrl.com/myFolderName/) through android and retrieve the address of that url.

Here is my code

```<code>class SaveFile extends AsyncTask<String,String,String>
{
    FileInputStream fileInputStream;
    HttpURLConnection connection;
    URL url;
    DataOutputStream outputStream;
    int bytesRead,bytesAvailable,bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File selectedFile = new File(selectedImagePath);
    //selectedImagePath = path of Image in phonememory
    @Override
    protected String doInBackground(String... params)
    {
        Log.v(TAG,"Image path is  " + selectedImagePath);

        try
        {
            fileInputStream = new FileInputStream(selectedFile);
            url = new URL(SEND_IMAGE);
            connection= (HttpURLConnection)url.openConnection();
            Log.v(TAG,"connection established");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setRequestProperty("ENCTYPE","multipart/form-data");
            connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
            //connection.setRequestProperty("image1",selectedImagePath);
            //connection.setRequestProperty("user_id","1");
            outputStream = new DataOutputStream(connection.getOutputStream());

            outputStream.writeBytes("--*****\r\n");
            outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
            outputStream.writeBytes("\r\n");
            //outputStream.writeBytes("--*****\r\n");
            bytesAvailable = fileInputStream.available();
            bufferSize =  Math.min(bytesAvailable,maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer,0,bufferSize);
            while (bytesRead>0)
            {
                outputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }
            outputStream.writeBytes("\r\n");
            outputStream.writeBytes("--*****--\r\n");

            int  serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            if(serverResponseCode  == HttpURLConnection.HTTP_OK) {
                String line;
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                Log.v(TAG,"Response is " +sb.toString());

            }
            Log.v("UploadImage", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        }
        catch (Exception e)
        {
            Log.v("UploadImage"," " + e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

    }
}
</code>```

but I am getting serverResponse 404

I tried solutions like Uploading Image to Server - Android but not worked.

I searched a lot.but couldnt find solution

Please Help!!

答: I want to say that this maybe a server error. 404 in most cases is an error that says, "you have used wrong url". Check whether this url is correct.try to upload your data in your browser.</p>

Body:
I want to upload Image to Perticular Url(www.myUrl.com/myFolderName/) through android and retrieve the address of that url.

Here is my code

class SaveFile extends AsyncTask<String,String,String>
{
    FileInputStream fileInputStream;
    HttpURLConnection connection;
    URL url;
    DataOutputStream outputStream;
    int bytesRead,bytesAvailable,bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File selectedFile = new File(selectedImagePath);
    //selectedImagePath = path of Image in phonememory
    @Override
    protected String doInBackground(String... params)
    {
        Log.v(TAG,"Image path is  " + selectedImagePath);

        try
        {
            fileInputStream = new FileInputStream(selectedFile);
            url = new URL(SEND_IMAGE);
            connection= (HttpURLConnection)url.openConnection();
            Log.v(TAG,"connection established");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setRequestProperty("ENCTYPE","multipart/form-data");
            connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
            //connection.setRequestProperty("image1",selectedImagePath);
            //connection.setRequestProperty("user_id","1");
            outputStream = new DataOutputStream(connection.getOutputStream());

            outputStream.writeBytes("--*****\r\n");
            outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
            outputStream.writeBytes("\r\n");
            //outputStream.writeBytes("--*****\r\n");
            bytesAvailable = fileInputStream.available();
            bufferSize =  Math.min(bytesAvailable,maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer,0,bufferSize);
            while (bytesRead>0)
            {
                outputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }
            outputStream.writeBytes("\r\n");
            outputStream.writeBytes("--*****--\r\n");

            int  serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            if(serverResponseCode  == HttpURLConnection.HTTP_OK) {
                String line;
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                Log.v(TAG,"Response is " +sb.toString());

            }
            Log.v("UploadImage", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        }
        catch (Exception e)
        {
            Log.v("UploadImage"," " + e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

    }
}

but I am getting serverResponse 404

I tried solutions like Uploading Image to Server - Android but not worked.

I searched a lot.but couldnt find solution

Please Help!!