text:
Q: Why can't the switch statement be applied to strings? Compiling the following code gives the error message: type illegal.
int main()
{
    // Compilation error - switch expression of type illegal
    switch(std::string("raj"))
    {
    case"sda":
    }
}

You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar to switch on strings?

A: As mentioned previously, compilers like to build lookup tables that optimize switch statements to near O(1) timing whenever possible. Combine this with the fact that the C++ Language doesn't have a string type - std::string is part of the Standard Library which is not part of the Language per se.
I will offer an alternative that you might want to consider, I've used it in the past to good effect. Instead of switching over the string itself, switch over the result of a hash function that uses the string as input. Your code will be almost as clear as switching over the string if you are using a predetermined set of strings:
enum string_code {
    eFred,
    eBarney,
    eWilma,
    eBetty,
    ...
};

string_code hashit (std::string const& inString) {
    if (inString == "Fred") return eFred;
    if (inString == "Barney") return eBarney;
    ...
}

void foo() {
    switch (hashit(stringValue)) {
    case eFred:
        ...
    case eBarney:
        ...
    }
}

There are a bunch of obvious optimizations that pretty much follow what the C compiler would do with a switch statement... funny how that happens.

A: In C++ and C switches only work on integer types. Use an if else ladder instead. C++ could obviously have implemented some sort of swich statement for strings - I guess nobody thought it worthwhile, and I agree with them.

A: Why not? You can use switch implementation with equivalent syntax and same semantics.
The C language does not have objects and strings objects at all, but
strings in C is null terminated strings referenced by pointer.
The C++ language have possibility to make overload functions for
objects comparision or checking objects equalities.
As C as C++ is enough flexible to have such switch for strings for C
language and  for objects of any type that support comparaison or check
equality for C++ language. And modern C++11 allow to have this switch
implementation enough effective.
Your code will be like this:
std::string name = "Alice";

std::string gender = "boy";
std::string role;

SWITCH(name)
  CASE("Alice")   FALL
  CASE("Carol")   gender = "girl"; FALL
  CASE("Bob")     FALL
  CASE("Dave")    role   = "participant"; BREAK
  CASE("Mallory") FALL
  CASE("Trudy")   role   = "attacker";    BREAK
  CASE("Peggy")   gender = "girl"; FALL
  CASE("Victor")  role   = "verifier";    BREAK
  DEFAULT         role   = "other";
END

// the role will be: "participant"
// the gender will be: "girl"

It is possible to use more complicated types for example std::pairs or any structs or classes that support equality operations (or comarisions for quick mode).
Features

*

*any type of data which support comparisions or checking equality

*possibility to build cascading nested switch statemens.

*possibility to break or fall through case statements

*possibility to use non constatnt case expressions

*possible to enable quick static/dynamic mode with tree searching (for C++11)

Sintax differences with language switch is

*

*uppercase keywords

*need parentheses for CASE statement

*semicolon ';' at end of statements is not allowed

*colon ':' at CASE statement is not allowed

*need one of BREAK or FALL keyword at end of CASE statement

For C++97 language used linear search.
For C++11 and more modern possible to use quick mode wuth tree search where return statement in CASE becoming not allowed.
The C language implementation exists where char* type and zero-terminated string comparisions is used.
Read more about this switch implementation.

A: C++
constexpr hash function:
constexpr unsigned int hash(const char *s, int off = 0) {
    return !s[off] ? 5381 : (hash(s, off+1)*33) ^ s[off];
}

switch( hash(str) ){
case hash("one") : // do something
case hash("two") : // do something
}

Update:
The example above is C++11. There constexpr function must be with single statement. This was relaxed in next C++ versions.
In C++14 and C++17 you can use following hash function:
constexpr uint32_t hash(const char* data, size_t const size) noexcept{
    uint32_t hash = 5381;

    for(const char *c = data; c < data + size; ++c)
        hash = ((hash << 5) + hash) + (unsigned char) *c;

    return hash;
}

Also C++17 have std::string_view, so you can use it instead of const char *.
In C++20, you can try using consteval.

A: I think the reason is that in C strings are not primitive types, as tomjen said, think in a string as a char array, so you can not do things like:
switch (char[]) { // ...
switch (int[]) { // ...

A: In c++ strings are not first class citizens. The string operations are done through standard library. I think, that is the reason. Also, C++ uses branch table optimization to optimize the switch case statements. Have a look at the link.
http://en.wikipedia.org/wiki/Switch_statement

A: Late to the party, here's a solution I came up with some time ago, which completely abides to the requested syntax.
#include <uberswitch/uberswitch.hpp>

int main()
{
    uswitch (std::string("raj"))
    {
        ucase ("sda"): /* ... */ break;  //notice the parenthesis around the value.
    }
}

Here's the code: https://github.com/falemagn/uberswitch

A: The reason why has to do with the type system.  C/C++ doesn't really support strings as a type.  It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.
In order to generate the code for a switch statement the compiler must understand what it means for two values to be equal.  For items like ints and enums, this is a trivial bit comparison.  But how should the compiler compare 2 string values?  Case sensitive, insensitive, culture aware, etc ...  Without a full awareness of a string this cannot be accurately answered.
Additionally, C/C++ switch statements are typically generated as branch tables.  It's not nearly as easy to generate a branch table for a string style switch.

A: C++ 11 update of apparently not @MarmouCorp above but http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4067/Switch-on-Strings-in-C.htm
Uses two maps to convert between the strings and the class enum (better than plain enum because its values are scoped inside it, and reverse lookup for nice error messages).
The use of static in the codeguru code is possible with compiler support for initializer lists which means VS 2013 plus. gcc 4.8.1 was ok with it, not sure how much farther back it would be compatible.
/// <summary>
/// Enum for String values we want to switch on
/// </summary>
enum class TestType
{
    SetType,
    GetType
};

/// <summary>
/// Map from strings to enum values
/// </summary>
std::map<std::string, TestType> MnCTest::s_mapStringToTestType =
{
    { "setType", TestType::SetType },
    { "getType", TestType::GetType }
};

/// <summary>
/// Map from enum values to strings
/// </summary>
std::map<TestType, std::string> MnCTest::s_mapTestTypeToString
{
    {TestType::SetType, "setType"},
    {TestType::GetType, "getType"},
};

...
std::string someString = "setType";
TestType testType = s_mapStringToTestType[someString];
switch (testType)
{
    case TestType::SetType:
        break;

    case TestType::GetType:
        break;

    default:
        LogError("Unknown TestType ", s_mapTestTypeToString[testType]);
}

A: You could put the strings in an array and use a constexpr to convert them to indices at compile time.
constexpr const char* arr[] = { "bar", "foo" };
constexpr int index(const char* str) { /*...*/ }

do_something(std::string str)
{
    switch(quick_index(str))
    {
        case index("bar"):
            // ...
            break;

        case index("foo"):
            // ...
            break;

        case -1:
        default:
            // ...
            break;
    }

For quick_index, which doesn't have to be constexpr, you could e.g. use an unordered_map to do it O(1) at runtime. (Or sort the array and use binary search, see here for an example.)
Here's a full example for C++11, with a simple custom constexpr string comparer. Duplicate cases and cases not in the array (index gives -1) will be detected at compile time. Missing cases are obviously not detected. Later C++ versions have more flexible constexpr expressions, allowing for simpler code.
#include <iostream>
#include <algorithm>
#include <unordered_map>

constexpr const char* arr[] = { "bar", "foo", "foobar" };

constexpr int cmp(const char* str1, const char* str2)
{
    return *str1 == *str2 && (!*str1 || cmp(str1+1, str2+1));
}

constexpr int index(const char* str, int pos=0)
{
    return pos == sizeof(arr)/sizeof(arr[0]) ? -1 : cmp(str, arr[pos]) ? pos : index(str,pos+1);
}

int main()
{
    // initialize hash table once
    std::unordered_map<std::string,int> lookup;
    int i = 0;
    for(auto s : arr) lookup[s] = i++;
    auto quick_index = [&](std::string& s)
        { auto it = lookup.find(s); return it == lookup.end() ? -1 : it->second; };

    // usage in code
    std::string str = "bar";

    switch(quick_index(str))
    {
        case index("bar"):
            std::cout << "bartender" << std::endl;
            break;

        case index("foo"):
            std::cout << "fighter" << std::endl;
            break;

        case index("foobar"):
            std::cout << "fighter bartender" << std::endl;
            break;

        case -1:
        default:
            std::cout << "moo" << std::endl;
            break;
    }
}

A: hare's comment to Nick's solution is really cool. here the complete code example (in C++11):
constexpr uint32_t hash(const std::string& s) noexcept
{
    uint32_t hash = 5381;
    for (const auto& c : s)
        hash = ((hash << 5) + hash) + (unsigned char)c;
    return hash;
}

constexpr inline uint32_t operator"" _(char const* p, size_t) { return hash(p); }

std::string s = "raj";
switch (hash(s)) {
case "sda"_:
    // do_something();
    break;
default:
    break;
}

A: The problem is that for reasons of optimization the switch statement in C++ does not work on anything but primitive types, and you can only compare them with compile time constants.
Presumably the reason for the restriction is that the compiler is able to apply some form of optimization compiling the code down to one cmp instruction and a goto where the address is computed based on the value of the argument at runtime. Since branching and and loops don't play nicely with modern CPUs, this can be an important optimization.
To go around this, I am afraid you will have to resort to if statements.

A: std::map + C++11 lambdas pattern without enums
unordered_map for the potential amortized O(1):  What is the best way to use a HashMap in C++?
#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

int main() {
    int result;
    const std::unordered_map<std::string,std::function<void()>> m{
        {"one",   [&](){ result = 1; }},
        {"two",   [&](){ result = 2; }},
        {"three", [&](){ result = 3; }},
    };
    const auto end = m.end();
    std::vector<std::string> strings{"one", "two", "three", "foobar"};
    for (const auto& s : strings) {
        auto it = m.find(s);
        if (it != end) {
            it->second();
        } else {
            result = -1;
        }
        std::cout << s << " " << result << std::endl;
    }
}

Output:
one 1
two 2
three 3
foobar -1

Usage inside methods with static
To use this pattern efficiently inside classes, initialize the lambda map statically, or else you pay O(n) every time to build it from scratch.
Here we can get away with the {} initialization of a static method variable: Static variables in class methods , but we could also use the methods described at: static constructors in C++? I need to initialize private static objects
It was necessary to transform the lambda context capture [&] into an argument, or that would have been undefined: const static auto lambda used with capture by reference
Example that produces the same output as above:
#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

class RangeSwitch {
public:
    void method(std::string key, int &result) {
        static const std::unordered_map<std::string,std::function<void(int&)>> m{
            {"one",   [](int& result){ result = 1; }},
            {"two",   [](int& result){ result = 2; }},
            {"three", [](int& result){ result = 3; }},
        };
        static const auto end = m.end();
        auto it = m.find(key);
        if (it != end) {
            it->second(result);
        } else {
            result = -1;
        }
    }
};

int main() {
    RangeSwitch rangeSwitch;
    int result;
    std::vector<std::string> strings{"one", "two", "three", "foobar"};
    for (const auto& s : strings) {
        rangeSwitch.method(s, result);
        std::cout << s << " " << result << std::endl;
    }
}

A: To add a variation using the simplest container possible (no need for an ordered map)... I wouldn't bother with an enum--just put the container definition immediately before the switch so it'll be easy to see which number represents which case.
This does a hashed lookup in the unordered_map and uses the associated int to drive the switch statement. Should be quite fast. Note that at is used instead of [], as I've made that container const. Using [] can be dangerous--if the string isn't in the map, you'll create a new mapping and may end up with undefined results or a continuously growing map.
Note that the at() function will throw an exception if the string isn't in the map. So you may want to test first using count().
const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
switch(string_to_case.at("raj")) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;

}

The version with a test for an undefined string follows:
const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
// in C++20, you can replace .count with .contains
switch(string_to_case.count("raj") ? string_to_case.at("raj") : 0) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;
  case 0: //this is for the undefined case

}

A: In C++ you can only use a switch statement on int and char

A:     cout << "\nEnter word to select your choice\n";
    cout << "ex to exit program (0)\n";
    cout << "m     to set month(1)\n";
    cout << "y     to set year(2)\n";
    cout << "rm     to return the month(4)\n";
    cout << "ry     to return year(5)\n";
    cout << "pc     to print the calendar for a month(6)\n";
    cout << "fdc      to print the first day of the month(1)\n";
    cin >> c;
    cout << endl;
    a = c.compare("ex") ?c.compare("m") ?c.compare("y") ? c.compare("rm")?c.compare("ry") ? c.compare("pc") ? c.compare("fdc") ? 7 : 6 :  5  : 4 : 3 : 2 : 1 : 0;
    switch (a)
    {
        case 0:
            return 1;

        case 1:                   ///m
        {
            cout << "enter month\n";
            cin >> c;
            cout << endl;
            myCalendar.setMonth(c);
            break;
        }
        case 2:
            cout << "Enter year(yyyy)\n";
            cin >> y;
            cout << endl;
            myCalendar.setYear(y);
            break;
        case 3:
             myCalendar.getMonth();
            break;
        case 4:
            myCalendar.getYear();
        case 5:
            cout << "Enter month and year\n";
            cin >> c >> y;
            cout << endl;
            myCalendar.almanaq(c,y);
            break;
        case 6:
            break;

    }

A: More functional workaround to the switch problem:
class APIHandlerImpl
{

// define map of "cases"
std::map<string, std::function<void(server*, websocketpp::connection_hdl, string)>> in_events;

public:
    APIHandlerImpl()
    {
        // bind handler method in constructor
        in_events["/hello"] = std::bind(&APIHandlerImpl::handleHello, this, _1, _2, _3);
        in_events["/bye"] = std::bind(&APIHandlerImpl::handleBye, this, _1, _2, _3);
    }

    void onEvent(string event = "/hello", string data = "{}")
    {
        // execute event based on incomming event
        in_events[event](s, hdl, data);
    }

    void APIHandlerImpl::handleHello(server* s, websocketpp::connection_hdl hdl, string data)
    {
        // ...
    }

    void APIHandlerImpl::handleBye(server* s, websocketpp::connection_hdl hdl, string data)
    {
        // ...
    }
}

A: You can use switch on strings.
What you need is table of strings, check every string
char** strings[4] = {"Banana", "Watermelon", "Apple", "Orange"};

unsigned get_case_string(char* str, char** _strings, unsigned n)
{
    while(n)
    {
        n--
        if(strcmp(str, _strings[n]) == 0) return n;
    }
    return 0;
}

unsigned index = get_case_string("Banana", strings, 4);

switch(index)
{
    case 1: break;/*Found string `Banana`*/
    default: /*No string*/
}

A: Switches only work with integral types (int, char, bool, etc.).  Why not use a map to pair a string with a number and then use that number with the switch?

A: You can't use string in switch case.Only int & char are allowed. Instead you can try enum for representing the string and use it in the switch case block like
enum MyString(raj,taj,aaj);

Use it int the swich case statement.

A: That's because C++ turns switches into jump tables. It performs a trivial operation on the input data and jumps to the proper address without comparing. Since a string is not a number, but an array of numbers, C++ cannot create a jump table from it.
movf    INDEX,W     ; move the index value into the W (working) register from memory
addwf   PCL,F       ; add it to the program counter. each PIC instruction is one byte
                    ; so there is no need to perform any multiplication.
                    ; Most architectures will transform the index in some way before
                    ; adding it to the program counter

table                   ; the branch table begins here with this label
    goto    index_zero  ; each of these goto instructions is an unconditional branch
    goto    index_one   ; of code
    goto    index_two
    goto    index_three

index_zero
    ; code is added here to perform whatever action is required when INDEX = zero
    return

index_one
...

(code from wikipedia https://en.wikipedia.org/wiki/Branch_table)

A: in many cases you can avid extra work by pulling the first char from the string and switching on that. may end up having to do a nested switch on charat(1) if your cases start with the same value. anyone reading your code would appreciate a hint though because most would prob just if-else-if


text:
Q: Ubuntu 10.04 on vmplayer 3.0.0 build-197124 I'm using vmplayer 3.0.0 build-197124 on Windows 7 Pro as host and installed Ubuntu 10.04 as guest OS. On booting into Ubuntu , it cannot detect the keyboard. How do I fix this. I also installed a Opensue 11.1 VM and the keybaord worked fine.

A: One work-around is to enable the virtual keyboard (through the accessibility options at the login page). Login and then make a quick change to  /etc/default/console-setup. Find XBVARIANT and remove the value for it, leaving you with
XKBVARIANT=""
Some other options are mentioned in the comments of this blog post: http://www.solo-technology.com/blog/2010/05/01/ubuntu-10-0-4-vmware-and-no-keyboard

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ indentifier "read" conflicts? Recently I'm working on my toy final c++ project, which will read content from a file at the begining and then process it.
Here's the simplified code.
#include <iostream>
#include <fstream>
//using namespace std;
struct command{
    int a;
};
command read[1];
int main() {
    std::ifstream fin;
    fin.open("123.txt");
    if (!fin){
        std::cout << "failed" << std::endl;
        return 0;
    }
    char c;
    fin >> c;
    std::cout << c;
    return 0;
}

It works fine with Visual Studio 2019. However, when I'm trying to use devc++ 5.11 TDM-GCC 4.9.2, a strange bug happens. I get a segmentation fault on line fin>>c;, with return code 3221225477.
With great effort, the easiest way to make this code works is changing the identifier read to names like reading or whatever. Besides, moving the line command read[1]; into main function also helps.
My questions are:

*

*Is it a behavior related to the compiler? MSVC is fine but GCC 4.9.2 is a little bit old or ...?

*Does the identifier read conflict with something in my code? Why does it not a compile error but a segmentation fault?

*Why does moving the declaration of read into main function help?

Update:Thanks for tips and I removed using namespace std. I think it has something to do with ifstream, because just std::cout<<"hello world"; works.
-Wall -Wextra provides no warnings.

A: GCC compiler is stricter than other compiler.
According to tadman's describe, we can guess there's read symbol in namespace std.
So you put it out of main,it's a conflict, you put in the main, it become a local symbol.

A: There is very likely a collision happening between your read and another in the global namespace.  Not all compilers handle this situation the same way, but you can always avoid it if you are careful.
Visual Studio's Intellisense (or whatever alternative you prefer) can help you identify what symbol your read is colliding with.  To do that, scope or comment out your code, then start typing "read".  If there's another read in your scope, you'll likely see it and be able to get information about it.
This is one of the reasons I don't like using namespace std;.  It pollutes your global namespace with a bunch of stuff and increases your chance of collision with a standard library identifier.


text:
Q: I want to set a password to shut down a bot on discord.py, and I don't know how to write the code. Someone help me witht the code I want to set a password to shut down a bot on discord.py, and I don't know how to write the code. Someone help me with the code
@client.command()
@commands.has_permissions(administrator = True)
async def offline(ctx):
    await ctx.message.delete()
    msgg = await ctx.send("Please enter password in DM to continue shut down. This is a password protected command")
    msg = await ctx.author.send("Please enter password here. This command will timeout in 10 seconds")
password = []
def check(reaction, user):
    return str(password) == "testo"

try:

    message = await client.wait_for('password', timeout=10, check=check)

except:
    await msg.edit("Password is incorrect. Please try again or contact bot developer")
    return

else:
    password.append(msg.content)

if:
    password == "testo"

    await msgg.edit("Bot is shutting down")
    await ctx.author.send("Password is correct. Bot will be shutting down")
    await asyncio.sleep(3)
    await msgg.edit(content="Bot has shut down. To start it again, please contact bot dev")
    await bot.logout()
    return

Thats all I got so far

A: You have some formatting errors in your code, even if the approach was not bad.
You need to include a real/existing check function first. This will check that the reply was really made in the bot's direct message and that it came from the user who executed the command.
We then wait with a wait_for for an answer. You can set timeout as you like or omit it. Then we check the content of the message and if it matches the set password then the bot shuts down, otherwise it does not. (This will take some time!)
Your full code would be:
@client.command()
@commands.has_permissions(administrator=True)
async def offline(ctx):
    await ctx.send(f"{ctx.message.author.mention}, check your DM's!")
    await ctx.message.delete()
    await ctx.author.send("Please enter the password to shut me down!")

    def check(m):
        return ctx.author == m.author and isinstance(m.channel, discord.DMChannel) # Check that it is a DM channel
    try:
        test = await client.wait_for('message', check=check, timeout=100) # We wait 100 seconds for a user response/message in the DMs
        if test.content == "123": # Content can be changed to whatever you want
            await ctx.author.send("Correct password, I will shutdown.")
            await client.logout()
        else:
            await ctx.author.send("Wrong password, run the command again!")
    except asyncio.TimeoutError:
        await ctx.author.send("The time was not enough? Alright.", delete_after=5)

A: You can simply define your command named offline like this:
password = '12345'

@client.command()
async def offline(ctx, *, password_check=None):
    if password_check and password_check == password:
        await ctx.message.channel.purge(limit=1)
        await ctx.send('Shutting down bot...')
        await ctx.bot.logout()
    elif not password_check:
        await ctx.send('Please enter the password!')
    else:
        await ctx.send('You got the password wrong.')


text:
Q: MD5 digest vs. hexdigest collision risk I am comparing personal info of individuals, specifically their name, birthdate, gender, and race by hashing a string containing all of this info, and comparing the hash objects' hexdigests. This produces a 32 digit hexadecimal number, which I am using as a primary key in a database. For example, using my identifying string would work like this:
>> import hashlib
>> id_string = "BrianPeterson08041993MW"
>> byte_string = id_string.encode('utf-8')
>> hash_id = hashlib.md5(bytesring).hexdigest()
>> print(hash_id)
'3b807ad8a8b3a3569f098a575091bc79'

At this point, I am trying to ascertain collision risk. My understanding is that MD5 doesn't have significant collision risk, at least for strings that are relatively small, which mine are (about 20-40 characters in length). However, I am not using the 128-bit digest object, but the 32 digit hexdigest.
Now, I believe the hexdigest is a compression of the digest (that is, it's stored in fewer characters), so isn't there an increased risk of collision when comparing hexdigests? Or am I off-base?

A:
Now, I believe the hexdigest is a compression of the digest (that is, it's stored in fewer characters), so isn't there an increased risk of collision when comparing hexdigests? Or am I off-base?
[...]
I guess my question is: don't different representations have different chances to be non-unique based on how many units of information they use to do the representation vs. how many units of information the original message takes to encode? And if so, what is the best representation to use? Um, let me preface your next answer with: talk to me like I'm 10

Old question, but yes, you were a bit off base, so to speak.
It's the number of random bits that matters, not the length of the presentation.
The digest is just a number, an integer, which could be converted to a string using different amount of distinct digits. For example, a 128-bit number shown in some different radices:
"340106575100070649932820283680426757569" (base 10)
"ffde24cb47ecbff8d6e461a67c930dc1" (base 16, hexadecimal)
"7vroicmhvcnvsddp31kpu963e1" (base 32)

Shorter is nicer and more convenient (in auth tokens etc), but each representation has the exact same information and chance of collision. Shorter representations are shorter for the same reason as why "55" is shorter than "110111", while still encoding the same thing.
This answer might also clarify things, as well as toying with code like:
new BigInteger("340106575100070649932820283680426757569").toString(2)

...or something equivalent in other languages (Java/Scala above).
On a more practical level,

[...] which I am using as a primary key in a database

I don't see why not do away with any chance of collision by using a normal autoincremented id column (BIGINT AUTO_INCREMENT in MySQL, BIGSERIAL in PostgreSQL).

A: An abbreviated 32-bit hexdigest (8 hex characters) would not be long enough to effectively guarantee a collision-free database of users.
The formula for the birthday collision probability is here:
What is the probability of md5 collision if I pass in 2^32 sets of string?
Using a 32-bit key would mean that your software would start to break at around 10,000 users.  The collision probability would be about 1%.  It gets a lot worse very fast after that.  At 100,000 users, the collision probability is 69%.
A 64-bit key, and a 10 billion users is another breaking point of about 2.7% collision rate.
For 100 billion users (a generous upper bound of the earth's population for the foreseeable future), a 96-bit key is a little risky in my opinion: collision chance is about one in 100 million.  Really, you need a 128-bit key, which gives you a collision rate of about 1X10^-17.
128-bit keys are 128/4 = 32 hex characters long.  If you wanted to use, a shorter key, for aesthetic purposes, you need to use 23 alphanumeric characters to exceed 128 bits.  Or if you use printable characters (ASCII 32-126), you could get away with 20 characters.
So when you're talking about users, you need at least 128 bits for a collision-free random key, or a 20-32 character long string, or a 128/8 = 16 byte binary representation.


text:
Q: In spring-boot, how to log MDC using application properties? In my spring-boot project I am using Logback-"Mapped Diagnostic Context" MDC for logging diagnostic context.
MDC-data is not logged (to console or file) by default.
Is there a way for getting this MDC logs into the output-log, using only application properties?

A: spring-boot provides some application properties for this. Have a look at common-application-properties.html.
You can find logging.pattern.level here. By setting
logging.pattern.level=%5p %mdc

data from MDC will be logged, too.


text:
Q: JS sortable POST start and update function together? I would like to know how can I the current list and the sorted list sending together with POST?
I got the results well, put the posting sending only one list. The problem is the currentlist VAR is outside of UPDATE. How can I find it?

A: To do what you require you need to store currentlist within scope of both function handlers. A global variable would do this, but is bad practice.
A better approach would be to store the array in a data attribute on the relevant .wrapper container. Then you can access this wherever necessary.
Also note that you can use the map() function to simplify creating the array from the drag handle id attributes.

$(".wrapper").sortable({
  handle: ".draghandler",
  connectWith: $('.wrapper'),
  distance: 10, // reduced to 10 to make this demo easier to use
  opacity: 0.4,
  cursor: 'move',
  start: function(e, ui) {
    var currentlist = $('.draghandler').map((i, el) => el.id).get();
    $(e.target).closest('.wrapper').data('currentlist', currentlist);
    $('#currentlist').html(currentlist);
  },
  update: function(e, ui) {
    var currentlist = $(e.target).closest('.wrapper').data('currentlist');
    var newsortedlist = $('.draghandler').map((i, el) => el.id).get();
    $('#newsortedoutput').html(newsortedlist);

    // Commented as the AJAX call will cause an error in an SO snippet...
    /*
    $.post('/megrendelesek/sortmouse.php', {
      'currentid': currentlist,
      'sortid': newsortedlist
    }, function(theResponse) {
      $('#responsefromserver').html(theResponse);
    });
    */
  }
});

$(".wrapper").disableSelection();
$(".draghandler").disableSelection();

<link rel="stylesheet" href="https://code.jquery.com/ui/jquery-ui-git.css" />

    Foo

DRAG

    Foo

DRAG

    Foo

DRAG


text:
Q: Как пропустить действие не используя try except? Как мне избежать ошибку и прогнать следующее значение в цикле? Когда в img_list нет файла срабатывает try except и переходит к следующему действию, заполняется text, но так как у меня нечего вкладывать в параметр photo выскакивает ошибка, если в параметре photo нет файлов ,мне как то нужно пропустить действие с url
    for pi in img_list:

        try:
            url = 'https://api.vk.com/method/photos.getWallUploadServer?group_id=%d&v=5.131&access_token=%s' % (
                    group_id, vk_key)
            resp = requests.get(url).json()['response']
            upload_url = resp['upload_url']
            files = {'file1': open(pi, 'rb')}
        except Exception:
            print(f"Что пошло не так с постом id {post_id}")

    url = 'https://api.vk.com/method/wall.post?owner_id=%s&from_group=1&message=%s&attachments=%s&v=5.131&access_token=%s' % \
                  (-group_id, text, photo, vk_key)

    resp = requests.get(url).json()
    print(resp)

A: Перед циклом установите переменную в None, а после цикла проверяйте удалось ли в цикле ее значение установить:
photo = None
for pi in img_list:

    try:
        url = 'https://api.vk.com/method/photos.getWallUploadServer?group_id=%d&v=5.131&access_token=%s' % (
                group_id, vk_key)
        resp = requests.get(url).json()['response']
        upload_url = resp['upload_url']
        files = {'file1': open(pi, 'rb')}
        photo = ...
    except Exception:
        print(f"Что пошло не так с постом id {post_id}")

if photo:
    url = 'https://api.vk.com/method/wall.post?owner_id=%s&from_group=1&message=%s&attachments=%s&v=5.131&access_token=%s' % \
              (-group_id, text, photo, vk_key)

    resp = requests.get(url).json()
    print(resp)


text:
Q: Does the reception indicator show voice or data signal strength, or are they the same? I was informed by multiple people at T-Mobile that having a strong data connection doesn't necessarily mean a strong voice connection, but that confused me and I'm not sure if they're right. So how do the two relate? If there's strong LTE and weak EDGE would the iPhone show full bars or low bars, and would that tell you both how good the voice and data signal is or just one of those?

A: The bars on the phone are representation for Voice signals. A full bar will mean you will have the clear calls, on the other hand, the data can be seen by the type of Data service you are getting, LTE,3G(WCDMA),H or 3.5G(HSPA) and E(EDGE). Despite having the full connection bars you may have an E(For EDGE) which may give a slower network connection. It's the same thing the other way round as well, Despite getting a LTE network you may not be getting full bars, It depends on the Network tower you are connected to, the data it supports. Generally near the areas with people using less Internet over the network the companies put up towers which are good for voice signals.

A: Every phone only uses one antenna at a time, so, if you see the LTE icon on the statusbar, that means that it's connected on a LTE signal only, so, it goes for the voice and data signal.

A: tubedogg was right..EDGE is only a Data signal and doesn't support voice calls. same goes with LTE as well, momentarily LTE voice calls have not come into existence except few operators from US, UK & china. Apparently there are different signal strengths for Voice & Data signals and are clearly indicated on your latest smartphones. Voice signals  & Data signals use circuit switching & Packet switching respectively and their transmission process are completely different.


text:
Q: how to handle with python selenium chrome webdriver stuck when loading All, I'm working on analyzing my instagram followers and to do it I'm using selenium in python.
I'm using the code attached below simply to scroll the window that appears when I click on "followers". (How is that window technically called? dialogue box?)
The code works perfect until, as you can see in my attached screenshot, chrome gets stuck and that window doesn't allow to scroll down anymore.
Code:
    num_current_users_found = 0
    individual_user_class_when_scrolling  = 'NroHT'
    time.sleep(5)
    while (num_current_users_found / tot_actual_num_of_users *100) < 99:
        try:
            visible_individual_users = driver.find_elements_by_class_name(individual_user_class_when_scrolling)
            print("scrolling to the bottom...    len(visible_individual_users) = ",str(len(visible_individual_users)), "  vs. expected total users = ", str(tot_actual_num_of_users))
            pre_scroll_num_of_visible_users = len(visible_individual_users)
            last_visible_user_elem = visible_individual_users[-1]
            actions = ActionChains(driver)
            actions.move_to_element(last_visible_user_elem)
            actions.perform()
            random_sleep(0,2)
            last_visible_user_elem.location_once_scrolled_into_view
            visible_individual_users = driver.find_elements_by_class_name(individual_user_class_when_scrolling)
            num_current_users_found = len(visible_individual_users)

            if num_current_users_found == pre_scroll_num_of_visible_users:
                time.sleep(1)
        except:
            print("can't scroll anymore")

How can I handle chrome, without closing that window with all my followers and push the scroll all the way to the bottom?


text:
Q: Collection of surjective functions implies axiom of choice if I have this:
(a) If $\left \{ f_i:A_i\rightarrow B_i|i\epsilon I \right \}$ is a collection of surjective functions then $\prod_{i\epsilon I}    f_i: \prod_{i\epsilon I}  A_i\rightarrow \prod_{i\epsilon I}  B_i$ with $(a_i)_{i\epsilon I} \mapsto (f_i(a_i))_{i\epsilon I} $ is a surjective function.
(b) Every nonempty set has a choice function.
How can I prove that (a) implies (b)?

A: We will prove the contraposition. It is known that, the axiom of choice is equivalent to following statement:

If $\{A_i\}_{i\in I}$ is a family of nonempty sets, then $\prod_{i\in I}A_i$ is nonempty.

Assume that the choice fails, then there is a family of nonempty sets $\{A_i\}_{i\in I}$ with $\prod_{i\in I}A_i=\varnothing$. For each $i$, define $f_i:A_i\to \{0\}$ such that $f_i(x)=0$. We can check that each $f_i$ is surjective. However, the function $\prod f_i:\prod A_i\to\{0\}^I$ has empty domain and nonempty codomain so is not surjective.


text:
Q: SQL stored procedure results in PHP errors In my website I changed this:
$genre_result = mysql_query
(
"       SELECT  g.genre_id, g.genre_name
    FROM    genres as g;"
);
$game_result = mysql_query
(
"       SELECT  g.genre_id, g.game_id, g.game_name
    FROM    games as g;"
);
$genre_array    = array();
$game_array = array();

while ($genre_row = mysql_fetch_row($genre_result))
{
    $genre_index = $genre_row[0] - 1;
    $genre_array[$genre_index] = $genre_row[1];
    $game_array[$genre_index] = array();
    $game_array[$genre_index][] = array();
    $game_array[$genre_index][] = array();
}
while ($game_row = mysql_fetch_row($game_result))
{
    $genre_index = $game_row[0] - 1;
    $game_array[$genre_index][0][] = $game_row[1];
    $game_array[$genre_index][1][] = $game_row[2];
}

to this (I copied the SELECT blocks into two new procedures):
$genre_result = mysql_query
(
    "CALL get_genres();"
);
$game_result = mysql_query
(
    "CALL get_games();"
);
$genre_array    = array();
$game_array = array();

while ($genre_row = mysql_fetch_row($genre_result))
{
    $genre_index = $genre_row[0] - 1;
    $genre_array[$genre_index] = $genre_row[1];
    $game_array[$genre_index] = array();
    $game_array[$genre_index][] = array();
    $game_array[$genre_index][] = array();
}
while ($game_row = mysql_fetch_row($game_result))       // line #61
{
    $genre_index = $game_row[0] - 1;
    $game_array[$genre_index][0][] = $game_row[1];
    $game_array[$genre_index][1][] = $game_row[2];
}

Now I get a PHP error for line #61 (which I have marked in the above code):

Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /home2/isometr1/public_html/keyboard/keyboard.php on line 61

The get_genres() and get_games() procedures work properly in phpmyadmin, returning the proper values. What did I do wrong so that my code doesn't work?
Also, phpmyadmin issues this complaint, though I don't know if it's related:

You are using PHP's deprecated 'mysql' extension, which is not capable of handling multi queries. The execution of some stored routines may fail! Please use the improved 'mysqli' extension to avoid any problems.

[edit 1]
I tried mysql_error() like this:
$genre_result = mysql_query("CALL get_genres();", $con);
echo mysql_errno($con) . ": " . mysql_error($con) . "\n";
$game_result = mysql_query("CALL get_games();", $con);
echo mysql_errno($con) . ": " . mysql_error($con) . "\n";

And got this error:

0: 2014: Commands out of sync; you can't run this command now

Here are my version numbers:
MySQL version 5.1.70-cll
phpMyAdmin version 3.5.8
cpanel version 11
PHP version 5.3.22

[edit 2]
Based on GolezTrol's suggestions I also tried this with no improvement:
// genres & games
$genre_array    = array();
$game_array = array();
$genre_result = mysql_query("CALL get_genres();", $con);
while ($genre_row = mysql_fetch_row($genre_result))
{
    $genre_index = $genre_row[0] - 1;
    $genre_array[$genre_index] = $genre_row[1];
    $game_array[$genre_index] = array();
    $game_array[$genre_index][] = array();
    $game_array[$genre_index][] = array();
}
$game_result = mysql_query("CALL get_games();", $con);
while ($game_row = mysql_fetch_row($game_result))
{
    $genre_index = $game_row[0] - 1;
    $game_array[$genre_index][0][] = $game_row[1];
    $game_array[$genre_index][1][] = $game_row[2];
}


text:
Q: If $p$ can divide $a^n+b^n+c^n$ , can $p^k$ divide it as well? Related to this

Is there a method to decide whether a given function of the form $f(n)=a^n+b^n+c^n$ ($a,b,c$ fixed positive integers , $n$ running over the positive integers) satisfies the following property : If $p$ is a prime number with $p\mid f(s)$ for some positive integer $s$ and $k$ is any positive integer , then there is a positive integer $t$ with $p^k\mid f(t)$. In other words , if a prime can divide this expression, every power of this prime can it as well.

I am particular interested in the case $(a,b,c)=(5,6,10)$ , so $f(n)=5^n+6^n+10^n$ because in this case my prime search revealed a probable prime quite late (for $n=3168$) , but no other probable prime upto $n=60\ 000$. Furthermore I try to factor numbers of this form the last months (see the linked question)
I tried to use that $p\mid f(n)$ is equivalent to $p\mid u^n+2^n+1$ where $u$ is one of $\frac{p+6}{5},\frac{2p+6}{5},\frac{3p+6}{5},\frac{4p+6}{5}$ depending on which of those is an integer. But this led to nowhere.
For this special case $(a,b,c)=(5,6,10)$ I found out the following :

*

*For $p\le 2\cdot 10^5$ and $k=2$  the conjecture is true.

*For $p\le 14\ 000$ and $3\le k\le 5$ the conjecture is true.

A: This is a partial answer that's too long for a comment, also I will assume $p\ne 2$ and $a,b,c$ are not divisible by $p$ for convenience and try to simplify some of what I described in my comment so it's less to digest.
Hensel's lemma can be extended to p-adic power series. I should have been more clear in my comment earlier, breaking up the exponentials how I described allows us to get a convergent power series expansion.
So instead of looking at the discontinuous (as a p-adic function) $f(n)=a^n+b^n+c^n$ we instead break it up into $p-1$ separate functions $F_t(s)=f(t+(p-1)s)$ for $0\le t <p-1$. The reason for this is to turn the exponentials into a nice, differentiable p-adic power series.
Specifically if we focus on just one of the exponentials, we can expand it as
$$g(s)=a^ta^{(p-1) s} = \exp(s \log(a^{p-1})) = \sum_{n\ge 0}\frac{a^t\log(a^{p-1})^n}{n!}s^n$$
A quick diversion for a moment, this next part can be skipped. At this point it should be somewhat plausible that this is looking similar to a polynomial in $s$ and how Hensel's lemma will start to fit in. One way to evaluate the logarithm is with the regular power series you know of from real analysis,
$$\log(a^{p-1}) = \log(1-(1-a^{p-1})) = -\sum_{n\ge 1} \frac{(1-a^{p-1})^n}{n}$$
You can approximate this to arbitrary accuracy by just computing terms $\mod p^N$ for some fixed $N$ and eventually the powers $(1-a^{p-1})^n$ will all end up all being $0\mod P^N$ for large enough $n$.
Now back from the diversion and on track, for your case here all that you probably need to use is the fact that the derivative is $g'(s) = g(s)\log(a^{p-1})$ as you might have guessed from real analysis, but remember these are all p-adic series. For our uses, Hensel's lemma will look like this,
$$|F_t(s)|_p < |F_t'(s)|_p^2$$
(Roughly speaking as a quick refresher, when $x$ is a rational number you can interchange these two statements $x \equiv 0 \mod p^m \iff |x|_p \le \frac{1}{p^m}$.)
This means we know from the original problem we have some $n=t+(p-1)s$ which gives us $|f(n)|_p \le \frac 1 p$ so we have $|F_t(s)|_p \le \frac 1 p$. Now looking at the derivative,
$$|F_t'(s)|_p = |a^t(a^{p-1})^s \log(a^{p-1}) + b^t(b^{p-1})^s \log(b^{p-1}) + c^t(c^{p-1})^s \log(c^{p-1})|_p$$
For the terms individually we have $|x^t(x^{p-1})^s|_p=1$ and $|\log(x)|_p\le \frac 1 p$ and the ultrametric inequality will give us,
$$|F_t'(s)|_p \le \max(|a^t(a^{p-1})^s\log(a^{p-1})|_p, |b^t(b^{p-1})^s \log(b^{p-1})|_p, |c^t(c^{p-1})^s \log(c^{p-1})|_p)$$
$$|F_t'(s)|_p \le \frac 1 p$$
Since we care about when $|F_t(s)|_p < |F_t'(s)|_p^2$, we're left with
$|F_t(s)|_p \le \frac 1 p$ and $|F_t'(s)|_p^2 \le \frac{1}{p^2}$. In other words, the assumption that $f(n)$ is divisible by $p$ is not strong enough to  tell us that we will have a solution that's divisible by $p^k$. However, you might expect that if $f(n)$ is divisible by $p^3$ then it's more likely you will have a solution that's divisible by $p^k$ for all $k$.
This might be able to be strengthened with some work, to see when it's certain that it's divisible by $p^3$ is not just necessary, but also sufficient. If that is the case, and I'm not mistaken then that means by continuity we can safely check finitely many values of $s$ so that we exhaust the possible values that satisfy the Hensel's lemma inequality. I wish I had more time to polish this and check for errors before sending it, but that's life!


text:
Q: Collecting Geometries using ArcMap Objective: Convert different single part features with same attribute in a field (say 'Country') to a single multipart feature while retaining original geometries.
I have been looking for an ArcMap alternative of collect geometries tool available in QGIS 3.0+ but strangely enough, couldn't find it.
Closest match probably is dissolve tool which is identical to 'Collect Geometries' tool in QGIS as far as features (with same country name) are disjoint. For overlapping or adjacent features, it doesn't retain the original shapes and dissolve the shapes as well. I have also tried union and different other tools but no success.
I am open to ArcPy solutions as well. I hope that this image will help to understand the concept.

A: Thank you Vince for your comments. If you had answered the question, I would have marked it as accepted answer.
So the answer is, the requirement I stated above leads to topologically invalid polygons and Esri environment doesn't allow it. I have produced my desired output shapefile in QGIS and tried to open it in ArcMap. It opens fine but the common/overlapping area is stripped while rendering. Following image may explain the concept better. Please note that the shapefile in image has just one multipart feature having FID=0.


text:
Q: Flutter / Dart - Post File to Directory on Server and User Info to Mysql Database Is there a good way to post an audio file to a directory on a server and then insert the userid and filename into a Mysql database?
I've tried using PHP's file_get_contents and file_put_contents function to get the file data from the php://input and onto the server. Unfortunately though the file does appear in the directory it has zero bytes.
Is there a better way to do this? Here's the Dart/Flutter method I'm calling to make the http post request;
  import 'dart:async';
  import 'package:http/http.dart' as http;
  import 'package:http_parser/http_parser.dart';

Future<String> uploadAudio({String currentuserid, String audiotitle, String filepath}) async {
  final serverurl = "http://example.com/audiotest2.php?userid=" +  currentuserid + "&title=" + audiotitle;
  var request = http.MultipartRequest('POST', Uri.parse(serverurl));
  var multiPartFile = await http.MultipartFile.fromPath("audio", filepath, contentType: MediaType("audio", "mp4"));

  request.files.add(multiPartFile);
  request.send().then((result) async {http.Response.fromStream(result).then((response)
  {
  if (response.statusCode == 200)
  {
  print('response.body '+response.body);
  }
  return response.body;
    });
  });
}

And here's the audiopost.php (Note: this unsecure mysql code is temporary just to get it working until I learn to prepare the mysql statements correctly.):
<?php

header("Content-Type: audio/mp4");
require_once (dirname(__FILE__).'/PHP_Compat-1.6.0a3/Compat/Function/file_get_contents.php');

    $link = mysqli_connect("xxx", "xxx", "xxx", "xxx");
    $userid=$_GET['userid'];
    $title=$_GET['title'];
    $data = php_compat_file_get_contents('php://input');
    $audioname = $userid."-talk".m4a";
    $isql = "INSERT INTO audioposts (userid, audioname, title) VALUES ('$userid','$audioname','$title' )";

    if (file_put_contents($audioname,$data)) {
    if (filesize($audioname) != 0) {echo "Recording Saved.";
    if (mysqli_query($link, $isql)){echo "Success record insert";} else {echo "Failed record insert";}
    } else {echo "File is empty.";}
    } else { echo "File transfer failed."; }

?>

Here's the response I'm getting from flutter in Android Studio;
response.body File is empty  File transfer failed.

I'm not seeing any errors in the PHP logs.

A: So it seems I didn't need the PEAR package after all. The _FILES function in PHP slotted in just fine;
<?php

header("Content-Type: audio/mp4");

    $link = mysqli_connect("xxx", "xxx", "xxx", "xxx");
    $userid=$_GET['userid'];
    $title=$_GET['title'];
    $userSQL= "SELECT postcount FROM users WHERE id = '$userid'";
    $postResult = $link->query($userSQL);
    $audioid="";

  if ($postResult->num_rows >= 0) {
    while($row = $postResult->fetch_assoc()) {
    $postcount = $row["postcount"];
    $newpostcount = $postcount + 1;
    $audioname = $userid."-talk-".$newpostcount.".m4a";
    $usql = "UPDATE users SET postcount='$newpostcount' WHERE id='$userid'";
    $isql = "INSERT INTO audioposts (userid, audioname, title) VALUES ('$userid','$audioname','$title' )";

    if (isset($_FILES["audio"]) && $_FILES["audio"]["error"] == 0) {
    $uploaddir = '/myuploadir/';
    $uploadfile = $uploaddir . basename($_FILES['audio']['name']);
    $oldname = $_FILES['audio']['name'];
    if (move_uploaded_file($_FILES['audio']['tmp_name'], $uploadfile)) {echo "File was uploaded. \n";
    if (rename($oldname, $audioname)) {echo $oldname." to ".$audioname."\n";
    if (mysqli_query($link, $usql)){echo "Successful postcount update! \n";
    if (mysqli_query($link, $isql)){$audioid = $link->insert_id; echo $audioid; } else {echo "Failed record insert";}
    } else {echo "Failed postcount update";}
    } else {echo "Rename failed";}
    } else {echo "Upload failed";}
    } else {echo "There's an error";}
            }
        }
?>


text:
Q: http request object params in javascript not recognized I have this API url that I have test in postman and it works.
https://cdn.contentful.com/spaces/master/entries/?select=fields&content_type=events&fields.eventType=vue
As you can see I have fields.eventTypes because that's the way I have to do it according to the docs from contentful : https://www.contentful.com/developers/docs/concepts/relational-queries/
My problem is that when I use axios I want to pass the params object as follow.
const CONTENTFUL_PARAMS = {
  select: 'fields',
  fields.eventType: 'vue', //js doesn't like this line
  content_type: 'events',
};

I have also tried
const CONTENTFUL_PARAMS = {
  select: 'fields',
  fields: {
    eventType: 'vue' //got error 400 in the response
  },
  content_type: 'events',
};

I know I can put everything in one string and do string concat put I don't want to do it that way. How can I achieve that I want to do in a Object that contains the parameters.
return axios.get(BASE_URL, { params: CONTENTFUL_PARAMS });

A: Just like that
const CONTENTFUL_PARAMS = {
   select: 'fields',
   "fields.eventType": 'vue',
   content_type: 'events'
};


text:
Q: edittext spinner in android Hi In My Application I am Designing one popup registration form. In That Class field i want to display drop down menu for that one i used spinner but that one its taking separate field
I don't want in separate field i want in place of class i want drop down menu can please tell me what i did mistake.
popupregistration.java:
    public class PopupRegistration extends Activity implements OnItemSelectedListener
   {
    private String[] state = { "1", "2", "3",
            "4", "5", "6", "7",
            "8", "9"};

    public String log;
    public DatabaseHandlers db;

    GSfeedback cn;

    EditText etName,etClass,etrollno,etparentname,etphno;
    Button btnregister;

    Spinner spinnerOsversions;
    EditText selVersion;
    TextView textView;
    String PHONE_REGEX;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_registration);
        System.out.println(state.length);
        db = new DatabaseHandlers(this);

        etName=(EditText)findViewById(R.id.etName);
        selVersion=(EditText)findViewById(R.id.selVersion);
        etrollno=(EditText)findViewById(R.id.etrollno);
        etparentname=(EditText)findViewById(R.id.etparentname);
        etphno=(EditText)findViewById(R.id.etphno);

        btnregister=(Button)findViewById(R.id.registerbutton);

        PHONE_REGEX = "[0-9]+";
        spinnerOsversions = (Spinner) findViewById(R.id.osversions);
        ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, state);
        adapter_state
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerOsversions.setAdapter(adapter_state);
        spinnerOsversions.setOnItemSelectedListener(this);

        btnregister.setOnClickListener(new View.OnClickListener()
        {
        public void onClick(View v) {
             if(!validate()) {
                //Toast.makeText(getApplicationContext(), "Not Valid", Toast.LENGTH_SHORT).show();
             } else {
             if(!validates()) {
                    // Toast.makeText(getApplicationContext(), "Not valid", Toast.LENGTH_SHORT).show();
                 } else {
                     //Toast.makeText(getApplicationContext(), "valid", Toast.LENGTH_SHORT).show();
                     String studentname=etName.getText().toString();
                     String classid=etClass.getText().toString();
                     String rollno=etrollno.getText().toString();
                    String parentname=etparentname.getText().toString();
                     String phno=etphno.getText().toString();

                     // Save the Data in Database
                     db.addGSfeedback(new GSfeedback(studentname,classid,rollno,parentname,phno));

                     Toast.makeText(getApplicationContext(), "Thanks for Registration, Welcome to Lilttle Flowers Public School Android App.", Toast.LENGTH_LONG).show();

                     etName.setText("");
                     etClass.setText("");
                     etrollno.setText("");
                     etparentname.setText("");
                     etphno.setText("");

                     finish();
                     Intent nextScreen = new Intent(getApplicationContext(), Splashscreen.class);
                     startActivity(nextScreen);

                 }
             }
        }

        });
        }

        public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
            spinnerOsversions.setSelection(position);
            String selState = (String) spinnerOsversions.getSelectedItem();
            selVersion.setText("Selected Android OS:" + selState);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

        private boolean validate(){
        if(etName.length() == 0 || etClass.length() == 0 || etrollno.length() == 0 || etphno.length() == 0 || etparentname.length() == 0){
            Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
            return false;
        } if(etName.length() > 30 && etparentname.length() > 30){
            //Toast.makeText(getApplicationContext(), "pls enter less the 25 characher", Toast.LENGTH_SHORT).show();
            etName.setError("pls enter less the 30 charachter");
            return true;

        } else if(etphno.length() < 6 || etphno.length() > 13){
            //etNumber.setError("Not Valid Phone Number");
            Toast.makeText(getApplicationContext(), "Enter valid Phone Number", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

        private boolean validates(){
        if(etphno.getText().toString().trim().matches(PHONE_REGEX)) {
            return true;
        } else {
            Toast.makeText(getApplicationContext(), "Enter Valid Phone Number", Toast.LENGTH_SHORT).show();
             return false;
        }
    }
    }

popupregistration.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

    <EditText
        android:id="@+id/etName"
        android:hint="Student Name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <requestFocus />
    </EditText>

     <Spinner
        android:id="@+id/osversions"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />
    <EditText
        android:id="@+id/selVersion"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
          android:layout_below="@+id/osversions"
        android:hint="Class"/>
    <EditText
        android:id="@+id/etrollno"
        android:hint="Roll Number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <requestFocus />
    </EditText>

     <EditText
        android:id="@+id/etparentname"
        android:hint="Parent Name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <requestFocus />
    </EditText>
    <EditText
        android:id="@+id/etphno"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Phone Number" />

    <Button
        android:id="@+id/registerbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="REGISTER"
        android:layout_marginBottom="60dp" />

    </LinearLayout>
    </ScrollView>

   </LinearLayout>

Thank You.

A: If you want a popup for the registration you can just use a PopupWindow instead of a Spinner. You would use a spinner to select a value from a list, not to show a registration popup.
And the PopupWindow has a method showAsDropDown which will show it beneath an anchor making it look like a dropdown.
Hope this helps
Example :
    // inflate your layout where you might add some edit texts for login and password
    View popupWindowView = getActivity().getLayoutInflater().inflate(R.layout.your_layout, null, false);
    mPw = new PopupWindow(
            popupWindowView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true);

    mPw.setOutsideTouchable(true);
    mPw.showAsDropDown(anchor, xOffset, yOffset);


text:
Q: Fetch PUT : SyntaxError: JSON Parse error: Unexpected EOF I'm sending files (image / video) on amazon S3 with Fetch but I don't understand why I can't reach the response.
The image / video is properly update on amazon and I can access it on my bucket.
 const result = await fetch(url.data, {
      method: "PUT",
      body: path,
    });
    const json = await result.json();
    console.log(json);

// url.data : presigned url
// path : {uri : https....com}

And i got the following error : Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected EOF
any idea ?


text:
Q: select in a drop-down menu is not dropping down Why don't my dropdown-menus drop down?
I am unfamiliar with using style sheets and wonder if I have to tell it something because in earlier appengine work without css, the menus dropped down as expected.

Could the problem be that the jinja2 syntax is different from the django syntax upon which this template is based? I cannot find any jinja2 docs for this situation.
#inputdata {margin:0 20%}
#inputdata {background:#bfe2f9}

    Year:
      <select name="year">
        {% for year in years %}
        <option
    {% ifequal year yearset %}
    selected="selected"
    {% endifequal %}
        value={{year}}>{{year}}</option>
        {% endfor %}
      </select>
    Month:
      <select name="month">
        {% for month in months %}
        <option
    {% ifequal month monthset %}
    selected="selected"
    {% endifequal %}
        value={{month}}>{{month}}</option>
        {% endfor %}
      </select>
    Day:
      <select name="day">
        {% for day in days %}
        <option
    {% ifequal day dayset %}
    selected="selected"
    {% endifequal %}
        value={{day}}>{{day}}</option>
        {% endfor %}
      </select>

A: It needs to look like
<select>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
</select>

http://www.tizag.com/htmlT/htmlselect.php/

A:
<select><option value="All the years!">[2012,2013,2014]</option></select>

That isn't how <select> tags work. You only have one option so there is nothing to drop down.
You need to break your selectable items into their own option tags:
<select>
  <option>2012</option>
  <option>2013</option>
  <option>2014</option>
</select>

A: It looks like your syntax is something like:
<select>
  <option>[2012, 2013, 2014]</option>
</select>

When it should look like:
<select>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
</select>

A: It looks like you are passing years, months and days as lists that are too deeply nested.  If len(years) == 1 then you'll want to change what you are passing to Jinja from this:
years = [[2012, 2013, 2014]]

to this:
years = [2012, 2013, 2014]

(And do the same for months and days).
Also, Jinja2 doesn't have an ifequals tag - you can just use the if block:
{% for year in years %}
<option {% if year == yearmark %}selected="selected"{% endif %} value="{{year}}">
{{ year }}</option>
{% endfor %}


text:
Q: populate id from database in select box option value in zend framework hi I am new in zend framework Basically I want to populate company name list from the database. Actually I have doen it but i want to also populate its id in option box
example
select
option value='1'> tcs option
select
this is my code
Application_Form_Clientcompanyform extends Zend_Form

$company_list = new Application_Model_Clientcompany;
        $showlist  = $company_list->companyNameList();

        $list=array();
        $id=array();
                    foreach($showlist as $key => $value)
                         {
                             $list[]=$value['companyName'];
                             $id[]=$value['id'];
                         }

$this->addElement('select', 'companyName', array(

            'required'   => true,
            'filters'    => array('StringTrim'),
            'style'    => array('width:103px'),

            'multiOptions' => $list,
            'decorators'=>Array(
            'ViewHelper','Errors'

but Now i want to set the value in option in select box width $id from database

A: $companyName = new Zend_Form_Element_Select('companyName');
$companyName->setRequired(true);
$companyName->addFilter('StringTrim');
    $company_list = new Application_Model_Clientcompany;
    $showlist  = $company_list->companyNameList();
    //add selections to multioption, assumes object...change notation if using array
    foreach($showlist as $company) {
        $name = ucfirst($company->name);
        $companyName->addMultiOption($company->id, $name);
    }
$this->addElement($companyName);

I know I changed the syntax style, I just find it easier to keep things straight this way.
Everything else you may need is in http://framework.zend.com/manual/1.12/en/zend.form.html, get used to using the reference and the the api for the framework, they really help.


text:
Q: Wrong Timing relative to Windows Message Loop in 3D appli? I have got a Pb  possibly with timing in regards of the Windows Message Loop, I think (?):
While Manipulating a 3D scene drawn under (OpenGL + C++) for Windows, I want that  in response to a WM_ LBUTTONDOWN  user event , to change continuously the camera  position from a point A to point B ( but with same lookAt point). I would like also a ~ 2sec duration for that move:
In my OnLButtonDown()  handler for WM_ LBUTTONDOWN message, I enter a 100 iterations loop like this:
{ m_camera.setEyePos(...pos #i...);
SendMessage(m_hWnd, WM_PAINT,0,0);}
ending at  the desired camera position.

BUT my scene isn't redrawned at all in the 99 intermediate states:
    It is just redrawn in the final position! (but in a correct way)
    it jump directly from the initial point of view to the final one! (but it takes 2sec to do so, as intended..)

What's  wrong?
Can you help? Thanks.
P.S. Sorry for my English (I am French..) ...and beginner with Windows programming...

A: There are problems with this approach. If you are iterating in a loop 100 times then you are not processing Windows messages. So you won't process the WM_PAINT until you leave the loop. Then there is the problem that WM_PAINT has a clipping region associated with it, known only to the operating system, so it is never valid to send the message yourself. Instead, call InvalidateRect to request the operating system to generate a WM_PAINT. You should do this from a timer or from your game loop so that messages will continue to be processed.


text:
Q: Bound for the derivative of a holomorphic map in the disk Let $D$ be the unitary disk, and let $f: D \to D$ be a holomorphic map. Prove that
$$
  \left|f^\prime(z)\right| \leq \frac{1 - |f(z)|^2}{1 - |z|^2} \qquad \forall z\in D.
$$

A: Hint: Apply Schwartz-Pick for a suitable composition of your function and an automorphism of the unit disc. If $f:\mathbb{D} \to \mathbb{D} $  and $a$ inside the disc , then $\left|\frac{f(z)-a}{1-\bar{a}f(z)}\right|\le \left|\frac{z-a}{1-\bar{a}z}\right|$ . This will give you the result.


text:
Q: Select all  after  tag This question might sound strange since an easy way to handle it is just to add a specific class or id to those . But my html is rendered by some other tools so that I cannot manage those specific
 myself, but I just want to padding the
 after
 here. Those
 are all children of a
, the code

ipsum

lorem

foo

I tried to solve this problem with h3 + p selector, but it can only do change to the first
. I want to select all the p after h3.

A: Just use the general sibling selector ~ (instead of the adjacent sibling selector +):

h3 ~ p {
  color: red;
}

ipsum

lorem

foo

A:
+ : The + combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.
~ : The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.

So, use ~ instead of +
h3 ~ p {your code...}

h3 ~ p { background-color:yellow }

ipsum

lorem

foo


text:
Q: CakePHP Model is not associated with another model, association issue I have a controller called rewards_controller and in that controller I have:
var $name = 'Rewards';
var $uses = array('Membership', 'Product');

In this controller I have this action:
function redeemed()
{
    //snipped for brevity
        $this->paginate = array('conditions' =>
            array('Reward.user_id' => $this->Auth->user('id')),
            'limit' => 50,
            'order' => array('Reward.created' => 'desc'),
            'contain' => array('Product' => array('Image' => array('limit' => 1)),
            'Status'));
        $this->set('rewards', $this->paginate()); // This line causes the warning
}

Today users started reporting a warning when they access rewards/redeemed. The warning is:
Warning (512): Model "Membership" is not associated with model "Product"
[CORE/cake/libs/model/behaviors/containable.php, line 363]

And
Warning (512): Model "Membership" is not associated with model "Status"
[CORE/cake/libs/model/behaviors/containable.php, line 363]

So this is because it is trying to link membership to products and status but no link/relationship exists.
So is there a way I can tell the paginate() call to only use the rewards model, instead of using the membership model which is in the $uses?

A: The problem is your $uses. In V1.3, the name of the current controller's model must also be included.
Change your "original code" to:
var $uses = array('Reward', 'Membership', 'Product');


text:
Q: Pivot table with date_shutdown and factory_name and type_shutdown and time_shutdown I need to make a pivot table that includes a factory name column along with a column for every type of shutdown; in the intersection the period of the shutdown. Factory names and shutdown types are limited so it's just a static pivot; I guess.
The table should somehow include the date of the shutdown; which I don't know how to do. On a certain date, more than one type of shutdown can occur at a certain factory, so I need to give the total of shutdowns periods as well.
Schema
create database Project_DB;
use Project_DB;

create table usine(
nom_u varchar(30) default 'Maroc Phosphore I' primary key,
);

create table produit(
nom_p varchar(50) primary key
);

create table un_prod(
nom_un varchar(50) primary key /*check(install_axis='Nissan/LP-A' or install_axis='Nissan/LP-B' or install_axis='Nissan/LP-D' or install_axis='Rhône-Poulenc/LP-F' or install_axis='Polimex/LS-A' or install_axis='Polimex/LS-B' or install_axis='Polimex/LS-D' or install_axis='Mansonto/LS-H' )*/,
production_prev decimal,
nom_u varchar(30) foreign key references usine(nom_u) default 1,
);

create table production(
nom_un varchar(50) foreign key references un_prod(nom_un),
nom_p varchar(50) foreign key references produit(nom_p),
date_prod date,
production decimal,
trg_p decimal,
map decimal,
comment varchar(max) default ''
constraint pkp primary key (nom_un,nom_p,date_prod)
);

/*create unique index index_dateprod on production(nom_un,date_prod);
*/
create table arret(
type_arret varchar(50) primary key,
duree_prev decimal
);

create table arrets(
nom_un varchar(50) foreign key references un_prod(nom_un),
type_arret varchar(50) foreign key references arret(type_arret),
date_arret date,
duree_arret decimal,
trg_a decimal,
comment varchar(max) default '',
constraint pkar primary key(nom_un,type_arret,date_arret)
);

Sample data
insert into usine
values('MPI');

insert into produit
values('tp2o5');
insert into produit
values('sio2');

insert into un_prod
values('Nissan/LP-A',19000,'MPI'),
('Nissan/LP-B',26000,'MPI'),
('Nissan/LP-D',21000,'MPI'),
('Rhône-Poulenc/LP-F',48000,'MPI'),
('Polimex/LS-A',32000,'MPI'),
('Polimex/LS-B',24500,'MPI'),
('Polimex/LS-D',23000,'MPI'),
('Mansonto/LS-H',12000,'MPI');

insert into arret
values('Arrêts_planifié',14.52),
('Arrêts_programmé',1.80),
('Arrêts_process',1),
('Pannes_MM',2),
('Pannes_Autres',0.50),
('Réd_vitesse_endogène',0.86),
('Causes_endogènes_division',0),
('Manque_Phosphate',0),
('Qualité_Phosphate',0),
('Manque_Soufre',10),
('Manque Enlèvement',2),
('SiO2_Elevé',9),
('Autre',0);

insert into production(nom_un,nom_p,date_prod,production)
values('Nissan/LP-A','tp2o5','10-02-2016',6000),
('Nissan/LP-b','tp2o5','10-02-2016',12300),
('Nissan/LP-d','tp2o5','10-02-2016',21000),
('Nissan/LP-a','tp2o5','10-03-2016',6000),
('Rhône-Poulenc/LP-F','tp2o5','10-02-2016',19000),
('Polimex/LS-A','SiO2','10-02-2016',1000),
('Polimex/LS-b','SiO2','10-02-2016',6000),
('Polimex/LS-d','SiO2','11-02-2016',16000),
('Mansonto/LS-h','SiO2','11-02-2016',21000),
('Nissan/LP-A','tp2o5','11-05-2016',16000),
('Polimex/LS-d','SiO2','11-06-2016',12000),
('Nissan/LP-a','tp2o5','11-20-2016',19000),
('Nissan/LP-A','tp2o5','11-25-2016',6000),
('Nissan/LP-d','tp2o5','12-30-2015',21000);

insert into arrets(nom_un,type_arret,date_arret,duree_arret)
values('Nissan/LP-A','Arrêts_programmé','10-02-2016',12),
('Nissan/LP-A','Arrêts_planifié','10-02-2016',1),
('Nissan/LP-b','Manque_Soufre','11-20-2016',2),
('Mansonto/LS-h','SiO2_Elevé','11-20-2016',10),
('Rhône-Poulenc/LP-F','Causes_endogènes_division','11-20-2016',8),
('Polimex/LS-d','Pannes_Autres','12-21-2016',1),
('Polimex/LS-d','Autre','11-22-2016',0),
('Nissan/LP-a','Manque_Phosphate','12-01-2016',6),
('Nissan/LP-A','Arrêts_programmé','11-25-2016',12),
('Nissan/LP-A','Manque_Phosphate','11-25-2016',1),
('Nissan/LP-b','Arrêts_process','11-20-2016',12),
('Nissan/LP-d','Pannes_MM','12-30-2015',1);

My query
select
    nom_un,
    year(date_arret) as année ,
    month(date_arret)as mois,
    Arrêts_planifié,
    Arrêts_programmé
from arrets as a
pivot (count(duree_arret)
for type_arret in (Arrêts_planifié,Arrêts_programmé)
) as p
group by month(date_arret),nom_un,Arrêts_planifié,Arrêts_programmé,date_arret;

It's giving me an error in count(a.duree_arret). I don't know what's the problem. Any help would be appreciated


text:
Q: How can you test Touch ID for macOS? I am working on an app for macOS. We want to use the Touch ID sensor in the new MacBook Pro's to unlock our app. On iOS, you can test the Local Authentication framework from the simulator.
Is there a way to test Touch ID for Mac apps? The latest XCode build provides a nice Touch Bar simulator, but I cannot find anything for Touch ID.
Thanks!

A: Rick Fillion (from 1Password) was kind enough to offer some advice: https://twitter.com/rickfillion/status/794370861646172160
Use LAPolicy.DeviceOwnerAuthentication to test.
Here's the code I am running (Swift 2.3):
import Cocoa
import LocalAuthentication

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let myContext = LAContext()
        let myLocalizedReasonString = "unlock itself"

        var authError: NSError? = nil
        if #available(iOS 8.0, OSX 10.12, *) {
            if myContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, error: &authError) {
                myContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason: myLocalizedReasonString) { (success, evaluateError) in
                    if (success) {
                        // User authenticated successfully, take appropriate action
                        print("Success")
                    } else {
                        // User did not authenticate successfully, look at error and take appropriate action
                        print("Failure")
                    }
                }
            } else {
                // Could not evaluate policy; look at authError and present an appropriate message to user
                print("Evaluation")
                print(authError)
            }
        } else {
            // Fallback on earlier versions
            print("Fallback")
        }
        // Do any additional setup after loading the view.
    }
}


text:
Q: Write gif loaded from glide to file Above question is root goal for sharing images which in process puts me to several issues in     Glide.
 I am using Glide 3.6 with retrofit 2 to fetch gif urls and loading them in   recyclerview.This is working fine but now i need to share the loaded image which requires me to save/write loaded gif in a file and there comes the problem :
1: I cant' save cached image to a file since it cache location is not very clear.
2: I am using listener which provides GlideGifDrawble as resource variable but how to write GlideGifdrawble to a file since binary data from gifdrawble will in turn will lead to static bitmap.
Code:
final File file=new    File(mContext.getCacheDir(),"images/images"+number+".Gif");
number++;

    holder.img_thumbnail.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            {
                Glide.with(mContext)
                        .load(lm.get(position).getUrl())
                        .asGif()
                        .placeholder(R.mipmap.ic_launcher)
                        .crossFade()
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .listener(new RequestListener<String, GifDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GifDrawable>     target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GifDrawable resource, String model, Target<GifDrawable> target,
                                                           boolean isFromMemoryCache, boolean isFirstResource) {

                                BufferedOutputStream s ;
                                frames= resource.getFrameCount();
                                try {
                                    s = new BufferedOutputStream(new FileOutputStream(file));
                                    s.write(resource.getData());
                                    s.flush();
                                    s.close();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                return false;
                            }
                        });


text:
Q: how to recover an unsaved edited pdf on ubuntu 16.04? i was editing a document viewer PDF file as in adding comments and stuff    and i accidentally forgot to save my edits, so is there any possible way for me to recover those edits?

A: Not really
Files that are being edited by a program are loaded in RAM. They are generally never written to disk until you save, so there is no data to recover from the disk.
In some instances some text strings can be extracted from RAM, but this requires obtaining a RAM dump from the running system. This is a difficult process that should be performed by trained digital forensics experts. Also, if you turned off your computer in the meantime then it will be completely worthless.


text:
Q: SQL - how to remove whole row if one of the column in subquery return NULL I am stuck in 1 SQL query
SELECT u.*,

um2.meta_value as parent_user_id,
( select u.user_email FROM wp_users u WHERE u.ID = um2.meta_value ) AS parent_user_email

FROM

wp_users u

JOIN wp_usermeta um2 ON u.ID = um2.user_id
AND um2.meta_key = 'parent_user_id'

GROUP BY
u.ID

This query return 4 row ( As shown in the screenshot )
I want a scenario like : If subquery return NULL , then the whole row will not be shown.
So in this example "childthree" should not be shown , as "parent_user_email" is NULL , so the whole 3rd row need to remove

A: Use a join instead:
SELECT u.*, um2.meta_value as parent_user_id,
       u2.user_email as parent_user_email
FROM wp_users u JOIN
     wp_usermeta um2
     ON u.ID = um2.user_id AND
        um2.meta_key = 'parent_user_id' JOIN
     wp_users u2
     ON u2.ID = um2.meta_value
GROUP BY u.ID;

Note:  This assumes that the email value itself is never NULL.  If that is possible, add WHERE u2.user_email IS NOT NULL.
Also, your query should fail because the GROUP BY columns are inconsistent with the SELECT.  However, logically it seems ok, because there is only one parent and user email per user.  However, I would include those columns in the GROUP BY.


text:
Q: How to route to page using Dynamic Routes in next.js I am trying to route these urls to [id].js file in next.js, So everything is working for url 2 and 3 below, but its not working for url 1 so I have to create another index.js file which I dont want. Is is possible to use the same [id].js file? for url 1 also.
url 1 -> /settings
url 2 -> /settings/notifications
url 3 -> /settings/security

my file structure
settings > [id].js

getting the id
const router = useRouter()
const { id } = router.query;

A: A file structure like the below is one way to do it:
settings
    > [id]
    > index

But if you do not want to add an index file you can make use of optional catch-all routes feature. Please note that it comes with other features you might not want and this might change your code a little too.
This is the structure you will have to follow:
settings
    >[[...id]]

{ } // GET `/post` (empty object)
{ "slug": ["notifications"] } // `GET /settings/notifications ` (single-element array)
{ "slug": ["notifications", "security"] } // `GET /settings/notifications/security ` (multi-element array)


text:
Q: Having trouble with simple integral sorry I'm having some trouble evaluating this integral
$\frac{dv}{dt} = -k(v-gt)^2-g$ where g and k are constants
I'm assuming you just separate and integrate but I cannot seem to get it to work out.

A: Let $y=v-gt$. Then $\frac{dv}{dt}=\frac{dy}{dt}+g$.
So our differential equation can be rewritten as
$$\frac{dy}{dt}+g=-ky^2-g,$$
and then  as
$$\frac{dy}{dt}=-(ky^2+2g).$$
This is a separable differential equation. We are solving
$$\frac{dy}{ky^2+2g}=-dt.$$
Integrate. We will get an arctan on the left.


text:
Q: Received response with content-encoding: gzip, but failed to decode it When making a GET request to
https://apicache.vudu.com/api2/?_type=contentSearch&contentEncoding=gzip&contentId={}&dimensionality=any&followup=ultraVioletability&followup=longCredits&followup=superType&followup=episodeNumberInSeason&followup=advertContentDefinitions&followup=tag&followup=hasBonusWithTagExtras&followup=subtitleTrack&followup=ratingsSummaries&followup=geneGenres&followup=seasonNumber&followup=trailerEditionId&followup=genres&followup=usefulStreamableOffers&followup=walmartOffers&followup=preOrderOffers&followup=editions&followup=merchandiseContentMaps&followup=promoTags&followup=advertEnabled&format=application%2Fjson

from AWS, I intermittently receive the following error:
ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing: incorrect header check',))

Example:
requests.get(url.format('832504'))
<Response [200]>
requests.get(url.format('460398'))
<Response [200]>
requests.get(url.format('27616'))
<Response [200]>
requests.get(url.format('23657'))
<Response [200]>
requests.get(url.format('8661'))
ContentDecodingError...
requests.get(url.format('14250'))
<Response [200]>
requests.get(url.format('516307'))
ContentDecodingError...
requests.get(url.format('10366'))
<Response [200]>

I have tried different combinations of headers (including the suggestion here: https://github.com/requests/requests/issues/3849) and removing the contentEncoding=gzip param (which returns 502 status code).
Considering this API works flawlessly on my PC, perhaps there is some conflict between Vudu and AWS?

A: I think this is current python requests library limitation (or design behavior, see here)
So you have to use resp.raw to get the raw bytes.  (Note: to access resp.raw, it also requires stream=True).
resp = session.get(url, stream=True)
data = resp.raw.read()


text:
Q: Why my replacer function in JSON.stringify(value, replacer) doesn't receive keys in Angular application? Trying to implement JSON.stringify as explained here: Hide certain values in output from JSON.stringify() and exclude some fields from serialization but it doesn't work.
For example in my controller I've the following code:
.controller('ExampleController', ['$scope', function($scope) {
    $scope.event = {
      id:1,
      title: 'event title',
      users: [{
        id: 1,
        name: 'Anatoly'
      },{
        id: 2,
        name: 'Roman'
      }],
      private1: 1,
      private2: 2
    };

    var replacer = function(key, value){
        console.log(key);
    };

    $scope.stringified1 = JSON.stringify($scope.event, replacer);

    // $scope.stringified = JSON.stringify($scope.event, ['id','title','users','name']);

 }]);

Why console.log(key) prints nothing? The function itself is invoked, but key parameter is empty.
I've done plunker here: http://plnkr.co/edit/U6ZcIuPVr5RzMIBl8X6c?p=preview
I'm using Angular 1.4.9 and Chrome 48.0.2564.116
P.S. I've done this functionality with passed array and it works, but using a function can give a much more flexibility so I'd like to understand why it doesn't work.

A: Ok, it isn't clear from manual here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify  but because replacer called in a recursively manner it should return object on which it's being called, root object itself too:

Initially it gets called with an empty key representing the object
  being stringified

you should return this object, if you return nothing it won't be called on other properties of this object

and it then gets called for each property on the object or array
  being stringified

So, thanks to @charlietfl hint, I fixed it, you can see fixed plunker here: http://plnkr.co/edit/a3S8yGx78b7vJSKwORw5?p=preview


text:
Q: Can a Delta Live Table (DLT) be passed as a parameter to a User Defined Functions (UDF) in Databricks? Databricks' documentation on UDFs shows very simple examples, e.g. integer transformation with integers as parameters (https://docs.databricks.com/spark/latest/spark-sql/udf-python.html), but says nothing about passing Delta Live Tables as a parameters.
In my case, I have two DLTs that are being created, and I then need to perform some transformations on them that are only possible with pandas, finally receiving a DLT as well.
I need something like this:
@dlt.table
def dlt1():
  return spark.sql("query...")

@dlt.table
def dlt2():
  return spark.sql("query...")

@dlt.table
def dlt3():
  return spark.sql("SELECT * FROM search(LIVE.dlt1, LIVE.dlt2)")

def search(dlt1, dlt2):
  dlt2_not_null = list(dlt2.filter("someColumn").isNotNull()).distinct().toPandas()["someColumn"].values)
  result = dlt1.filter(~dlt1["someColumn"].isin(dlt2_not_null))

  return result

spark.udf.register("search", search)

A: No, you can't pass the Spark or DLT tables as function parameters for use in SQL. (Same is the true for "normal" Spark SQL as well).  But really, your function doesn't look like UDF - it's just a "normal" function that works with two dataframes, so you can easily implement it in DLT, like this:
@dlt.table
def dlt3():
  dlt1 = dlt.read("dlt1")
  dlt2 = dlt.read("dlt2")
  dlt2_not_null = list(dlt2.filter("someColumn").isNotNull()).distinct().toPandas()["someColumn"].values)
  result = dlt1.filter(~dlt1["someColumn"].isin(dlt2_not_null))

  return result

If you have the same pattern in multiple places, then you can programmatically create DLT tables/views as described in documentation, something like this:
def make_search(table_name, dlt1_name, dlt2_name):
  @dlt.table(name=table_name)
  def temp_func():
    dlt1 = dlt.read(dlt1_name)
    dlt2 = dlt.read(dlt2_name)
    dlt2_not_null = list(dlt2.filter("someColumn").isNotNull()).distinct().toPandas()["someColumn"].values)
    result = dlt1.filter(~dlt1["someColumn"].isin(dlt2_not_null))

    return result

Although, frankly speaking, this kind of logic should be doable with the normal joins...


text:
Q: Get Specific Data from json file using vue I am trying to add a select option. In this option there should be the name of the employees. Once an employee is selected vue should render its profile information something like this:

*

*Name: Bob

*Title: Mr

*Gender: Male

All information is stored in a json file.

        Employee Name

         <select v-model="employee" class="is-small">
            <option v-for="employees in employees">{{ employee.name }}</option>
          </select>

{{ employee.name }}, {{ employee.gender }}, {{ employee.designation }}

And the json file is something like this:
[{
  "name": "Bob",
  "gender": "male",
  "title": "Mr"
}, {
  "name": "Alice",
  "gender": "female",
  "title": "Mrs"
}]

I think there is something wrong with the function. Any help would be appreciated.
PS: The browser console do not show any error or warning.


text:
Q: Evaluating a double integral with change of coordinates. $\int\!\!\int_{R} (x+y)\,dA$ It looks simple, but I'm having a bit of difficulty with trying to obtain the proper change of coordinates.

Evaluate the following integral
  $$\displaystyle\int\!\!\!\int_{R} (x+y)\,dA$$
with region R in the first quadrant bounded by $-1\le y-x\le 1$ and $1\le x^2+y^2 \le 4$

I've tried $u=x^2+y^2$ and $v=y-x$, but I can't seem to express $x+y$ in terms of $u$ and $v$. Is it possible to express $x+y$ in terms of $u$ and $v$ with the above substitutions? Or do we need another change of variables?
What other change of coordinates is possible to approach this problem?
Based on what region $R$ looks like, I don't think polar coordinates would work for this even though there is an $x^2+y^2$ term (though I could be mistaken).

A: Below is the region (both the blue and red) over which you are integrating.
$$I = \int_{\Omega} (x+y) dA = \int_{\text{Red region}} (x+y) dA + \int_{\text{Blue region}} (x+y) dA$$
Denoting $\arctan((4-\sqrt{7})/3)$ as $\theta_1$ and $\arctan((4-\sqrt{7})/3)$ as $\theta_2$, we get that
In the red region, you have the $$\int_{\text{Red region}} = \int_{\theta = \theta_1}^{\theta = \theta_2} \int_{r=1}^{r=2} (\cdot) dr d \theta$$
In the blue region, you have the $$\int_{\text{Blue region}} = \underbrace{\int_{\theta = 0}^{\theta = \theta_1} \int_{r=1}^{r=f_1(\theta)} (\cdot) dr d \theta}_{\text{Blue region below}} + \underbrace{\int_{\theta = \theta_2}^{\theta = \pi/2} \int_{r=1}^{r=f_2(\theta)} (\cdot) dr d \theta}_{\text{Blue region above}}$$
Now all you need to find are the functions $f_1,f_2$ and perform the integral. The functions $f_1,f_2$ are easy to find since you know the equation of the line below is $x-y = 1$ and the equation of the line above is $y-x=1$. Hence, $$f_1(\theta) = \dfrac1{\cos(\theta) - \sin(\theta)} \text{ and } f_2(\theta) = \dfrac1{\sin(\theta) - \cos(\theta)}$$


text:
Q: Do falcons, the birds, exist in the Star Wars universe? Inspired by this comic from XKCD:

Is there anything to confirm whether or not falcons exist in the Star Wars Universe? If they don't then what is the in-universe reason for the name of the Millennium Falcon?

A: Legends:

The bat-falcon was a swift species of flying creatures. It inspired
  the name of the starship Millennium Falcon.

http://starwars.wikia.com/wiki/Bat-falcon
http://starwars.wikia.com/wiki/Millennium_Falcon_(novel)

The snow falcon was an avian native to Rhinnal.

http://starwars.wikia.com/wiki/Snow_falcon

The spire falcon was a bird native to the planet Coruscant. It was at
  the top of the food chain of animals such as gully rats, grate toads,
  ferro-worms, and trantor pigeons.

http://starwars.wikia.com/wiki/Spire_falcon
Regarding canon - other than the Falcon name it appears not. It seems an unnecessary question imo - one could engage in ever increasing navel gazing over the necessity of language use in the film. Do ducks exist in canon? They are referenced in Episode 1. Does a Star Wars duck look like a duck and walk like a duck or is it different from an earth duck?
The name itself inherently implies that such a creature exists in some form and that is swift and agile. This is the simplest and logical explanation


text: Q: What variables are defined by FastCGI? I'm currently using nginx as a server, and while configuring php (ie where I set php-fpm for nginx) I got curious as to what variables are defined by a fastcgi client (such as nginx). I have tried to search the internet but I have not found information about it, do you know what are all the possible variables that a fastcgi client has or can define? Whether with requests such as GET, POST, etc...


text:
Q: Fixtures, Tests, and Preconditions When using factories, although more work is required up front, you know that you will be setting the correct pre-conditions for your test (up to what you have written.) However, when you use fixtures, although no work is required to setup the database state, someone (including the developer of the test) could easily change the fixtures by accident in some way in the future and render the test useless (e.g. make it always pass no matter what!)
How should a develop guard against this to protect the integrity of the test in the future? Should the pre-conditions be asserted before the test runs? Is this considered best practice?

A: If a specific property of the environment is important for that test, then yes, do verify that precondition directly in the test. In particular, this is helpful when the system under tests performs a kind of state transition.
For example, I am writing a user account management system. I want to test that I can add new users. In order to test whether a new user has been created, it makes sense to ensure the user didn't exist previously. E.g. expressed in Cucumber notation:

Scenario: adding a new user
  Given I have an account management system
    And no user named "Fred" exists
   When I add a user named "Fred"
   Then a user named "Fred" exists

or more xUnit-ly:
void test_addingANewUser() {
  assertNull(accounts.getUserByName("Fred"));

  accounts.createUser("Fred");

  assertNotNull(accounts.getUserByName("Fred"));
}

I think verifying these preconditions is a perfectly clear thing to do, regardless of how you create the system state prior to the test. Without this precondition, the test case is incomplete and depends on some setup code for the full details. With this precondition, the test is more self-contained and thus more maintainable.