问:
How to print odd numbers in python
Here is my code.  I can't get the odd numbers to print just the odd numbers and I don't know how to not print the []'s on the output.  can someone help?</p>
```<code>size = 5

def get_numbers(num):
    numbers = []
    user_input = input('Enter {} integers:\n'.format(num))

    i = 0
    for token in user_input.split():
        number = int(token)     # Convert string input into integer
        numbers.append(number)  # Add to numbers list

        print(i, number)
        i += 1

    return numbers

def print_all_numbers(numbers):
    # Print numbers
    print('Numbers:', numbers)

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', nums)

def print_negative_numbers(numbers):
    # Print all negative numbers
    for neg in numbers:
        if neg <= 0:
            print('Negative numbers:', nums)

nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
</code>```

答:
If you want to print each individual odd number on its own line, just print number:

```<code>def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', number)
print_odd_numbers([1, 2, 3, 4, 5, 6])
</code>```

Output:

```<code>Odd numbers: 1
Odd numbers: 3
Odd numbers: 5
</code>```

If you want to print them like a normal list without the square brackets, you could use list-comprehension:

```<code>def print_odd_numbers(numbers):
    odd_numbers = [str(number) for number in numbers if number % 2 == 1]
    print('Odd numbers:', ', '.join(odd_numbers))
print_odd_numbers([1, 2, 3, 4, 5, 6])
</code>```

Output:

```<code>Odd numbers: 1, 3, 5
</code>```

Title: How to print odd numbers in python

Body:
Here is my code.  I can't get the odd numbers to print just the odd numbers and I don't know how to not print the []'s on the output.  can someone help?

size = 5

def get_numbers(num):
    numbers = []
    user_input = input('Enter {} integers:\n'.format(num))

    i = 0
    for token in user_input.split():
        number = int(token)     # Convert string input into integer
        numbers.append(number)  # Add to numbers list

        print(i, number)
        i += 1

    return numbers

def print_all_numbers(numbers):
    # Print numbers
    print('Numbers:', numbers)

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', nums)

def print_negative_numbers(numbers):
    # Print all negative numbers
    for neg in numbers:
        if neg <= 0:
            print('Negative numbers:', nums)

nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)

Body:
If you want to print each individual odd number on its own line, just print number:

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', number)
print_odd_numbers([1, 2, 3, 4, 5, 6])

Output:

Odd numbers: 1
Odd numbers: 3
Odd numbers: 5

If you want to print them like a normal list without the square brackets, you could use list-comprehension:

def print_odd_numbers(numbers):
    odd_numbers = [str(number) for number in numbers if number % 2 == 1]
    print('Odd numbers:', ', '.join(odd_numbers))
print_odd_numbers([1, 2, 3, 4, 5, 6])

Output:

Odd numbers: 1, 3, 5


来源: stackexchange

问:
Using e.printStackTrace() in Java
This is probably a newbie question, but hope you can help me. :) I have something like this:

```<code>try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}
</code>```

I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?

Thanks!

答:
It is just a recommendation. In eclipse it is fine - I believe it is just the IDE telling you that there are more conventional methods of doing it, like some of the other answers.
I find that it is useful for debugging, and that you should tell users when a fatal error is going to occur, to use a debug mode (like a console switch -d) to collect these logs.</p>

ContentLicense: CC BY-SA 3.0

Title: Using e.printStackTrace() in Java

Body:
This is probably a newbie question, but hope you can help me. :) I have something like this:

try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}

I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?

Thanks!


问:
I keep getting this error when I try to drive my contract with the scripts
I'm trying to use the scripts from the 'Learn-NEAR/starter--near-sdk-as' to drive my own contract but I keep getting this bash error:

Which account did you authorize for use with NEAR CLI?
Enter it here (if not redirected automatically):
Logged in as [ melchizedek.testnet ] with public key [ ed25519:BmiLAN... ] successfully

gitpod /workspace/MyAssemblyContract (main) $ ./scripts/1.dev-deploy.sh
bash: ./scripts/1.dev-deploy.sh: Permission denied
gitpod /workspace/MyAssemblyContract (main) $

Everything else was working fine up to this point.

答:
Finally found the issue: I didn't have execution privileges to that file.
Funny because I had execution privileges to all the other files except this one.

Fixed it using

```<code>chmod u+x 1.dev-deploy.sh
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Finally found the issue: I didn't have execution privileges to that file.
Funny because I had execution privileges to all the other files except this one.

Fixed it using

chmod u+x 1.dev-deploy.sh


问:
Can't print a 10 from .format() in superscript in tex in matplotlib
In matplotlib I'm creating a series of graphs using the following code.
When I plot it, the calculated superscripts from 1 to 9 render correctly, but in x^10 through x^12, only the 1 is in the superscript, the following digit (0, 1, 2) is on the same line as the x :

```<code>fig, axes = plt.subplots(nrows=2, ncols=6, figsize = (14,4.5))

for i, ax in enumerate(axes.flatten()):
    ax.set_title("$x^{}$".format(i+1))
    ax.plot(x,  x**(i+1))

fig.tight_layout();
</code>```

How do I get it to put all the digits in the superscript?

答:
Try replacing the line

    ax.set_title("$x^{}$".format(i+1))
```
<p>with</p>
<pre class="lang-py prettyprint-override"><code>    ax.set_title("$x^{{{}}}$".format(i+1))
</code>```

Matplotlib supports the use of (some) LaTeX expressions in axis titles. In LaTeX, the ^ character causes the next character, or group, to be formatted in superscript. When processing x^10, LaTeX will only set the 1 in superscript, leaving the 0 on the same line as the x, but when processing x^{10} it will set 10 in superscript because 10 is inside the group that the braces { and } surround.  (If it didn't do this, how would it know when the superscript ended?)

When .format encounters {{ and }}, it takes them to mean that you want an actual { or } character in the resulting string, and that they are not part of a placeholder it has to fill with a value.  The {} in the middle of "$x^{{{}}}$" is interpreted as the placeholder.

You end up with three pairs of braces, because it happens that { and } characters have a meaning to both the .format method and to LaTeX.

Body:
In matplotlib I'm creating a series of graphs using the following code.
When I plot it, the calculated superscripts from 1 to 9 render correctly, but in x^10 through x^12, only the 1 is in the superscript, the following digit (0, 1, 2) is on the same line as the x :

fig, axes = plt.subplots(nrows=2, ncols=6, figsize = (14,4.5))

for i, ax in enumerate(axes.flatten()):
    ax.set_title("$x^{}$".format(i+1))
    ax.plot(x,  x**(i+1))

fig.tight_layout();

How do I get it to put all the digits in the superscript?

Body:
Try replacing the line

    ax.set_title("$x^{}$".format(i+1))

with

    ax.set_title("$x^{{{}}}$".format(i+1))

Matplotlib supports the use of (some) LaTeX expressions in axis titles. In LaTeX, the ^ character causes the next character, or group, to be formatted in superscript. When processing x^10, LaTeX will only set the 1 in superscript, leaving the 0 on the same line as the x, but when processing x^{10} it will set 10 in superscript because 10 is inside the group that the braces { and } surround.  (If it didn't do this, how would it know when the superscript ended?)

When .format encounters {{ and }}, it takes them to mean that you want an actual { or } character in the resulting string, and that they are not part of a placeholder it has to fill with a value.  The {} in the middle of "$x^{{{}}}$" is interpreted as the placeholder.

You end up with three pairs of braces, because it happens that { and } characters have a meaning to both the .format method and to LaTeX.


问:
How can I POST directly to a database (similar to S3 post method)?
S3 allows you to post directly from browser to S3 bypassing your webserver (http://doc.s3.amazonaws.com/proposals/post.html). How can I upload files to a database in a similar fashion. I don't want to first stage the file in the webserver in a temporary file and then upload from there to the database. Thanks.
If I cannot avoid the webserver, then how do I just use the webserver for streaming and not actually land the file in the webserver before loading to the database.
Thanks.</p>

答:
A handful of DBMSes provide an HTTP connection design, but this is more the exception, not the rule.

That said, you can make the HTTP server a thin layer over a more traditional database, but this is probably a bad idea, because most databases assume that anything that can access them has full privilege to execute queries on them, and an application (read "web server") will act as a gatekeeper between the database and obnoxious or malicious clients.

Basically, You're going to do best using a database engine that does all of these things at a fine grained level, expressly designed for it.  MongoDB mostly addresses this exact use case.  Otherwise, you'll just have to write an application that sits between HTTP and the raw database connection.


问:
React Native fetch() Network Request Failed
When I create a brand new project using react-native init (RN version 0.29.1) and put a fetch in the render method to the public facebook demo movie API, it throws a Network Request Failed. There is a very useless stack trace and I can't debug network requests in the chrome console. Here is the fetch I'm sending:

```<code>fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });
</code>```

答:
Just add

```<code><uses-permission android:name="android.permission.INTERNET" />

    <application
      android:usesCleartextTraffic="true"
</code>```

in your AndroidManifest.xml and then replace fetch URL domain (localhost) with your IP address,

```<code>const dataRaw = await fetch('http://192.168.8.102:4000');
</code>```

Body:
When I create a brand new project using react-native init (RN version 0.29.1) and put a fetch in the render method to the public facebook demo movie API, it throws a Network Request Failed. There is a very useless stack trace and I can't debug network requests in the chrome console. Here is the fetch I'm sending:

fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });

Body:
Just add

<uses-permission android:name="android.permission.INTERNET" />

    <application
      android:usesCleartextTraffic="true"

in your AndroidManifest.xml and then replace fetch URL domain (localhost) with your IP address,

const dataRaw = await fetch('http://192.168.8.102:4000');


问:
xCode indenting driving be batty
I use xCode as my C editor for a small makefile project I'm working on. I keep noticing during Git commits that the whitespace is being changed on me. Here's an example:

```<code>void parse_key_values(Card *card, Errors *errors)
{
     char str[MAX_LINE_LEN];
     char key[MAX_LINE_LEN], value[MAX_LINE_LEN];
</code>```

Although difficult to see, if you cursor through this you will notice there is a single 2-space-wide tab and a space at the front of the lines. The tab is correct and what I would expect to see. I have no idea where the space is coming from. When I remove it manually and re-indent, it re-inserts it.

Here is my setup:

I have tried changing "prefer tabs" to "prefer spaces", and then goes ahead and inserts three spaces.

I suspected that it was counting the opening brace and indenting from there, but then noticed the same problem on code like this:

```<code>  if(split != NULL) {
     if (split[0] == '=') split++;
     if (split[0] == ':') split++;
</code>```

This is driving me crazy, and causing all sorts of annoyance during commits. Anyone know what's going on here?

答:
sigh

So right over on the right side of the screen is this little bit of UI:

Somehow, and it absolutely was not deliberate, the second of those two settings was changed to "3", so xcode was doing precisely what it was told to do.

Having never used that field, ever, I have never even looked at it. I'm still lost as to how I managed to change it.

Title: xCode indenting driving be batty

Body:
I use xCode as my C editor for a small makefile project I'm working on. I keep noticing during Git commits that the whitespace is being changed on me. Here's an example:

void parse_key_values(Card *card, Errors *errors)
{
     char str[MAX_LINE_LEN];
     char key[MAX_LINE_LEN], value[MAX_LINE_LEN];

Although difficult to see, if you cursor through this you will notice there is a single 2-space-wide tab and a space at the front of the lines. The tab is correct and what I would expect to see. I have no idea where the space is coming from. When I remove it manually and re-indent, it re-inserts it.

Here is my setup:

I have tried changing "prefer tabs" to "prefer spaces", and then goes ahead and inserts three spaces.

I suspected that it was counting the opening brace and indenting from there, but then noticed the same problem on code like this:

  if(split != NULL) {
     if (split[0] == '=') split++;
     if (split[0] == ':') split++;

This is driving me crazy, and causing all sorts of annoyance during commits. Anyone know what's going on here?


问:
Generically wrap member function of object to modify return type
Version restriction: C++17.

I'm trying to create a type capable of accepting a callable object of any type and wrapping one of its member functions (in this case, operator()) to take the same arguments, but modify (cast) the return type. An example follows:

```<code>template <typename Ret, typename Callable>
struct ReturnConverter : Callable
{
    ReturnConverter(Callable cb) : Callable(cb) { }

    Ret operator()(argsof(Callable::operator()) args)  // magic happens here
    {
        return static_cast<Ret>(Callable::operator()(std::forward<??>(args)); // how to forward?
    }
};

template <typename Ret, typename Callable>
auto make_converter(Callable cb)
{
    return ReturnConverter<Ret, Callable>(cb);
}

int main()
{
    auto callable = []() { return 1.0f; };
    auto converted = make_converter<int>(callable);

    auto x = converted(); // decltype(x) = int
}
</code>```

ReturnConverter can take an object and override that object's operator() to cast whatever it returns to Ret.

The problem is expressing the argument types of the wrapping function - they should be exactly the same as those of Callable::operator(). Using a variadic template with std::forward does not satisfy this goal, as it would modify the signature of the function (operator() now becomes a template where it wasn't before).

How can I express the argsof operator I've highlighted above?

Motivation: I'd like to modify the std::visit overload technique demonstrated in this article to be able to specify the desired return type from multiple lambda functors, so that I don't have to strictly match the return type in every lambda, for instance:

```<code>std::variant<int, float, void*> v = ...;
auto stringify = overload(
    [](int x) { return "int: " + std::to_string(x); },
    [](float x) { return "float: " + std::to_string(x); },
    [](auto v) { return "invalid type!"; }  // error! const char* != std::string
);
std::visit(stringify, v);
</code>```

With the change above, I'd be able to write something like auto stringify = overload<std::string>(...);

答:
I don't see a way to respond to your exact answer but... considering the "Motivation" of the question... I propose a wrapper for overload (a class that inherit from a class with one or more operator(), call the appropriate operator() from the base class and cast the return value to type Ret)

```<code>template <typename Ret, typename Wrpd>
struct wrp_overload : public Wrpd
{
  template <typename ... Args>
  Ret operator() (Args && ... as)
  { return Wrpd::operator()(std::forward<Args...>(as)...); }
};
</code>```

and, given the Ret type isn't deducible from the argument (the overload class) and that CTAD doesn't permit to explicit a template argumend, seems to me that a make_wrp_overload() function is required

```<code>template <typename Ret, typename ... Cs>
auto make_wrp_overload (Cs && ... cs)
{ return wrp_overload<Ret, overload<Cs...>>{{std::forward<Cs>(cs)...}}; }
</code>```

so your std::visit() call become

```<code>std::visit(make_wrp_overload<std::string>(
           [](int x) { return "int: " + std::to_string(x); },
           [](float x) { return "float: " + std::to_string(x); },
           [](auto v) { return "invalid type!"; }
), package);
</code>```

The following is a full compiling C++17 example

```<code>#include <iostream>
#include <variant>

template <typename ... Ts>
struct overload : public Ts...
{ using Ts::operator()...; };

// not required anymore (also C++17)
//template <typename ... Ts> overload(Ts...) -> overload<Ts...>;

template <typename Ret, typename Wrpd>
struct wrp_overload : public Wrpd
{
  template <typename ... Args>
  Ret operator() (Args && ... as)
  { return Wrpd::operator()(std::forward<Args...>(as)...); }
};

template <typename Ret, typename ... Cs>
auto make_wrp_overload (Cs && ... cs)
{ return wrp_overload<Ret, overload<Cs...>>{{std::forward<Cs>(cs)...}}; }

int main() {
    std::variant<int, float, void*> package;

    std::visit(make_wrp_overload<std::string>(
               [](int x) { return "int: " + std::to_string(x); },
               [](float x) { return "float: " + std::to_string(x); },
               [](auto v) { return "(no more) invalid type"; }
    ), package);
}
</code>```

Body:
Version restriction: C++17.

I'm trying to create a type capable of accepting a callable object of any type and wrapping one of its member functions (in this case, operator()) to take the same arguments, but modify (cast) the return type. An example follows:

template <typename Ret, typename Callable>
struct ReturnConverter : Callable
{
    ReturnConverter(Callable cb) : Callable(cb) { }

    Ret operator()(argsof(Callable::operator()) args)  // magic happens here
    {
        return static_cast<Ret>(Callable::operator()(std::forward<??>(args)); // how to forward?
    }
};

template <typename Ret, typename Callable>
auto make_converter(Callable cb)
{
    return ReturnConverter<Ret, Callable>(cb);
}

int main()
{
    auto callable = []() { return 1.0f; };
    auto converted = make_converter<int>(callable);

    auto x = converted(); // decltype(x) = int
}

ReturnConverter can take an object and override that object's operator() to cast whatever it returns to Ret.

The problem is expressing the argument types of the wrapping function - they should be exactly the same as those of Callable::operator(). Using a variadic template with std::forward does not satisfy this goal, as it would modify the signature of the function (operator() now becomes a template where it wasn't before).

How can I express the argsof operator I've highlighted above?

Motivation: I'd like to modify the std::visit overload technique demonstrated in this article to be able to specify the desired return type from multiple lambda functors, so that I don't have to strictly match the return type in every lambda, for instance:

std::variant<int, float, void*> v = ...;
auto stringify = overload(
    [](int x) { return "int: " + std::to_string(x); },
    [](float x) { return "float: " + std::to_string(x); },
    [](auto v) { return "invalid type!"; }  // error! const char* != std::string
);
std::visit(stringify, v);

With the change above, I'd be able to write something like auto stringify = overload<std::string>(...);

Body:
I don't see a way to respond to your exact answer but... considering the "Motivation" of the question... I propose a wrapper for overload (a class that inherit from a class with one or more operator(), call the appropriate operator() from the base class and cast the return value to type Ret)

template <typename Ret, typename Wrpd>
struct wrp_overload : public Wrpd
{
  template <typename ... Args>
  Ret operator() (Args && ... as)
  { return Wrpd::operator()(std::forward<Args...>(as)...); }
};

and, given the Ret type isn't deducible from the argument (the overload class) and that CTAD doesn't permit to explicit a template argumend, seems to me that a make_wrp_overload() function is required

template <typename Ret, typename ... Cs>
auto make_wrp_overload (Cs && ... cs)
{ return wrp_overload<Ret, overload<Cs...>>{{std::forward<Cs>(cs)...}}; }

so your std::visit() call become

std::visit(make_wrp_overload<std::string>(
           [](int x) { return "int: " + std::to_string(x); },
           [](float x) { return "float: " + std::to_string(x); },
           [](auto v) { return "invalid type!"; }
), package);

The following is a full compiling C++17 example

#include <iostream>
#include <variant>

template <typename ... Ts>
struct overload : public Ts...
{ using Ts::operator()...; };

// not required anymore (also C++17)
//template <typename ... Ts> overload(Ts...) -> overload<Ts...>;

template <typename Ret, typename Wrpd>
struct wrp_overload : public Wrpd
{
  template <typename ... Args>
  Ret operator() (Args && ... as)
  { return Wrpd::operator()(std::forward<Args...>(as)...); }
};

template <typename Ret, typename ... Cs>
auto make_wrp_overload (Cs && ... cs)
{ return wrp_overload<Ret, overload<Cs...>>{{std::forward<Cs>(cs)...}}; }

int main() {
    std::variant<int, float, void*> package;

    std::visit(make_wrp_overload<std::string>(
               [](int x) { return "int: " + std::to_string(x); },
               [](float x) { return "float: " + std::to_string(x); },
               [](auto v) { return "(no more) invalid type"; }
    ), package);
}


问:
Apply editbin in cmake
I'm trying to automatically call editbin with some options from within a cmake script after the executable has been build. So far without any luck.

is there any example for using editbin in cmake?

is there an example for using any executable in cmake after an executable has been build?

答:
You can use add_custom_command for build events, that is, it will be executed each time you build your target.

From the docs:

A POST_BUILD event may be used to post-process a binary after linking. For example, the code:

```<code>add_executable(myExe myExe.c)
add_custom_command(
  TARGET myExe POST_BUILD
  COMMAND someHasher -i "$<TARGET_FILE:myExe>"
                     -o "$<TARGET_FILE:myExe>.hash"
  VERBATIM)
</code>```

will run someHasher to produce a .hash file next to the executable after linking.

As for VERBATIM:

All arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add_custom_command even sees the arguments. Use of VERBATIM is recommended as it enables correct behavior. When VERBATIM is not given the behavior is platform specific because there is no protection of tool-specific special characters.

So in your case you first need to find an executble for editbin and then add your command:

```<code>add_custom_command(TARGET target_name POST_BUILD
    COMMAND "${editbin_exe} $<TARGET_FILE:target_name>")
</code>```

Where $<TARGET_FILE:target_name> is a generator expression which yields a path to the output binary file of target target_name.

Title: Apply editbin in cmake

Body:
You can use add_custom_command for build events, that is, it will be executed each time you build your target.

From the docs:

A POST_BUILD event may be used to post-process a binary after linking. For example, the code:

add_executable(myExe myExe.c)
add_custom_command(
  TARGET myExe POST_BUILD
  COMMAND someHasher -i "$<TARGET_FILE:myExe>"
                     -o "$<TARGET_FILE:myExe>.hash"
  VERBATIM)

will run someHasher to produce a .hash file next to the executable after linking.

As for VERBATIM:

All arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add_custom_command even sees the arguments. Use of VERBATIM is recommended as it enables correct behavior. When VERBATIM is not given the behavior is platform specific because there is no protection of tool-specific special characters.

So in your case you first need to find an executble for editbin and then add your command:

add_custom_command(TARGET target_name POST_BUILD
    COMMAND "${editbin_exe} $<TARGET_FILE:target_name>")

Where $<TARGET_FILE:target_name> is a generator expression which yields a path to the output binary file of target target_name.


问:
Java + Membase + spymemcached bulk operations
I am currently writing an application that requires bulk operations on a key/value store, at this time I am using membase.

spymemcached allows bulk get, but not bulk CAS or add; features that I think would be widely used if implemented.

At this point my code for a set of bulk operations is roughly as shown below.

"client" is a single MemcachedClient.

```<code>ArrayList<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
ArrayList<String> bulkGet = new ArrayList<String>();
for(int i=0; i<50; i++){
    String key = "Key_" + x + "_" + i;
    Future<Boolean> fut = client.add(key, 0, "Value_" + x + "_" + i);
    futures.add(fut);
    bulkGet.add(key);
}

int count = 0;
for(Future<Boolean> fut : futures){
    if(fut.get()==true){
        count++;
    }
}
System.out.println("Added " + count + " records.");

Map<String,Object> bulkGot = client.getBulk(bulkGet);
System.out.println("Retrieved " + bulkGot.size() + " records");
</code>```

The blocking call on Future.get() seems highly inefficient, is there a better way? In my actual scenario I'd like the ability to handle the futures as soon as they return (which may or may not be in the order in which they were sent?).

Also, are the following operations possible (or planning to be implemented)?

-Add or return existing value

-Delete if value equals a known value

-Set if value equals a known value

Thanks,
Marcus

答:
I'll try to address as many things here as possible.

Spymemcached allows bulk get, but not bulk CAS or add; features that I think would be widely used if implemented.

I completely agree here, but we probably wouldn't go about this by adding bulkAdd, bulkCas, ... functions to MemcachedClient. Spymemcached currently, by default optimizes get and set operations by sending them as bulk sets or bulk gets whenever it can. There are plans to extend this to all memcached operations, but it hasn't been done yet. When it is though it will happen behind the scenes and probably won't be directly available to spymemcached users.

The blocking call on Future.get() seems highly inefficient?

Yes, which I will address below, but also note that if this was a bulk operation then your code would still block for a little bit. With individual add operations you code would probably only block for the first operation because after that all of the other operations will have already finished so calls to Future.get() after the first call would return immediately.

So is there a better way?

You can extend the MemcachedClient class and copy one of the existing functions and add your own code to the callback function.

Also, are the following operations possible (or planning to be implemented)?

Spymemcached implements all of the functionality that memcached offers. The operations you mention can already be build with the the functionality Spymemcached has.

-Add or return existing value

add keyA. If it fails get keyA.

-Delete if value equals a known value

get keyA. If keyA equals a known value, delete keyA

-Set if value equals a known value

get keyA. If keyA equals a known value, set keyB.

If you are looking to get new options added to memcached then you should post your requests on memcached.org. To be honest though, the memcached guys like to keep the api as small as possible so I don't think it is likely these will get addded.

Body:
I am currently writing an application that requires bulk operations on a key/value store, at this time I am using membase.

spymemcached allows bulk get, but not bulk CAS or add; features that I think would be widely used if implemented.

At this point my code for a set of bulk operations is roughly as shown below.

"client" is a single MemcachedClient.

ArrayList<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
ArrayList<String> bulkGet = new ArrayList<String>();
for(int i=0; i<50; i++){
    String key = "Key_" + x + "_" + i;
    Future<Boolean> fut = client.add(key, 0, "Value_" + x + "_" + i);
    futures.add(fut);
    bulkGet.add(key);
}

int count = 0;
for(Future<Boolean> fut : futures){
    if(fut.get()==true){
        count++;
    }
}
System.out.println("Added " + count + " records.");

Map<String,Object> bulkGot = client.getBulk(bulkGet);
System.out.println("Retrieved " + bulkGot.size() + " records");

The blocking call on Future.get() seems highly inefficient, is there a better way? In my actual scenario I'd like the ability to handle the futures as soon as they return (which may or may not be in the order in which they were sent?).

Also, are the following operations possible (or planning to be implemented)?

-Add or return existing value

-Delete if value equals a known value

-Set if value equals a known value

Thanks,
Marcus


问:
Why is default required in importing JSON file in JS code
I have a JSON data which I can get from this API.
However when I copy the contents of this link into a local file and save it as JSON, and then import in in JS like:

```<code>import * as data from "./data.json" assert { type: "json" };

console.log(data)
</code>```

I am getting a module in my console where the default parameter contains my JSON object.

But when I do:

```<code>import * as data from "./data.json" assert { type: "json" };

console.log(data.default)
</code>```

Then only I can view my JSON object like normal, i.e. what would the output have been if I did:

async function populate() {

  const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  const request = new Request(requestURL);

  const response = await fetch(request);
  const superHeroes = await response.json();
  console.log(superHeroes)
}

populate();```

Why does this happen? And is there any better method of importing my JSON file so that I can access it in my code?

答:
This happens because the import * as line imports    an_entire_modules_contents where cause the absence of an explicit export default  the default property coincides with the content of your json file. If you want the data variable contains your json file you can use instead:

```<code>import {default as data} from "./data.json";
console.log(data); //<-- it will print the content of your json file
</code>```

Or the simple shorthand below:

```<code>import data from "./data.json";
</code>```

Body:
I have a JSON data which I can get from this API.
However when I copy the contents of this link into a local file and save it as JSON, and then import in in JS like:

import * as data from "./data.json" assert { type: "json" };

console.log(data)

I am getting a module in my console where the default parameter contains my JSON object.

But when I do:

import * as data from "./data.json" assert { type: "json" };

console.log(data.default)

Then only I can view my JSON object like normal, i.e. what would the output have been if I did:

async function populate() {

  const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  const request = new Request(requestURL);

  const response = await fetch(request);
  const superHeroes = await response.json();
  console.log(superHeroes)
}

populate();

Why does this happen? And is there any better method of importing my JSON file so that I can access it in my code?

Body:
This happens because the import * as line imports    an_entire_modules_contents where cause the absence of an explicit export default  the default property coincides with the content of your json file. If you want the data variable contains your json file you can use instead:

import {default as data} from "./data.json";
console.log(data); //<-- it will print the content of your json file

Or the simple shorthand below:

import data from "./data.json";


问:
is Key Sort, and thus a data structure to allocate keys to an object's members, a viable alternative to quicksort and merge sort and their variants
Learning about sorting algorithms... In a specialized case where the values in a list are incremented from 1 to n --> and thus the values become keys to their position in the list

```<code>GenerateNumbers(std::vector<int>& values){
     for(int i = 0; i < values.size(); i++)
          values.push_back(i+1);
}
</code>```

We then shuffle the list...

```<code>std::random_device rd;
std::mt19937 mt(rd());
std::shuffle(std::begin(values), std::end(values), mt);
</code>```

and sort, using the values as the index where they belong in the list...

```<code>void KeyIndexSort(std::vector<int> &values) {//Linear (0(n)) Time Complexity ---- constant (0(1)) Space Complexity

int indexStart = 0; //indexStart Begins at first element of List e.g [2][1][4][3] indexStart is at location [2]
int indexMid = (values.size() / 2); //indexMid Begins in middle of List e.g [2][1][4][3] indexMid is at location [4]

for (int i = 0; i < values.size(); i++) {
    if (values[indexMid] != indexMid + 1)//if value found in List[indexMid] is not equal to (indexMid + 1) Swap values
        Swap(values, indexMid);//e.g List = [2][1][4][3] indexMid starts at [4] Swap with [3]
                               //result =  [2][1][3][4]
    else {
        ShiftIndexRight(indexMid, values.size());//else indexMid is equal --> shift indexMid to the Right one Position
                                                 //e.g List = [2][1][3][4] indexMix in Position [3] shift indexMid to position [4]
    }

    if (values[indexStart] != indexStart + 1)//if value found in List[indexStart] is not equal to indexStart Swap values
        Swap(values, indexStart);//e.g List = [2][1][4][3] indexStart begins at [2] Swap with [1]
                                 //result = [1][2][4][3]
    else {
        ShiftIndexRight(indexStart, values.size());//else indexStart is equal --> shift indexStart to the right on Position
                                      //e.g List = [1][2][4][3] indexStart in Position [1] shift indexStart to position [2]
    }
}
</code>```

Helper Functions

```<code>void ShiftIndexRight(int &index, const int size) {
if (index < size - 1)//if index value is less than size of List
    ++index;//increment index --> e.g [1][2][3][4] index = [1] move to position [2]
}

void Swap(std::vector<int>& values, const int index) {
    int temp = values[index];
    values[index] = values[temp - 1];
    values[temp - 1] = temp;
}
</code>```

Being an 0(n) runtime it is faster than both quick sort and merge sort (and their variations)

Example runtime using 2 million non duplicate values ranging from 1 - 2 million over 30 shuffled runs:

Dual Pivot QuickSort with binary insertion sort cutoff at 15 (Sedgewick - Princeton implementation - shuffled n(log(n)) time, 0(1) space): 2.65 seconds on average

MergeSort with binary insertion sort cutoff at 15 (Sedgewick - Princeton implementation - n(log(n)) time, 0(n) space): 2.49 seconds on average

KeyIndexSort 0(n) time, 0(1) space: 0.33 seconds on average

Since KeyIndexSort was so quick I decided to run the algorithm again with more values...

10 million non duplicate values ranging from 1 - 10 million over 30 shuffled runs:

KeyIndexSort: 0(n) time, 0(1) space: 2.08 seconds on average

Still learning about time and space complexity calculations...

should we then consider a data structure when space is not an issue that holds an array of key values (index locations) for each member of the data structure... Note: on each insertion of a new object we would have to find the index for each member in that object (do a merge or quick sort for each member and change the indexes accordingly)

c = number of members in data structure... insertion of new object would take c * n(log(n)) time approximately... if my math is correct...

```<code>struct DataStructure{
    int index[2];//index location of members in struct

    std::string firstName;
    std::string lastName;
};
</code>```

we should then be able to sort the indexes of each member as opposed to the member itself... however if I am correct, this is 0(n)^2 space complexity for the data structure... that may be an issue...

as an aside, I have yet to find a data set, whether small or large, where Quick Sort outperforms Merge Sort, though they are close up to a point... However, again, with my implementation of Merge Sort it is 0(n) space complexity... thus, I rationalize the performance by noting that an increase in space complexity can decrease time complexity...

I have yet to study Tim Sort...

答:
If you store the data along with an index of the current positions, you are effectively storing a sorted data structure.

As you mentioned, insertion (and also removal) of data into your proposed structure is really inefficient. You need to sort at every single insertion. Normally, sorting is an operation you only have to do once.

If you want a data struture that can be efficiently sorted all the time, consider using something like std::map, a red-black tree.

Alternatively, you can store the data in a sorted vector. Then insertion takes linear time per member which is still more efficient than your O(n log n) per insertion.

Body:
Learning about sorting algorithms... In a specialized case where the values in a list are incremented from 1 to n --> and thus the values become keys to their position in the list

GenerateNumbers(std::vector<int>& values){
     for(int i = 0; i < values.size(); i++)
          values.push_back(i+1);
}

We then shuffle the list...

std::random_device rd;
std::mt19937 mt(rd());
std::shuffle(std::begin(values), std::end(values), mt);

and sort, using the values as the index where they belong in the list...

void KeyIndexSort(std::vector<int> &values) {//Linear (0(n)) Time Complexity ---- constant (0(1)) Space Complexity

int indexStart = 0; //indexStart Begins at first element of List e.g [2][1][4][3] indexStart is at location [2]
int indexMid = (values.size() / 2); //indexMid Begins in middle of List e.g [2][1][4][3] indexMid is at location [4]

for (int i = 0; i < values.size(); i++) {
    if (values[indexMid] != indexMid + 1)//if value found in List[indexMid] is not equal to (indexMid + 1) Swap values
        Swap(values, indexMid);//e.g List = [2][1][4][3] indexMid starts at [4] Swap with [3]
                               //result =  [2][1][3][4]
    else {
        ShiftIndexRight(indexMid, values.size());//else indexMid is equal --> shift indexMid to the Right one Position
                                                 //e.g List = [2][1][3][4] indexMix in Position [3] shift indexMid to position [4]
    }

    if (values[indexStart] != indexStart + 1)//if value found in List[indexStart] is not equal to indexStart Swap values
        Swap(values, indexStart);//e.g List = [2][1][4][3] indexStart begins at [2] Swap with [1]
                                 //result = [1][2][4][3]
    else {
        ShiftIndexRight(indexStart, values.size());//else indexStart is equal --> shift indexStart to the right on Position
                                      //e.g List = [1][2][4][3] indexStart in Position [1] shift indexStart to position [2]
    }
}

Helper Functions

void ShiftIndexRight(int &index, const int size) {
if (index < size - 1)//if index value is less than size of List
    ++index;//increment index --> e.g [1][2][3][4] index = [1] move to position [2]
}

void Swap(std::vector<int>& values, const int index) {
    int temp = values[index];
    values[index] = values[temp - 1];
    values[temp - 1] = temp;
}

Being an 0(n) runtime it is faster than both quick sort and merge sort (and their variations)

Example runtime using 2 million non duplicate values ranging from 1 - 2 million over 30 shuffled runs:

Dual Pivot QuickSort with binary insertion sort cutoff at 15 (Sedgewick - Princeton implementation - shuffled n(log(n)) time, 0(1) space): 2.65 seconds on average

MergeSort with binary insertion sort cutoff at 15 (Sedgewick - Princeton implementation - n(log(n)) time, 0(n) space): 2.49 seconds on average

KeyIndexSort 0(n) time, 0(1) space: 0.33 seconds on average

Since KeyIndexSort was so quick I decided to run the algorithm again with more values...

10 million non duplicate values ranging from 1 - 10 million over 30 shuffled runs:

KeyIndexSort: 0(n) time, 0(1) space: 2.08 seconds on average

Still learning about time and space complexity calculations...

should we then consider a data structure when space is not an issue that holds an array of key values (index locations) for each member of the data structure... Note: on each insertion of a new object we would have to find the index for each member in that object (do a merge or quick sort for each member and change the indexes accordingly)

c = number of members in data structure... insertion of new object would take c * n(log(n)) time approximately... if my math is correct...

struct DataStructure{
    int index[2];//index location of members in struct

    std::string firstName;
    std::string lastName;
};

we should then be able to sort the indexes of each member as opposed to the member itself... however if I am correct, this is 0(n)^2 space complexity for the data structure... that may be an issue...

as an aside, I have yet to find a data set, whether small or large, where Quick Sort outperforms Merge Sort, though they are close up to a point... However, again, with my implementation of Merge Sort it is 0(n) space complexity... thus, I rationalize the performance by noting that an increase in space complexity can decrease time complexity...

I have yet to study Tim Sort...


问:
Can i use or in .replace function?
I'm trying to make a temperature converter. It convert Celsius to Fahrenheit and vice versa. The code I wrote is:

```<code>user_input = input("Insert the temperature you would like to convert: ")
user_num = user_input.replace('F' or 'C', '')
user_temp = float(user_num)

if ('F' in user_input or 'f' in user_input):
  print(((user_temp - 32) * 5/9), 'C') # conversion from F to C

elif ('C' in user_input or 'c' in user_input):
  print(((user_temp * 9/5) + 32), 'F') # conversion fron C to F

else:
  print("Try again.")
</code>```

I can convert Fahrenheit to Celsius, but can't do the opposite.
When I try to convert c to f i get
   user_temp = float(user_num) ValueError: could not convert string to float: '36C'

Also, I want to make the code so it replaces either 'F' or 'f' and 'C' or 'c'.

What I can fix in order to make this work?

答:
```<code>user_num = user_input.replace('F' or 'C', '')
</code>```

Look at the line above: it will only search for 'F' since the or logic operator doesn't work the way you expected.

This will work instead:

```<code>for i in ['F', 'C']:
    user_num = user_input.replace(i, '')
</code>```

or also a double .replace call:

```<code>user_num = user_input.replace('F', '').replace('C', '')
</code>```

Oterwise you could consider a regex solution, as @LeopardShark suggested, that needs a module and is a less-beginner solution.

Title: Can i use or in .replace function?

Body:
I'm trying to make a temperature converter. It convert Celsius to Fahrenheit and vice versa. The code I wrote is:

user_input = input("Insert the temperature you would like to convert: ")
user_num = user_input.replace('F' or 'C', '')
user_temp = float(user_num)

if ('F' in user_input or 'f' in user_input):
  print(((user_temp - 32) * 5/9), 'C') # conversion from F to C

elif ('C' in user_input or 'c' in user_input):
  print(((user_temp * 9/5) + 32), 'F') # conversion fron C to F

else:
  print("Try again.")

I can convert Fahrenheit to Celsius, but can't do the opposite.
When I try to convert c to f i get
   user_temp = float(user_num) ValueError: could not convert string to float: '36C'

Also, I want to make the code so it replaces either 'F' or 'f' and 'C' or 'c'.

What I can fix in order to make this work?

Body:
user_num = user_input.replace('F' or 'C', '')

Look at the line above: it will only search for 'F' since the or logic operator doesn't work the way you expected.

This will work instead:

for i in ['F', 'C']:
    user_num = user_input.replace(i, '')

or also a double .replace call:

user_num = user_input.replace('F', '').replace('C', '')

Oterwise you could consider a regex solution, as @LeopardShark suggested, that needs a module and is a less-beginner solution.


问:
GitHub gh-pages to work with the app domain name?
I deployed a react app on gh-pages. The problem is that the URL, like https://username.io/react-app-name doesn't work. I'm running into a problem, because the app doesn't have a route to "react-app-name"...it has to be just "/" or "/users" etc. So by this kind of error loads a "not found" page. The not found has a go back home button, which takes me to the homepage "/", and from there the app works. How can I resolve this problem?
Sorry for my bad English, hopefully you get it what I want to ask.</p>

答:
Are you using React Router?
Having more info on your routing code and lib, or a link to your code would greatly help.

If you are indeed using React Router, I believe the basename property would help.

```<code>  <BrowserRouter basename="react-app-name">
    <Routes>
      <Route path="/" element={<App />}>
        <Route path="users" element={<Users />} />
      </Route>
    </Routes>
  </BrowserRouter>
</code>```

Body:
Are you using React Router?
Having more info on your routing code and lib, or a link to your code would greatly help.

If you are indeed using React Router, I believe the basename property would help.

  <BrowserRouter basename="react-app-name">
    <Routes>
      <Route path="/" element={<App />}>
        <Route path="users" element={<Users />} />
      </Route>
    </Routes>
  </BrowserRouter>


问:
can I like fan page with application?
My question is if I can like a fan page with some graph api or something else?
here is my code:

```<code>$facebook->api('[fanpage_id]/likes', 'post',
array('access_token' => 'my_token'));
</code>```

and if I can do it by javascript SDK without the likebox?
also I gave the publish_stream permission.

答: No, this is not possible. Likes can only be registered and submitted via the like button.</p>

Title: can I like fan page with application?

Body:
My question is if I can like a fan page with some graph api or something else?
here is my code:

$facebook->api('[fanpage_id]/likes', 'post',
array('access_token' => 'my_token'));

and if I can do it by javascript SDK without the likebox?
also I gave the publish_stream permission.


问:
change state of button with document.getElementById("id").innerHTML
I have a button that display a certain text at first, but when i click it i would like it to display something else.

Here is the html input:

```<code><label class="button">
<input type="checkbox" id="control" onchange="changeState();">
<span class="button1" style="color: #4CAF50">Pull</span>
</label>
</code>```

and here is my function:

```<code>function changeState() {
  if (active == false) {
    active = true;
    start_timer();
    var myStop = "Stop"
    document.getElementById("control").innerHTML = myStop.fontcolor("#f00");
  } else {
    active = false;
    var myPull = "Pull"
    document.getElementById("control").innerHTML = myPull.fontcolor("#4CAF50");
  }
}
</code>```

When i used <button></button> instead of <input> it used to work but i need to use the input for something else. any idea what i would have to change to get it to work? I'm really new to HTML and JavaScript so I'm sort of clueless right now.

答:
the input is just a checkbox. As mentioned, there's no innerHTML.  It's the span you want to change.

let button = document.getElementById('button1')

function changeState() {
  let checked = document.getElementById('control').checked
  if (checked) {
     let myStop = "Stop"
     button.innerText = myStop;
     button.style.color='red'
  }else{
     let myPull = "Pull"
     button.innerText = myPull;
     button.style.color="#4CAF50";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="button">
   <input type="checkbox" id="control" onchange="changeState();">
   <span id="button1" style="color: #4CAF50">Pull</span>
</label></code>```

Body:
I have a button that display a certain text at first, but when i click it i would like it to display something else.

Here is the html input:

<input type="checkbox" id="control" onchange="changeState();">
Pull

and here is my function:

function changeState() {
  if (active == false) {
    active = true;
    start_timer();
    var myStop = "Stop"
    document.getElementById("control").innerHTML = myStop.fontcolor("#f00");
  } else {
    active = false;
    var myPull = "Pull"
    document.getElementById("control").innerHTML = myPull.fontcolor("#4CAF50");
  }
}

When i used <button></button> instead of <input> it used to work but i need to use the input for something else. any idea what i would have to change to get it to work? I'm really new to HTML and JavaScript so I'm sort of clueless right now.

Body:
the input is just a checkbox. As mentioned, there's no innerHTML.  It's the span you want to change.

let button = document.getElementById('button1')

function changeState() {
  let checked = document.getElementById('control').checked
  if (checked) {
     let myStop = "Stop"
     button.innerText = myStop;
     button.style.color='red'
  }else{
     let myPull = "Pull"
     button.innerText = myPull;
     button.style.color="#4CAF50";
  }
}

<label class="button">
   <input type="checkbox" id="control" onchange="changeState();">
   <span id="button1" style="color: #4CAF50">Pull</span>
</label>


答:
'F' or 'C' just evaluates to 'F'. I don’t think this is what you want. You can either replace twice:

user_num = user_input.replace('F', '').replace('C', '')
```
<p>or use a RegEx:</p>
<pre class="lang-py prettyprint-override"><code>import re

user_num = re.sub('F|C', '', user_input)
</code>```

I think your later 'f' and 'c' should probably be capitalised.

Title: Can i use or in .replace function?

Body:
'F' or 'C' just evaluates to 'F'. I don’t think this is what you want. You can either replace twice:

user_num = user_input.replace('F', '').replace('C', '')

or use a RegEx:

import re

user_num = re.sub('F|C', '', user_input)

I think your later 'f' and 'c' should probably be capitalised.


问:
sorting search result in django rest framework
I have written a search api for my website in django rest framework.
when you search a name (e.g. "jumanji") there might be more than one result for the search for many reasons. what I want is for the result to be ordered by the "rating" field or "releaseDate" field of the Film model.

here are my codes.

```<code># models.py
class Film(models.Model):
    filmID = models.AutoField(primary_key=True)
    title = models.CharField(max_length=150)
    duration = models.PositiveIntegerField()
    typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),])
    rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),])
    releaseDate = models.DateTimeField(null=True)
</code>```
```<code># serializers.py

class FilmSerializer(serializers.ModelSerializer):
    class Meta:
        model = Film
        fields = [
            "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating",
            "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory",
        ]
</code>```
```<code># views.py
'''Override get_search_fields method of SearchFilter'''
class DynamicSearch(filters.SearchFilter,):
    def get_search_fields(self,view, request):
        return request.GET.getlist('search_fields',[])

'''Override page_size_query_param attribute of PageNumberPagination'''
class CustomizePagination(PageNumberPagination):
    page_size_query_param = 'limit'

"""Pagination Handler"""
class PaginationHanlerMixin(object):
    @property
    def paginator(self):
        if not hasattr(self, '_paginator'):
            if self.pagination_class is  None:
                 self._paginator =None
            else :
                self._paginator = self.pagination_class()
        else :
            pass

        return self._paginator

    def  paginate_queryset(self,queryset):
        if self.paginator is None:
            return None

        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    def get_paginated_response(self,data):
        if self.paginator is None:
            raise "Paginator is None"
        return self.paginator.get_paginated_response(data)

class SearchFilm(APIView,PaginationHanlerMixin):
    authentication_classes = ()
    permission_classes = (AllowAny,)
    def __init__(self,):
        APIView.__init__(self)
        self.search_class=DynamicSearch
        self.pagination_class=CustomizePagination

    def filter_queryset(self,queryset):
      filterd_queryset=self.search_class().filter_queryset(self.request, queryset ,self)
      return filterd_queryset

    def get(self, request):
        films= Film.objects.all()
        filtered_queryset=self.filter_queryset(films)
        #Get appropriate results for each page
        results=self.paginate_queryset(filtered_queryset)
        if(results is not None):
            serializer=FilmSerializer(results,many=True)
            serializer=self.get_paginated_response(serializer.data)
        else :
            serializer=FilmSerializer(filtered_queryset,many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

答:
It as simple as using function order_by to QuerySet of your films. If you give few options, it will be firstfully ordered by leftmost, then second to the left etc.

```<code>films = Film.objects.all().order_by('rating', 'releaseDate')
</code>```

Body:
I have written a search api for my website in django rest framework.
when you search a name (e.g. "jumanji") there might be more than one result for the search for many reasons. what I want is for the result to be ordered by the "rating" field or "releaseDate" field of the Film model.

here are my codes.

# models.py
class Film(models.Model):
    filmID = models.AutoField(primary_key=True)
    title = models.CharField(max_length=150)
    duration = models.PositiveIntegerField()
    typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),])
    rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),])
    releaseDate = models.DateTimeField(null=True)

# serializers.py

class FilmSerializer(serializers.ModelSerializer):
    class Meta:
        model = Film
        fields = [
            "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating",
            "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory",
        ]

# views.py
'''Override get_search_fields method of SearchFilter'''
class DynamicSearch(filters.SearchFilter,):
    def get_search_fields(self,view, request):
        return request.GET.getlist('search_fields',[])

'''Override page_size_query_param attribute of PageNumberPagination'''
class CustomizePagination(PageNumberPagination):
    page_size_query_param = 'limit'

"""Pagination Handler"""
class PaginationHanlerMixin(object):
    @property
    def paginator(self):
        if not hasattr(self, '_paginator'):
            if self.pagination_class is  None:
                 self._paginator =None
            else :
                self._paginator = self.pagination_class()
        else :
            pass

        return self._paginator

    def  paginate_queryset(self,queryset):
        if self.paginator is None:
            return None

        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    def get_paginated_response(self,data):
        if self.paginator is None:
            raise "Paginator is None"
        return self.paginator.get_paginated_response(data)

class SearchFilm(APIView,PaginationHanlerMixin):
    authentication_classes = ()
    permission_classes = (AllowAny,)
    def __init__(self,):
        APIView.__init__(self)
        self.search_class=DynamicSearch
        self.pagination_class=CustomizePagination

    def filter_queryset(self,queryset):
      filterd_queryset=self.search_class().filter_queryset(self.request, queryset ,self)
      return filterd_queryset

    def get(self, request):
        films= Film.objects.all()
        filtered_queryset=self.filter_queryset(films)
        #Get appropriate results for each page
        results=self.paginate_queryset(filtered_queryset)
        if(results is not None):
            serializer=FilmSerializer(results,many=True)
            serializer=self.get_paginated_response(serializer.data)
        else :
            serializer=FilmSerializer(filtered_queryset,many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)

Body:
It as simple as using function order_by to QuerySet of your films. If you give few options, it will be firstfully ordered by leftmost, then second to the left etc.

films = Film.objects.all().order_by('rating', 'releaseDate')


问:
MongoDB - Convert values of each object in array
So I have documents following this structure :

username: "JohnDoe"
activities: [
    {
        name: "tennis",
        lastTime: <number>
    },
    {
        name: "soccer",
        lastTime: <number>
    }

]
```
<p>I want to convert the "lastTime" field from number to date in each activity object of my document.</p>
<p>I already did convert number into date in the past but it was a direct field like this :</p>
<pre class="lang-js prettyprint-override"><code>name: "Thomas",
birthday: <number>
</code>```

I used this query :

db.coll.updateOne({name: "Thomas"},[{$set: {"birthday": {$toDate: "$birthday"}}}])
```
<p>but if I try something similar now like :</p>
<pre class="lang-js prettyprint-override"><code>db.coll.updateOne({username: "JohnDoe"},[{$set: {"activities.lastTime": {$toDate: "$activities.lastTime"}}}])
</code>```

It returns "Unsupported conversion from array to date in $convert with no onError value".
I kind of get it but I don't know what do to...

答:
Ok so I kept digging and found that I needed to use $map.
https://docs.mongodb.com/manual/reference/operator/aggregation/map/

Here is it :

db.coll.updateOne(
    {username: "JohnDoe"},
    [{$set: {
        "activities": {
            $map: {
                input: "$activities",
                in: {
                    name: "$$this.name",
                    lastTime: {$toDate: "$$this.lastTime"},
                }
            }
        }
    }}]
)
```
<p><strong>EDIT :</strong></p>
<p>Or better, if I just want to change the "lastTime" field :</p>
<pre class="lang-js prettyprint-override"><code>db.coll.updateOne(
    {username: "JohnDoe"},
    [{$set: {
        "activities": {
            $map: {
                input: "$activities",
                in: {
                    $mergeObjects: ["$$this",{lastTime: {$toDate: "$$this.lastTime"}}]
                }
            }
        }
    }}]
)
</code>```

Body:
So I have documents following this structure :

username: "JohnDoe"
activities: [
    {
        name: "tennis",
        lastTime: <number>
    },
    {
        name: "soccer",
        lastTime: <number>
    }

]

I want to convert the "lastTime" field from number to date in each activity object of my document.

I already did convert number into date in the past but it was a direct field like this :

name: "Thomas",
birthday: <number>

I used this query :

db.coll.updateOne({name: "Thomas"},[{$set: {"birthday": {$toDate: "$birthday"}}}])

but if I try something similar now like :

db.coll.updateOne({username: "JohnDoe"},[{$set: {"activities.lastTime": {$toDate: "$activities.lastTime"}}}])

It returns "Unsupported conversion from array to date in $convert with no onError value".
I kind of get it but I don't know what do to...

Body:
Ok so I kept digging and found that I needed to use $map.
https://docs.mongodb.com/manual/reference/operator/aggregation/map/

Here is it :

db.coll.updateOne(
    {username: "JohnDoe"},
    [{$set: {
        "activities": {
            $map: {
                input: "$activities",
                in: {
                    name: "$$this.name",
                    lastTime: {$toDate: "$$this.lastTime"},
                }
            }
        }
    }}]
)

EDIT :

Or better, if I just want to change the "lastTime" field :

db.coll.updateOne(
    {username: "JohnDoe"},
    [{$set: {
        "activities": {
            $map: {
                input: "$activities",
                in: {
                    $mergeObjects: ["$$this",{lastTime: {$toDate: "$$this.lastTime"}}]
                }
            }
        }
    }}]
)


问:
JSON object return of an array of objects which contains the keys and its values
Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.

JSON file with data:
https://challenge.codingsans.com/beers.json

Output Example:

```<code>[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]
</code>```

//

I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)

```<code>request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);

        //final list

        var finalList = [];

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();
</code>```

答:
So basically, you can create a new array which will be final output(in our case let's say 'aBeerNBrands'). And you can push new object with required properties (like 'brand': string, ids: array) there.
And then you can loop over main array(in your case :'data') element and in nested loop you can check if that brand object is present in new array('aBeerNBrands') or not, if it is present then push the id to ids array present inside aBeerNBrands's object; else create new object inside 'aBeerNBrands' with required properties. Below code works fine for your requirement.</p>
```<code>request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
debugger;
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var aBeerNBrands = [];

        // Iteration

        for (var key in data) {
            if(aBeerNBrands.length > 0){
              for(var key2 in aBeerNBrands){
                  if(aBeerNBrands[key2].brand === data[key].brand){
                                            aBeerNBrands[key2].ids.push(data[key].id);
                      break;
                  }

                  if(key2 == aBeerNBrands.length - 1 && aBeerNBrands[key2].brand !== data[key].brand){
                    var oBrandObject = {
                     brand: data[key].brand,
                     ids: [data[key].id]
                    };
                    aBeerNBrands.push(oBrandObject);
                  }
              }
            } else{
              var oBrandObject = {
                 brand: data[key].brand,
                 ids: [data[key].id]
                };
                aBeerNBrands.push(oBrandObject);
              }

            // console.log(beerIDs);
            // console.log(beerBrand);
        }

        console.log(aBeerNBrands);

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();
</code>```

Body:
Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.

JSON file with data:
https://challenge.codingsans.com/beers.json

Output Example:

[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]

//

I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)

request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);

        //final list

        var finalList = [];

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();

Body:
So basically, you can create a new array which will be final output(in our case let's say 'aBeerNBrands'). And you can push new object with required properties (like 'brand': string, ids: array) there.
And then you can loop over main array(in your case :'data') element and in nested loop you can check if that brand object is present in new array('aBeerNBrands') or not, if it is present then push the id to ids array present inside aBeerNBrands's object; else create new object inside 'aBeerNBrands' with required properties. Below code works fine for your requirement.

request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
debugger;
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var aBeerNBrands = [];

        // Iteration

        for (var key in data) {
            if(aBeerNBrands.length > 0){
              for(var key2 in aBeerNBrands){
                  if(aBeerNBrands[key2].brand === data[key].brand){
                                            aBeerNBrands[key2].ids.push(data[key].id);
                      break;
                  }

                  if(key2 == aBeerNBrands.length - 1 && aBeerNBrands[key2].brand !== data[key].brand){
                    var oBrandObject = {
                     brand: data[key].brand,
                     ids: [data[key].id]
                    };
                    aBeerNBrands.push(oBrandObject);
                  }
              }
            } else{
              var oBrandObject = {
                 brand: data[key].brand,
                 ids: [data[key].id]
                };
                aBeerNBrands.push(oBrandObject);
              }

            // console.log(beerIDs);
            // console.log(beerBrand);
        }

        console.log(aBeerNBrands);

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();


问:
Is nesting iterators inside each other expectable where for loops would break
Would you consider it good or bad to nest iterators like this?

Context: for loop version breaks because I am appending synonyms at same time as using it in a for loop.

```<code>// HashSet inside HashMap
HashMap<String, HashSet<String>> synonyms = new HashMap<String, HashSet<String>>();

// loops through synonyms
Iterator word = synonyms.keySet().iterator();

while(word.hasNext()) {
    // loops through synonyms
    Iterator line = synonyms.get(word.next().toString()).iterator();

    while(line.hasNext()) {
        // adds to Synonyms, this breaks for loop version
        addToSynonyms(word, line.next())
    }
}
</code>```

Alternatively in the for loop versions I could make a copy of the HashMap<String, HashSet> and feed the copy to the for loop and append only the original but would the above be cleaner?

Thank you

Edited hopefully a better example below.

```<code>import java.util.Iterator;
import java.util.HashSet;
import java.util.HashMap;

// examples of looping through HashMap<String, HashSet<String>> numbersAndWords;
//
public class Example {

    HashMap<String, HashSet<String>> numbersAndWords;

    public Example() {
        numbersAndWords = new HashMap<String, HashSet<String>>();

        // data
        numbersAndWords.put("five", new HashSet<>());
        numbersAndWords.get("five").add(("1 2 3 4 5"));
    }

    /**
     * uses two iterators to loop through numbersAndWords and adds to numbersAndWords without breaking loops
     */
    public void exampleOne() {

        // loops through HashMap Strings of words "five"
        Iterator words = numbersAndWords.keySet().iterator();

        while(words.hasNext()) {

            // loops through HashSet Strings of numbers "1 2 3 4 5"
            Iterator numbers = numbersAndWords.get(words.next().toString()).iterator();
            while(numbers.hasNext()) {

                // data is arbitrary reason for exmaple is this appends
                // numbersAndWords which breaks the for loop
                // Their for I have to use an iterator but should I be using to
                // or have things in a different format
                numbersAndWords.put("three", new HashSet<>());
                numbersAndWords.get("three").add(("1, 2, 3"));

                numbers.next();
            }
        }
    }

    public static void main(String[] args) {
            Example example = new Example();
            example.exampleOne();
        }

}
</code>```

Currently looking into replacing the first itr with a for loop using HashMap.size() so it wont break when I append HashMap later.

Thank you

答:
The purpose of this code is still a bit vague even after the latest updates.

If some new data need to be created and appended to the original map numbersAndWords, and they depend somehow on the current state of the original map, then a new temporary map has to be created and populated (using enhanced for loops, Stream API with map/flatMap, whatever).  When done, the contents of this new map may be added to the original one, using Map::putAll:

public void exampleOne() {
    Map<String, HashSet<String>> toAppend = new HashMap<>();

    for (Map.Entry<String, HashSet<String>> me : numbersAndWords.entrySet()) {
        for (String str : me.getValue()) {
            System.out.println("Appending for key: " + me.getKey() + "; value=" + str);
            toAppend.computeIfAbsent("three", k -> new HashSet<>())
                    .add("1 2 3"); // or whatever is really needed
        }
    }
    numbersAndWords.putAll(toAppend);

    System.out.println(numbersAndWords);
}
```
<p>Assuming that the original map is set up like this:</p>
<pre class="lang-java prettyprint-override"><code>public Example() {
    numbersAndWords = new HashMap<String, HashSet<String>>();

    // data
    numbersAndWords.computeIfAbsent("five", k -> new HashSet<>()).add("1 2 3 4 5");
    numbersAndWords.computeIfAbsent("five", k -> new HashSet<>()).add("5 4 3 2 1");
    numbersAndWords.computeIfAbsent("four", k -> new HashSet<>()).add("1 2 3 4");
}
</code>```

The output is as follows when invoking new Example().exampleOne();:

```<code>Appending for key: four; value=1 2 3 4
Appending for key: five; value=1 2 3 4 5
Appending for key: five; value=5 4 3 2 1
{four=[1 2 3 4], five=[1 2 3 4 5, 5 4 3 2 1], three=[1 2 3]}
</code>```

However, such population of hardcoded values is pretty meaningless because no duplicate entries can be created in the map for a hardcoded key as well as adding the same values to a set is useless.

Body:
Would you consider it good or bad to nest iterators like this?

Context: for loop version breaks because I am appending synonyms at same time as using it in a for loop.

// HashSet inside HashMap
HashMap<String, HashSet<String>> synonyms = new HashMap<String, HashSet<String>>();

// loops through synonyms
Iterator word = synonyms.keySet().iterator();

while(word.hasNext()) {
    // loops through synonyms
    Iterator line = synonyms.get(word.next().toString()).iterator();

    while(line.hasNext()) {
        // adds to Synonyms, this breaks for loop version
        addToSynonyms(word, line.next())
    }
}

Alternatively in the for loop versions I could make a copy of the HashMap<String, HashSet> and feed the copy to the for loop and append only the original but would the above be cleaner?

Thank you

Edited hopefully a better example below.

import java.util.Iterator;
import java.util.HashSet;
import java.util.HashMap;

// examples of looping through HashMap<String, HashSet<String>> numbersAndWords;
//
public class Example {

    HashMap<String, HashSet<String>> numbersAndWords;

    public Example() {
        numbersAndWords = new HashMap<String, HashSet<String>>();

        // data
        numbersAndWords.put("five", new HashSet<>());
        numbersAndWords.get("five").add(("1 2 3 4 5"));
    }

    /**
     * uses two iterators to loop through numbersAndWords and adds to numbersAndWords without breaking loops
     */
    public void exampleOne() {

        // loops through HashMap Strings of words "five"
        Iterator words = numbersAndWords.keySet().iterator();

        while(words.hasNext()) {

            // loops through HashSet Strings of numbers "1 2 3 4 5"
            Iterator numbers = numbersAndWords.get(words.next().toString()).iterator();
            while(numbers.hasNext()) {

                // data is arbitrary reason for exmaple is this appends
                // numbersAndWords which breaks the for loop
                // Their for I have to use an iterator but should I be using to
                // or have things in a different format
                numbersAndWords.put("three", new HashSet<>());
                numbersAndWords.get("three").add(("1, 2, 3"));

                numbers.next();
            }
        }
    }

    public static void main(String[] args) {
            Example example = new Example();
            example.exampleOne();
        }

}

Currently looking into replacing the first itr with a for loop using HashMap.size() so it wont break when I append HashMap later.

Thank you

Body:
The purpose of this code is still a bit vague even after the latest updates.

If some new data need to be created and appended to the original map numbersAndWords, and they depend somehow on the current state of the original map, then a new temporary map has to be created and populated (using enhanced for loops, Stream API with map/flatMap, whatever).  When done, the contents of this new map may be added to the original one, using Map::putAll:

public void exampleOne() {
    Map<String, HashSet<String>> toAppend = new HashMap<>();

    for (Map.Entry<String, HashSet<String>> me : numbersAndWords.entrySet()) {
        for (String str : me.getValue()) {
            System.out.println("Appending for key: " + me.getKey() + "; value=" + str);
            toAppend.computeIfAbsent("three", k -> new HashSet<>())
                    .add("1 2 3"); // or whatever is really needed
        }
    }
    numbersAndWords.putAll(toAppend);

    System.out.println(numbersAndWords);
}

Assuming that the original map is set up like this:

public Example() {
    numbersAndWords = new HashMap<String, HashSet<String>>();

    // data
    numbersAndWords.computeIfAbsent("five", k -> new HashSet<>()).add("1 2 3 4 5");
    numbersAndWords.computeIfAbsent("five", k -> new HashSet<>()).add("5 4 3 2 1");
    numbersAndWords.computeIfAbsent("four", k -> new HashSet<>()).add("1 2 3 4");
}

The output is as follows when invoking new Example().exampleOne();:

Appending for key: four; value=1 2 3 4
Appending for key: five; value=1 2 3 4 5
Appending for key: five; value=5 4 3 2 1
{four=[1 2 3 4], five=[1 2 3 4 5, 5 4 3 2 1], three=[1 2 3]}

However, such population of hardcoded values is pretty meaningless because no duplicate entries can be created in the map for a hardcoded key as well as adding the same values to a set is useless.


问:
How to print odd numbers in python
Here is my code.  I can't get the odd numbers to print just the odd numbers and I don't know how to not print the []'s on the output.  can someone help?</p>
```<code>size = 5

def get_numbers(num):
    numbers = []
    user_input = input('Enter {} integers:\n'.format(num))

    i = 0
    for token in user_input.split():
        number = int(token)     # Convert string input into integer
        numbers.append(number)  # Add to numbers list

        print(i, number)
        i += 1

    return numbers

def print_all_numbers(numbers):
    # Print numbers
    print('Numbers:', numbers)

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', nums)

def print_negative_numbers(numbers):
    # Print all negative numbers
    for neg in numbers:
        if neg <= 0:
            print('Negative numbers:', nums)

nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
</code>```

答:
First you have to filter numbers - ie. using append() inside for-loop, and later you can dispay this nums

```<code>def print_odd_numbers(numbers):
    # --- before loop ---
    nums = []

    # --- loop ---
    for number in numbers:
        if number % 2 == 1:
            nums.append(number)

    # --- after loop ---
    print('Odd numbers:', nums)
</code>```

To display without [] you have to convert numbers to strings and create one string using join

```<code>    # --- after loop ---

    # convert numbers to strings
    nums = [str(s) for x in nums]

    # create single string
    nums_txt = ", ".join(nums)

    # display it
    print('Odd numbers:', nums_txt)
</code>```

BTW: you can all this make shorter using list comprehension like in @richardec answer - but at start my version can be more readable for beginners.

Title: How to print odd numbers in python

Body:
Here is my code.  I can't get the odd numbers to print just the odd numbers and I don't know how to not print the []'s on the output.  can someone help?

size = 5

def get_numbers(num):
    numbers = []
    user_input = input('Enter {} integers:\n'.format(num))

    i = 0
    for token in user_input.split():
        number = int(token)     # Convert string input into integer
        numbers.append(number)  # Add to numbers list

        print(i, number)
        i += 1

    return numbers

def print_all_numbers(numbers):
    # Print numbers
    print('Numbers:', numbers)

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', nums)

def print_negative_numbers(numbers):
    # Print all negative numbers
    for neg in numbers:
        if neg <= 0:
            print('Negative numbers:', nums)

nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)

Body:
First you have to filter numbers - ie. using append() inside for-loop, and later you can dispay this nums

def print_odd_numbers(numbers):
    # --- before loop ---
    nums = []

    # --- loop ---
    for number in numbers:
        if number % 2 == 1:
            nums.append(number)

    # --- after loop ---
    print('Odd numbers:', nums)

To display without [] you have to convert numbers to strings and create one string using join

    # --- after loop ---

    # convert numbers to strings
    nums = [str(s) for x in nums]

    # create single string
    nums_txt = ", ".join(nums)

    # display it
    print('Odd numbers:', nums_txt)

BTW: you can all this make shorter using list comprehension like in @richardec answer - but at start my version can be more readable for beginners.


问:
Could not post data to PHP
I am trying to post some data to the php but i could not send anything and see where the problem is.The codes looks fine to me.In other words, i could not reach inside of if statement.Codes;

```<code><form method="post" action="home.php" name="home" id="home">
    <label for="in_come">enter something: </label><input type="text" name="in_come" id="in_come" /><br/>
</code>```

```<code><?php
echo "outside if";
if(isset($_POST['in_come']))
{
    echo "inside if";
    $income = $_POST['in_come'];

    $registerquery = mysql_query("INSERT INTO income (income) VALUES ('".$in_come."')");
    if ($registerquery)
    {
        echo "sended";
    }
}
?>
</code>```

答:
You assign $income but later you use $in_come in your query

```<code>$income = $_POST['in_come'];

$registerquery = mysql_query("INSERT INTO dersler (income) VALUES ('".$in_come."')");
//-----------------------------------------------------------------^^^^^^^^^^^^^^^
</code>```

Incidentally, this won't hurt your PHP, but the you also have used  while the input's id is actually id='in_come'.

To debug the contents of your POST and verify that $_POST['in_come'] is set, use:

```<code>var_dump($_POST);
</code>```

Title: Could not post data to PHP

Body:
I am trying to post some data to the php but i could not send anything and see where the problem is.The codes looks fine to me.In other words, i could not reach inside of if statement.Codes;

<form method="post" action="home.php" name="home" id="home">
    enter something: <input type="text" name="in_come" id="in_come" />

<?php
echo "outside if";
if(isset($_POST['in_come']))
{
    echo "inside if";
    $income = $_POST['in_come'];

    $registerquery = mysql_query("INSERT INTO income (income) VALUES ('".$in_come."')");
    if ($registerquery)
    {
        echo "sended";
    }
}
?>

Body:
You assign $income but later you use $in_come in your query

$income = $_POST['in_come'];

$registerquery = mysql_query("INSERT INTO dersler (income) VALUES ('".$in_come."')");
//-----------------------------------------------------------------^^^^^^^^^^^^^^^

Incidentally, this won't hurt your PHP, but the you also have used <label for='income'> while the input's id is actually id='in_come'.

To debug the contents of your POST and verify that $_POST['in_come'] is set, use:

var_dump($_POST);


问:
Cannot load `swrast` and `iris` drivers in Fedora 35
Essentially, trying to write the following code results in the error below:

Code

from matplotlib import pyplot as plt
plt.plot([1,2,3,2,1])
plt.show()
```
<h4>Error</h4>
```libGL error: MESA-LOADER: failed to open iris: /home/xxx/.conda/envs/stat/lib/python3.8/site-packages/pandas/_libs/window/../../../../../libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /usr/lib64/dri/iris_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: iris
libGL error: MESA-LOADER: failed to open swrast: /home/xxx/.conda/envs/stat/lib/python3.8/site-packages/pandas/_libs/window/../../../../../libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /usr/lib64/dri/swrast_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: swrast
```

I found similar errors on StackOverflow but none were what is needed here.

答:
Short answer: export LD_PRELOAD=/usr/lib64/libstdc++.so.6

Long answer:

The underlying problem is that we have a piece of software that was built with an older C++ compiler. Part of the compiler is its implementation of libstdc++ which becomes part of the runtime requirements for anything built by the compiler. The software in question has, evidently, brought its own, older implementation of libstdc++ along for the ride, and given its libstdc++ precedence over the system's libstdc++. Typically, this is done via the $LD_LIBRARY_PATH environment variable. Unfortunately, /usr/lib64/dri/swrast_dri.so is a piece of system software built by the native compiler for that system, and it's more recent than the compiler that built the other software in question. The result of this is that the older compiler's libstdc++ gets loaded first, with its older, more limited symbol set. When it then wants to load swrast, this fails because swrast insists on having the level of compiler/runtime with which it was built. The solution to this whole mess is the force the system's (newer) libstdc++ into use and prevent the older libstdc++ from being brought into play. This is achieved via the code snippet export LD_PRELOAD=/usr/lib64/libstdc++.so.6 where we set the preload environment variable.

Body:
Essentially, trying to write the following code results in the error below:

Code

from matplotlib import pyplot as plt
plt.plot([1,2,3,2,1])
plt.show()

Error

libGL error: MESA-LOADER: failed to open iris: /home/xxx/.conda/envs/stat/lib/python3.8/site-packages/pandas/_libs/window/../../../../../libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /usr/lib64/dri/iris_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: iris
libGL error: MESA-LOADER: failed to open swrast: /home/xxx/.conda/envs/stat/lib/python3.8/site-packages/pandas/_libs/window/../../../../../libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /usr/lib64/dri/swrast_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: swrast

I found similar errors on StackOverflow but none were what is needed here.


问:
What is the Difference between "\" and "/"?
For Example This Both are Opening same path

C:\Users\XYZ\Pictures

C:/Users/XYZ/Pictures/

答: More programs use the backslash.</p>

Body: More programs use the backslash.


问:
Android Room Kotlin: entities with non data classes
Regarding to classes that can/may be used for entities in room whith Kotlin,

Is it mandatory to use data classes? Or could I use 'normal classes', i.e., the ones I use for the 'bussiness logic'

In case data classes are mandatory: can I add functionality to what they have by default? i.e, can I add functions (for whatever taks they may need) to them?

The documentation doesn't say anything about limiting entities to data classes (although each and every code snippet use a data class).

Thanks.

答:
Is it mandatory to use data classes?

No, you can use either including a mix.

data classes are a convenience class

can I add functionality to what they have by default?

Yes.

Perhaps consider the following:-

```<code>@Entity
class Table1 {
    @PrimaryKey
    var id: Long? = null
    var name: String = ""
    @Ignore
    var notAColumnInTheTable = false

    constructor(){}

    @Ignore
    constructor(name: String) {
        this.id = null
        this.name = name
        this.notAColumnInTheTable = true
    }

    fun getIdAndName(): String {
        return id.toString() + ":" + name
    }
}
</code>```

and :-

```<code>@Entity
data class Table2(
    @PrimaryKey
    var id: Long? = null,
    var name: String,
    @Ignore
    var notAColumnInTheTable: Boolean = false
) {
    constructor(name: String) : this( id = null,name = name, notAColumnInTheTable = true)
    fun getIdAndName(): String {
        return id.toString() + ":" + name
    }
}
</code>```

basically they are the same.

Using :-

```<code>@Dao
abstract class Table1And2Dao {
    @Insert
    abstract fun insert(table1: Table1): Long
    @Insert
    abstract fun insert(table2: Table2): Long
    @Query("SELECT * FROM table1")
    abstract fun getAllFromTable1(): List<Table1>
    @Query("SELECT * FROM table2")
    abstract fun getAllFromTable2(): List<Table2>
}
</code>```

note the use of an abstract class rather than the normally see interface

along with a suitable @Database annotated class, in this case one that has a function that returns an instance of the built database and for convenience/brevity allows running on the main thread.

Then using :-

```<code>    var db = AppDatabase.getDatabase(this)
    var dao = db.getTable1AndTable2Dao()

    dao.insert(Table1("TABLE1_1"))
    dao.insert(Table2("TABLE2_1"))
    for(t1: Table1 in dao.getAllFromTable1()) {
        Log.d("DBINFO","Name is ${t1.name} ID is ${t1.id} NotAColumnInTable is ${t1.notAColumnInTheTable} idandname = ${t1.getIdAndName()}")
    }
    for(t2: Table2 in dao.getAllFromTable2()) {
        Log.d("DBINFO","Name is ${t2.name} ID is ${t2.id} NotAColumnInTable is ${t2.notAColumnInTheTable} idandname = ${t2.getIdAndName()}")
    }
</code>```

Results in the log including:-

```<code>D/DBINFO: Name is TABLE1_1 ID is 1 NotAColumnInTable is true idandname = 1:TABLE1_1
D/DBINFO: Name is TABLE2_1 ID is 1 NotAColumnInTable is true idandname = 1:TABLE2_1
</code>```

Via App Inspection :-

and :-

Body:
Is it mandatory to use data classes?

No, you can use either including a mix.

data classes are a convenience class

can I add functionality to what they have by default?

Yes.

Perhaps consider the following:-

@Entity
class Table1 {
    @PrimaryKey
    var id: Long? = null
    var name: String = ""
    @Ignore
    var notAColumnInTheTable = false

    constructor(){}

    @Ignore
    constructor(name: String) {
        this.id = null
        this.name = name
        this.notAColumnInTheTable = true
    }

    fun getIdAndName(): String {
        return id.toString() + ":" + name
    }
}

and :-

@Entity
data class Table2(
    @PrimaryKey
    var id: Long? = null,
    var name: String,
    @Ignore
    var notAColumnInTheTable: Boolean = false
) {
    constructor(name: String) : this( id = null,name = name, notAColumnInTheTable = true)
    fun getIdAndName(): String {
        return id.toString() + ":" + name
    }
}

basically they are the same.

Using :-

@Dao
abstract class Table1And2Dao {
    @Insert
    abstract fun insert(table1: Table1): Long
    @Insert
    abstract fun insert(table2: Table2): Long
    @Query("SELECT * FROM table1")
    abstract fun getAllFromTable1(): List<Table1>
    @Query("SELECT * FROM table2")
    abstract fun getAllFromTable2(): List<Table2>
}

note the use of an abstract class rather than the normally see interface

along with a suitable @Database annotated class, in this case one that has a function that returns an instance of the built database and for convenience/brevity allows running on the main thread.

Then using :-

    var db = AppDatabase.getDatabase(this)
    var dao = db.getTable1AndTable2Dao()

    dao.insert(Table1("TABLE1_1"))
    dao.insert(Table2("TABLE2_1"))
    for(t1: Table1 in dao.getAllFromTable1()) {
        Log.d("DBINFO","Name is ${t1.name} ID is ${t1.id} NotAColumnInTable is ${t1.notAColumnInTheTable} idandname = ${t1.getIdAndName()}")
    }
    for(t2: Table2 in dao.getAllFromTable2()) {
        Log.d("DBINFO","Name is ${t2.name} ID is ${t2.id} NotAColumnInTable is ${t2.notAColumnInTheTable} idandname = ${t2.getIdAndName()}")
    }

Results in the log including:-

D/DBINFO: Name is TABLE1_1 ID is 1 NotAColumnInTable is true idandname = 1:TABLE1_1
D/DBINFO: Name is TABLE2_1 ID is 1 NotAColumnInTable is true idandname = 1:TABLE2_1

Via App Inspection :-

and :-


问:
filter array based on another arrays dynamically
I am new to JS. I want to apply filter on array based on other arrays. For example : Filter data array based on property names from colNames and values from Values array. The  colNames and Values arrays can have any length (not always 2).

var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "320800",
      "start_date": "2011\/04\/25",
      "office": "Edinburgh",
      "rating": "5421"
    },
    {
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "170750",
      "start_date": "2011\/07\/25",
      "office": "Tokyo",
      "rating": "8422"
    },
    {
      "name": "Garrett Winters",
      "position": "Analyst",
      "salary": "170750",
      "start_date": "2011\/07\/25",
      "office": "Tokyo",
      "rating": "8422"
    },
    {
      "name": "Ashton Cox",
      "position": "Junior Technical Author",
      "salary": "86000",
      "start_date": "2009\/01\/12",
      "office": "San Francisco",
      "rating": "1562"
    },
    {
      "name": "Cedric Kelly",
      "position": "Senior Javascript Developer",
      "salary": "433060",
      "start_date": "2012\/03\/29",
      "office": "Edinburgh",
      "rating": "6224"
    }
  ]

  var colNames = ['name', 'position']
  var Values = ['Garrett Winters', 'Accountant']```
</div>
</div>
</p>
<p><strong>Expected Outcome</strong></p>
```   [{
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "170750",
      "start_date": "2011\/07\/25",
      "office": "Tokyo",
      "rating": "8422"
    }]
```

答:
You could filter with the iteration of all keys and check with the values.

const
    data = [{ name: "Tiger Nixon", position: "System Architect", salary: "320800", start_date: "2011\\/04\\/25", office: "Edinburgh", rating: "5421" }, { name: "Garrett Winters", position: "Accountant", salary: "170750", start_date: "2011\\/07\\/25", office: "Tokyo", rating: "8422" }, { name: "Garrett Winters", position: "Analyst", salary: "170750", start_date: "2011\\/07\\/25", office: "Tokyo", rating: "8422" }, { name: "Ashton Cox", position: "Junior Technical Author", salary: "86000", start_date: "2009\\/01\\/12", office: "San Francisco", rating: "1562" }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: "433060", start_date: "2012\\/03\\/29", office: "Edinburgh", rating: "6224" }],
    cols = ['name', 'position'],
    values = ['Garrett Winters', 'Accountant'],
    result = data.filter(o => cols.every((k, i) => o[k] === values[i]));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I am new to JS. I want to apply filter on array based on other arrays. For example : Filter data array based on property names from colNames and values from Values array. The  colNames and Values arrays can have any length (not always 2).

var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "320800",
      "start_date": "2011\/04\/25",
      "office": "Edinburgh",
      "rating": "5421"
    },
    {
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "170750",
      "start_date": "2011\/07\/25",
      "office": "Tokyo",
      "rating": "8422"
    },
    {
      "name": "Garrett Winters",
      "position": "Analyst",
      "salary": "170750",
      "start_date": "2011\/07\/25",
      "office": "Tokyo",
      "rating": "8422"
    },
    {
      "name": "Ashton Cox",
      "position": "Junior Technical Author",
      "salary": "86000",
      "start_date": "2009\/01\/12",
      "office": "San Francisco",
      "rating": "1562"
    },
    {
      "name": "Cedric Kelly",
      "position": "Senior Javascript Developer",
      "salary": "433060",
      "start_date": "2012\/03\/29",
      "office": "Edinburgh",
      "rating": "6224"
    }
  ]

  var colNames = ['name', 'position']
  var Values = ['Garrett Winters', 'Accountant']

Expected Outcome

   [{
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "170750",
      "start_date": "2011\/07\/25",
      "office": "Tokyo",
      "rating": "8422"
    }]

Body:
You could filter with the iteration of all keys and check with the values.

const
    data = [{ name: "Tiger Nixon", position: "System Architect", salary: "320800", start_date: "2011\\/04\\/25", office: "Edinburgh", rating: "5421" }, { name: "Garrett Winters", position: "Accountant", salary: "170750", start_date: "2011\\/07\\/25", office: "Tokyo", rating: "8422" }, { name: "Garrett Winters", position: "Analyst", salary: "170750", start_date: "2011\\/07\\/25", office: "Tokyo", rating: "8422" }, { name: "Ashton Cox", position: "Junior Technical Author", salary: "86000", start_date: "2009\\/01\\/12", office: "San Francisco", rating: "1562" }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: "433060", start_date: "2012\\/03\\/29", office: "Edinburgh", rating: "6224" }],
    cols = ['name', 'position'],
    values = ['Garrett Winters', 'Accountant'],
    result = data.filter(o => cols.every((k, i) => o[k] === values[i]));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }