text:
Q: how to check if the string contains only numbers or word in c My teacher gave us code that Write a function declared as "int categorize(char *str)" which accepts a string as an input parameter and categorize the string. The function should return the category number as decribed below:
Category 1: If the string contains only capital letters (e.g. ABCDEF), the function should return 1.
Category 2: If the string contains only small letters (e.g. abcdef), the function should return 2.
Category 3: If the string contains only letters but no other symbols (e.g. ABCabc), the function should return 3.
Category 4: If the string contains only digits (e.g. 12345), the function should return 4.
Category 5: If the string contains both letters and digits but no other symbols (e.g. Hello123), the function should return 5.
Category 6: Otherwise, the function should return 6.
I write this but not working
#include<stdio.h>
#include<string.h>

// Write your categorize function here
int categorize(char *str) {
int x=0;
while(str[x]!= '\0'){
     if((*str>='A'&&*str<='Z')  && (*str>='a'&&*str<='z') && (*str>='0'&&*str<='9'))
    return 5;
    else if((*str>='A'&&*str<='Z') && (*str>='a'&&*str<='z'))
    return 3;
    if((*str>='A') && (*str<='Z'))
    return 1;
    else if((*str>='a')&&(*str<='z'))
    return 2;
    else if((*str>='0')&&(*str<='9'))
    return 4;
    x++;
}
return 6;
}

///////////////////////////////////////
// Test main()
  // DO NOT MODIFY main()
  // or your code will not be evaluated
  int main() {
  char str[100];
  scanf("%s",str);
  int c = categorize(str);
  printf("%d\n",c);
  return 0;
 }
///////////////////////////////////////

A: *str this is a pointer to the first character of the string so along your cycle it only checks this first character.
Furthermore you are returning values before checking the entire string, you need to use flags and set them along the cycle for digits caps and small letters, and in the end return the values according to those flags.
There is the <ctype.h> library which has functions like isalpha and isdigit and can make your job easier, for that I refer you to @DevSolar answer as a better method.
If you can't use it this is the way to go:
Live demo
int categorize(char *str) {

    int x = 0;
    int is_digit, is_cap, is_small;
    is_cap = is_digit = is_small = 0;

    while (str[x] != '\0') {

        if (!(str[x] >= 'a' && str[x] <= 'z') && !(str[x] >= 'A' && str[x] <= 'Z') && !(str[x] >= '0' && str[x] <= '9'))
             return 6;
        if (str[x] >= 'A' && str[x] <= 'Z' && !is_cap)  //if there are caps
            is_cap = 1;
        if (str[x] >= '0' && str[x] <= '9' && !is_digit) //if there are digits
            is_digit = 1;
        if (str[x] >= 'a' && str[x] <= 'z' && !is_small) //if there are smalls
            is_small = 1;
        x++;
    }
    if ((is_small || is_cap) && is_digit){
        return 5;
    }
    if(is_small && is_cap){
        return 3;
    }
    if(is_digit){
        return 4;
    }
    if(is_small){
        return 2;
    }
    if(is_cap){
        return 1;
    }
    return 6;
}

Note that this kind of character arithmetic works well in ASCII but fails in other character encodings like EBCDIC which don't have sequencial order for alphabetic characters.

A: You can do this in O(n) as follows:
#include <ctype.h>
#include <stdio.h>

int check_str(char* str)
{
    int category = 0;   // 0b001 -> Uper | 0b010 -> Lower | 0b100 -> Number

    for ( ; *str != 0; str++) {
        if (isupper(*str)) {
            category |= 1;
        }
        else if (islower(*str)) {
            category |= 2;
        }
        else if (isdigit(*str)) {
            category |= 4;
        }
        else
            return 6;
    }

    if (category == 1)
        return 1;

    if (category == 2)
        return 2;

    if (category == 3)
        return 3;

    if (category == 4)
        return 4;

    if (category == 7)
        return 5;

    return 6;
}

int main()
{
    printf("%d\n", check_str("ABCDEF"));
    printf("%d\n", check_str("abcdef"));
    printf("%d\n", check_str("ABCabc"));
    printf("%d\n", check_str("12345"));
    printf("%d\n", check_str("Hello123"));
    printf("%d\n", check_str("Hello World 123"));

    return 0;

}

OUTPUT
1
2
3
4
5
6

EDIT
Since 0b... is not portable, binary numbers are changed to their decimal equivalents

A: The standard header <ctype.h> literally has everything you are looking for:

*

*Category 1 is if isupper() is true for all characters.

*Category 2 is if islower() is true for all characters.

*Category 3 is if isalpha() is true for all characters.

*Category 4 is if isdigit() is true for all characters.

*Category 5 is if isalnum() is true for all characters.
A quick-and-dirty approach could just iterate through the input once for each of the above:
int categorize( char * str )
{
    char * s;

    for ( s = str; *s; ++s )
    {
        /* Need the cast to unsigned char here; negative values
           are reserved for EOF!
        */
        if ( ! isupper( (unsigned char)*s ) )
        {
            break;
        }
    }

    if ( ! *s )
    {
        /* True if the loop ran its full course without breaking */
        return 1;
    }

    /* Same for the other categories */

    return 6;
}

Once you got this done, you could start getting funny with the logic, putting all the checks into one loop and keeping track of conditions met.

A: You seem to have a pretty good start for your project.  You capture a String, and then categorize it.
Where you need to improve is the logic for categorization.  I would start by making each of your categories into a function.
int isOnlyCapital(char* string)

might return 1 if the string is only comprised of capital letters, and 0 otherwise.  The logic might look like
    char* position = string;
    while (position != '\0') {
      if (*position < 'A' || *position > 'Z') {
        return false;
      }
      position++;
    }
    return true;

Note that you can only return true if you managed to check all charaters with the above code, as you have looped over all characters until you hit the NULL character \0.
With some work, you can modify the above loop to handle your other cases.  That would make your logic for the overall top level look like.
 if (isOnlyCapital(string)) return 1;
 if (isOnlyLowercase(string)) return 2;
 ... and so on...


text:
Q: how to change editor for to read only On the edit screen I am allowing the user to edit a record.
But I dont want them to edit the lastUseDate. How can I set it to read only, instead of EditorFor LastUseDate, disabled?
@Html.EditorFor(x => x.Device.LastUseDate)

A: <%= @Html.TextBoxFor(x => x.Device.LastUseDate, new { @readonly = "readonly", disabled = "disabled", }) %>

A: Try this:
@Html.EditorFor(x => x.Device.LastUseDate, new { disabled = "disabled", @readonly = "readonly" })

It'll add disabled and readonly attribute to your textbox.

redpajama_set_name: RedPajamaStackExchange


text:
Q: **ERROR*** TypeError: Cannot read property 'replace' of undefined I am facing this TypeError: "Cannot read property 'replace' of undefined" when I made a small application with nodejs, express.js, MongoDB, mongoose and when I connect my express applications with mongoose at that time when I replace my password I face this type of error
const mongoose = require('mongoose');

const dotenv = require('dotenv');

const app = require('./app');

dotenv.config({ path: './config.env' });

const DB = process.env.DATABASE.replace(
  '<PASSWORD>',
  process.env.DATABASE_PASSWORD
);

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log(con.connections);
    console.log('DB connection succesful!!');
  });

const port = process.env.PORT || 3001;

app.listen(port, (req, res) => {
  console.log(`App is running on ${port}...`);
});

How to resolve this error?

A: The issue usually occurs due to not assigning the environment configuration file path properly. Pay attention to the dotenv.config({ path: './config.env' }); line. You are searching for the config.env file within the current folder. Make sure that the file exists on the current working directory. If not, assign the path of the config file properly. The issue will be solved right after that.

A: I got the same error and i resolved by correcting my config.env file where
DATABASE = mongodb+srv://shailesh:@cluster0.n1pjr.mongodb.net/natours?retryWrites=true/majority?
I removed characters after true/ i.e. Majority.
However if this does not solve your problem then just ensure that Database is registered as an environment variable. Because error pertains to the issue that application is not able to find environment variable called "DATABASE"

A: *

*Cannot read property because there is an error to read your config.env file, to check that

console.log(process.env);
// use thie before const DB to check file is accessible

If you access to .env now check DATABASE and DATABASE_PASSWORD is mentioned correctly.

*If everything is written correct then there is problem with your password to correct your password by customise it and don't use special character.
2.1 to reset password of mongoDB Atlas cluster got to DATABASE ACCESS click on it now it will show your user, at right end click to edit.
2.2 now popup open, edit your password and save it. and got config.env file change it.

*IN config.env file contain and check these should be written correctly. DATABASE url you get from atlas just copy and paste it just replace password to PASSWORD. thats it.
NODE_ENV=development
PORT=8000
DATABASE=mongodb+srv://***USER_name***:<PASSWORD>@cluster0.awemngr.mongodb.net/***DATABASENAME***?retryWrites=true&w=majority
DATABASE_PASSWORD= your_password


text:
Q: How can I avoid SQL injection attacks? Yesterday I was speaking with a developer, and he mentioned something about restricting the insertions on database field, like, strings such as -- (minus minus).
At the same type, what I know is that is a good approach to escape HTML chars like <, > etc. Not --. Is this true? Do I have to worry about --, ++? Is it more like a myth or old stuff?

Update
Thanks a lot for all the answers, it's easy to understand like that since I'm kind of new to all of this.
Well, to be more specific in this case our discussion was about and C# ASP.NET MVC website we're developing, so there's a complex open an account form in there with important information, so I'm not sure if MVC using Linq to interface with database already comes with this kind of protection or not. So if anyone could provides some hints about it, it would be great.
Thanks again

A: The proper way to avoid SQL Injection attacks is NOT to simply disallow certain problematic characters, but rather to use parameterized SQL. In short, parameterized SQL prevents the database from executing raw user input as part of the SQL command this prevents user input like "drop table" from being executed. Just escaping characters does not stop all forms of SQL injection attacks and excluding certain words such as "Drop" does not work in all cases; there can be certain fields where "Drop" is a perfectly valid part of the data entry.
You can find some good articles on the subject of paramaterized SQL here:
https://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
http://www.codeproject.com/KB/database/ParameterizingAdHocSQL.aspx
Now that you mentioned that you are working with ASP.net I can give you some links that deal specifically with SQL Injection in ASP.
https://dzone.com/articles/aspnet-preventing-sql-injectio
https://www.c-sharpcorner.com/UploadFile/75a48f/how-sql-injection-can-be-possible-in-asp-net-websites/
Here is a more general article on making your ASP more secure:
http://www.codeproject.com/KB/web-security/Securing_ASP_NET_Apps.aspx
And, of course the MSDN article on SQL injection:
http://msdn.microsoft.com/en-us/library/ms998271.aspx

A: SQL injection is a high security risk for most websites that allow users to squirt parameters into a statement that gets executed on a database.
A simple example would be:
Input field "Name: _________
"SELECT * FROM tblCustomer WHERE Name = '" + nameInputField + "'"

So if I type in "Bob" we have
"SELECT * FROM tblCustomer WHERE Name = 'Bob'"

But if I type in "'; DROP TABLE tblCustomer", we end up with the rather more sinister
"SELECT * FROM tblCustomer WHERE Name = ''; DROP TABLE tblCustomer"

There are lots of ways to avoid these problems, and many are built into whatever language you are using - so rather than think of all the dodgy possibilities ";", "--", "/*" etc, try and use something that already exists.
Shout out what language you're using and I'm sure we can tell you how to avoid these attacks.

A: He was talking about SQL Injection attacks, as is quite right in what he said.
The problem is not with such data existing in the database, but in passing input data directly to the database without sanitizing it.
Without cleaning it up, if someone passes in a string ending with a ; they can then follow it with anything they want (select * from sys.objects, for example) or something more malicious, like dropping some tables.
It is difficult to guard against fully, but if you use a good DB library from your code and follow known practices, such as using paremeterized queries you limit the possible damage.
Store as many -- in your database as you want, but do not pass that through to your database without going through a cleanup process (this is where a good DB library is vital - it should cleanup quotes and other potentially harmful input).

A: There's nothing "dangerous" about inserting a string containing -- in a database.
It is dangerous to insert anything in a database table that comes directly from user input without processing it, otherwise you leave yourself open to SQL injection attacks. Example: A coder lets the user type in their name in a field, and the user types:
Joe '); drop table users; commit transaction; --

and then the coder puts that in their MySQL database like so:
conn.execute("insert into users (username) values ('" + userInput + "')");

Boom The user has deleted the users table (assuming the database login had rights to do that, which it shouldn't -- but that's a different topic), because the coder didn't ensure that the string from the user was escaped correctly, and so it got sent directly to the DB engine and the attacker has a good laugh. :-)
Use whatever tools your environment provides to ensure that strings are escaped correctly. For instance, JDBC uses the PreparedStatement class for this. Most environments will have something similar.

A: Use parameterized queries.  These queries represent the variables as a placeholder in the SQL, such as select * from person where name = ?.  After creating the SQL query, you set the parameter values in the query.  Parameterized queries ensure that whatever was substituted for the placeholder will not be considered as part of the SQL statement.
See Jeff Atwood's article for a good overview of parameterized queries.

A: It is not dangerous as long as you correctly escape the data when doing INSERT/UPDATE/...
And escaping HTML characters is NOT a good approach. Imagine you wrote a function that escapes such characters and you have stored some escaped text in the database. Then you notice that your function did not escape '<', so you change the function... now what happens to the records that are already in the database? - Their '<' characters will stay unescaped.
Thus, NEVER escape text before storing it in the database (escape the SQL query, of course). Escaping should happen when the HTML/XML/... page is produced out of the text, that is, after querying the original text from the database!


text:
Q: Automatic image zoom without touching the screen I want to zoom an image automatically without touching the screen.
I.e. the image must be zoomed in as soon as the activity starts without any touch from the user.

A: Inside onCreate of MainActivity class you should define AnimationUtils and load the Animation on image view to whom you want to zoom Automatically.
 Now make an xml class inside the anim and declare the xml inside load animation as second parameter.
this is the Java Class
public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom);
      image.startAnimation(animation1);
   }
}

This is the Anim xlm for zoom animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

   <scale xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromXScale="0.5"
      android:toXScale="3.0"
      android:fromYScale="0.5"
      android:toYScale="3.0"
      android:duration="5000"
      android:pivotX="50%"
      android:pivotY="50%" >
   </scale>

   <scale xmlns:android="http://schemas.android.com/apk/res/android"
      android:startOffset="5000"
      android:fromXScale="3.0"
      android:toXScale="0.5"
      android:fromYScale="3.0"
      android:toYScale="0.5"
      android:duration="5000"
      android:pivotX="50%"
      android:pivotY="50%" >
   </scale>

</set>

A: Please visit this link. It will really help you. Just try to understand the whole program and you'll be able to achieve what you want. I just did! Don't call the zoomImageFromThumb method from any touch or click event. You can call it from any other event, such as you want to call at the activity startup, you can call it in onCreate method. It will work.


text:
Q: Clang link libc++ statically On Ubuntu 20.04 I need to use libc++ since the default libstdc++ is lacking required support. In order to not have to ship libc++ I need to statically link against libc++.
I have a static version of libc++ available which has been created locally using the following series of commands (as per https://libcxx.llvm.org/BuildingLibcxx.html):
git clone --single-branch --branch release/15.x --depth 1 https://github.com/llvm/llvm-project.git
mkdir /llvm-project/build

cmake -G "Ninja" -S /llvm-project/runtimes -B /llvm-project/build \
-DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" \
-DLIBCXX_INCLUDE_BENCHMARKS=OFF \
-DLIBCXX_INCLUDE_TESTS=OFF \
-DLIBCXX_ENABLE_SHARED=ON \
-DLIBCXX_ENABLE_STATIC=ON \
-DLIBCXXABI_ENABLE_SHARED=ON \
-DLIBCXXABI_ENABLE_STATIC=ON \
-DLIBCXX_CXX_ABI=libcxxabi \
-DCMAKE_INSTALL_PREFIX=/usr \
-DCMAKE_BUILD_TYPE=Release

ninja -C /llvm-project/build cxx cxx-abi unwind
ninja -C /llvm-project/build install-cxx install-cxxabi install-unwind

I fail to make it achieve the desired results of not of not having any runtime dependency on  libc++.
Trying to compile the following simple example:
#include <iostream>

int main(int, const char**) {
    std::cout << "Clang " <<  __clang_version__ << '\n';
#ifdef _LIBCPP_VERSION
    std::cout << "  Using libc++ " << _LIBCPP_VERSION << '\n';
#endif
    return 0;
}

Using clang++ test.cpp -std=c++20 -static-libstdc++ -static-libgcc will result in no undesired runtime dependencies (only linux-vdso, libm, libc, ld-linux), however it is using stdlibc++ which will not work for the actual code.
Using clang++ test.cpp -stdlib=libc++ -std=c++20 -static-libstdc++ -static-libgcc results in lots of linker errors about missing standard stuff.
Using clang++ test.cpp -stdlib=libc++ -std=c++20 -static-libstdc++ -static-libgcc -lc++abi  followed by an ldd a.out will show it having a dependency on libc++abi.so and libgcc_s.so.1 which are both undesired, the former more so than the latter.
(Why do I have to explicitly link c++abi anyway, should it not just do it by itself like it does with c++?)
In an attempt to not have the pesky runtime dependency doing clang++ test.cpp -stdlib=libc++ -std=c++20 -static-libstdc++ -static-libgcc -lc++abi -static will result in
ld: error: duplicate symbol: __lll_lock_wait_private
>>> defined at libc-lowlevellock.o:(__lll_lock_wait_private) in archive /lib/x86_64-linux-gnu/libc.a
>>> defined at lowlevellock.c:27
>>>            lowlevellock.o:(.text+0x0) in archive /lib/x86_64-linux-gnu/libpthread.a

No idea why it suddenly decides to have pthread in there, as I never specified that and it would not seem to be required given the example code but whatever.
How can one convince clang to actually statically link libc++ (and libc++abi), without errors, so that it will not have non-standard runtime dependencies?

A: The entire C++ standard library (libc++/libstdc++ etc) all rely on the standard C library and pthreads among others.
C++ standard libs on Linux are just a tiny shell around the infrastructure that the C language provides, the real workhorse.
std::thread is basically just syntax sugar on top of pthreads. This is a hard reality most C++ developers find very hard to stomach.
See examples:
std::threadlibstdc++ libc++
std::chrono libstdc++ libc++
std::filesystem libstdc++ libc++


text:
Q: strtod with limited string length If I want to parse the first 3 characters from the char array as a double, ignoring the following characters, do I really need to do this?

int main() {
    const char a[] = "1.23";
    char *b = malloc(sizeof(char) * 4);

    memcpy(b, a, sizeof(char) * 3);
    b[3] = '\0';

    printf("%f\n", strtod(b, NULL)); // Prints 1.20000, which is what I want

    free(b);
}

Isn't there a function like strtod that allows you to specify the maximum string length it should be searching for digits?
Edit: I want it to print 1.2 (which it currently does), not 1.23!

A: While strtod() doesn't allow you to limit the string length, you can use sscanf() with a maximum field width and an optional check for the number of characters consumed, like so:
#include <stdio.h>

double parseDouble(const char *str){
    double val = 0;
    int numCharsRead;

    // Handle errors by setting or returning an error flag.
    if(sscanf(str, "%3lf%n", &val, &numCharsRead) != 1){
        puts("Failed to parse double!");
    }
    else if(numCharsRead != 3){
        puts("Read less than three characters!");
    }

    return val;
}

int main(){
    printf("%lf\n", parseDouble("1.3")); // 1.300000
    printf("%lf\n", parseDouble("1.5999")); // 1.500000
    printf("%lf\n", parseDouble(".391")); // 0.390000
    printf("%lf\n", parseDouble(".3")); // Read less than three characters!\n0.300000
    return 0;
}

sscanf(str, "%3lf%n", &val, &numCharsRead is the important part: you specify a maximum width of 3, which means that sscanf() will read up to 3 characters for that particular field, and also store the number of characters consumed by the end of the parse in numCharsRead. You can then check that value if you care about reading exactly 3 characters every time; if you're fine with 3 or less, you can just use sscanf(str, "%3lf", &val). For reference, here's the documentation for width specifiers:

An  optional  decimal  integer  which specifies the maximum field width.
  Reading of characters stops either when this maximum is reached or when a
  nonmatching character is found, whichever happens first.  Most conversions
  discard  ini‐ tial  white  space  characters (the exceptions are noted below),
  and these discarded characters don't count toward the maximum field width.
  String input conversions store a terminating null byte ('\0') to mark the end
  of the input;  the maximum field width does not include this terminator.

A: If you always want to only consider the three first characters from a given string, you can use the following code:
#include <stdio.h>
#include <string.h>

double parse_double(const char *str) {
  char *tmp = 0;
  double result = 0;

  asprintf(&tmp, "%.3s", str);
  result = strtod(tmp, 0);
  free(tmp);

  return result;
}

int main(void) {
  printf("%f\n", parse_double("1.23")); // 1.2
  printf("%f\n", parse_double("1234")); // 123
  printf("%f\n", parse_double("0.09")); // 0.0

  return 0;
}

A: The signature of strtod is like this
   double strtod(const char *nptr, char **endptr);

The function will return the initial portion of the string pointed to by nptr. If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.
So it does not let you specify the number of characters that need to be converted. Hence you have to modify your input itself and pass it to strtod.

A: No, there isn't such a function in the standard library.
But it's fun to roll one's own:
/*
 * Same as strtod() but only takes the first n characters into account.
 * Additionally returns 0. and sets errno to EINVAL if 'nptr' is NULL.
 */
double strntod(const char *nptr, char **endptr, size_t n)
{
  double result;

  /* perform input validation */
  if (!nptr)
  {
    errno = EINVAL;

    result = 0.;
    if (endptr)
    {
      *endptr = nptr;
    }

    goto lblExit;
  }

  if (strlen(nptr) <= n)
  {
    /* Nothing to truncate: fall back to standard 'strtod()' */
    result = strtod(nptr, endptr);
  }
  else
  {
    /* create working copy of string */
    char * ptmp = strdup(nptr);

    /* Test whether 'strdup()' failed */
    if (!ptmp)
    {
      result = 0.;
      if (endptr)
      {
        *endptr = nptr;
      }

      goto lblExit;
    }

    /* truncate working copy to n characters */
    ptmp[n] = '\0';

    /* do original 'strtod()' on truncated working copy */
    result = strtod(ptmp, endptr);

    /* adjust '*endptr' to point to original character array, but to working copy */
    if (endptr)
    {
      *endptr = nptr + (*endptr - ptmp);
    }

    /* free working copy */
    free(ptmp);
  }

  lblExit:

  return result;
}


text:
Q: Dividing a string I have a list, i want to split the every string from "And" and join it to first action.
OLD_Txt=
["User enters validusername "MAXI" And password "768"",
"User enters phonenumber "76567898" And ZIPcode "97656"",
"User Verifys Country  "ENGLAND" And City "LONDON""]

I want my list look like this
New_Txt:
["User enters validusername "MAXI"",
"User enters password "768"",
"User enters phonenumber "76567898"",
"User enters ZIPcode "97656"",
"User Verifys Country "ENGLAND"",
"User Verifys City "LONDON""]

A: OLD_Txt= [
    'User enters validusername "MAXI" And password "768"',
    'User enters phonenumber "76567898" And ZIPcode "97656"',
    'User Verifys Country "ENGLAND" And City "LONDON"']

base_word = 'User '

new_text = []
for string_obj in OLD_Txt:
    first_part, second_part = string_obj.split('And')
    verb_for_second_part = first_part.split(' ')[1]
    # from split you ll get ["User" "enters", "validusername", "MAXI"]
    # and you need text at index 1 i.e: verb_at_index
    new_text.append(first_part)

    second_part = base_word + verb_for_second_part + second_part
    new_text.append(second_part)

print(new_text)

output
['User enters validusername "MAXI" ', 'User enters password "768"', 'User enters phonenumber "76567898" ', 'User enters ZIPcode "97656"', 'User Verifys Country "ENGLAND" ', 'User Verifys City "LONDON"']

A: If I understood you corectly, you want to join your strings.
So you really want to:
New_Txt = ' '.join(OLD_Txt)


text:
Q: An example of series such that $0\le a_n\le b_n$ and $\sum a_n$ converges but $\sum b_n$ diverges Looking to get some help with the following question.
I need to find nonnegative sequences $(a_n)$and $(b_n)$ such that $a_n\leq b_n$ for all $n$ and $\sum a_n$ converges but $\sum b_n$ diverges.
So the terms of $a_n$ must turn to $0$ but $b_n$ does not. But how do I find examples of this series?

A: Well, if $a_n=\frac1{2^n}$ and $b_n=n$, then
$$a_n\le b_n$$
$$\sum_{n=1}^\infty\frac1{2^n}=1<+\infty$$
$$\sum_{n=1}^\infty n=+\infty$$
But it is not necessary for $\require{cancel}b_n\cancel\to0$, for example, with $b_n=\frac1n$,
$$\sum_{n=1}^\infty\frac1n>\int_1^\infty\frac1x\ dx=\lim_{t\to\infty}\ln(t)=+\infty$$
But it is necessary for $a_n\to0$ by the term test.


text:
Q: Ahlfors page 123: Compute $\int_{|z|=2}z^n(1-z)^mdz$. What happens when $n,m<0$? Residue Theory? Cauchy's Theorem? This is a question from Ahlfors, page $123$, number $1b$:  Compute $\int_{|z|=2}z^n(1-z)^mdz$.  He doesn't specify anything about $n$ and $m$ on the page, so I am not sure if they are natural numbers or integers.  If they are natural numbers, then the integrand is analytic and so the integral is $0$, so I assume they aren't natural.  So, I imagine we consider cases depending on which $n$ or $m$ is less than $0$ and which one is greater than or equal to $0$.  When doing so, we either get a pole of order $n$ at $0$ or a pole of order $m$ at $1$.  I can write these out in the standard residue form, but is there a way to "clean them up", so to speak?  In particular, if you were, say, teaching a class on Complex Analysis, what would you expect from your students?  (note: I am not a current student, just looking back through some old notes and problems from several years ago).
EDIT: In particular, I am talking about, for instance, when $n\geq 0$ and $m<0$, then we have $\int_{|z|=2}\frac{z^n}{(1-z)^m}dz=\frac{1}{(m-1)!}\lim_{z\rightarrow m}\frac{z^{m-1}}{dz^{m-1}}z^n$.  But, $m<0$, so what is the negative-th derivative of $z^n$?  Similarly, we can consider the case when $n<0$, $m\geq 0$ and $n,m<0$.  (I feel like I am missing some cases).  Moreover, this problem comes in Ahlfors book BEFORE Residue theory.  So, maybe there is a better way to tackle it?  I just wasn't seeing a nice way of using Cauchy's theorem.
EDIT (number 2): The question was asked here: Computing $\int_{|z|=2} z^n(1 - z)^m\ dz$ for $n,m\in\Bbb Z$, but I'm finding issues with the answer.  In particular, I am not seeing how they arrived to their answer, and they are only dealing with one case.
EDIT (number 3, last update): The question was also asked here: Computing $\int_{|z|=2} z^n(1 - z)^m\ dz$, handling most of the cases.  However, the case whenever both $n,m$ are strictly negative is still not clear to me.

A: From the context, Alhfors is assuming that $n$ and $m$ are integers (and otherwise, the integrand wouldn't be well-defined). Since he hasn't covered the residue theorem by that point in the book, presumably he's expecting students to use the form of Cauchy's Theorem  on pp. 120--121. (I'm a bit surprised he doesn't prove Eq. 24 there, which is what I'm more familiar with as the usual form of Cauchy's Theorem. Maybe it's subsumed into the residue theorem).
Anyway, if this were my class, I would expect most correct answers from students to have an argument like:

*

*Split the disk $D = \{z\in \mathbb{C}:\, |z| \leq 2\}$ into two regions $\Gamma_0, \Gamma_1$, via, say, a vertical line segment through the point $\frac{1}{2}$. Thus the integrand $f(z) = z^n (1 - z)^m$ is analytic on $\Gamma_0$ off $z = 0$ and on $\Gamma_1$ off $z = 1$.

*Use Cauchy's Theorem, Eq. $24$, Lemma 3, or etc. to compute the integrals of $f$ over $\partial \Gamma_0$ and $\partial \Gamma_1$.

*Reconstruct $\int_{\partial D} f$ from the two integrals above, being careful about orienting the contours.

That having been said, it's pretty much a standard exercise applying the residue theorem, and in fact the setup outlined above comes close to a proof of the residue theorem: Reduce an integral over the boundary of a region to integrals around small loops encircling each of an isolated set of poles, and compute those integrals via Cauchy's Theorem. (Turning that into a full proof involves some results about the topology of contours in the plane, and which I seem to recall that Ahlfors mostly (justifiably) sweeps under the rug anyway. Unfortunately, there's no easy way around the topological results necessary to go from Cauchy's Theorem for a circle or rectangle to the general case.)


text:
Q: File and networking portability among different byte sizes In C, the fread function is like this:
size_t fread(void *buf, size_t max, FILE *file);

Usually char* arrays are used as buf. People usually assume that char = 8 bit. But what if it isn't true? What happens if files written in 8 bit byte systems are read on 10 bit byte systems? Is there any single standard on portability of files and network streams between systems with bytes of different size? And most importantly, how to write portable code in this regard?

A: With regard to network communications, the physical access protocols (like ethernet) define how many bits there go in a "unit of information" and it is up to the implementation to map this to an appropriate type. So, for network communications there is no problem with supporting weird architectures.
For file access, stuff gets more interesting if you want to support weird architectures, because there are no standards to refer to and even the method of putting the files on the system may influence how you can access them.
Fortunately, the only systems currently in use that don't support 8-bit bytes are DSP's and similar small embedded systems that don't support a filesystem at all, so the issue is essentially moot.

A: Systems with bit sizes other than 8 is pretty rare these days. But there are machines with other sizes, and files are not guaranteed to be portable to those machines.
If uberportability is required, then you will have to have some sort of encoding in your file that copes with char != 8 bits.
Do you have something in mind where this may have to run on a DEC 10 or really old IBM mainframes, in DSP's or some such, or are you just asking for the purpose of "I want to know". If the latter, I would just "ignore the case". It is pretty special machines that don't have 8-bit characters - and you most likely will have OTHER problems than bits per char to use your "files" on the system then - like how to get the file there in the first place, as you probably can't plug in a USB stick or transfer it with FTP (although the latter is perhaps the most likely one)


text:
Q: Data not getting saved using RMS In my j2me app, I write data using this:
RecordStore rs = RecordStore.openRecordStore("mydb", true);
String buf = "Some text";
rs.addRecord(buf.getBytes(), 0, buf.getBytes().length);
rs.closeRecordStore();

The data stays as long as the app is running, but when I restart the app, there is no "mydb"
I tested it on emulator and device both. I know there can be some problems in emulator but it should work on the device at least.
I'm using:
Java Me SDK 3.0
CLDC 1.1
MIDP 2.0
Device: Samsung S5620
OS:Vista
Is it related to some permissions or the app should be signed before running?


text:
Q: Integrate Google, Yahoo and OpenID in android application? I want to integrate Google, Yahoo and OpenID in my android application. I have successfully done with facebook, twitter. I had used facebook android sdk for facebook integration and twitter4j-core-android-2.2.3.jar for twitter integration. Now I am looking for Yahoo, Google and openId integration. I searched for yahoo integration also registered to get consumer key, consumer secrete key and application id. But I didn't find any jar or sdk for yahoo integration. There is for iPhone but not any thing for android.
I want my user to able to login in my application using any off the yahoo, gmail, openid account.
Plz guide me to if any jars or sdk is available for these integration.
Thanks in advance....

A: You can start with the Yahoo API, the Google API, and the OpenID developer site.


text:
Q: Customer IP address on Magento Order Email The customer's IP address is stored against the order record in the back end of Magento (ver 1.7.0.2 but it is not available as a variable to add to the New Order Confirmation Email.
Can anyone help me change the email template so that I can get this field added to the email?
Many thanks

A: 6 months late maybe, but is this what you're looking for?
$order->getRemoteIp()

I've not tried it in the context of an email template but I'd guess this:
{{var remote_ip}}

or failing that, try:
{{var order.getRemoteIp()}}

FWIW I found the getRemoteIp() function used in app/design/adminhtml/default/default/template/sales/order/view/info.phtml.


text:
Q: Extract JSON from text An AJAX call is returning a response text that includes a JSON string. I need to:

*

*extract the JSON string

*modify it

*then reinsert it to update the original string

I am not too worried about steps 2 and 3, but I can't figure out how to do step 1. I was thinking about using a regular expression, but I don't know how as my JSON might have multiple levels with nested objects or arrays.

A: You cannot use a regex to extract JSON from an arbitrary text. Since regexes are usually not powerful enough to validate JSON (unless you can use PCRE) they also cannot match it - if they could, they could also validate JSON.
However, if you know that the top-level element of your JSON is always an object or array, you can go by the following approach:

*

*Find the first opening ({ or [) and last closing (} or ]) brace in your string.

*Try to parse that block of text (including the braces) using JSON.parse(). If it succeeded, finish and return the parsed result.

*Take the previous closing brace and try parsing that string. If it succeeds, you are done again.

*Repeat this until you got no brace or one that comes before the current opening brace.

*Find the first opening brace after the one from step 1. If you did not find any, the string did not contain a JSON object/array and you can stop.

*Go to step 2.

Here is a function that extracts a JSON object and returns the object and its position. If you really need top-level arrays, too, it should be to extend:
function extractJSON(str) {
    var firstOpen, firstClose, candidate;
    firstOpen = str.indexOf('{', firstOpen + 1);
    do {
        firstClose = str.lastIndexOf('}');
        console.log('firstOpen: ' + firstOpen, 'firstClose: ' + firstClose);
        if(firstClose <= firstOpen) {
            return null;
        }
        do {
            candidate = str.substring(firstOpen, firstClose + 1);
            console.log('candidate: ' + candidate);
            try {
                var res = JSON.parse(candidate);
                console.log('...found');
                return [res, firstOpen, firstClose + 1];
            }
            catch(e) {
                console.log('...failed');
            }
            firstClose = str.substr(0, firstClose).lastIndexOf('}');
        } while(firstClose > firstOpen);
        firstOpen = str.indexOf('{', firstOpen + 1);
    } while(firstOpen != -1);
}

var obj = {'foo': 'bar', xxx: '} me[ow]'};
var str = 'blah blah { not {json but here is json: ' + JSON.stringify(obj) + ' and here we have stuff that is } really } not ] json }} at all';
var result = extractJSON(str);
console.log('extracted object:', result[0]);
console.log('expected object :', obj);
console.log('did it work     ?', JSON.stringify(result[0]) == JSON.stringify(obj) ? 'yes!' : 'no');
console.log('surrounding str :', str.substr(0, result[1]) + '<JSON>' + str.substr(result[2]));

Demo (executed in the nodejs environment, but should work in a browser, too): https://paste.aeum.net/show/81/

A: For others who are looking (as I was) for extracting JSON strings from text in general (even if they're not valid), you could take a look at this Gulp plugin https://www.npmjs.com/package/gulp-extract-json-like. It searches for all strings which appear to be formatted like JSON strings.
Create a folder and install packages.
mkdir project && cd project
npm install gulp gulp-extract-json-like

Create a file ./gulpfile.js and put following content into it:
var gulp = require('gulp');
var extractJsonLike = require('gulp-extract-json-like');

gulp.task('default', function () {
  return gulp.src('file.txt')
    .pipe(extractJsonLike())
    .pipe(gulp.dest('dist'));
});

Create a file called ./file.txt which contains your text and run the following command.
gulp

Found JSON strings will be in the ./dist/file.txt.

A: If the JSON is returned as part of an ajax response, why not use the browsers native JSON parsing (beware of gotchas)? Or jQuery JSON Parsing?
If the JSON is totally mangled up with the text, that really reeks of a design issue IMHO - if you can change it, I would strongly recommend doing so (i.e. return a single JSON object as the response, with the text as a property of the object).
If not, then using RegEx is going to be an absolute nightmare. JSON is naturally very flexible, and ensuring accurate parsing is going to be not only time-consuming, but just wasteful. I would probably put in content markers at the start/end and hope for the best. But you're going to be wide-open to validation errors etc.


text:
Q: python lxml eats a lot of memory when only one element exist all,
I have a huge xml file, and need to first check the value of "status" tag in the root. It eat even double of the memory than when processing tag = item. And I have no idea why.
I use lxml version 2.3.2, and python 2.7.3 in ubuntu 14.04.
Structure of the xml is as below:
<root>
<status>s_value</status>
<count>c_value</count>
<items>
<item>***</item>
<item>***</item>
...
</items>
</root>

I try to process the file as below (ignore the namespace):
from lxml import etree
status = etree.iterparse('file.xml', tag='status')
for event, element in status:
    value = element.text
    element.clear()
del status

This code still eat a lot memory and also take long time (15s).
I tried to use a "break", and it gets the same result, but is much faster (1s), can not see the memory usage, as it is fast.
from lxml import etree
status = etree.iterparse('file.xml', tag='status')
for event, element in status:
    value = element.text
    element.clear()
    break
del status

It seems something happen after run the first status, but as there is only one element in status, I am wondering what is processed?
Dose any one has any idea what is happening? Thanks very much

A:
It seems something happen after run the first status

Yes. It is vainly searching for the second status.
Without the break, your loop must process the entire file. The loop searches for all of the <status> tags. Without reading the file to the end, it cannot know if it has found the final tag.
Alternatively, with the break, the loop stops immediately.
Consider these two loops:
for i in range(1000000):
    if i == 1:
        print(i)

for i in range(1000000):
    if i == 1:
        print(i)
        break

Hopefully, you can see that the first loop must run one million times, even though it will find the one-and-only 1 immediately.
Similarly with your code, your non-break loop must run over a bajillion lines, even though it will find the one-and-only <status> immediately.


text:
Q: Joomla blank template loading very slowly I made a site in Joomla! and its loading very slowly.
For testing purpose I removed all the contents from my templates and rendered a blank template without any modules, comp,css, images etc.
enabled debug and tested but it loading something 6.8 MB
the debug result
Profile Information
Application 0.000 seconds (+0.000); 0.77 MB (+0.767) - afterLoad
Application 1.077 seconds (+1.077); 3.83 MB (+3.065) - afterInitialise
Application 1.092 seconds (+0.015); 4.50 MB (+0.673) - afterRoute
Application 1.163 seconds (+0.071); 6.79 MB (+2.283) - afterDispatch
Application 1.167 seconds (+0.004); 6.82 MB (+0.034) - afterRender

Hosted in ISS server.
Please help.

A: do you have cache enabled? do you have 3rd party plugins? did you try disabling some system plugins? did you try on apache web server? (it also runs on windows)


text:
Q: Context not available? Im playing around trying to create a custom activity in wf4.  I found a tutorial / example and have been using this to get started, however i seem to have a problem.
public sealed class SaveRequest : NativeActivity {
    // Define an activity input argument of type string
    [RequiredArgument]
    public InArgument<Request> Request { get; set; }

    // If your activity returns a value, derive from CodeActivity<TResult>
    // and return the value from the Execute method.
    protected override void Execute(NativeActivityContext context) {
        Request Request = this.Request.Get(context);
        Request.Id = Guid.NewGuid();
        Request.Title = "New Test";
        RequestMonkeyRepository Rep = new RequestMonkeyRepository();
        Rep.save(Request);
    }
}

The code above always errors out with an null object instance when assigning the guid.  Im presuming its because i havent passed the request object to the workflow, but i cant see how they did this in the example.
Im running a console app and my execution code is below
WorkflowInvoker.Invoke(new RequestMonkeyTest1.TestWorkflow());

A: Did you set the Request InArgument in your workflow to some expression that returns an instance of a Request object? If not try adding "new Request()" in the expression and run your workflow again.


text:
Q: Elastic Net / Lasso as a solution to multiple comparisons and p-hacking? Inferential/Descriptive stats I have a very large dataset, and I'm trying to find which variable(s) may describe the truth about a certain variable. I've considered just doing OLS on variables that make logical sense. But I've stumbled upon elastic net regression, and I'm wondering, is this a solution to p-hacking?
I know it's used mostly for prediction, which is not my purpose, but does elastic net have any properties that would allow me to tailor it for descriptive statistics? i.e. make me be able to more decisively say, "This variable is more important for describing the truth about this other variable"? (I don't have too much of a background in causal inference, so if I'm thinking about this wrongly, then please let me know). Thank you so much!


text: Q: Upper bound the measure of a set My question is taken from section 1.2 of this book. Specifically, given a probability measure $\mathbf{P}$ on a metric space $\mathcal X$ (which is equipped with the metric $d$) and suppose that $X$ is a random variable taking values in $\mathcal X$ with distribution $\mathbf{P}$. The authors claimed that we have $$\mathbf{P}\left(\{x \in \mathcal{X} \colon f(x) \leq \mathbb{E} f(X)\right) \geq \frac 12,$$ where $f \colon \mathcal{X} \to \mathbb R$ is $1$-Lipschitz, i.e., $|f(x) - f(y)| \leq d(x,y)$ for all $x,y \in \mathcal{X}$. May I know how this inequality is derived? I tried a routine Markov's inequality but this inequality seems to be useless for this problem and I am really curious as to where does the $\frac 12$ come from.


text:
Q: Does building two exact matching C# projects on different computers always generate the same executable? This is assuming both computers have copied the exact same C# .NET project from one computer to the other. When you build the projects on both computers, are the executables exactly the same? If not, what's the difference?
The reason I ask is so source code can be validated as matching an executable. This is to assure users that are willing to build the program themselves that it's an exact match.

A: To quote Eric Lippert:

No.
Well, that was an easy blog to write.

There is a GUID called the "Mvid" included when you build, to ensure that each build is different. Also, the C# compiler is not guaranteed to write the same instructions each time you run it. But in practice, in similar enough environments (for some definition of "similar"), I'd expect it to.
You can tell your users about this, and allow them to check for differences. If the only difference is in the Mvid, then they're done. If there are other changes, then they'd need to examine the functionality of the IL code to make sure that it is equivalent to yours. (this can be made easier with a decompiler like ILSpy)
If they're that paranoid, the best bet is probably just to build from the source themselves every time, and use their own build. But I do understand the usefulness of being able to audit it, e.g. you'd want to know that the official TrueCrypt or Bitcoin clients are legit.


text:
Q: How to solve this operator equation? May be $\alpha(t)$ a non-invertible Operator on a Hilbert space for a real-valued Parameter $t$. Also, let be $A(t),B(t)$ arbitrary Operators also dependent on $t$ and $f(t)$ an $L^\infty$-integrable function. How can I solve the following Operator equation
$\alpha(t)(\frac{d}{dt}-A(t))f(t)=B(t)f(t)$?
My thoughts: I know that the solution of the Operator equation $(\frac{d}{dt}-A(t))f(t)=0$ is given by the parameter-ordered exponential in $A(t)$. But the Problem is that $\alpha(t)$ cannot be inverted.
Can I alternatively solve the generalized Eigenvalue Problem $det(\alpha(t)(\frac{d}{dt}-A(t))-B(t))=0$ so that I can obtain the "eigenvectors" $f(t)$?

A: Using a generalized eigenvalue problem approach would be the way to go, as this is typically the approach when one of the associated operators is non-invertable.
The problem would take the form of:
  $$
\det\left(\alpha\!\left(t\right)\left(\frac{\text{d}}{\text{d}t}-\mathbf{A}(t)\right)-\mathbf{B}(t)\right)=0
$$
The determinant being a functional determinant in this case.
Solving this will give you the eigenvalues of the operator, which you can then use to get the eigenvectors.


text:
Q: Cassandra - Per CF Partitioner I want to know if we can change the partitioner on per CF basis on the same keyspace. I want to do this because I have data on some CFs that is already hashed with murmur3 and this hash result is my partition key, and I want to avoid cassandra to perform the hash of my hash just to produce another number for the partitioning when it could simply just use mine.
Thanks.

A: No, and you cannot change a partitioner. Once set the cluster is permanently tied to it. Murmur3 is fast and there really isn't any concerned about the hash of the hash, you should still end up with balanced cluster.


text:
Q: How new keyword works in c# There's a class which is compiled into a dll
//HeaderFile.h
//version 1.0
class __declspec(dllexport) A {
    int variable;
//member functions omitted for clarity
};

//implementation file omitted for clarity

You build an exe which uses above class from the dll it was compiled into
#include "HeaderFile.h"
int main() {
    A *obj = new A();
    obj->CallSomeFuncOnObj();

    //
    //whatever
    //
}

Up til now your program is working fine. But now you recompile your dll with the following code
//HeaderFile.h
//version 2.0
class __declspec(dllexport) A {
    int variable;
    int anotherVariable;
//member functions omitted for clarity
};

//implementation file omitted for clarity

and you do not recompile your exe but start using the recompiled dll from the old exe. What will happen now is that your exe has the code that will allocate memory = sizeof(class A version 1.0) but the constructor in your new dll has code that assumes it is being passed a memory block = sizeof(class A version 2.0). There's an integer's worth size difference between the two - a recipe for unpredictability.
A similar example is shown in the first chapter of an excellent book - Essential COM by Don Box. Now for the question. In a similar situation in c#(or any other .Net languare) what would happen?

A: In COM, your DLL implements an object factory: The DLL creates the object itself in order to avoid such 'syncho' problems. In .NET, the CLR instantiates the object based on type knowledge pulled from the DLL where the type is implemented. In both cases, the problem you mention is avoided.


text:
Q: Take only first certificate found Having a behaviour for a endpoint, I specified a serviceCertificate to be used.
Everything works fine, but every year we get a new certificate on our servers while the old ones are being left undeleted.
This results in 2 valid certificates (overlapping few days in validity period), both with the same name. When having 2 certificates with the same name, using the service throws an error:

The exception message is: Found multiple X.509 certificates using the following search criteria: StoreName 'My', StoreLocation 'LocalMachine', FindType 'FindBySubjectName', FindValue 'CertName'. Provide a more specific find value

<behaviors>
  <serviceBehaviors>
    <behavior name="serviceBehaviour">
      <serviceCredentials>
        <serviceCertificate findValue="CertName" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"  />
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>

I know how to solve this problem for now by deleting the old certificate, but I found no way to solve this for long term, i.e. taking always the first valid certificate.
Is there any way to specify to take one certificate, regardless of the number of available ones that match? I don't want to modify our config files everytime we get a certifcate renewed.


text:
Q: How to delete session when user leaves page? I have a small chat website with only one page. I save all the data in session when user logs in. Session is deleted when user logs out through a logout button. But if user closes the page and comes back in like 5 minutes, he is still logged in, thus session is still active and I don't want that.

A: There's a beacon request in modern browsers that sends a request when a tab / windows is gonna be closed and guarantees its delivery (it won't be cancelled).
With its help you can send a request to terminate a session.
More info you can read here: https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API/Using_the_Beacon_API
window.onunload = function analytics(event) {
  if (!navigator.sendBeacon) return;

  var url = "https://example.com/analytics";
  // Create the data to send
  var data = "state=" + event.type + "&location=" + location.href;

  // Send the beacon
  var status = navigator.sendBeacon(url, data);

  // Log the data and result
  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};

A usual implementation - to send a ping request every N seconds and store the timestamp of the last request in the session.
When session starts to check its timestamp with current one and unset current session's variables if it differs more than 2-3 timeframes.

A: Here are some answers for your problem:
Unset Session When browser tab is closed
PHP - Session destroy after closing browser
But you can send frequent ajax requests to the server to keep the session and if within 10 second there was no ajax request, you unset session
setInterval(() => {
    // ajax requset
}, 1000)


text:
Q: ModuleNotFoundError: No module named 'XXXX' I have a Python package which looks similar to this directory structure:
paymod/
    client.py
    region.py
tests/
    unit.py

The client.py file has a class named: PayClient and has multiple methods inside it. I want to call one particular function from that class and I am importing it in Unit.py file like this:
from paymod.client import PayClient

But when I run the unit.py file by python3 unit.py I am constantly getting this error:
>> python3 unit.py
Traceback (most recent call last):
  File "unit.py", line 2, in <module>
    from paymod.client import PayClient
ModuleNotFoundError: No module named 'paymod'

Am I missing something here? It looks fine to me but I am not able to resolve this.


text:
Q: Phonegap jsCallback in Objective C So I understand that we can call a native function by
cordova.exec(success,failure,...
Instead of associating a callback like
ChildBrowser._onClose = function()
{
    window.plugins.childBrowser.onClose();
};

Instead of doing something like :
NSString* jsCallback = [NSString stringWithFormat:@"window.plugins.childBrowser.onClose('%@');", (NSString*) booleanString];

How can I call my success callback function when I successfully complete some scenario ?

A: try implement this example into your project.
make sure you already define your plugin in your config.xml
<feature name="CustomPlugin">
      <param name="ios-package" value="CustomPlugin" />
</feature>

Implementing the plug-in by using Objective-C code
CustomPlugin.h
#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>

@interface CustomPlugin : CDVPlugin

- (void)sayHello:(CDVInvokedUrlCommand*)command;

@end

CustomPlugin.m
#import "CustomPlugin.h"

    @implementation CustomPlugin

    - (void)sayHello:(CDVInvokedUrlCommand*)command{

        NSString *responseString =
            [NSString stringWithFormat:@"Hello World, %@", [command.arguments objectAtIndex:0]];

        CDVPluginResult *pluginResult =
            [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:responseString];

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }

    @end

Calling a plug-in from JavaScript
function initial(){
    var name = $("#NameInput").val();
    cordova.exec(sayHelloSuccess, sayHelloFailure, "CustomPlugin", "sayHello", [name]);
}

function sayHelloSuccess(data){
    alert("OK: " + data);
}

function sayHelloFailure(data){
    alert("FAIL: " + data);
}


text:
Q: Missing a notification for a trashed/deleted file I am using push notifications to watch changes. When I add or update a file everything is ok.
When I delete a file (i.e. it goes to bin) then I do get a notification for that file lets say changeid=81477. When I go to get that change I find that it no longer exists so I can't work out what changed. However if I then go and look at changes I can see a change id=81478 that I never received a notification for. Looking at this change I can see that explicityTrashed = true, which is indicates this is related to the deleted file.
Now, my guess is that change 81477 was superceded by 81478 for some reason, but why do I not receive a notification for 81478?
Someone (non-google) on google+ suggested keeping a track of last change processed and grabbing all changes greater than that when a notification arrives, but this is a workaround to me.
The problem I have is not getting one of the notifications at all. I am posting here in the hope that someone from Google can answer this satisfactorily.
Is it a bug? Or is it expected?
Should we not rely on getting all changes from notifications and implement something similar to suggested?


text:
Q: Is $\mathcal P(\Bbb R)\sim$ the set of all real functions defined on $\Bbb R$ with values in $\{0,1\}$? Is $\mathcal P(\Bbb R)\sim$ the set of all real functions defined on $\Bbb R$ with values in $\{0,1\}$ ?
I'm pretty sure this is true because I believe that for function $\mathfrak F$,
card ($\mathcal P(\Bbb R))=$ card$(\mathfrak F(\Bbb R))=\{\mathfrak f:\Bbb R\mapsto \{0,1\}\}=\{0,1\}^\Bbb R $. This is correct right?
I've been looking up online information on proving the cardinality equivalence of infinite sets, and to prove this, I was thinking of using an indicator/characteristic function. I'm not sure if I am writing out the proof right, but here is my attempt:
$\mathcal P(\Bbb R)=\{A: A \subseteq \Bbb R \}$
Now, create a character function of A. Let $\mathfrak f(A)= \chi _A(x)=\begin{cases}
1,  & \text{if $x\in A$} \\
0, & \text{if $x\in \Bbb R\setminus A$}
\end{cases}$
Let $B$ be another set such that $B \subseteq P(\Bbb R) $ , $ \mathfrak f(B)= \chi _B(x)$, and $\chi _B(x)=\chi _A (x)$
This implies $\chi _B(x)= \begin{cases}
1,  & \text{if $x\in B$} \\
0, & \text{if $x\in \Bbb R\setminus B$}
\end{cases}$
So, for $x\in A$ and $x\in B$, $\chi _B(x) = \chi _A(x)=1$ and
for $x\in \Bbb R\setminus A$ and $x\in \Bbb R\setminus B$, $\chi _B(x) = \chi _A(x)=0$
Thus, $ \mathfrak f(A)= \mathfrak f(B) \implies A=B$ so is one-to-one.
Let $\mathfrak g \in \{0,1\}^\Bbb R = \{\mathfrak g:\Bbb R\mapsto \{0,1\}\} $.
We know $A \subseteq \Bbb R \implies \mathfrak g(x) = \chi _A(x)$ for all $x \in \Bbb R $ so is onto.
Therefore, by definition, $\mathcal P(\Bbb R)\sim \{\mathfrak f:\Bbb R\mapsto \{0,1\}\} $.
Is this correct?
Thanks a lot.

A: This statement is correct, though your proof is not entirely correct.  In proving your map is one-to-one, it is not very clear how you are concluding that $A=B$.  You need to state more explicitly that for all $x$, $x\in A$ if and only if $x\in B$ (and why this is true).
In the proof that your map is onto, you need to explain how you are finding a set $A$ such that $\mathfrak{g}=\chi_A$.  This certainly isn't true for an arbitrary set $A\subseteq\mathbb{R}$.  So you need to explicitly define what this set $A$ is in terms of $\mathfrak{g}$.


text:
Q: Replace '/' with '-' I am trying to change the format of a date in a string from mm/dd/yyyy to mm-dd-yyyy.
I have tried using the following but it does not work
str.replace(///g,"-");

A: Two problems :

*

*you need to escape the / in the regex

*replace returns a new string and doesn't change the old one (strings are immutable)

Use
str = str.replace(/\//g, "-")

A: Since / delimits the regular expression, if you want to use a / character as data within one, you must escape it:
/\//g

A: it works.
'12/5/13'.replace(/\//g, '-');


text:
Q: docker exe into container does not show container id? When I enter a nginx container, it does not show container id on the prompt.
Also the nginx is not behaving as expected, and I have triple checked the html file that it serves.  It is showing the "Welcome to Nginx" when that html file does not exist anywhere in the container.
[ec2-user@ip-10-0-0-194 ~]$ docker -v
Docker version 1.9.1, build a34a1d5/1.9.1

[ec2-user@ip-10-0-0-194 ~]$ docker ps
CONTAINER ID        IMAGE                           COMMAND                  CREATED             STATUS              PORTS                                              NAMES
813b76df0094        quikordernginx                  "nginx -g 'daemon off"   6 minutes ago       Up 5 minutes        80/tcp, 443/tcp                                    mad_banach
bef84977861e        nscithelp/adminrenderclient:    "nginx -g 'daemon off"   6 minutes ago       Up 6 minutes                                                           small_wozniak
bdaa17e05c9d        nscithelp/adminrenderservice:   "npm start"              6 minutes ago       Up 6 minutes        0.0.0.0:1338->1338/tcp                             big_banach
2c9381e15f28        nscithelp/renderservice:        "npm start"              6 minutes ago       Up 6 minutes        0.0.0.0:1337->1337/tcp, 8000/tcp                   modest_rosalind
7096fa7ec8de        nscithelp/phoenixservices:      "npm start"              6 minutes ago       Up 6 minutes                                                           prickly_mcnulty
2e15c84fed6b        jenkinssaved                    "/bin/sh -c 'BUILD_ID"   4 days ago          Up 5 hours          0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   sick_carson
[ec2-user@ip-10-0-0-194 ~]$ docker exec -it bef8 bash
root@ip-10-0-0-194:/#

A: I figured it out... That container bef8 is using --net=host flag


text:
Q: Filenames of images in tex4ht I have two systems where I need to run tex4ht/make4ht. They are different versions of Ubuntu, I believe 18.04 LTS vs 19.04. I use the most recent version of make4ht from github, but the version of tex4ht is whatever is available in the apt package manager.
Either way, differing versions of tex4ht (presumably) mean that when compiling doc.tex with an image fig.eps, say, the image included in the HTML output is called doc0x.png on one system (the older one), and fig.png on the other.
I don't particularly mind about the naming convention here. But I would like it to be consistent, otherwise I will need to write an even worse Makefile than I already have.
So is there a way that I can either go back to the doc0x.png convention on the newer version, or activate the fig.png convention on the older one? I've read the tex4ht FAQ but I am none the wiser.

A: The original image files should be used by default. The behavior you describe is an issue which was caused by a recent update to the Graphics package. I've updated the TeX4ht sources with a fix, so it should be fixed in TL soon. Meanwhile, you can use the following graphics.4ht file:
% graphics.4ht (2019-10-13-23:30), generated from tex4ht-4ht.tex
% Copyright 1997-2009 Eitan M. Gurari
% Copyright 2009-2019 TeX Users Group
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c of this license or (at your option) any
% later version. The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions
% of LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% The Current Maintainer of this work
% is the TeX4ht Project <http://tug.org/tex4ht>.
%
% If you modify this program, changing the
% version identification would be appreciated.

   \expandafter\let\csname includegraphics \endcsname\includegraphics
\def\includegraphics{\expandafter\protect\csname includegraphics \endcsname}
\def\grf:removequote"#1"{#1}
\def\grf:thrashname#1\relax{}
\def\grf:fixquotes{%
    \@ifnextchar"{\edef\Gin@base{\expandafter\grf:removequote\Gin@base}\grf:thrashname}{\grf:thrashname}}
\def\grp:warning#1{\no:bound#1(no BoundingBox)//\:warning{#1}}
\def\no:bound#1(no BoundingBox)#2//{\gdef\noBoundingBox{#2}\ifx
   \noBoundingBox\empty \global\let\noBoundingBox\:UnDef\fi}
\let\:tempc\Gin@setfile
\pend:defIII\:tempc{\a:graphics
    \global\let\noBoundingBox\:UnDef
    \let\@latex@error\grp:warning \let\@ehc\empty}
\append:defIII\:tempc{\b:graphics\grf:gobble\leavevmode grf:gobble}
\HLet\Gin@setfile\:tempc
\NewConfigure{graphics*}[2]{%
   \expandafter\ifx \csname :.#1\endcsname\relax
      \pend:defIII\n:Gin@setfile:{\csname :.#1\endcsname}%
   \fi
   \def\:temp{#2}\ifx \:temp\empty
     \expandafter\let\csname :.#1\endcsname\:UnDef
   \else
     \expandafter\def\csname :.#1\endcsname{\edef\:temp{\detokenize{.#1}}%
        \ifx \:temp\Gin@ext  \let\a:graphics\relax
           \def\G:cnfg{#2}\expandafter\grf:gobble \fi}%
   \fi }
\NewConfigure{graphics}{2}
\def\grf:gobble#1\leavevmode#2grf:gobble{%
   \PictureOff\expandafter\grf:fixquotes\Gin@base\relax#1\PictureOn \G:cnfg \let\G:cnfg\relax}
\let\G:cnfg\relax

\let\old:GreadEps\Gread@eps
\def\Gread@eps#1{\old:GreadEps{"#1"}}
\def\if:boundingbox#1#2{\ifdim\Gin@req@width=\Gin@nat@width\ifx\noBoundingBox\UnDefined#1\else#2\fi\else#1\fi}

\Hinput{graphics}
\endinput

Here is a sample:
% https://tex.stackexchange.com/q/512238/2891

\documentclass{article}
\usepackage{graphicx}

\begin{document}

\includegraphics{example-image.png}

\includegraphics{epssample.eps}

\end{document}

And resulting html:


text:
Q: Angle between left and right tangent to the graph I am supposed to determine the angle between the left and the right tangent to the graph g, in the point $$\left [ 1, \frac{\sqrt{3}\pi }{6} \right ]$$where $$g(x)=\frac{1}{\sqrt{3}}\arcsin \frac{2x}{1+x^{2}}$$
I tried to do first derivation, which is equal to $$ \frac{2\sqrt{3}}{3+3x^{2}}$$
and limits: $$\lim_{x\rightarrow 1^{+}} \frac{2\sqrt{3}}{3+3x^{2}}=\frac{\sqrt{3}}{3}$$ and $$\lim_{x\rightarrow 1^{-}} \frac{2\sqrt{3}}{3+3x^{2}}=-\frac{\sqrt{3}}{3}$$ but I do not know, what to do next.
Can anyone help me?
Thanks

A: As has been mentioned in the comments, the correct derivative is
$$g'(x) = \frac{-2(x-1)(x+1)}{\sqrt3 (x^2+1)\cdot |x-1| \cdot |x+1|}$$
However, your limits are correct. Considering that the derivative $g'(x)$ is equal to the slope of the tangent at the point $(x, g(x))$, the angle between the tangent and the $x$ axis is $\alpha=\arctan(g'(x))$.
Hence, if $\alpha_1$ and $\alpha_2$ are the angles of the left tangent and the right tangent respectively, then the angle between them is
$$\alpha_1-\alpha_2 = \arctan\left(\frac{\sqrt3}{3}\right) - \arctan\left(-\frac{\sqrt3}{3}\right) = \frac{\pi}{3}$$


text:
Q: Problem with mdframed, lstlisting and subfig I'm trying to understand why the following code does not compile.
\documentclass[12pt]{article}
\usepackage[svgnames]{xcolor}
\usepackage{filecontents}
\usepackage{tikz}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{listings}
\lstnewenvironment{lstframed}
{
    \mdframed[backgroundcolor=LightSlateGray!10] }
{
    \endmdframed
}

\usepackage{subfig}
\begin{document}

\begin{figure}[H]
    \centering
    \subfloat[A]{
        B
    } \\
    \subfloat[C]{
        \begin{lstframed}
            D
        \end{lstframed}
    }
    \caption{E}
\end{figure}
\end{document}

If I do not use mdframed, then everything is fine, but I'm using a fancy frame in my real document, so I really need it.

A: The problem is that you are trying to put verbatim material in the argument of a command (\subfloat) and this has severe limitations, as you've experienced. One option would be to previously box the listing material:
\documentclass[12pt]{article}
\usepackage[svgnames]{xcolor}
\usepackage{filecontents}
\usepackage{tikz}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{listings}
\usepackage{subfig}

\lstnewenvironment{lstframed}
  {
    \mdframed[backgroundcolor=LightSlateGray!50]
  }
  {
    \endmdframed
  }

\newsavebox\mybox

\begin{document}

\begin{lrbox}{\mybox}
\begin{minipage}{\linewidth}
\begin{lstframed}
Some test code
\end{lstframed}
\end{minipage}
\end{lrbox}

\begin{figure}[H]
    \centering
    \subfloat[Caption for the first subfloat]{%
    \rule{5cm}{2cm}%
    } \par
    \subfloat[Caption for the second subfloat]{%
    \usebox\mybox%
    }
    \caption{E}
\end{figure}

\end{document}

Another approach here would be to use the tcolorbox package instead, since it offers out of the box support for the listings package. In any case, since you are going to place verbatim material inside the argument of \subfloat you'll need the previous boxing:
\documentclass[12pt]{article}
\usepackage[svgnames]{xcolor}
\usepackage{filecontents}
\usepackage{tikz}
\usepackage{tcolorbox}
\tcbuselibrary{listings}
\usepackage{subfig}

\newtcblisting{lstframed}{
  colback=LightGray!50,
  listing only
}

\newsavebox\mybox

\begin{document}

\begin{lrbox}{\mybox}
\begin{minipage}{\linewidth}
\begin{lstframed}
Some test code
\end{lstframed}
\end{minipage}
\end{lrbox}

\begin{figure}[H]
    \centering
    \subfloat[Caption for the first subfloat]{%
    \rule{5cm}{2cm}%
    } \par
    \subfloat[Caption for the second subfloat]{%
    \usebox\mybox%
    }
    \caption{E}
\end{figure}

\end{document}


text:
Q: Find the minimnum of the $\max{(2x_{1}+x_{2},2x_{2}+x_{3},\cdots,2x_{n-1}+x_{n})}$ Let $n$ is give postive integers,and for $x_{i}\ge 0$,such
$$x_{1}+x_{2}+\cdots+x_{n}=1$$
find $I$ minimum of the value
$$I=\max{(2x_{1}+x_{2},2x_{2}+x_{3},\cdots,2x_{n-1}+x_{n})}$$
I try to find the
$$2x_{1}+x_{2}\le I$$
$$2x_{2}+x_{3}\le I$$
$$\cdots$$
$$2x_{n-1}+x_{n}\le I$$
add all
$$(n-1)I\ge 3(x_{1}+\cdots+x_{n})-x_{1}-2x_{n}=3-x_{1}-2x_{n}$$
but $x_{1}+x_{n}$ maximum is?

A: Assume that $n\geq 2$.  Observe that, as $x_1,x_2,\ldots,x_n\geq0$ (in particular, $x_{n-1}\geq 0$), we have
$$\begin{align}
S&:=\sum_{i=1}^{n-2}\,\left(\frac{2^i-(-1)^i}{3}\right)\,2^{n-2-i}\,\left(2x_{i}+x_{i+1}\right)+2^{n-2}\left(2x_{n-1}+x_n\right)
\\
&=\left(\frac{2^n-(-1)^n}{3}\right)\,x_{n-1}+2^{n-2}\,\sum_{i=1}^{n}\,x_i\geq 2^{n-2}\,\sum_{i=1}^n\,x_i=2^{n-2}\,.
\end{align}$$
On the other hand,
$$\begin{align}
S&\leq I\left(\sum_{i=1}^{n-2}\,\left(\frac{2^i-(-1)^i}{3}\right)\,2^{n-2-i}+2^{n-2}\right)
\\&= I\,\left(2^{n-2}+(n-2)\frac{2^{n-2}}{3}-\frac{(-1)^n}{3}\,\sum_{i=1}^{n-2}(-2)^{n-2-i}\right)
\\
&=\frac{I}{3}\left((n+1)2^{n-2}-(-1)^n\,\sum_{i=0}^{n-3}\,(-2)^i\right)
\\
&=\frac{I}{3}\Biggl((n+1)2^{n-2}-(-1)^n\,\left(\frac{1-(-2)^{n-2}}{3}\right)\Biggr)
\\
&=\frac{I}{3^2\cdot 2^2}\big((3n+3)\,2^n-4\cdot(-1)^n+2^n\big)
\\
&=\frac{I}{3^2\cdot 2^2}\big((3n+4)\, 2^n-4(-1)^n\big)\,.
\end{align}\,.$$
Ergo,
$$I\geq \frac{3^2\cdot 2^2\cdot S}{(3n+4)\, 2^n-4(-1)^n}\geq \frac{9\cdot 2^n}{(3n+4)\, 2^n-4(-1)^n}\,.$$
Therefore,
$$I\geq \frac{9\cdot 2^n}{(3n+4)\, 2^n-4(-1)^n}=:m_n\,.$$
The equality holds if and only if $2x_i+x_{i+1}=m_n$ for all $i=1,2,\ldots,n-1$ and $x_{n-1}=0$, which then yields the unique minimizing point:
$$\left(x_1,x_2,\ldots,x_n\right)=\frac{m_n}{3}\,\Biggl(1-\frac{1}{(-2)^{n-2}},1-\frac{1}{(-2)^{n-3}},1-\frac{1}{(-2)^{n-4}},\ldots,0,3\Biggr)\,.$$
For instances, $m_2=1$, $m_3=\frac{2}{3}$, $m_4=\frac{4}{7}$, and $m_5=\frac{8}{17}$ with the following respective minimizing points: $(0,1)$, $\left(\frac{1}{3},0,\frac{2}{3}\right)$, $\left(\frac{1}{7},\frac{2}{7},0,\frac{4}{7}\right)$, and $\left(\frac{3}{17},\frac{2}{17},\frac{4}{17},0,\frac{8}{17}\right)$.


text:
Q: style.display="block" for event.target element and style.display="none" for other elements I am trying to set the display property to "none" for all elements that has the "option" class, but then I want to extract the element I clicked on and change the display property from "none" back to "block".
I would like to find a solution in vanilla JS.

Header 1

Header 2

Header 3

Header 4

Header 5

document.querySelector('*').addEventListener('click', (event) => {
    let clickedId = event.target.id;
    let clickedClass = event.target.className;

    if (clickedClass === "option") {
        var list = document.querySelectorAll(".option");
            for (var i = 0; i < list.length; i++) {
                    list[i].style.display = "none";
            };

            document.getElementById(clickedId).style.display = "block";
    }

    console.log(event.target.style.display);
});

Thanks

A: just ignore the one that was clicked.

document.querySelector('*').addEventListener('click', (event) => {
    let clickedId = event.target.id;
    let clickedClass = event.target.className;

    if (clickedClass === "option") {
        var list = document.querySelectorAll(".option");
            for (var i = 0; i < list.length; i++) {

                    // ignore the one that was clicked
                    if (list[i] == event.target) continue

                    list[i].style.display = "none";
            };

            // document.getElementById(clickedId).style.display = "block";
    }

    // it is only useful if you display all the hidden again.
    event.target.style.display = "block";

    console.log(event.target.style.display);
});

Header 1

Header 2

Header 3

Header 4

Header 5

A: Your code works, but does some unnecessary things like:

*

*the call to document.querySelector('*') when you already have the document object to which to attach events

*the call to document.getElementById(clickedId) when you already have the event.target to point to your clicked element

*setting the display style to none and then to block for your clicked element

Ideally, you should attach the click event to the closest parent of your elements, if possible. Here's how I would rewrite your code:
let parent = document.querySelector("#all_options_parent") || document;

parent.addEventListener('click', (event) => {
    if (event.target.className === "option") {
        event.target.style.display = "block";

        let allOptions = parent.querySelectorAll(".option");

        for (let option of allOptions) {
            if (option != event.target) {
                option.style.display = "none";
            }
        }

    }
});


text:
Q: Get specific JSON data value using array from Coin Market Cap API I want to get the symbol and other information using the "name" in my array.
$.getJSON("//api.coinmarketcap.com/v1/ticker/?limit=0", function(data) {

    var crypto = [
      "Ethereum",
      "Ripple",
      "Tron",
    ];

    // used for array to get length
    var arrayLength = crypto.length;

    for (var i = 0; i < data.length; i++) {

        console.log( data[i].name == crypto[i] );
    }
  });

I've tried to use:
console.log( data[i].name == crypto[i] );
but can't get this to work. As of now it lists everything when I only want to list data from the items in my array.
I want to get the data in the array using the name to retrieve its information from the API.
Any help is appreciated.

A: use inArray function.
example:
$.getJSON("//api.coinmarketcap.com/v1/ticker/?limit=0", function(data) {

    var crypto = [
      "Ethereum",
      "Ripple",
      "Tron",
    ];

    // used for array to get length
    var arrayLength = crypto.length;

    for (var i = 0; i < data.length; i++) {
        if(jQuery.inArray(data[i].name, crypto) !== -1)
            console.log('Finded: ' + data[i].name);
    }
  });


text:
Q: Avoid redirect in post request I'm trying to display a contents of a JSON that I receive from the backend onto the frontend without redirecting to a new page.
I want to avoid redirecting in this POST request, but it automatically goes to the URL search_results/ and prints out the json. How can I avoid this?
It does, however, print out on the console "Success in redirect post" before redirecting.
        $(document).ready(function () {
            $.extend(
            {
                redirectPost: function(location, args)
                {
                    var form = $('<form></form>');
                    form.attr("method", "post");
                    form.attr("action", location);

                    $.each( args, function( key, value ) {
                        var field = $('<input></input>');

                        field.attr("type", "hidden");
                        field.attr("name", key);
                        field.attr("value", value);

                        form.append(field);
                    });
                    $(form).appendTo('body').submit();
                }
            });

            $("#submitButton").click(function() {
                console.log("submitButton clicked")

                $("#search_form").submit(function(e) {
                    e.preventDefault();

                    $.redirectPost("./search_results/", {

                            inheritance: $("input[name=inheritance]:checked").attr("id"),
                            penetrance: $("input[name=penetrance]:checked").attr("id"),
                            mortality: $("input[name=mortality]:checked").attr("id"),

                            success: function(response){
                                console.log("Success in redirect post!")

                                var json_results_list = response.body.results_list

                            }

                    });

                });
            });
        });

My backend code looks something like this:
app.post('/search_results', callName)

function callName(request, response) {
//...insert serverside code..
//...set global_data to a JSON in string form
response.send(JSON.parse(global_data))
}

A: So basically what you want is called ajax. You don't need to create the redirectPost method which will make a invisible form and them submit it. Just use $.post instead.
$.post("./search_results/", {
    inheritance: $("input[name=inheritance]:checked").attr("id"),
    penetrance: $("input[name=penetrance]:checked").attr("id"),
    mortality: $("input[name=mortality]:checked").attr("id")
}, function (response) {
    console.log("Success in redirect post!")
    var json_results_list = response.body.results_list

});

You can check more examples here


text:
Q: Update data.table by reference but populate only certain rows when duplicates are present using a prioritized vector I didn't quite know how to word the title, but here is what I'm trying to do. I'd like to grow the data table dt1 using columns from dt2. In dt1, there are duplicated data in the column I'm updating/merging by. My goal is to populate new columns in dt1 at duplicates only if a condition is met
specified by another variable. Let me demonstrate what I mean:
library(data.table)

dt1 <- data.table(common_var = c(rep("a", 3), rep("b", 2)),
                  condition_var = c("update1", rep(c("update2", "update3"), 2)),
                  other_var = 1:5)

dt2 <- data.table(common_var = c("a", "b", "C", "d"),
                  new_var1 = 11:14,
                  new_var2 = 21:24)

# What I want to obtain is the following
dt_goal <- data.table(common_var = dt1$common_var,
                      condition_var = dt1$condition_var,
                      other_var = dt1$other_var,
                      new_var1 = c(11, NA, NA, 12, NA),
                      new_var2 = c(21, NA, NA, 22, NA))
dt_goal

Updating by reference or merging populates all the matching rows (as expected), but this is not what I want:
# Updating by reference populates all the duplicate rows as expected
# (doesn't work for my purpose)
dt1[, names(dt2) := as.list(dt2[match(dt1$common_var, dt2$common_var),])]

# merging also populates duplicate rows as expected.
# dt3 <- merge(dt1, dt2, by="common_var")

I tried overriding the rows of merged dt3 (or updated dt1) with NAs where I don't want to have data:
dt3 <- dt3[which(alldup(dt3$common_var) & dt3$condition_var %in% c("update2", "update3")), names(dt2)[2:3] := NA]
dt3

The logic in the code above finds duplicates and the unwanted conditional cases, and replaces the selected columns with NA. This partially works, with two problems:
1) If the value to keep (update1) isn't present in other duplicate rows (b in my example), they get erased too
2) This approach requires hard-coding the case I want to keep. In my real-world application, I will loop this type of data prep and the conditional values will change. I know the priority for updating the data table though:
order_to_populate_dups <- c("update1", "update2", "update3")

In other words, I want a code to grow the data table as follows:
1) When no duplicates, add columns by reference (or merge) normally
2) When duplicates are present under the id variable, look at condition_var
2a) If you see update1 add data, if not, next
2b) If you see update2 add data, if not, next
2c) If you see update3 add data, if not, next, ...
I couldn't locate a solution for this problem in SO. Please let me know if this is somehow duplicate.
Thanks!

A: Please let me know if i understood your example correctly or not. I can change the solution if needed.
# order dt1 by the common variable and
setorder(dt1, common_var, condition_var) condition
# calculate row_id for each group (grouped by common_var)
dt1[, row_index := rowid(common_var)]
# assume dt2 has only one row per common_var
dt2[, row_index := 1]

# left join on common_var and row_index, reorder columns.
dt3 <- dt2[dt1, on = c('common_var', 'row_index')][, list(common_var, condition_var, other_var, new_var1, new_var2)]

A: Are you looking for something like:
cols <- paste0("new_var", 1:2)
remap <- c(update1=1, update2=2, update3=3)
dt1[, rp := remap[condition_var]]

setkey(dt1, common_var, rp)
dt1[rowid(common_var)==1L, (cols) :=
    dt2[.SD, on=.(common_var), mget(paste0("i.",cols))]

Explanation:
You can use factor or a vector to remap your character vector into something that can be ordered accordingly. Then use setkey to sort the data before performing an update join on the first row of each group of common_var.


text:
Q: Opening Several PDF Files through Excel VBA and Saving as Text files I am trying to open several pdf files in a folder and save them as .txt files.
I have tried the approaches in the following thread
vba converting multiple pdf in folder to text file
As suggested in the answer to the above thread, I tried the following code which failed with an error "User-defined type not defined"
Sub ONLYConvertPDF()

    Dim AcroXApp As Acrobat.AcroApp
    Dim AcroXAVDoc As Acrobat.AcroAVDoc
    Dim AcroXPDDoc As Acrobat.AcroPDDoc

    Dim Filename As String, DFilename As String, jsObj As Object

    Filename = "C:\MyPath\MyFile.pdf"
    DFilename = "C:\MyPath\MyFile.txt"
    Set AcroXApp = CreateObject("AcroExch.App")
    AcroXApp.Show
    Set AcroXAVDoc = CreateObject("AcroExch.AVDoc")
    AcroXAVDoc.Open Filename, "Acrobat"
    Set AcroXPDDoc = AcroXAVDoc.GetPDDoc
    Set jsObj = AcroXPDDoc.GetJSObject
    jsObj.SaveAs DFilename, "com.adobe.acrobat.plain-text"

    AcroXAVDoc.Close False
    AcroXApp.Hide
    AcroXApp.Exit

End Sub

I have tried similar other threads involving Acrobat.acroApp, Acrobat.AcroAVDoc, Acrobat.AcroPDDoc but somewhere the same error repeats.
I also tried the Follow Hyperlink method to open pdf documents suggested in one of the threads on this forum but that method does not seem to work if you want to close the file after the file is manipulated. (I do not know how to close the file)
I have added the following libraries

When i tried to add a) PDFPrevHndlr 1.0 Type Library & b) PDFShellServer 1.0 Type Library (I do not know if either of them is necessary) I got an error "Error in loading DLL"
Do I need to add anything? I have Adobe Acrobat Reader DC installed

I do not have a good understanding of handling libraries, dLLs etc.
Can someone help please? Thank you very much in advance.

A: Xpdf provides some command-line tools, one is pdftotext.exe, what exports text from pdf to a file.
Private Sub PdfToText(ByVal PdfPath As String, ByVal TextPath As String)
Const PathToPdfToText As String = "" '"path\to\exe" 'add path to exe if not in windows path
With CreateObject("wscript.shell")
    .Run Chr(34) & PathToPdfToText & "pdftotext.exe" & Chr(34) & " " & Chr(34) & PdfPath & Chr(34) & " " & Chr(34) & TextPath & Chr(34), 1, 1
End With
End Sub

use like
PdfToText "path\to\pdfdoc.pdf", "path\to\textfile.txt"

Old reader control suggestion (maybe useful for someone) is missing SaveAs method
Get Adobe Reader AciveX control in Office x86
On an elevated powershell do:
& "$env:SystemRoot\SysWOW64\regsvr32"  "C:\Program Files (x86)\Common Files\Adobe\Acrobat\ActiveX\AcroPDFImpl.dll"

to register the control.
After registering you have an "Adobe PDF Reader Imp" ActiveX control that can be used on x86. Credits for that go to Nouba.
But I am not sure if Reader provides saveas text.

A: You need Adobe Acrobat Professional installed!  Try this code.
Option Explicit
Option Private Module

Sub SavePDFAsOtherFormat(PDFPath As String, FileExtension As String)

    'Saves a PDF file as another format using Adobe Professional.

    'By Christos Samaras
    'https://myengineeringworld.net/////

    'In order to use the macro you must enable the Acrobat library from VBA editor:
    'Go to Tools -> References -> Adobe Acrobat xx.0 Type Library, where xx depends
    'on your Acrobat Professional version (i.e. 9.0 or 10.0) you have installed to your PC.

    'Alternatively you can find it Tools -> References -> Browse and check for the path
    'C:Program FilesAdobeAcrobat xx.0Acrobatacrobat.tlb
    'where xx is your Acrobat version (i.e. 9.0 or 10.0 etc.).

    Dim objAcroApp      As Acrobat.AcroApp
    Dim objAcroAVDoc    As Acrobat.AcroAVDoc
    Dim objAcroPDDoc    As Acrobat.AcroPDDoc
    Dim objJSO          As Object
    Dim boResult        As Boolean
    Dim ExportFormat    As String
    Dim NewFilePath     As String

    'Check if the file exists.
    If Dir(PDFPath) = "" Then
        MsgBox "Cannot find the PDF file!" & vbCrLf & "Check the PDF path and retry.", _
                vbCritical, "File Path Error"
        Exit Sub
    End If

    'Check if the input file is a PDF file.
    If LCase(Right(PDFPath, 3)) <> "pdf" Then
        MsgBox "The input file is not a PDF file!", vbCritical, "File Type Error"
        Exit Sub
    End If

    'Initialize Acrobat by creating App object.
    Set objAcroApp = CreateObject("AcroExch.App")

    'Set AVDoc object.
    Set objAcroAVDoc = CreateObject("AcroExch.AVDoc")

    'Open the PDF file.
    boResult = objAcroAVDoc.Open(PDFPath, "")

    'Set the PDDoc object.
    Set objAcroPDDoc = objAcroAVDoc.GetPDDoc

    'Set the JS Object - Java Script Object.
    Set objJSO = objAcroPDDoc.GetJSObject

    'Check the type of conversion.
    Select Case LCase(FileExtension)
        Case "eps": ExportFormat = "com.adobe.acrobat.eps"
        Case "html", "htm": ExportFormat = "com.adobe.acrobat.html"
        Case "jpeg", "jpg", "jpe": ExportFormat = "com.adobe.acrobat.jpeg"
        Case "jpf", "jpx", "jp2", "j2k", "j2c", "jpc": ExportFormat = "com.adobe.acrobat.jp2k"
        Case "docx": ExportFormat = "com.adobe.acrobat.docx"
        Case "doc": ExportFormat = "com.adobe.acrobat.doc"
        Case "png": ExportFormat = "com.adobe.acrobat.png"
        Case "ps": ExportFormat = "com.adobe.acrobat.ps"
        Case "rft": ExportFormat = "com.adobe.acrobat.rft"
        Case "xlsx": ExportFormat = "com.adobe.acrobat.xlsx"
        Case "xls": ExportFormat = "com.adobe.acrobat.spreadsheet"
        Case "txt": ExportFormat = "com.adobe.acrobat.accesstext"
        Case "tiff", "tif": ExportFormat = "com.adobe.acrobat.tiff"
        Case "xml": ExportFormat = "com.adobe.acrobat.xml-1-00"
        Case Else: ExportFormat = "Wrong Input"
    End Select

    'Check if the format is correct and there are no errors.
    If ExportFormat <> "Wrong Input" And Err.Number = 0 Then

        'Format is correct and no errors.

        'Set the path of the new file. Note that Adobe instead of xls uses xml files.
        'That's why here the xls extension changes to xml.
        If LCase(FileExtension) <> "xls" Then
            NewFilePath = WorksheetFunction.Substitute(PDFPath, ".pdf", "." & LCase(FileExtension))
        Else
            NewFilePath = WorksheetFunction.Substitute(PDFPath, ".pdf", ".xml")
        End If

        'Save PDF file to the new format.
        boResult = objJSO.SaveAs(NewFilePath, ExportFormat)

        'Close the PDF file without saving the changes.
        boResult = objAcroAVDoc.Close(True)

        'Close the Acrobat application.
        boResult = objAcroApp.Exit

        'Inform the user that conversion was successfully.
        MsgBox "The PDf file:" & vbNewLine & PDFPath & vbNewLine & vbNewLine & _
        "Was saved as: " & vbNewLine & NewFilePath, vbInformation, "Conversion finished successfully"

    Else

        'Something went wrong, so close the PDF file and the application.

        'Close the PDF file without saving the changes.
        boResult = objAcroAVDoc.Close(True)

        'Close the Acrobat application.
        boResult = objAcroApp.Exit

        'Inform the user that something went wrong.
        MsgBox "Something went wrong!" & vbNewLine & "The conversion of the following PDF file FAILED:" & _
        vbNewLine & PDFPath, vbInformation, "Conversion failed"

    End If

    'Release the objects.
    Set objAcroPDDoc = Nothing
    Set objAcroAVDoc = Nothing
    Set objAcroApp = Nothing

End Sub

See the link below for more details.
https://myengineeringworld.net/2013/03/vba-macro-to-convert-pdf-files-into.html
Or, if you don't have a Acrobat installed, try the solution below, and of course, change the code to suit your needs.
Sub ChangeDocsToTxtOrRTFOrHTML()
    'with export to PDF in Word 2007
    Dim fs As Object
    Dim oFolder As Object
    Dim tFolder As Object
    Dim oFile As Object
    Dim strDocName As String
    Dim intPos As Integer
    Dim locFolder As String
    Dim fileType As String
    On Error Resume Next

    locFolder = InputBox("Enter the folder path to DOCs", "File Conversion", "C:\Users\your_path_here\")
    Select Case Application.Version
        Case Is < 12
            Do
                fileType = UCase(InputBox("Change DOC to TXT, RTF, HTML", "File Conversion", "TXT"))
            Loop Until (fileType = "TXT" Or fileType = "RTF" Or fileType = "HTML")
        Case Is >= 12
            Do
                fileType = UCase(InputBox("Change DOC to TXT, RTF, HTML or PDF(2007+ only)", "File Conversion", "TXT"))
            Loop Until (fileType = "TXT" Or fileType = "RTF" Or fileType = "HTML" Or fileType = "PDF")
    End Select

    Application.ScreenUpdating = False
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set oFolder = fs.GetFolder(locFolder)
    Set tFolder = fs.CreateFolder(locFolder & "Converted")
    Set tFolder = fs.GetFolder(locFolder & "Converted")

    For Each oFile In oFolder.Files
        Dim d As Document
        Set d = Application.Documents.Open(oFile.Path)
        strDocName = ActiveDocument.Name
        intPos = InStrRev(strDocName, ".")
        strDocName = Left(strDocName, intPos - 1)
        ChangeFileOpenDirectory tFolder
        Select Case fileType
            Case Is = "TXT"
                strDocName = strDocName & ".txt"
                ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatText
        Case Is = "RTF"
                strDocName = strDocName & ".rtf"
                ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatRTF
        Case Is = "HTML"
                strDocName = strDocName & ".html"
                ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatFilteredHTML
        Case Is = "PDF"
                strDocName = strDocName & ".pdf"
                ActiveDocument.ExportAsFixedFormat OutputFileName:=strDocName, ExportFormat:=wdExportFormatPDF
        End Select
        d.Close
        ChangeFileOpenDirectory oFolder
    Next oFile
    Application.ScreenUpdating = True

End Sub


text:
Q: Proving the formula of a function much similar to the Dirichlet kernel. Many of us know about the Dirichlet kernel which is on lower level stated as

$$D_n(\theta) =\frac {\sin \left(n+\frac 12\right)\theta}{\sin \frac {\theta}{2}}=1+2\sum_{r=1}^n \cos (r\theta)$$

I have a devised another similar formula for

$$\frac {\cos \left(n+\frac 12\right)\theta}{\cos \frac {\theta}{2}}$$

which I have verified and proved using some simple trigonometry and telescoping series but I want to know if I could somehow prove the result using complex numbers which I know is possible in the case of Dirichlet kernel. So the similar formula I devised be defined as

$$F_n(\theta)=
\frac {\cos \left(n+\frac 12\right)\theta}{\cos \frac {\theta}{2}}=  (-1)^n\left(1+2\sum_{r=1}^n (-1)^r \cos(r\theta)\right) $$

Any hints or some kind of help would be very beneficial.

A: You can actually prove it from the Dirichlet kernel by substituting for the angle. Replacing $\theta$ by $\theta+\pi$, we have
$$ \frac{\sin{(n+1/2)(\theta+\pi)}}{\sin{(\theta+\pi)/2}} = \frac{\sin{(n+1/2)\theta}\cos{(n+1/2)\pi}+\cos{(n+1/2)\theta}\sin{(n+1/2)\pi}}{\cos{(\theta/2)}} \\
= \frac{\cos{(n+1/2)\theta}}{\cos{\theta}} (-1)^n, $$
while on the other side, $\cos{(r(\theta+\pi))} = \cos{r\theta}\cos{r\pi} = (-1)^r \cos{r\theta}$. Putting these together gives the result.
This also tells you that if you really want, you can prove this using complex numbers by considering the sum of $e^{ir(\theta+\pi)}$, with exactly the same steps as the Dirichlet kernel.


text:
Q: How do I convert the decimal value in hex string and hex string and hex string to byte I have bytes array of decimal values like [0, 4, 20, 141] and I want that to be converted as [0x00, 0x04, 0x14, 0x8D] which I need to use this array as bytes to add in a buffer
Current data:
byte[] packet = new byte[4];

packet[0] = 0;
packet[1] = 4;
packet[2] = 20;
packet[3] = 141;

and expected data to send to the serial port is as below:
byte[] mBuffer = new byte[4];

mBuffer[0] = 0x02;
mBuffer[1] = 0x04;
mBuffer[2] = 0x14;
mBuffer[3] = 0x8D;

Tried:
Convert.ToByte(string.Format("{0:X}", packet[0]));

But throwing an exception:

Input string was not in a correct format.

A: You're getting the exception because you're trying to substitute a variable in the string without the "$" prefix. Try this:
// Converts integer 141 to string "8D"
String parsed = String.Format($"{0:X}", packet[3]);

Then, you should be able to convert to a byte using this:
// Parses string "8D" as a hex number, resulting in byte 0x8D (which is 141 in decimal)
Byte asByte = Byte.Parse(parsed, NumberStyles.HexNumber);


text:
Q: How to write protractor test for aria-hidden How to identify whether the aria-hidden attribute is true or not in protractor tests. The place I want to use it is here.

Thanks in advance.

A: You could use
expect(element(by.css('span')).getAttribute('aria-hidden')).toBeTruthy()


text:
Q: Joomla 2.5 ACL restrict to specific features/views I seem to be having a problem identifying how to restrict Joomla 2.5 back-end users to specific features / Views in a custom component I am writing.  According to my understanding I should be able to add my views as a section in the access.xml file.  I have attempted this by naming a section the same name as my view but I don't seem to be able to change the access to that view independently from the component as a whole.  Does anybody have a more in depth example I can review or tips?  Is this even possible?

A: I believe what you are trying to do is not supported by Joomla.
My suggestion is to add a custom rule for views in access.xml

   <action name="core.admin" title="JACTION_ADMIN" description="JACTION_ADMIN_COMPONENT_DESC" />
   <action name="core.manage" title="JACTION_MANAGE" description="JACTION_MANAGE_COMPONENT_DESC" />
   <action name="core.create" title="JACTION_CREATE" description="JACTION_CREATE_COMPONENT_DESC" />
   <action name="core.delete" title="JACTION_DELETE" description="JACTION_DELETE_COMPONENT_DESC" />
   <action name="core.edit" title="JACTION_EDIT" description="JACTION_EDIT_COMPONENT_DESC" />
   <action name="core.edit.state" title="JACTION_EDITSTATE" description="COM_CATEGORIES_ACCESS_EDITSTATE_DESC" />

   <action name="core.admin" title="JACTION_ADMIN" description="JACTION_ADMIN_COMPONENT_DESC" />

Then save your view in the #__assets table with a name like com_component.view.playerlist,
in the rules field you should save a JSON encoded list of your rules:
{"core.admin":{}}

You can check if current user can or cannot access a determinate section using JAccess
$user_id=JFactory::getUser()->id;
$has_permission = JAccess::check($user_id,'core.admin','com_component.view.playerlist');
if($has_permission){
    draw_view();
}else{
    JError::riseError(403,JText::_('PERMISSION_DENIED'));
    // or
    JError::raiseWarning(403,JText::_('PERMISSION_DENIED'));
}

If you have any doubt, feel free to comment.