问:
Generating Karaf Bundle
I've got a hello world opendaylight app (created following the tutorials) which compiles using a mvn clean install, and appears when I run the karaf package that is also generated.

However I am unable to get it to run in another ODL install (downloaded the binary with all the other packages from the website), and even using a

```<code>bundle:install mvn:org.andrew.test
</code>```

results in unable to install bundle (tried copying to deploy and system/org/andrew....)

How do you get a bundle which can be used in another install?

答:
Why do you want to bundle:install instead of feature:install ?

What most existing ODL projects do for you, and what the example generated by the archetype should also show you how to do for your custom org.andrew.test one (have you used the archetype? try it..) is that there is a local karaf/ artifact which correctly depends on the features/odl-something feature of your example, and lets you install it, which will install your bundle/s.

In theory and if you really know what you are doing, you can also get it to work for what you call "in another install" in your question, but you have to use repo-app and what not - most people do not use it like that AFAIK (at least in ODL development); so I wouldn't bother, if I were you.

If you want to learn more about this in general outside of OpenDaylight, the general Karaf documentation manual is not bad.  Beware that in ODL we've tweaked a few things though; for example, we have (intentionally) disabled the direct installation from ~/.m2/repository (for better isolation).

Title: Generating Karaf Bundle

Body:
I've got a hello world opendaylight app (created following the tutorials) which compiles using a mvn clean install, and appears when I run the karaf package that is also generated.

However I am unable to get it to run in another ODL install (downloaded the binary with all the other packages from the website), and even using a

bundle:install mvn:org.andrew.test

results in unable to install bundle (tried copying to deploy and system/org/andrew....)

How do you get a bundle which can be used in another install?


来源: stackexchange

问:
Pointer as generic type argument
I have a bunch of external C functions that in C# become something like this:

```<code>public extern static int clGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    void* param_value,
    out IntPtr param_value_size_ret);
</code>```

Because there are a bunch of similar looking function, I wanted to create a method which reads the data provided by these C functions. This is what I went with:

```<code>unsafe public static ErrorCode GetInfoString(
    IntPtr handle, uint property,
    Func<IntPtr, uint, IntPtr, void*, IntPtr, int> infoFunc,
    out string value)
{
    // reading logic
}
</code>```

My problem is that C# does not allow me to use the void* as a generic argument of Func. Is there any way around this problem?

I can neither change the signature of external C function nor the signature of the C# function (I'm using a library).

答:
As @MarcinJuraszek pointed out:

Can you define a custom delegate type instead of reusing Func

Yes, I can. Using a delegate works for me.

```<code>unsafe public delegate int GetInfoMethod(
    IntPtr handle, uint param_name, IntPtr param_value_size,
    void* param_value, out IntPtr param_value_size_ret);

unsafe public static ErrorCode GetInfoString(
    IntPtr handle, uint property,
    GetInfoMethod infoFunc,
    out string value)
{
    // reading logic
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pointer as generic type argument

Body:
I have a bunch of external C functions that in C# become something like this:

public extern static int clGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    void* param_value,
    out IntPtr param_value_size_ret);

Because there are a bunch of similar looking function, I wanted to create a method which reads the data provided by these C functions. This is what I went with:

unsafe public static ErrorCode GetInfoString(
    IntPtr handle, uint property,
    Func<IntPtr, uint, IntPtr, void*, IntPtr, int> infoFunc,
    out string value)
{
    // reading logic
}

My problem is that C# does not allow me to use the void* as a generic argument of Func. Is there any way around this problem?

I can neither change the signature of external C function nor the signature of the C# function (I'm using a library).

Body:
As @MarcinJuraszek pointed out:

Can you define a custom delegate type instead of reusing Func

Yes, I can. Using a delegate works for me.

unsafe public delegate int GetInfoMethod(
    IntPtr handle, uint param_name, IntPtr param_value_size,
    void* param_value, out IntPtr param_value_size_ret);

unsafe public static ErrorCode GetInfoString(
    IntPtr handle, uint property,
    GetInfoMethod infoFunc,
    out string value)
{
    // reading logic
}


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
You should use stl as much as possible.

It has been written by pretty sophisticated programmers and it is very unlikely that you can write a more optimized version of any of stl stuff.

Do not re-invent the wheel

ContentLicense: CC BY-SA 2.5


Title: Swaping columns of numpy array in all rows but the first one

Body:
Given a numpy array

import numpy as np
a = np.arange(4*7).reshape([4, 7])

array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12, 13],
       [14, 15, 16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25, 26, 27]])

I can apply slicing to swap the second and third columns by:

a[:, [0, 2, 1, 3, 4, 5, 6]]

array([[ 0,  2,  1,  3,  4,  5,  6],
       [ 7,  9,  8, 10, 11, 12, 13],
       [14, 16, 15, 17, 18, 19, 20],
       [21, 23, 22, 24, 25, 26, 27]])

But, can I use slices to swap the second and third columns for all rows but the first one? The expected output would be:

array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7,  9,  8, 10, 11, 12, 13],
       [14, 16, 15, 17, 18, 19, 20],
       [21, 23, 22, 24, 25, 26, 27]])

Body:
For in-situ edit, we can use flipping after slicing out the two columns -

a[1:,1:3] = a[1:,2:0:-1]

Sample run -

In [556]: a = np.arange(4*7).reshape([4, 7])

In [557]: a
Out[557]:
array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12, 13],
       [14, 15, 16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25, 26, 27]])

In [559]: a[1:,1:3] = a[1:,2:0:-1]

In [560]: a
Out[560]:
array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7,  9,  8, 10, 11, 12, 13],
       [14, 16, 15, 17, 18, 19, 20],
       [21, 23, 22, 24, 25, 26, 27]])

For columns that are two-step apart, use a stepsize of 2 to assign (LHS) and -2 to select (RHS). Hence, for column IDs 1 & 3 -

In [577]: a = np.arange(4*7).reshape([4, 7])

In [578]: a
Out[578]:
array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12, 13],
       [14, 15, 16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25, 26, 27]])

In [579]: a[1:,1:4:2] = a[1:,3:0:-2]

In [580]: a
Out[580]:
array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7, 10,  9,  8, 11, 12, 13],
       [14, 17, 16, 15, 18, 19, 20],
       [21, 24, 23, 22, 25, 26, 27]])

Another method would be with explicit column numbered indexing -

a[1:,[1,2]] = a[1:,[2,1]]

Note that this creates a copy with a[1:,[2,1]] and as such would be less memory efficient than the first method.


问:
Trigger created with compilation errors for Oracle SQL
I tried to create code using Oracle trigger syntax, but there is a warning:

trigger created with compilation errors

Here is the code. I want to raise an error when the price in table itemtype is set to over four times the minimum old price. How can I do that?

I tried to fix the previous problem! I created the trigger successfully, but it only works when insert, the "mutating table" error still occurs when I was tring to update the price on table itemType. How can I change my code to make it also works when updating?

```<code>    CREATE or replace TRIGGER tr_price before insert or update on itemType for each row
    declare minimum float;
    begin
      select min(price)
      into minimum
      from itemType;
      if :new.price > 4*minimum
        then
        raise_application_error (-20000,'new price can not over 4 times min old price');
      END IF;
    end;
    /
</code>```

答:
As clarified in the Comments (or, if you answer my request, as edited in the post itself), you are running into the "mutating table" error. And you would like to know how to fix it.

Alas, this is not a programming error. It is a logical problem (which Oracle chose not to ignore, by rising the "mutating table" error).

Oracle is a multi-user environment, and SQL allows you to insert/alter/delete many rows in one transaction. Both of these things are GOOD, but they mean you can't do things like what you are trying to do.

What is the "old" minimum price? Suppose you had 20 rows already, and the minimum price was $55. You add one more row with the price $50. Now you try to add another row with price $210. What is "the old minimum"? $220? Why, because the row with the price of $50 was inserted, but not committed yet? Or is it $200? What if, in the same transaction, but later in your code, you DELETE the row with the $55 price and the next lowest is $60 - shouldn't you allow prices up to $240?

Then compound this problem: you insert a few rows, but you don't commit yet. Then someone else inserts (or updates or deletes) in the same table, and they commit their transaction. Now you want to commit. Shouldn't the "check" be performed again, at the end of the transaction, and not "for each row"?

The whole idea of tying the behavior of DML statements to data in the table, as it exists at one time or another (and as may change in the middle of your transaction, as caused either by your own other activity or by the activity of other users at the same time), is something you must understand clearly, and discuss with the "business managers" or "business users" who may not know or understand SQL, but who must understand this issue and who must come up with logical requirements. Only allowing inserts where the price is "no more than four times the old minimum" is not internally consistent, and Oracle, wisely, does not allow you to do something that wouldn't make sense.

So - the short answer is "you can't fix the solution, because the solution is not broken, the problem itself is broken." You must fix the problem first.

Body:
I tried to create code using Oracle trigger syntax, but there is a warning:

trigger created with compilation errors

Here is the code. I want to raise an error when the price in table itemtype is set to over four times the minimum old price. How can I do that?

I tried to fix the previous problem! I created the trigger successfully, but it only works when insert, the "mutating table" error still occurs when I was tring to update the price on table itemType. How can I change my code to make it also works when updating?

    CREATE or replace TRIGGER tr_price before insert or update on itemType for each row
    declare minimum float;
    begin
      select min(price)
      into minimum
      from itemType;
      if :new.price > 4*minimum
        then
        raise_application_error (-20000,'new price can not over 4 times min old price');
      END IF;
    end;
    /


问:
Update React Component after render
I am using react-native-sortable-listview to change order of list-item by drag and drop. Only drag item is again rendered so its position is updated but other have their previous position. When This component is re-rendered by other cause like some increment button, all position are being correct.
 So my question is when my react-native-sortable-list is rendered how can I re-render this again.
 Both ways to render by forceUpdate() and this.setState() , I could not follow as I can not update state in render function.
 What can be a possible way for doing this.

答:
You could pass a reRender function down to your sortable list. ReactNativeList accepts a prop called onChangeOrder that is called each time row order is changed.

```<code>class ParentComponent extends Component {
    reRender = () => {
      this.forceUpdate()
    }

    render() {
      return <ReactNativeList onChangeOrder={this.reRender} />
    }
}
</code>```

Title: Update React Component after render

Body:
You could pass a reRender function down to your sortable list. ReactNativeList accepts a prop called onChangeOrder that is called each time row order is changed.

class ParentComponent extends Component {
    reRender = () => {
      this.forceUpdate()
    }

    render() {
      return <ReactNativeList onChangeOrder={this.reRender} />
    }
}


问:
extract same values in a list of dictionaries if it present
I'm trying ti implement a search engine for documents, so i have my index:

```<code>{'term1': [[document_id1, term_frequency], [document_id2, term_frequency]......]},
{'term2': [[document_id3, term_frequency], [document_id2, term_frequency]......]}
</code>```

and so on...

I should ask for some terms and find all documents that have it(have done this part),
but how can I find ALL the doc_ids that present in my list of dictionaries?

In other words, I need all documents which have ALL the words of the query.
I tried this, but it doesn't work

```<code>    def match(query):
        match_docs=[]
        for doc in find_doc(query):
            for k,v in doc.items():
                for j in v:
                    if j[0] in i:
                       match_docs.append(j)
        return match_docs
</code>```

For example

```<code>    terms=[{'rose':[['3',2],['4',4]]},{'trains':[['3',4],['6',5]]}]
</code>```

I need that it returns me '3'

答:
Given a document, it is trivial to find if a word is in it:

```<code>>>> "plump" in open("ulysses.txt", 'r').read()
True
</code>```

The same approach can be taken with a more elaborate query:

```<code>>>> query = ["Stately", "plump", "Buck", "Mulligan"]
>>> [_ in open("ulysses.txt", 'r').read() for _ in query]
[True, True, True, True]
</code>```

The last hint that I'll give, is that the all(iterable) function returns True if the iterable is empty, or if bool(x) evaluates to True for all its values .

```<code>>>> all([_ in open("ulysses.txt", 'r').read() for _ in query])
True
>>> all([_ in open("dubliners.txt", 'r').read() for _ in query])
False
</code>```

And you should have no problem extending this approach to examine more documents.

Body:
I'm trying ti implement a search engine for documents, so i have my index:

{'term1': [[document_id1, term_frequency], [document_id2, term_frequency]......]},
{'term2': [[document_id3, term_frequency], [document_id2, term_frequency]......]}

and so on...

I should ask for some terms and find all documents that have it(have done this part),
but how can I find ALL the doc_ids that present in my list of dictionaries?

In other words, I need all documents which have ALL the words of the query.
I tried this, but it doesn't work

    def match(query):
        match_docs=[]
        for doc in find_doc(query):
            for k,v in doc.items():
                for j in v:
                    if j[0] in i:
                       match_docs.append(j)
        return match_docs

For example

    terms=[{'rose':[['3',2],['4',4]]},{'trains':[['3',4],['6',5]]}]

I need that it returns me '3'

Body:
Given a document, it is trivial to find if a word is in it:

>>> "plump" in open("ulysses.txt", 'r').read()
True

The same approach can be taken with a more elaborate query:

>>> query = ["Stately", "plump", "Buck", "Mulligan"]
>>> [_ in open("ulysses.txt", 'r').read() for _ in query]
[True, True, True, True]

The last hint that I'll give, is that the all(iterable) function returns True if the iterable is empty, or if bool(x) evaluates to True for all its values .

>>> all([_ in open("ulysses.txt", 'r').read() for _ in query])
True
>>> all([_ in open("dubliners.txt", 'r').read() for _ in query])
False

And you should have no problem extending this approach to examine more documents.


问:
How to connect to LocalDB in Visual Studio Server Explorer?
I can't believe I couldn't find a working solution to this after an hour of searching. I'm following this article on Entity Framework 6.0 which gives a simple walk-through on Code First. I created the project and installed the latest EF Nuget package for the project to compile. I also verified that I have Microsoft SQL Server 2012 Express LocalDB installed which came with Visual Studio 2013. I don't have any other instances of SQL installed on my local computer. The program runs and entries are added to the database and outputted in the console. But when the article says "check your localdb" it doesn't say how! I don't see any '.mdf' or '.ldf' files created under the project folder. I tried every way to connect Visual Studio's Server Explorer to LocalDB. The wizard cannot locate (localdb) or cannot find any provider in Server Explorer to accept connection string like (localdb)\v11.0;Integrated Security=true; I've seen this asked several places in StackOverflow but no answer works or marked as answer. Please help, this doesn't have to be this frustrating!

What are the steps to connect Visual Studio Server Explorer to LocalDB?

答: With SQL Server 2017 and Visual Studio 2015, I used localhost\SQLEXPRESS


问:
How to store Bytes/Slice(UInt8) as a string in Crystal?
I'm encoding an Object into Bytes (ie Slice(UInt8)) via MessagePack. How would I store this in a datastore client (eg Crystal-Redis) that only accepts Strings?

答:
If you have no other choice to store the Slice as a String, you can encode it as a String, but at the cost of reduced performance.

There's Base64 strict_encode/decode:

```<code>encoded = An_Object.to_msgpack # Slice(UInt8)
save_to_datastore "my_stuff", Base64.strict_encode(encoded)
from_storage = get_from_datastore "my_stuff"
if from_storage
   My_MsgPack_Mapping.from_msgpack( Base64.decode(from_storage) )
end
</code>```

Or you can use  Slice#hexstring  and  String#hexbytes:

```<code>encoded = An_Object.to_msgpack # Slice(UInt8)
save_to_datastore "my_stuff", encoded.hexstring
from_storage = get_from_datastore "my_stuff"
if from_storage && from_storage.hexbytes?
   My_MsgPack_Mapping.from_msgpack( from_storage.hexbytes )
end
</code>```

(Crystal-Redis users have another option: see this issue.)

Body:
If you have no other choice to store the Slice as a String, you can encode it as a String, but at the cost of reduced performance.

There's Base64 strict_encode/decode:

encoded = An_Object.to_msgpack # Slice(UInt8)
save_to_datastore "my_stuff", Base64.strict_encode(encoded)
from_storage = get_from_datastore "my_stuff"
if from_storage
   My_MsgPack_Mapping.from_msgpack( Base64.decode(from_storage) )
end

Or you can use  Slice#hexstring  and  String#hexbytes:

encoded = An_Object.to_msgpack # Slice(UInt8)
save_to_datastore "my_stuff", encoded.hexstring
from_storage = get_from_datastore "my_stuff"
if from_storage && from_storage.hexbytes?
   My_MsgPack_Mapping.from_msgpack( from_storage.hexbytes )
end

(Crystal-Redis users have another option: see this issue.)


问:
Map SQL table rows to C++ structures
I'm trying to implement some kind of persistent storage of C++ structures into an SQLite database. It looks nice in the beginning but then it becomes complicated with all those SQL requests, data binds and manual getting field values one after another.

Ideally I'd like to have some kind of mapping from a table row in SQLite to a C++ structure, with a possibility of running SQL requests on that. On the other hand, I'd still like to keep it general enough to be able to run more complex requests with joins etc.

I even thought that an external utility that would auto-generate the corresponding C++/SQL glue code could be helpful.

What would be the right way to do this kind of mapping? I've heard people suggesting boost::serialization or Google's protocol buffers, would this be a much better option for what I want, or maybe there are some other good options?

答:
Sounds like you want an Object Relational Mapper (ORM).  Try reading through this stack overflow thread: https://stackoverflow.com/questions/74141/good-orm-for-c-solutions

The selected answer there talks about Database Template Library; I'd look into there as well.

Title: Map SQL table rows to C++ structures


问:
How to update a specific object within storage with React/Redux?
I'm considering using Redux for my app, but there's a common use case that I'm not sure how to handle with it. I have a component that displays some object and allows the user to edit it. Every action will create a shallow copy of the object, but what then? How is the component supposed to know how to update the storage with it? In the samples I see that the component is passed a key instead of the actual object, but doesn't that break the concept of incapsulation, since a component isn't supposed to know where it's state/props come from? I want the component to be fully reusable, so it receives an object and information on how to update it in a more general form, which seems to be awkward to implement with Redux (I'm going to have to pass write callbacks to every component, and then chain them somehow).

Am I using Redux wrong, or is there a more suitable alternative for this use case? I'm thinking of making one myself (where every state object knows it's owner and key via some global WeakMap), but I don't want to be reinventing the wheel.

For instance, if my storage looks like this:

```<code>Storage = {
  items: {
    item1: { ... },
    item2: { ... },
    ...
  },
  someOtherItems: {
    item1: { ... },
    ...
  },
  oneMoreItem: { ... },
};
</code>```

I want to be able to display all item objects with the same component. But the component somehow has to know how to write it's updated item back to the storage, so I can't just pass it item1 as key. I could pass a callback that would replace a specific item in the (cloned) storage, but that doesn't work well if, for instance, I have a component that displays a list of items, since I would have to chain those callbacks somehow.

答:
This is a common use case, and yes - you're missing the point here. react/redux makes this really easy.

I usually structure it as follows: Components receive a modelValue object prop and changeValue function prop. The former is the current value, the latter is the function we call to change the value. These props are going to be supplied by redux.

Now we write a connect hoc (higher order component), a simple example might look like this:

```<code>const mapStateToProps = (state, ownProps) => {
    return {
        modelValue: _.get(state, ownProps.model),
    };
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        changeValue: (val) => dispatch({
            type: "your/reducer/action",
            model: ownProps.model,
            value: val,
        })
    };
};

const mergeProps = (stateProps, dispatchProps, ownProps) => {
    return {
        ...stateProps,
        ...dispatchProps,
        ...ownProps,
    };
};

const MyConnectedComponent = connect(mapStateToProps, mapDispatchToProps, mergeProps)(MyGenericComponent);
</code>```

This is an example where we pass in a model string to the hoc, and it wires up modelValue and changeValue for us. So now all we need to do is pass in a model like "some.javascript.path" to our component and that's where it will get stored in the state. MyGenericComponent still doesn't know or care about where it's stored in the state, only MyConnectedComponent does.

Usage would be as follows:

```<code><MyConnectedComponent model="some.path.in.the.state" />
</code>```

And inside MyGenericComponent just consume modelValue for the current value, and execute changeValue to change the value.

Note that you need to also wire up a redux reducer to handle your/reducer/action and actually do the update to the state, but that's a whole other topic.

Edit

You mentioned that you need sub components to be aware of the parent state, this can be achieved by passing model via context. The following examples are using recompose:

```<code>const mapStateToProps = ...

const mapDispatchToProps = ...

const mergeProps = ...

const resolveParentModel = (Component) => {
    return (props) => {
        // we have access to 'model' and 'parentModel' here.
        // parentModel comes from parent context, model comes from props
        const { parentModel, model } = props;

        let combinedModel = model;

        // if our model starts with a '.' then it should be a model relative to parent.
        // else, it should be an absolute model.
        if (model.startsWith(".")) {
            combinedModel = parentModel + model;
        }

        return <Component {...props} model={combinedModel} />;
    }
}

const myCustomHoc = (Component) => (
    // retrieve the current parent model as a prop
    getContext({ parentModel: React.PropTypes.string })(
        // here we map parent model and own model into a single combined model
        resolveParentModel(
            // here we map that combined model into 'modelValue' and 'changeValue'
            connect(mapStateToProps, mapDispatchToProps, mergeProps)(
                // we provide this single combined model to any children as parent model so the cycle continues
                withContext({ parentModel: React.PropTypes.string }, (props) => props.model)(
                    Component
                )
            )
        )
    )
);
</code>```

In summary, we pass a context value parentModel to all children. Each object maps parent model into it's own model string conditionally. Usage would then look like this:

```<code>const MyConnectedParentComponent = myCustomHoc(MyGenericParentComponent);
const MyConnectedSubComponent = myCustomHoc(MyGenericSubComponent);

<MyConnectedParentComponent model="some.obj">
    {/* the following model will be resolved into "some.obj.name" automatically because it starts with a '.' */}
    <MyConnectedSubComponent model=".name" />
</MyConnectedParentComponent>
</code>```

Note that nesting this way could then go to any depth. You can access absolute or relative state values anywhere in the tree. You can also get clever with your model string, maybe starting with ^ instead of . will navigate backwards: so some.obj.path and ^name becomes some.obj.name instead of some.obj.path.name etc.

Regarding your concerns with arrays, when rendering arrays you almost always want to render all items in the array - so it would be easy enough to write an array component that just renders X elements (where X is the length of the array) and pass .0, .1, .2 etc to each item.

```<code>const SomeArray = ({ modelValue, changeValue }) => (
    <div>
        {modelValue.map((v, i) => <SomeChildEl key={i} model={"." + i} />)}

        <span onClick={() => changeValue([...modelValue, {}])} >Add New Item</span>
    </div>
);
</code>```

Body:
I'm considering using Redux for my app, but there's a common use case that I'm not sure how to handle with it. I have a component that displays some object and allows the user to edit it. Every action will create a shallow copy of the object, but what then? How is the component supposed to know how to update the storage with it? In the samples I see that the component is passed a key instead of the actual object, but doesn't that break the concept of incapsulation, since a component isn't supposed to know where it's state/props come from? I want the component to be fully reusable, so it receives an object and information on how to update it in a more general form, which seems to be awkward to implement with Redux (I'm going to have to pass write callbacks to every component, and then chain them somehow).

Am I using Redux wrong, or is there a more suitable alternative for this use case? I'm thinking of making one myself (where every state object knows it's owner and key via some global WeakMap), but I don't want to be reinventing the wheel.

For instance, if my storage looks like this:

Storage = {
  items: {
    item1: { ... },
    item2: { ... },
    ...
  },
  someOtherItems: {
    item1: { ... },
    ...
  },
  oneMoreItem: { ... },
};

I want to be able to display all item objects with the same component. But the component somehow has to know how to write it's updated item back to the storage, so I can't just pass it item1 as key. I could pass a callback that would replace a specific item in the (cloned) storage, but that doesn't work well if, for instance, I have a component that displays a list of items, since I would have to chain those callbacks somehow.

Body:
This is a common use case, and yes - you're missing the point here. react/redux makes this really easy.

I usually structure it as follows: Components receive a modelValue object prop and changeValue function prop. The former is the current value, the latter is the function we call to change the value. These props are going to be supplied by redux.

Now we write a connect hoc (higher order component), a simple example might look like this:

const mapStateToProps = (state, ownProps) => {
    return {
        modelValue: _.get(state, ownProps.model),
    };
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        changeValue: (val) => dispatch({
            type: "your/reducer/action",
            model: ownProps.model,
            value: val,
        })
    };
};

const mergeProps = (stateProps, dispatchProps, ownProps) => {
    return {
        ...stateProps,
        ...dispatchProps,
        ...ownProps,
    };
};

const MyConnectedComponent = connect(mapStateToProps, mapDispatchToProps, mergeProps)(MyGenericComponent);

This is an example where we pass in a model string to the hoc, and it wires up modelValue and changeValue for us. So now all we need to do is pass in a model like "some.javascript.path" to our component and that's where it will get stored in the state. MyGenericComponent still doesn't know or care about where it's stored in the state, only MyConnectedComponent does.

Usage would be as follows:

<MyConnectedComponent model="some.path.in.the.state" />

And inside MyGenericComponent just consume modelValue for the current value, and execute changeValue to change the value.

Note that you need to also wire up a redux reducer to handle your/reducer/action and actually do the update to the state, but that's a whole other topic.

Edit

You mentioned that you need sub components to be aware of the parent state, this can be achieved by passing model via context. The following examples are using recompose:

const mapStateToProps = ...

const mapDispatchToProps = ...

const mergeProps = ...

const resolveParentModel = (Component) => {
    return (props) => {
        // we have access to 'model' and 'parentModel' here.
        // parentModel comes from parent context, model comes from props
        const { parentModel, model } = props;

        let combinedModel = model;

        // if our model starts with a '.' then it should be a model relative to parent.
        // else, it should be an absolute model.
        if (model.startsWith(".")) {
            combinedModel = parentModel + model;
        }

        return <Component {...props} model={combinedModel} />;
    }
}

const myCustomHoc = (Component) => (
    // retrieve the current parent model as a prop
    getContext({ parentModel: React.PropTypes.string })(
        // here we map parent model and own model into a single combined model
        resolveParentModel(
            // here we map that combined model into 'modelValue' and 'changeValue'
            connect(mapStateToProps, mapDispatchToProps, mergeProps)(
                // we provide this single combined model to any children as parent model so the cycle continues
                withContext({ parentModel: React.PropTypes.string }, (props) => props.model)(
                    Component
                )
            )
        )
    )
);

In summary, we pass a context value parentModel to all children. Each object maps parent model into it's own model string conditionally. Usage would then look like this:

const MyConnectedParentComponent = myCustomHoc(MyGenericParentComponent);
const MyConnectedSubComponent = myCustomHoc(MyGenericSubComponent);

<MyConnectedParentComponent model="some.obj">
    {/* the following model will be resolved into "some.obj.name" automatically because it starts with a '.' */}
    <MyConnectedSubComponent model=".name" />
</MyConnectedParentComponent>

Note that nesting this way could then go to any depth. You can access absolute or relative state values anywhere in the tree. You can also get clever with your model string, maybe starting with ^ instead of . will navigate backwards: so some.obj.path and ^name becomes some.obj.name instead of some.obj.path.name etc.

Regarding your concerns with arrays, when rendering arrays you almost always want to render all items in the array - so it would be easy enough to write an array component that just renders X elements (where X is the length of the array) and pass .0, .1, .2 etc to each item.

const SomeArray = ({ modelValue, changeValue }) => (
    <div>
        {modelValue.map((v, i) => <SomeChildEl key={i} model={"." + i} />)}

        <span onClick={() => changeValue([...modelValue, {}])} >Add New Item</span>
    </div>
);


问:
Issue with If Clause in php
I am very new to this site and this is my first question. I want to display different submission forms on the basis of input being sent via form. Please have a look at the following code:

```<code><?php
if(isset($_POST['submit'])){
    $camp = $_POST['camp'];

    if($camp == "Final Expense"){
        echo "FE Form Goes Here";
    }
    if($camp == "Home Improvements"){
        echo "HI Form Goes Here";
    }
?>
</code>```

Now since there is space between Home Improvements and also between Final Expense Word, therefore it is always false. If I remove the space from input and remove space from here e.g Home_Improvements and Final_Expense then it works.

How Can I maintain the input with spaces and the tests here with spaces too. Please answer anybody. Thanks..

答:
Well this worked for me just fine.</p>

```<code><?php
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["camp"])){
    $camp = $_POST['camp'];
    if (stripos($camp, "Final") > -1 && stripos($camp, "Expense") > -1) {
        echo "FE Form Goes Here";
    }
    if(stripos($camp, "Home") > -1 && stripos($camp, "Improvements") > -1){
        echo "HI Form Goes Here";
    }
}
?>
</code>```

Title: Issue with If Clause in php

Body:
I am very new to this site and this is my first question. I want to display different submission forms on the basis of input being sent via form. Please have a look at the following code:

<?php
if(isset($_POST['submit'])){
    $camp = $_POST['camp'];

    if($camp == "Final Expense"){
        echo "FE Form Goes Here";
    }
    if($camp == "Home Improvements"){
        echo "HI Form Goes Here";
    }
?>

Now since there is space between Home Improvements and also between Final Expense Word, therefore it is always false. If I remove the space from input and remove space from here e.g Home_Improvements and Final_Expense then it works.

How Can I maintain the input with spaces and the tests here with spaces too. Please answer anybody. Thanks..

Body:
Well this worked for me just fine.

<?php
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["camp"])){
    $camp = $_POST['camp'];
    if (stripos($camp, "Final") > -1 && stripos($camp, "Expense") > -1) {
        echo "FE Form Goes Here";
    }
    if(stripos($camp, "Home") > -1 && stripos($camp, "Improvements") > -1){
        echo "HI Form Goes Here";
    }
}
?>


问:
Devise user_root_path gets 404'd in production but not dev?
weird, i know but using user_root_path in production does not work.  When i click on the link myapp.com/user i get a 404 page.

The log file doesn't show spit but a failed attempt:

```<code>Started GET "/user" for 123.125.146.23 at 2011-01-19 19:40:45 +0000

ActionController::RoutingError (uninitialized constant User::UsersController):
</code>```

Now the only way to see something about this unitialized constant is to turn on rails c and type the constant into the console.  Here is what happens:

```<code>ruby-1.9.2-p136 :005 > User::UsersController
(irb):5: warning: toplevel constant UsersController referenced by User::UsersController
=> UsersController
</code>```

Now some digging found that this toplevel warning could be messing with it. But the log says bubkiss.

So i changed the route file from:

```<code>  devise_for :users
namespace :user do
  root :to => "users#index"
end
resources :subdomains
match '/user' => 'users#index'
</code>```

to:

```<code>devise_for :users
namespace :user do
  root :to => "subdomains#index"
end
resources :subdomains
match '/user' => 'users#index', :controller => :users
</code>```

The thought was that maybe production environment did not like a user#index... so i changed it to subdomains#index.  I can get /subdomains no problem. so the actual page will show, it's the route that is fudged... any thoughts?

setup: rails 3.0.3, devise 1.1.5 (and was 1.1.3 upgraded, same problem)

答:
I used

```<code>devise_for :users do
   match 'user' => "users#index", :as => :user_root, :constraints => { :domain => SITE_DOMAIN}
end
</code>```

In each of your development.rb or production.rb files you would have a SITE_DOMAIN constant so like:

```<code>::SITE_DOMAIN = "lvh.me"
#in development.rb I was using subdomains with the helpful lvh.me google it.
</code>```

or in production.rb

```<code>::SITE_DOMAIN = "mydomain.com"
</code>```

Again i needed subdomains, so this worked for me.

The devise wiki did not work for me.  Once i have time i will update that too, or submit a ticket, but this is just google juice for those that need it.

Body:
weird, i know but using user_root_path in production does not work.  When i click on the link myapp.com/user i get a 404 page.

The log file doesn't show spit but a failed attempt:

Started GET "/user" for 123.125.146.23 at 2011-01-19 19:40:45 +0000

ActionController::RoutingError (uninitialized constant User::UsersController):

Now the only way to see something about this unitialized constant is to turn on rails c and type the constant into the console.  Here is what happens:

ruby-1.9.2-p136 :005 > User::UsersController
(irb):5: warning: toplevel constant UsersController referenced by User::UsersController
=> UsersController

Now some digging found that this toplevel warning could be messing with it. But the log says bubkiss.

So i changed the route file from:

  devise_for :users
namespace :user do
  root :to => "users#index"
end
resources :subdomains
match '/user' => 'users#index'

to:

devise_for :users
namespace :user do
  root :to => "subdomains#index"
end
resources :subdomains
match '/user' => 'users#index', :controller => :users

The thought was that maybe production environment did not like a user#index... so i changed it to subdomains#index.  I can get /subdomains no problem. so the actual page will show, it's the route that is fudged... any thoughts?

setup: rails 3.0.3, devise 1.1.5 (and was 1.1.3 upgraded, same problem)

Body:
I used

devise_for :users do
   match 'user' => "users#index", :as => :user_root, :constraints => { :domain => SITE_DOMAIN}
end

In each of your development.rb or production.rb files you would have a SITE_DOMAIN constant so like:

::SITE_DOMAIN = "lvh.me"
#in development.rb I was using subdomains with the helpful lvh.me google it.

or in production.rb

::SITE_DOMAIN = "mydomain.com"

Again i needed subdomains, so this worked for me.

The devise wiki did not work for me.  Once i have time i will update that too, or submit a ticket, but this is just google juice for those that need it.


问:
Pandas rank method dense but skip a number
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

```<code>import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df
</code>```

it looks like:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0
</code>```

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0
</code>```

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0
</code>```

答:
Use a combination of groupby and sort_values

```<code>g = df.sort_values(
    ['HP', 'unit'], ascending=False
).groupby(['HP', 'unit'], sort=False)

df.assign(rank=g.ngroup().add(1).groupby(df.HP).transform('first'))

    HP N-D unit  rank
0   24  C1   UD     1
1   24  C2   UD     1
2   24  C3   UD     1
3    7  Q1   UC     2
4    7  Q2   UC     2
5    7  Q3   UC     2
6    7  D1   UA     2
7    7  D2   UA     2
8    7  D3   UA     2
9    5  E1   UB     4
10   5  E2   UB     4
11   5  E3   UB     4
</code>```

Another way using nunique and map

```<code>df.assign(
    rank=df.HP.map(
        df.sort_values(
            ['HP', 'unit'], ascending=False
        ).groupby(
            'HP', sort=False
        ).unit.nunique().shift().fillna(1).cumsum())
)

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0
</code>```

Body:
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df

it looks like:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0

Body:
Use a combination of groupby and sort_values

g = df.sort_values(
    ['HP', 'unit'], ascending=False
).groupby(['HP', 'unit'], sort=False)

df.assign(rank=g.ngroup().add(1).groupby(df.HP).transform('first'))

    HP N-D unit  rank
0   24  C1   UD     1
1   24  C2   UD     1
2   24  C3   UD     1
3    7  Q1   UC     2
4    7  Q2   UC     2
5    7  Q3   UC     2
6    7  D1   UA     2
7    7  D2   UA     2
8    7  D3   UA     2
9    5  E1   UB     4
10   5  E2   UB     4
11   5  E3   UB     4

Another way using nunique and map

df.assign(
    rank=df.HP.map(
        df.sort_values(
            ['HP', 'unit'], ascending=False
        ).groupby(
            'HP', sort=False
        ).unit.nunique().shift().fillna(1).cumsum())
)

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0


问:
Create xml with attribute value in xml format
How can values from a column in a table which is already in XML format be created as a value for an attribute in XML and retain its XML format (brackets, quotes, etc.)?  (It seems that the term for what is happening is that the characters (<, >, ") are being entitized.)  (SQL SERVER 2008 R2)

```<code>declare @T table (
ID int identity,
Col1 varchar(200),
Col2 varchar(max)
);

insert @T
select 'ABC', 'Value01'
union
select 'DEF', '<Ele01>A01</Ele01>'
union
select 'GHI', '<Elements><Ele02>A02</Ele02><Ele03>A03</Ele03></Elements>'
union
select 'JKL', '<Ele04 Att01="V01" Att02="V02" />';

select (
    select
        Col1 as '@Col1',
        Col2 as '@Col2'
    from @T
    for xml path(N'Item'), type
    ) as TValues
for xml path(N'T'), type, elements xsinil;
</code>```

The result should look like:

```<code><T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>
</code>```

This is the actual result:

```<code><T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>
</code>```

I have searched for an answer and these are some of the only links that I could find which deal with the issue somewhat:
http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/
How do I avoid character encoding when using "FOR XML PATH"?
https://www.red-gate.com/simple-talk/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/

I understand that I can replace the entitized characters after the fact but I believe there must be a better way.
I truly appreciate the help from someone who knows how to make this happen.

I apologize if my question fails to meet someone's standard.

答:
Your "should look like" XML is not XML at all -- that's why your tools are not helping you.  No conformant XML processor will help you generate non-well-formed XML.   You need to fix your XML design so that markup does not appear in attribute values, or you need to deal with the escaped version that your tools are providing you.

If you say you can't fix your XML design or deal with the escaped characters in your attribute values, then you have to live without the support of XML libraries and tools because they're not going to help you with your "should look like" format.  Prepare to operate at the level of character streams, and build up your own toolset.  Also prepare the consumers of your data that they won't be able to use XML tools either.

Bottom line: Don't generate non-well-formed XML.

Body:
How can values from a column in a table which is already in XML format be created as a value for an attribute in XML and retain its XML format (brackets, quotes, etc.)?  (It seems that the term for what is happening is that the characters (<, >, ") are being entitized.)  (SQL SERVER 2008 R2)

declare @T table (
ID int identity,
Col1 varchar(200),
Col2 varchar(max)
);

insert @T
select 'ABC', 'Value01'
union
select 'DEF', '<Ele01>A01</Ele01>'
union
select 'GHI', '<Elements><Ele02>A02</Ele02><Ele03>A03</Ele03></Elements>'
union
select 'JKL', '<Ele04 Att01="V01" Att02="V02" />';

select (
    select
        Col1 as '@Col1',
        Col2 as '@Col2'
    from @T
    for xml path(N'Item'), type
    ) as TValues
for xml path(N'T'), type, elements xsinil;

The result should look like:

<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>

This is the actual result:

<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TValues>
    <Item Col1="ABC" Col2="Value01" />
    <Item Col1="DEF" Col2="<Element01>A01</Element01>" />
    <Item Col1="GHI" Col2="<Elements><Element02>A02</Element02><Element03>A03</Element03></Elements>" />
    <Item Col1="JKL" Col2="<Element04 Att01="V01" Att02="V02" />" />
  </TValues>
</T>

I have searched for an answer and these are some of the only links that I could find which deal with the issue somewhat:
http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/
How do I avoid character encoding when using "FOR XML PATH"?
https://www.red-gate.com/simple-talk/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/

I understand that I can replace the entitized characters after the fact but I believe there must be a better way.
I truly appreciate the help from someone who knows how to make this happen.

I apologize if my question fails to meet someone's standard.


问:
CSS Image Split with Two Columns and a Split in the Center
I've looked a bit for this, and can't find it on SO. I basically have to put together a design as follows...

I'm using Bootstrap4 and I'm pretty good at CSS, and this is still giving me a bit of an issue. It should be full-screen, but I'd be open to giving it a max-width of 1400px.

My Idea: I currently had the idea of doing an element with the two elements on the side, and then use transform to rotate, and then put another element inside that has the background image and then uses transform to un-rotate it.

Here's my codepen to show what I've tried -
https://codepen.io/Gwapedwink/pen/ZaPvyo?editors=1100

```<code><section>
  <div class="image-splitter">
    <div class="inner left">
      <span style="background-image:url('http://placehold.it/940x240/222222/fff&text=left"></span>
    </div>
    <div class="inner right">
      <span style="background-image:url('http://placehold.it/940x240/b4d455/fff&text=right"></span>
    </div>
  </div>
</section>
</code>```

with the CSS of:

```<code>.image-splitter {
  background-color: #f1f1f1;
  position: relative; /* allows for absolute inside */
  height: 240px; /* height of this section is 240px */
  width: 100%;
  overflow: hidden; /* important for this idea */
}
.image-splitter .inner {
  position: absolute;
  width:1000px;
  height: 500px;
  top:50%;
  transform:translateY(-50%);
  -webkit-transform:translateY(-50%);
  overflow:hidden;
}
.image-splitter .inner.left {
  right: 50%;
  transform: rotate(5deg) translateY(-50%);
  z-index:10;
}
.image-splitter .inner.right {
  left: 50%;
  z-index:9;
}
.image-splitter .inner span {
  display: block;
  position: absolute;
  top: 50%;
  height:350px;
  width: 100%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  /* background image properties */
  background-position: center;
  background-size: cover;
}
.image-splitter .inner.left span {
  right: -50px;
  transform: rotate(-5deg) translateY(-50%);
  -webkit-transform: rotate(-5deg) translateY(-50%);
}
.image-splitter .inner.right span {
 left: 0;
}
</code>```

You can see that there are so many issues already, and I want to know if I'm missing something that's available. You can see that the text in the codepen should be level, but it isn't.

Thanks in advance!

答:
I think the vertical misalignment of the texts on the two sides is due to how placehold.it renders the text onto the images, and not related to your code. If you observe the two sample images –"left" and "right"– alone, you will notice that the baseline of the printed texts are already on different heights. Here is an overlay of the two images in question:

This thing happens because of the two strings have different overall heights. So by using texts of similar heights could solve your issue with the placeholder images. I would use square brackets to equalise the height like so: "[left]" and "[right]".

To demonstrate this, I used another approach to achieve your splitted image effect. This one makes use of the clip-path css property, which is not available on IE and Edge, so it might or might not work for you in production. On the other hand, this one simplifies the css big time.

body { margin: 0; }

.image-splitter {
    position: relative;
}
.inner {
    overflow: hidden;
    width: 60%;
    height: 240px;
    background: transparent no-repeat center center / cover;
}
.right {
    position: absolute;
    top: 0;
    right: 0;
    -webkit-clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);
    clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
    <div class="image-splitter">
        <div class="inner left" style="background-image:url('http://placehold.it/940x240/222222/fff&text=[left]">
        </div>

        <div class="inner right" style="background-image:url('http://placehold.it/940x240/b4d455/fff&text=[right]">
        </div>
    </div>
</section></code>```

Body:
I've looked a bit for this, and can't find it on SO. I basically have to put together a design as follows...

I'm using Bootstrap4 and I'm pretty good at CSS, and this is still giving me a bit of an issue. It should be full-screen, but I'd be open to giving it a max-width of 1400px.

My Idea: I currently had the idea of doing an element with the two elements on the side, and then use transform to rotate, and then put another element inside that has the background image and then uses transform to un-rotate it.

Here's my codepen to show what I've tried -
https://codepen.io/Gwapedwink/pen/ZaPvyo?editors=1100

with the CSS of:

.image-splitter {
  background-color: #f1f1f1;
  position: relative; /* allows for absolute inside */
  height: 240px; /* height of this section is 240px */
  width: 100%;
  overflow: hidden; /* important for this idea */
}
.image-splitter .inner {
  position: absolute;
  width:1000px;
  height: 500px;
  top:50%;
  transform:translateY(-50%);
  -webkit-transform:translateY(-50%);
  overflow:hidden;
}
.image-splitter .inner.left {
  right: 50%;
  transform: rotate(5deg) translateY(-50%);
  z-index:10;
}
.image-splitter .inner.right {
  left: 50%;
  z-index:9;
}
.image-splitter .inner span {
  display: block;
  position: absolute;
  top: 50%;
  height:350px;
  width: 100%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  /* background image properties */
  background-position: center;
  background-size: cover;
}
.image-splitter .inner.left span {
  right: -50px;
  transform: rotate(-5deg) translateY(-50%);
  -webkit-transform: rotate(-5deg) translateY(-50%);
}
.image-splitter .inner.right span {
 left: 0;
}

You can see that there are so many issues already, and I want to know if I'm missing something that's available. You can see that the text in the codepen should be level, but it isn't.

Thanks in advance!

Body:
I think the vertical misalignment of the texts on the two sides is due to how placehold.it renders the text onto the images, and not related to your code. If you observe the two sample images –"left" and "right"– alone, you will notice that the baseline of the printed texts are already on different heights. Here is an overlay of the two images in question:

This thing happens because of the two strings have different overall heights. So by using texts of similar heights could solve your issue with the placeholder images. I would use square brackets to equalise the height like so: "[left]" and "[right]".

To demonstrate this, I used another approach to achieve your splitted image effect. This one makes use of the clip-path css property, which is not available on IE and Edge, so it might or might not work for you in production. On the other hand, this one simplifies the css big time.

body { margin: 0; }

.image-splitter {
    position: relative;
}
.inner {
    overflow: hidden;
    width: 60%;
    height: 240px;
    background: transparent no-repeat center center / cover;
}
.right {
    position: absolute;
    top: 0;
    right: 0;
    -webkit-clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);
    clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);
}

<section>
    <div class="image-splitter">
        <div class="inner left" style="background-image:url('http://placehold.it/940x240/222222/fff&text=[left]">
        </div>

        <div class="inner right" style="background-image:url('http://placehold.it/940x240/b4d455/fff&text=[right]">
        </div>
    </div>
</section>


问:
Why is my Laravel factory unable to find my model?
I have created a Business model using artisan make:model command, a model factory and a seed method. When running my seed method I get the following error:

InvalidArgumentException Unable to locate factory with name [default]
  [App\Business].

Can someone tell me what I'm doing wrong?

Business model:

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];

    public function resources()
    {
        return $this->hasMany('App\Resource');
    }

}
</code>```

Business Factory

```<code>use Faker\Generator as Faker;

$factory->define(Business::class, function (Faker $faker) {
    return [
        'name' => $faker->company,
    ];
});
</code>```

Seeder Method

```<code>$business = factory(App\Business::class, 50)
                   ->create()
                   ->each(function ($u) {
                        $u->resources()->save(factory(App\Resource::class)->make());
                    });
</code>```

答:
Please, try to composer dump-autoload

Sometimes, it helps in such situations.

And make sure that when you declare such factory: $factory->define(Business::class,... your Business class is correctly imported, or consider changing it to App\Business.

Body:
I have created a Business model using artisan make:model command, a model factory and a seed method. When running my seed method I get the following error:

InvalidArgumentException Unable to locate factory with name [default]
  [App\Business].

Can someone tell me what I'm doing wrong?

Business model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];

    public function resources()
    {
        return $this->hasMany('App\Resource');
    }

}

Business Factory

use Faker\Generator as Faker;

$factory->define(Business::class, function (Faker $faker) {
    return [
        'name' => $faker->company,
    ];
});

Seeder Method

$business = factory(App\Business::class, 50)
                   ->create()
                   ->each(function ($u) {
                        $u->resources()->save(factory(App\Resource::class)->make());
                    });


问:
Send serial message to device until it is online
I am trying to update the firmware of a controller through a serial interface. To do this, I must send a reboot message to the controller (no problem there) and then send another message (the character 'w') THE MOMENT it starts up so that it may start up in write mode. This is easily done with the minicom utility by pressing w continuously while the device restarts.

I want to achieve this functionality using python code instead, but I can't figure out how to send a message until the device is up without throwing exceptions (since the device is not connected).

This is what I have tried, but it does not work (with pyserial):

```<code>def send_w(serial_port, baud_rate):
    msgw = "w_"
    ans = ""
    ser = serial.Serial(port=serial_port, baudrate=baud_rate,timeout = 10)
    ser.write(msgw)
    ans = ser.read(24)
    ser.close()
    print(ans)
    return ans

def set_firmware_version(serial_port, baud_rate):
    s = ""
    try:
        with serial.Serial(serial_port,baud_rate,timeout=1) as ser:
            msgr = "%reset "+sk+"_"
            ser.write(msgr)
            ser.close()
            print("reset")
    except (IOError) as e:
        print("Error in: set_firmware_version")
        print(e)
        return s
    time.sleep(1)
    send_w(serial_port, baud_rate)

set_firmware_version(sp,br)
</code>```

This gives the following error:

```<code>serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
</code>```

I also tried sending the messages in a loop with a short timeout, but had the same problem. Is there any way to send a message continuously and disregard exceptions if the device is not found?

Any help will be greatly appreciated.

Full Traceback:

```<code>Traceback (most recent call last):
  File "mc_config.py", line 69, in <module>
    set_firmware_version(sp,br)
  File "mc_config.py", line 64, in set_firmware_version
    send_w(serial_port, baud_rate)
  File "mc_config.py", line 46, in send_w
    ans = ser.read(24)
  File "/home/avidbots/.local/lib/python2.7/site-packages/serial/serialposix.py", line 501, in read
    'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
</code>```

(I am using ubuntu 16.04 and python 3)

答:
What if you put the excepting code into a try and then catch the exception with an except serial.serialutil.SerialException {...} block?

Clearly there's a significant window of time to submit the w ( otherwise the "press w" method wouldn't often work.)  Your requirement, then, would be to retry only the part of the code that's absolutely necessary to send the w, so that you send it quickly enough to "catch" the system in its bootup state.  Since the backtrace shows that the exceptions occurs in send_w, then you can add try/except blocks and a while loop around what is now one line at the end of set_firmware_version.

Instead of just this:

```<code>send_w(serial_port, baud_rate)
</code>```

Something like this might solve the problem:

```<code>while True:
  try:
    send_w(serial_port, baud_rate)
    break
  except serial.serialutil.SerialException:
    pass # retry
</code>```

You may need to change your imports to expose that exception, fyi.  And you may need to consider whether you're catching too many possible exceptions - it's possible that exception might also represent other errors that shouldn't be retried.  You might also need to add a small sleep time there - this is essentially a busy wait loop (https://en.wikipedia.org/wiki/Busy_waiting).

Body:
I am trying to update the firmware of a controller through a serial interface. To do this, I must send a reboot message to the controller (no problem there) and then send another message (the character 'w') THE MOMENT it starts up so that it may start up in write mode. This is easily done with the minicom utility by pressing w continuously while the device restarts.

I want to achieve this functionality using python code instead, but I can't figure out how to send a message until the device is up without throwing exceptions (since the device is not connected).

This is what I have tried, but it does not work (with pyserial):

def send_w(serial_port, baud_rate):
    msgw = "w_"
    ans = ""
    ser = serial.Serial(port=serial_port, baudrate=baud_rate,timeout = 10)
    ser.write(msgw)
    ans = ser.read(24)
    ser.close()
    print(ans)
    return ans

def set_firmware_version(serial_port, baud_rate):
    s = ""
    try:
        with serial.Serial(serial_port,baud_rate,timeout=1) as ser:
            msgr = "%reset "+sk+"_"
            ser.write(msgr)
            ser.close()
            print("reset")
    except (IOError) as e:
        print("Error in: set_firmware_version")
        print(e)
        return s
    time.sleep(1)
    send_w(serial_port, baud_rate)

set_firmware_version(sp,br)

This gives the following error:

serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

I also tried sending the messages in a loop with a short timeout, but had the same problem. Is there any way to send a message continuously and disregard exceptions if the device is not found?

Any help will be greatly appreciated.

Full Traceback:

Traceback (most recent call last):
  File "mc_config.py", line 69, in <module>
    set_firmware_version(sp,br)
  File "mc_config.py", line 64, in set_firmware_version
    send_w(serial_port, baud_rate)
  File "mc_config.py", line 46, in send_w
    ans = ser.read(24)
  File "/home/avidbots/.local/lib/python2.7/site-packages/serial/serialposix.py", line 501, in read
    'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

(I am using ubuntu 16.04 and python 3)

Body:
What if you put the excepting code into a try and then catch the exception with an except serial.serialutil.SerialException {...} block?

Clearly there's a significant window of time to submit the w ( otherwise the "press w" method wouldn't often work.)  Your requirement, then, would be to retry only the part of the code that's absolutely necessary to send the w, so that you send it quickly enough to "catch" the system in its bootup state.  Since the backtrace shows that the exceptions occurs in send_w, then you can add try/except blocks and a while loop around what is now one line at the end of set_firmware_version.

Instead of just this:

send_w(serial_port, baud_rate)

Something like this might solve the problem:

while True:
  try:
    send_w(serial_port, baud_rate)
    break
  except serial.serialutil.SerialException:
    pass # retry

You may need to change your imports to expose that exception, fyi.  And you may need to consider whether you're catching too many possible exceptions - it's possible that exception might also represent other errors that shouldn't be retried.  You might also need to add a small sleep time there - this is essentially a busy wait loop (https://en.wikipedia.org/wiki/Busy_waiting).


问:
Kotlin properties cannot be overridden with subinterface
In the following stripped down example, can you explain why the Kotlin compiler complains when overriding a that we restrict its type further(compiler message: Var-property type is 'B', which is not a type of overriden public abstract var a: A)

```<code>interface A

interface B : A {
    fun someFunc():Boolean
}

class C : B {
    override fun someFunc(): Boolean {
        return true
    }
}

abstract class D {
    abstract var a: A
}

class E : D() {
    override var a : B = C()

    fun otherFunc() {
        println(a.someFunc())
    }
}
</code>```

Furthermore, the compiler does not complain with the following snippet:

```<code>open class G

class H : G()

abstract class F {
    abstract val g: G
}

class I : F() {
    override var g : H = H()
}
</code>```

So I guess there is something going on with interface inheritance, which is not there with classes.

答:
Your first code snippet fails to compile, because otherwise weirdness like this would be possible:

```<code>val d: D = E()
d.a = object : A {}  // Some other sub-type of A, but definitely not a sub-type of B
</code>```

This is really a variant (no pun intended) of the lack of method parameter covariance in Java - especially given that a Kotlin var property is really just syntax sugar for a getter and setter method.

Conversely, your second snippet does compile because in this case, covariance isn't a problem - there's no setter in the base class (F) to be overriden, so the "weirdness" I described above isn't possible.

Body:
In the following stripped down example, can you explain why the Kotlin compiler complains when overriding a that we restrict its type further(compiler message: Var-property type is 'B', which is not a type of overriden public abstract var a: A)

interface A

interface B : A {
    fun someFunc():Boolean
}

class C : B {
    override fun someFunc(): Boolean {
        return true
    }
}

abstract class D {
    abstract var a: A
}

class E : D() {
    override var a : B = C()

    fun otherFunc() {
        println(a.someFunc())
    }
}

Furthermore, the compiler does not complain with the following snippet:

open class G

class H : G()

abstract class F {
    abstract val g: G
}

class I : F() {
    override var g : H = H()
}

So I guess there is something going on with interface inheritance, which is not there with classes.

Body:
Your first code snippet fails to compile, because otherwise weirdness like this would be possible:

val d: D = E()
d.a = object : A {}  // Some other sub-type of A, but definitely not a sub-type of B

This is really a variant (no pun intended) of the lack of method parameter covariance in Java - especially given that a Kotlin var property is really just syntax sugar for a getter and setter method.

Conversely, your second snippet does compile because in this case, covariance isn't a problem - there's no setter in the base class (F) to be overriden, so the "weirdness" I described above isn't possible.


问:
Rounding of Timestamp(9) in Oracle 11g stored procedure
The following procedure rounds the Timestamp(9) to a Timestamp(6):

```<code>CREATE
    TABLE MY_TABLE
    (
        MY_TIMESTAMP TIMESTAMP(9) NOT NULL
    )

CREATE OR REPLACE PROCEDURE "DB"."INSERT_ROW"
(myTimestamp IN TIMESTAMP)
AS
v_sys_error NUMBER := 0;
v_err INTEGER;
v_rc INTEGER;
BEGIN

BEGIN
    INSERT
INTO
    DB.INSERT_ROW
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        myTimestamp
    );
EXCEPTION
WHEN OTHERS THEN
v_sys_error := SQLCODE;
v_err := v_sys_error;
v_rc := SQL%ROWCOUNT;
RAISE;
END;

END;
</code>```

The call below will insert: 2007-12-12 12:23:45.123457000

```<code>@call DB.INSERT_ROW(TIMESTAMP '2007-12-12 12:23:45.123456789');
</code>```

Whereas the code below will insert this: 2007-12-12 12:23:45.123456789

```<code>INSERT
INTO
    DB.MY_TABLE
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        TIMESTAMP '2007-12-12 12:23:45.123456789'
    );
</code>```

How do I prevent this?  Using (myTimestamp IN TIMESTAMP(9)) fails to validate.

答:
One way to work around precision issues is to convert it (concat with '') or use to_char with a format when calling the PROC.

Take the input as VARCHAR2?

The conversion can take place in the INSERT within the proc to TIMESTAMP(9)

EDITED: Obviously I have assumed that your table field is correctly TIMESTAMP(9), but check that as well.

Body:
The following procedure rounds the Timestamp(9) to a Timestamp(6):

CREATE
    TABLE MY_TABLE
    (
        MY_TIMESTAMP TIMESTAMP(9) NOT NULL
    )

CREATE OR REPLACE PROCEDURE "DB"."INSERT_ROW"
(myTimestamp IN TIMESTAMP)
AS
v_sys_error NUMBER := 0;
v_err INTEGER;
v_rc INTEGER;
BEGIN

BEGIN
    INSERT
INTO
    DB.INSERT_ROW
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        myTimestamp
    );
EXCEPTION
WHEN OTHERS THEN
v_sys_error := SQLCODE;
v_err := v_sys_error;
v_rc := SQL%ROWCOUNT;
RAISE;
END;

END;

The call below will insert: 2007-12-12 12:23:45.123457000

@call DB.INSERT_ROW(TIMESTAMP '2007-12-12 12:23:45.123456789');

Whereas the code below will insert this: 2007-12-12 12:23:45.123456789

INSERT
INTO
    DB.MY_TABLE
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        TIMESTAMP '2007-12-12 12:23:45.123456789'
    );

How do I prevent this?  Using (myTimestamp IN TIMESTAMP(9)) fails to validate.


问:
Node promise error propagation between classes
Im currently in the process of making my code object oriented and have a problem with propagating promise errors between class instances.

Page.js:

```<code>exports.Page = class {
  constructor(link, limiter){
    this.link = link;
    //limiter is a instance of bottleneck, use it for rate limiting
    this.limiter = limiter;
  }

  setResults(){
    return new Request(this.link, this.limiter).makeRequest()
    .catch(err => {
      //i dont get here
      console.log(err);
    })
  }
}
</code>```

(is called and initiated from another class)

Request.js:

```<code>exports.Request = class {
  constructor(options, limiter){
    this.options = options;
    this.limiter = limiter;
  }

  makeRequest(){
    return this.limiter.schedule(this.request, this.options)
    .catch(err => {
      //i get here
      throw err;
    });
  }

  request(url){
    return rp("https://httpstat.us/500")
    .catch(err => {
      //i get here
      throw err;
    })
  }
}
</code>```

So my problem is, that the error wont be propagated back to the page.js but instead prints an unhandled rejection error in the console. I've tried running this without limiter.schedule but it doesnt make a difference. Would be great to get some pointers, cant figure it out.

答:
.catch() method is being used to handle Promises errors and rejections. It creates a new promise, so when you use throw inside it, then you create another unhandled Promise error.

The thing is, you can't trace where exactly error occurred with native JS.
You can use Promise.longStackTraces for Bluebird (a library) promises. Or things like zones.

Body:
Im currently in the process of making my code object oriented and have a problem with propagating promise errors between class instances.

Page.js:

exports.Page = class {
  constructor(link, limiter){
    this.link = link;
    //limiter is a instance of bottleneck, use it for rate limiting
    this.limiter = limiter;
  }

  setResults(){
    return new Request(this.link, this.limiter).makeRequest()
    .catch(err => {
      //i dont get here
      console.log(err);
    })
  }
}

(is called and initiated from another class)

Request.js:

exports.Request = class {
  constructor(options, limiter){
    this.options = options;
    this.limiter = limiter;
  }

  makeRequest(){
    return this.limiter.schedule(this.request, this.options)
    .catch(err => {
      //i get here
      throw err;
    });
  }

  request(url){
    return rp("https://httpstat.us/500")
    .catch(err => {
      //i get here
      throw err;
    })
  }
}

So my problem is, that the error wont be propagated back to the page.js but instead prints an unhandled rejection error in the console. I've tried running this without limiter.schedule but it doesnt make a difference. Would be great to get some pointers, cant figure it out.


问:
value of an option appended to a select ends with " before the fetched value ends
I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.

Here's the empty select:

```<code><select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>
</code>```

This is the jQuery code:

```<code>$('#SenderSelect').on('change', function() {
    $.ajax({
        type: "POST",
        url: 'operations/inner-operations/getNamesByService.php',
        data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
        success: function(data) {
            var responseObj = jQuery.parseJSON(data);
            console.log(responseObj);
            $.each(responseObj, function(i, value) {
                $("#SenderNames").append('<option value='+value+'>'+value+'</option>');
            });
        }
    });
});
</code>```

The appended option should look like this:

```<code><option value="First Second">First Second</option>
</code>```

However, it is appended like this:

```<code><option value="First" second="">First Second</option>
</code>```

答:
I just realised that I'm not closing the string properly. The append should be like this:

```<code>$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');
</code>```

the value tag must be wrapped by "".

Body:
I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.

Here's the empty select:

<select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>

This is the jQuery code:

$('#SenderSelect').on('change', function() {
    $.ajax({
        type: "POST",
        url: 'operations/inner-operations/getNamesByService.php',
        data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
        success: function(data) {
            var responseObj = jQuery.parseJSON(data);
            console.log(responseObj);
            $.each(responseObj, function(i, value) {
                $("#SenderNames").append('<option value='+value+'>'+value+'</option>');
            });
        }
    });
});

The appended option should look like this:

<option value="First Second">First Second</option>

However, it is appended like this:

<option value="First" second="">First Second</option>

Body:
I just realised that I'm not closing the string properly. The append should be like this:

$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');

the value tag must be wrapped by "".


问:
Push Pull Model in Web Development
I would like to create for myself a base core (or package) for handling interactions between the server side and client side.  My approach is this:

Set the time interval to every two seconds (arbitrarily picked)

Create a script on the PHP side.  This script will allow other PHP scripts to add functions to call (or remove them) to collect information that will be sent to the client.

Every 2 seconds, the client will call this PHP script to request the information.

When this occurs, the PHP script will call all added functions, store their data, and send all data back to the client.

The client will handle this data appropriately

I am not sure if this actually describes an implementation of the Push-Pull model, or of a similar, but different, model.  I imagine the "pushes" from the client to the server side would not need to be synchronized into this two second window.

The ultimate goal in all of this is for me to create a method in which the client side can remain up to date when displaying information that is likely to change while the browser window is open.

I would like to ask if this is a correct interpretation of the push pull model, if this is a suitable way to accomplish this goal, and if there is possibly a more suited paradigm for this goal.

答: PHP supports server sent events which sounds suitable for what you are trying to achieve</p>

Title: Push Pull Model in Web Development


问:
Java printing out alphabetically
I need my HashMap to print out alphabetically.
E.g Im making restaurant menu, with names of dishes and price.
I'm still learning these things but so far i realized that i will need HashMap due to fact that i will have certain item with both name and price.
Can i use something else, if yes what, if not how can i print just once for instance from avocado to zest of Lemon e.g. regardless of price.
I've seen some workarounds including integers but not with names.

Any help would be appreciated.

Thanks

答:
Just use tree map, it will sort items by natural order if their classes implement Comparable or if not you can specify Comparator, sample code:

```<code>package com.company;

import java.util.Map;

public class Main {

    public static void main(String[] args) {

        Map<String, Integer> map = new TreeMap<>();
        map.put("Pizza", 20);
        map.put("Spaghetti", 20);
        map.put("Ice Cream", 20);

        for (String s : map.keySet())
            System.out.println(s);
    }
}
</code>```

Output:

Ice Cream

Pizza

Spaghetti

Title: Java printing out alphabetically

Body:
Just use tree map, it will sort items by natural order if their classes implement Comparable or if not you can specify Comparator, sample code:

package com.company;

import java.util.Map;

public class Main {

    public static void main(String[] args) {

        Map<String, Integer> map = new TreeMap<>();
        map.put("Pizza", 20);
        map.put("Spaghetti", 20);
        map.put("Ice Cream", 20);

        for (String s : map.keySet())
            System.out.println(s);
    }
}

Output:

Ice Cream

Pizza

Spaghetti


问:
return a variable from ajax and php on success
I am using AJAX (jQuery) to post a form to user-ajax.php but the page actually needs to echo out a response such as "success". in ajax code im testing the response value if its equal to success im doing something but it's not working here is the php code

```<code>function ajaxlogin($config,$lang){
   //something
        $response = 'success';
        echo $response;

}
</code>```

the ajax code:

```<code>$(document).ready(function () {
    $("#login").click(function () {
        $("#login-status").show();
        var action = $("#lg-form").attr('action');
        var form_data = {
            action: action,
            username: $("#username").val(),
            password: $("#password").val(),
            is_ajax: 1
        };

        $.ajax({
            type: "POST",
            url: ajaxurl,
            data: form_data,
            success: function(response) {
                alert (response); //this alert show "success"
                if (response == 'success') {
                    $("#lg-form").slideUp('slow', function () {
                        $("#login-status").removeClass('info-notice').addClass('success-notice');
                        $("#login-status #login-status-message").html('Logged in success. Redirecting....');
                        location.reload();
                    });
                }
                else {
                    $("#login-status").removeClass('info-notice').addClass('error-notice');
                    $("#login-status #login-status-message").html(response);
                }
            }
        });
        return false;
    });
});
</code>```

My problem is that the alert show "success" but the "if (response == 'success')" instruction isn't executed it goes directly to else. normally 'success'== 'success'.

答: thx a lot for your help. I did exactly like you suggest console.log(response.length) and it shows 8. and i used if($.trim(response)=='success') and it's working. thx a lot for your support</p>

Body:
I am using AJAX (jQuery) to post a form to user-ajax.php but the page actually needs to echo out a response such as "success". in ajax code im testing the response value if its equal to success im doing something but it's not working here is the php code

function ajaxlogin($config,$lang){
   //something
        $response = 'success';
        echo $response;

}

the ajax code:

$(document).ready(function () {
    $("#login").click(function () {
        $("#login-status").show();
        var action = $("#lg-form").attr('action');
        var form_data = {
            action: action,
            username: $("#username").val(),
            password: $("#password").val(),
            is_ajax: 1
        };

        $.ajax({
            type: "POST",
            url: ajaxurl,
            data: form_data,
            success: function(response) {
                alert (response); //this alert show "success"
                if (response == 'success') {
                    $("#lg-form").slideUp('slow', function () {
                        $("#login-status").removeClass('info-notice').addClass('success-notice');
                        $("#login-status #login-status-message").html('Logged in success. Redirecting....');
                        location.reload();
                    });
                }
                else {
                    $("#login-status").removeClass('info-notice').addClass('error-notice');
                    $("#login-status #login-status-message").html(response);
                }
            }
        });
        return false;
    });
});

My problem is that the alert show "success" but the "if (response == 'success')" instruction isn't executed it goes directly to else. normally 'success'== 'success'.


问:
Pyodbc update cursor

Hi, I have a script on Python with SQL and I use fecthall() method to extract the elements I want and all great until there, because I want do modify two columns (datetime.date and datetime.time) to another timezone but I read docs and Its seems its not veare easy...

For now I have the next piece of code fetching the table and then trying to covert firts the date to another timezone, I know... Its a date but if in Spain now is 12am from 5/12/2017 in Mexico is 5pm from 04/12/2017 soooo...

BTW Im using pytz

```<code>cursor.execute(cadenaSQL + cadenaSQL_dos)
            su_dict[base+' hagent'] = cursor.fetchall()
            for row in su_dict[base+' hagent']:
                row = list(row)[0]
                print row
                row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico))
</code>```

For now I got this error with that code:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1535,
  in
      main()   File "cms_V2_30m.py", line 1444, in main
      select_hagent()   File "cms_V2_30m.py", line 211, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico)) TypeError: 'datetime.date' object
  is unsubscriptable

EDIT:

I think I´m close, the problem now is with row object, because it is a tuple... so it is inmutble, so I am trying to find a way to change this vale...

The New code:

```<code>    for row in su_dict[base + ' hagent']:
        print row[0]
        #list(row)
        #print my_date[0]
        #print datetime.datetime.combine(my_date[0], hoyUTC.time())
        row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico)
</code>```

The new error:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1538,
  in
      main()   File "cms_V2_30m.py", line 1447, in main
      select_hagent()   File "cms_V2_30m.py", line 214, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico) TypeError: 'tuple' object does not
  support item assignment

答: Looks like you are trying to chain the .astimezone() to the wrong entity. Maybe try row[0] = (hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico))

Title: Pyodbc update cursor

Body:
Hi, I have a script on Python with SQL and I use fecthall() method to extract the elements I want and all great until there, because I want do modify two columns (datetime.date and datetime.time) to another timezone but I read docs and Its seems its not veare easy...

For now I have the next piece of code fetching the table and then trying to covert firts the date to another timezone, I know... Its a date but if in Spain now is 12am from 5/12/2017 in Mexico is 5pm from 04/12/2017 soooo...

BTW Im using pytz

cursor.execute(cadenaSQL + cadenaSQL_dos)
            su_dict[base+' hagent'] = cursor.fetchall()
            for row in su_dict[base+' hagent']:
                row = list(row)[0]
                print row
                row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico))

For now I got this error with that code:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1535,
  in
      main()   File "cms_V2_30m.py", line 1444, in main
      select_hagent()   File "cms_V2_30m.py", line 211, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico)) TypeError: 'datetime.date' object
  is unsubscriptable

EDIT:

I think I´m close, the problem now is with row object, because it is a tuple... so it is inmutble, so I am trying to find a way to change this vale...

The New code:

    for row in su_dict[base + ' hagent']:
        print row[0]
        #list(row)
        #print my_date[0]
        #print datetime.datetime.combine(my_date[0], hoyUTC.time())
        row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico)

The new error:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1538,
  in
      main()   File "cms_V2_30m.py", line 1447, in main
      select_hagent()   File "cms_V2_30m.py", line 214, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico) TypeError: 'tuple' object does not
  support item assignment


问:
Window form execute a batch file
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

```<code> Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }
</code>```

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

```<code>public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }
</code>```

My main question is about process method,  can i execute it like that?  thanks

答:
Instead of invoking cmd.exe directly, you can set p.UseShellExecute.  This works with batch files, HTML files (launches the default browser), etc:

[NOTE: you need the @ sign in @"c:\temp" so the backslash isn't treated as an escape character.]

```<code>      Process p = new Process();
      p.StartInfo.FileName = @"c:\temp\xmlupdate.bat";
      p.StartInfo.WorkingDirectory = @"c:\temp";
      p.StartInfo.Arguments = textBox1.Text;
      p.UseShellExecute=true;
      p.Start();
</code>```

Title: Window form execute a batch file

Body:
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

 Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }

My main question is about process method,  can i execute it like that?  thanks

Body:
Instead of invoking cmd.exe directly, you can set p.UseShellExecute.  This works with batch files, HTML files (launches the default browser), etc:

[NOTE: you need the @ sign in @"c:\temp" so the backslash isn't treated as an escape character.]

      Process p = new Process();
      p.StartInfo.FileName = @"c:\temp\xmlupdate.bat";
      p.StartInfo.WorkingDirectory = @"c:\temp";
      p.StartInfo.Arguments = textBox1.Text;
      p.UseShellExecute=true;
      p.Start();