text:
Q: Pandas date time with timezone to timestamp I am playing with some data. Out of all, two columns make me curious, Datetime and Timezone. Sample data looks like:
|-----------------|------------|
| Datetime        | Timezone   |
|-----------------|------------|
| 2446159.1805556 | -5.5000000 |
| 2434633.2902778 | -5.5000000 |
| 2444298.3437500 | -5.5000000 |
| 2442694.3125000 | -5.5000000 |
| 2444622.0604167 | -5.5000000 |
| 2435409.3854167 |  8.0000000 |
|-----------------|------------|

While trying to convert these to timestamp format (YYYY-MM-DD hh:mm:ss), using the code below, I am getting all dates as 1970-01-29:
pd.to_datetime(df['Datetime'], unit='s')

How can I convert to the right date in the right timezone? I don't know the actual output, but I am certain that all dates are not going to be the same.

A: You can use the Timestamp class.
start = pd.Timestamp(2446159.1805556,unit ='s')
print(start)

Output

1970-01-29 07:29:19.180555600


text:
Q: MySql - Selecting if matching multiple values I have a DB like this:
TagSetMap
id | setId | tagId
------------------
1  |  1    |  1
2  |  2    |  2
3  |  3    |  1
4  |  3    |  2

I want to retrieve the setId if tagId matches 1 AND 2, which I've been able to do with:
SELECT TagSetMap.SetId From TagSetMap
WHERE TagSetMap.TagId IN (1, 2)
GROUP BY TagSetMap.SetId HAVING COUNT(*) = 2

However, this query doesn't work if I'm trying to get something like tagID = 1, because it will give me back both SetId = 1 and SetId = 3, even with the following query:
SELECT TagSetMap.SetId From TagSetMap
WHERE TagSetMap.TagId IN (1)
GROUP BY TagSetMap.SetId HAVING COUNT(*) = 1

Is there a way to modify the query so that it only gives me results that explicitly match my target set (and not supersets)?
Thank you!

A: select setId
from your_table
where tagId in (1,2)
group by setId
having sum(tagId = 1) > 0
or count(distinct tagId) = 2

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: signin.handleSignin is not a function I"ve seen this question asked before, but I cannot quite figure out what it is I'm doing wrong. I have an endpoint: app.post('/signin', signin.handleSignin(db, bcrypt)) in my server.js file. The console is alerting me that signin.handleSignIn is not a function. This endpoint is linked to a file in my controllers folder that is signin.js that looks like this:
const handleSignin = (db, bcrypt) => (req, res) => {
    const { email, password } = req.body;
    if (!email || !password) {
      return res.status(400).json('incorrect form submission');
    }
    db.select('email', 'hash').from('login')
      .where('email', '=', email)
      .then(data => {
        const isValid = bcrypt.compareSync(password, data[0].hash);
        if (isValid) {
          return db.select('*').from('users')
            .where('email', '=', email)
            .then(user => {
              res.json(user[0])
            })
            .catch(err => res.status(400).json('unable to get user'))
        } else {
          res.status(400).json('wrong credentials')
        }
      })
      .catch(err => res.status(400).json('wrong credentials'))
  }`enter code here`

 export default handleSignin;

server.js code:
import express, { application, response } from "express";
import bcrypt, { hash } from "bcrypt-nodejs";
import cors from "cors";
import knex from "knex";
import signin from "./controllers/signin.js"
const db = knex({
  client: "pg",
  connection: {
    host: "127.0.0.1",
    port: 5432,
    user: "postgres",
    password: "test",
    database: "smart-brain",
  },
});

db.select("*")
  .from("users")
  .then((data) => {});

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());

app.get("/", (req, resp) => {
  resp.send(db.users);
});

app.post('/signin', signin.handleSignin(db, bcrypt))

app.post("/signin", (req, resp) => {
  db.select("email", "hash")
    .from("login")
    .where("email", "=", req.body.email)
    .then((data) => {
      const isValid = bcrypt.compareSync(req.body.password, data[0].hash);
      if (isValid) {
        return db
          .select("*")
          .from("users")
          .where("email", "=", req.body.email)
          .then((user) => {
            console.log(user);
            resp.json(user[0]);
          })
          .catch((err) => resp.status(400).json("Unable to get user"));
      } else {
        resp.status(400).json("Wrong credentials");
      }
    })
    .catch((err) => resp.status(400).json("Wrong credentials"));
});

app.post("/register", (req, resp) => {
  const { name, email, password } = req.body;
  const hash = bcrypt.hashSync(password);
  db.transaction((trx) => {
    trx
      .insert({
        hash: hash,
        email: email,
      })
      .into("login")
      .returning("email")
      .then((loginemail) => {
        trx("users")
          .returning("*")
          .insert({
            name: name,
            email: loginemail[0],
            joined: new Date(),
          })
          .then((user) => {
            resp.json(user[0]);
          });
      })
      .then(trx.commit)
      .catch(trx.rollback);
  }).catch((err) => resp.status(400).json("unable to register"));
  // bcrypt.hash(password, null, null, function (err, hash) {
  //   console.log(hash);
  // });
});

app.get("/profile/:id", (req, resp) => {
  const { id } = req.params;
  db.select("*")
    .from("users")
    .where({ id })
    .then((user) => {
      if (user.length) {
        resp.json(user[0]);
      } else {
        resp.status(400).json("Not found");
      }
    })
    .catch((err) => resp.status(400).json("Error getting user"));
  // if (!found) {
  //   resp.status(400).json("not found");
  // }
});

app.put("/image", (req, resp) => {
  const { id } = req.body;
  db("users")
    .where("id", "=", id)
    .increment("entries", 1)
    .returning("entries")
    .then((entries) => {
      resp.json(entries[0]);
    })
    .catch((err) => resp.status(400).json("Unable to get entries"));
});

app.listen(3001, () => {
  console.log("App is running at port 3001");
});

A: You didn't exported signin from signin.js, you exported handleSignin.
so just import handleSignin and call it directly.
import handleSignin from "./controllers/signin.js"
...
app.post('/signin', handleSignin(db, bcrypt))


text:
Q: SAS: Reading all files containing a specific string I would like to read a set of files that all contain a specific string (xxx*.csv). So if my folder has the files below, the code should read in file #1 and #2.
1. xxx_123.csv
2. xxx_456.csv
3. xyz_111.csv
The first part of the filename is known, but the second part is unknown. Anyone know how I can achieve this in SAS Enterprise Guide?

A: You can create a wildcard fileref, not sure how to do it interactively in EG, but in Base SAS the code would be similar to the below.

filename wildxxx "/path/xxx*.csv" ;

data readin ;
  infile wildxxx /* + infile options */;
  /* input statement */
run ;


text:
Q: confusion with instanceof Array and String i read instanceof answer,but i have a question
When i code
["a","b"] instanceof Array

why it reutrns true as the same as
new Array("a","b") instanceof Array

while
"a" instanceof String

returns false not as the same as
new String("ab") instanceof String

?
very appreciate for your answers and help!

A: For strings, you have both

*

*primitive strings (the ones you manipulate most of the times, and that you get from literals)

*and instances of the String class.

And they're not the same.
Here's what the MDN says on the distinction between both.
Another way to see the difference, which the MDN doesn't point, is that you can add properties on objects :
var a = "a";
a.b = 3; // doesn't add the property to a but to a wrapped copy
console.log(a.b);  // logs undefined
a = new String("a");
a.b = 3;
console.log(a.b);  // logs 3

(remember that most of the times, you should use primitive strings)
For arrays, you only have arrays, there is nothing like a primitive array.

A: In your case
"a"

is not a String Object, it is a String literal or as it is called a "primitive".
So JS is not betraying you, claiming, that "a" is not an instance of String.
CF MDN on String

A: The instanceof check is defined as:

When the [[HasInstance]] internal method of F is called with value V,
  the following steps are taken:

*

*If V is not an object, return false.

*Let O be the result of calling the [[Get]] internal method of F with property name "prototype".

*If Type(O) is not Object, throw a TypeError exception.

*Repeat

*

*Let V be the value of the [[Prototype]] internal property of V.

*If V is null, return false.

*If O and V refer to the same object, return true.

So string fails the very first step because string is not an object. Also note that new String doesn't return a string but an object constructed from a constructor called String. This is one example how Java and Javascript is completely different.
Here is also code for a custom instanceOf, make it work however you like then:
function instanceOf(F, V) {
    if( typeof F !== "function" ) {
        throw new Error( "F must be a constructor" );
    }
    if( Object(V) !== V ) {
        return false; //not an object
    }
    var O = F.prototype;
    if( Object(O) !== O ) {
        throw new Error( ".prototype must be an object" );
    }
    while( true ) {
        V = Object.getPrototypeOf(V);
        if( V == null ) {
            return false;
        }
        if( V === O ) {
            return true;
        }
    }
}


text:
Q: Find all expressions of four 10s I was challenged with a CS problem.
The problem consists of recursively finding which expressions of the form ((10+10)/(10+10)) produces a number. For example, ((10+10)/(10+10)) produces 1. Find all the other expressions using the operators +, -, *, /, with 4 numbers of 10, and all the combinations of parentheses to enforce orders of operations.
I was referred to the Reverse Polish Notation, but that relies on postfix notation, which isn't required to solve this problem.
Some pseudocode I have is this. I know using recursion is the easiest way to solve this problem. But don't know how to make sure I get all combinations.
build([10,10,10,10], Expression) :-
      Operator
     /       \
   [10]     [10,10,10]
             Operator
              /     \
           [10]     [10,10]
                    Operator
                     /    \
                   [10]   [10]

This is a problem I am trying to solve in Prolog but C++ is good as well.

A: I have a partial solution which I will outline here and hopefully it will get you moving and you can find the complete solution.
The first tool you need is the ability to make some expressions:
build_expr(X, Y, X+Y).
build_expr(X, Y, X*Y).
build_expr(X, Y, X-Y).
build_expr(X, Y, X/Y).

This defines build_expr/3, which takes two variables or expressions and produces a new expression. This is how we are going to permute the operators. Now we need a way to handle the lists, so let's define build_expr/2 that operates on a list at once:
% base case: we are down to two variables and call build_expr/3
build_expr([X,Y], Expr) :- build_expr(X, Y, Expr).

% inductive case: make the expression on the rest of the list and combine
% with the leading variable here
build_expr([X|Rest], Expr) :-
    build_expr(Rest, Expr0),
    build_expr(X, Expr0, Expr).

Let's get a few solutions so we get the flavor of what it's doing:
3 ?- build_expr([10,10,10,10],X).
X = 10+(10+(10+10)) ;
X = 10*(10+(10+10)) ;
X = 10-(10+(10+10)) ;
X = 10/(10+(10+10)) ;
X = 10+10*(10+10) ;
X = 10*(10*(10+10)) ;
X = 10-10*(10+10) ;
X = 10/(10*(10+10)) ;
X = 10+(10-(10+10)) ;
X = 10*(10-(10+10)) ;
X = 10-(10-(10+10)) ;
X = 10/(10-(10+10)) ;

This looks pretty good to me. But like I said, I'm only generating the right-leaning tree. You will have to modify or replace build_expr/2 to produce the other shapes, if they actually matter (which I'm not convinced they do).
Now let's make the next step simpler by bundling in evaluation:
build_eval(L, Value) :- build_expr(L, Expr), Value is Expr.

Now we should be able to find all the unique solutions using setof/3:
6 ?- setof(X, build_eval([10,10,10,10],X), Results).
ERROR: Arithmetic: evaluation error: `zero_divisor'
ERROR: In:
ERROR:   [15] _582 is 10/(10* ...)
ERROR:   [14] build_eval([10,10|...],_622) at /Users/dlyons/fourtens.pl:11
ERROR:   [13] '$bags':findall_loop(_664,user:build_eval(...,_682),_668,[]) at /usr/local/Cellar/swi-prolog/7.6.4/libexec/lib/swipl-7.6.4/boot/bags.pl:97
ERROR:   [12] setup_call_catcher_cleanup('$bags':'$new_findall_bag','$bags':findall_loop(_728,...,_732,[]),_710,'$bags':'$destroy_findall_bag') at /usr/local/Cellar/swi-prolog/7.6.4/libexec/lib/swipl-7.6.4/boot/init.pl:443
ERROR:    [8] '$bags':setof(_770,user:build_eval(...,_786),_774) at /usr/local/Cellar/swi-prolog/7.6.4/libexec/lib/swipl-7.6.4/boot/bags.pl:240
ERROR:    [7] <user>
ERROR:
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.
ERROR:   [13] '$bags':findall_loop(_664,user:build_eval(...,_682),_668,[]) aabort
% Execution Aborted

Oops. Division by zero error. No problem, let's catch that and fail in those cases instead:
9 ?- setof(X, catch(build_eval([10,10,10,10],X), E, fail), Results), writeln(Results).
[-990,-900,-190,-100,-80,-20,-1,-0.1111111111111111,
 0,0.01,0.05,0.09090909090909091,0.3333333333333333,1.0,1,
 5.0,9.5,9.9,10,10.1,10.5,20.0,20,40,100.0,100,
 120,210,300,1010,1100,2000,10000]

I fiddled with the formatting there a little, but I think that's a pretty good solution, but I can already see one missing solution: (10+10)*(10+10)=400. So you will have to get more creative with build_expr/2 to make it produce other shapes of tree.
Edit: Adding the rest of the solutions
I found an answer by @gusbro that gives a way to enumerate the trees. I wasn't able to get it to work with the recursive trickery I was doing there (maybe someone else will show me a very easy trick) but I was able to adapt his answer to your problem, to wit:
build_tree([I1,I2|Items], Expr) :-
    append([L0|LR], [R0|RR], [I1,I2|Items]),
    build_tree([L0|LR], Left),
    build_tree([R0|RR], Right),
    build_expr(Left, Right, Expr).
build_tree([E], E).

Why am I using [L0|LR] and [R0|RR] instead of LeftList and RightList or some such? This is how I'm turning @gusbro's numeric constraints into list length constraints and ensuring that I always have at least one element in both the left and right lists, so my recursive calls to build_tree/2 will succeed.
Simplifying build_expr/3 from above down to a single operator you can see this generates all the various flavors you'd expect:
?- build_tree([10,10,10,10],X).
X = 10+(10+(10+10)) ;
X = 10+(10+10+10) ;
X = 10+10+(10+10) ;
X = 10+(10+10)+10 ;
X = 10+10+10+10 ;
false.

Switch it back, because we're still using the build_expr/3 function from the earlier example. I have simplified the evaluation somewhat using this build_eval/2 predicate:
build_eval(L, Value) :-
    build_tree(L, Expr), catch(Value is Expr, _, fail).

Here's what the final solution looks like:
 ?- setof(X, build_eval([10,10,10,10], X), Res), writeln(Res).
[-990,-900,-190,-100,-99,-90,-80,-20,-19,-10,-9.9,-9.5,-9,
 -8,-1.1111111111111112,-1,-0.9,-0.1111111111111111,
 0,0.01,0.05,0.09090909090909091,0.1111111111111111,
 0.2,0.3333333333333333,0.9,0.9090909090909091,1.0,1,
 1.1,1.1111111111111112,2,3,5.0,5,8,9,9.5,9.9,10,10.1,10.5,11,
 12,19,20.0,20,21,40,80,90,99,100.0,100,101,110,120,190,
 200,210,300,400,900,990,1010,1100,2000,10000]

Wow, quite a few alternatives, 68 to be exact!


text:
Q: How to share data between 2 apps in Android? Is there any way to share data between 2 different Applications?
I know how to share data between Activities in the same Application.
Please help me out.

A: you might get your problem solved in this link, which will show you how to create content provider for sharing your app's data with other apps
Android Content Provider

A: in your AndroidManifest  of the activity you want to send the data, register an BroadcastReceiver that will listen for Share Intents like this:
<activity android:name=".YourActivity">
<intent-filter
    android:label="Share with my app">
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

and than in your activity that has the share button:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));


text:
Q: Conditional expectation of a Poisson Process Given a Poisson process with parameter $q$, and if $X$ is the number of arrivals during $(0, 1]$, then what is $E(X | X > 0)$?
Could I use the memorylessness of the process to write:
$1 + E(X)$?
Thanks everyone.

A: Since $X$ has Poisson distribution with mean $q$, we compute
$$
\mathbb E\left[X\mid X>0\right] = \frac{\mathbb E\left[X\mathsf 1_{\left\{ X>0\right\}}\right]}{\mathbb P(X>0)} = \frac{\mathbb E\left[X\right]}{\mathbb P(X>0)} = \frac q{1-e^{-q}}.$$


text:
Q: CloudKit: Query predicate list against array I'm looking to construct a predicate which checks if a list of strings in CloudKit contains any element in an array of strings. I know I can check if a string is in a list in CloudKit by using the CONTAINS predicate, and I also know I can check if a string field is in an array using the IN predicate, however due to using an array/list of strings on both sides of the predicate I need form a CONTAINS IN predicate. anyone know how?

A: Use ANY array IN otherArray within the predicate


text:
Q: Looking to build a new desktop machine I'm in need of a new desktop machine for both work and play. I'll be running a few VBox instances at once and would like to have multiple monitors connected to this machine to support these instances. The goal is to have 4 monitors so I can run these instances and view them at the same time (still need the money for this but it is my goal hahaha). Rather then just tossing money around and hoping I'd like to start doing some research now on hardware. Where should I look to get a good idea which items are compatible with Ubuntu and fully support the OS? In the past I was building more for Windows and would run Ubuntu in an image but now I an finally be done with Windows and really want to build this machine solely for Ubuntu :)

A: Intel Provides an as-is linux compatibility lists for SOME motherboards.
List For Intel Desktop Boards:
Step #1 = http://www.intel.com/p/en_US/support/dsktpboards
Step #2 = Choose A Board
Step #3 = Under "Compatibility" choose supported operating systems. [Usually there are several charts, the first is windows only the second is windows and linux testing]
Intel Server/Workstation Boards:
Step #1 = http://www.intel.com/p/en_US/support/server
Step #2 = Scroll down to "Sever Motherboards"
Step #3 = Choose A Board
Step #4 = Under "Compatibility" choose "Tested Operating Systems" [Depending which board you've selected there may be little or no testing, while others have a fair bit]


text:
Q: MSVC project missing "__popcountdi2" when linking against GCC-built static library I have a windows executable project that links against a static library (.lib) built with GCC 6 (MinGW). The following error occurs during compilation:
LNK2019 unresolved external symbol __popcountdi2 referenced in function ...

The symbol is linked in as a result of using a GCC built-in function __builtin_popcount(), which resides in libgcc. However, despite adding -static-libgcc as an argument to gcc, the problem still persists.
Is there a way for my library (.lib) to contain parts of libgcc rather than requiring libgcc to be on the system for an executable to link against? Is some way around having to ship the library with libgcc?
__builtin_popcount() is not the only built-in function that I'm currently using. The library makes use of __builtin_bswap32(), which doesn't seem to run into this issue.
I'm using GCC 6.1.0. Updated to 6.2.0; same issue.

A: The issue was that on windows, MinGW (GCC) was not detecting the current CPU architecture properly when -march=native was passed in. It was falling back to an architecture that did not support POPCNT as a native instruction (probably i686). As a test, -mpopcnt was added to the build and everything worked fine.
The fix is to manually specify the architecture using -march=.
Furthermore: is this a bug with MingGW since the native architecture is not polled for properly?


text:
Q: How do I call a helper function to calculate percentiles by unique identifiers using Pandas? I have a dataset that shows unique ID and a numerical metric called "hardened_print_length". I am storing the unique IDs and metrics in a Pandas dataframe and need to calculate percentiles (exclusive) by each unique ID (50th percentile, 75th, 95th). I am using the following helper function:
def quantile_exc(ser, q):
     ser_sorted = ser.sort_values()
     rank = q * (len(ser) + 1) - 1
     assert rank > 0, 'quantile is too small'
     rank_l = int(rank)
     return ser_sorted.iat[rank_l] + (ser_sorted.iat[rank_l + 1] -
                                 ser_sorted.iat[rank_l]) * (rank - rank_l)

Calling Function (percentile_staging is a two column dataframe storing the unique ID as a string and the hardened_print_length as a decimal):
def test(percentile_staging):
df = pd.DataFrame(percentile_staging)
head = df.head()
print(head)
fifty = quantile_exc(percentile_staging,.5)

df.head() results:
     pm_lookup                    hardened_print_length
0  2.4.1Printland Slab 2                  None
1  2.4.1Printland Slab 2                  None
2  2.4.1Printland Slab 2                  None
3  2.4.1Printland Slab 2                  None
4  2.4.1Printland Slab 2                  None

ERROR CODE:
TypeError: _get_value() missing 1 required positional argument: 'col'

I believe my issue is that I am storing the data as a DataFrame and the helper function uses a series to calculate the percentile. I am wondering if there is a solution to this error. I am uncertain on how to make each unique ID associated with a specific series, and then return the percentiles by project ID.


text:
Q: Variadic template pack expansion argument id I am trying to make a variadic template function that reads elements in order (with an index). The goal is, for example to call the function read_tuple to read two ints with id 0 and 1 (with read_int(0) and read_int(1)).
Here is the code I get so far:
int data[] = {10,20,30,40};

int int_read(int id)
{
    return data[id];
}

template <typename T>
T read(int& index)
{
    index--;
    int value = int_read(index);
    std::cout << "index :" << index << " value: " << value << std::endl;
    return value;
}

template <typename... Args>
std::tuple<Args...> read_tuple()
{
    int index = sizeof...(Args);
    return std::tuple<Args...>(read<Args>(index)...);
}

I can call it like that:
auto tuple = read_tuple<int, int>();
std::cout << "First: " << std::get<0>(tuple) << std::endl;

And I get the following output:
index :1 value: 20
index :0 value: 10
First: 10

However, this code is dependent of the order of evaluation of the read function. How can I generate an index dependent of the pack expansion (to avoid undefined behavior)?

A: As Piotr pointed out, the order of evaluation is garanteed if you use braced-init-list. Be carefull though if you use GCC prior to 4.9.1 as it does not work (c.f. Evaluation order (sequenced-before relation) among initializer-clauses in braced-init-list).
If you use a version that does not garantee the order of initialization (or just want to generate ids) you can use an indexer (from other stackoverflow post):
template<int... I> struct index {
    template<int n> using append = index<I..., n>;
};
template<int N> struct make_index {
    typedef typename make_index<N - 1>::type::template append<N - 1> type;
};
template<> struct make_index<0> { typedef index<> type; };
template<int N> using indexer = typename make_index<N>::type;

You can use it like that:
int data[] = {10,20,30,40};

int int_read(int id)
{
    return data[id];
}

template <typename T>
T read(int index)
{
    int value = int_read(index);
    std::cout << "index :" << index << " value: " << value << std::endl;
    return value;
}

template <typename... Args, int... i>
std::tuple<Args...> read_tuple_indexed(index<i...>)
{
    return std::tuple<Args...>(read<Args>(i)...);
}

template <typename... Args>
std::tuple<Args...> read_tuple()
{
    return read_tuple_indexed<Args...>(indexer<(sizeof...(Args))>());
}


text:
Q: Finding the absolute min and max Find the absolute maximum and absolute minimum values of f on the given interval.
$$f(x)=4-x^2;\;\; x\in [-3,1]$$

A: We have $$f(x) = 4-x^2$$
$(1)\;$ Find $f'(x)$
$(2)\;$ Set $f'(x) = 0$ and solve for $x = x_0$.
$(3)\;$ Evaluate $\;f(-3),\;f(1),\;f(x_0)$ to identify which is/are absolute maximum(s), which is absolute minimum.

A: Hint : Set the derivate zero to find the local extrema and consider the values
        f(-3) and f(1) to find the global extrema.

A: Note that $x^2\ge 0$ so that $4\ge 4-x^2$.
If we have $x\gt y\gt 0$ then $(4-x^2)-(4-y^2)=(x+y)(x-y)$ is the product of two positive numbers, so the function is increasing for $x\gt 0$.
If $y\lt x \lt 0$ then the difference is is the product of a negative factor and a positive one, so the function is decreasing as $x$ increases for $x\lt 0$.
This is sufficient to identify the possible maximum/minimum points without using calculus.


text:
Q: How to prove that $\int\limits_0^{\pi} e^{\sin^2(x)}dx > {3\over2}\pi$? How to prove that $\int\limits_0^{\pi} e^{\sin^2(x)}\ dx > {3 \over 2}\pi$?

A: Use the inequality $e^t\ge 1+t$, valid for all $t$, to get:
$$
\int_0^\pi e^{\sin^2x}dx\ge\int_0^\pi(1+\sin^2x)dx=\int_0^\pi\left(\frac32 + \frac12\cos 2x\right)\,dx
$$
You should be able to take it from here. The inequality is in fact strict, because the difference $e^{\sin^2x}-(1+\sin^2x)$ is continuous, non-negative and not identically zero.

A: We can also use Taylor expansion: $e^{\sin^2(x)}=1+\sin^2(x)+\sin^4(x)/2+...$ and integrate it from $0$ to $\pi$
$\int_0^\pi(1+\sin^2(x)+(\sin^4(x))/2)dx=(27\pi)/16 ≈ 5.3014 > 3\pi/2$

A: The integral is a Bessel function:
$$\sqrt{e} \pi  I_0\left(\frac{1}{2}\right)$$
which has numerical value $5.50843$, which is indeed less than $3 \pi/2$.  This, it would seem, answers the question completely in a principled, and correct manner.  One might try any number of other techniques, but I cannot see how any could be better than solving the integral exactly.


text:
Q: how could the df command show the right mounts? Under redhat 7, given this fstab where a "bind mount" across file systems is defined:
/dev/mapper/datab_vg-lv_db    /appli/postgres    xfs    defaults   0 0
/appli/postgres/var           /var/postgres      none   bind       0 0

df -k is showing its values (1K-blocks     Used Available Use% Mounted on) relative to the wrong path. (/var/postgres instead of /appli/postgres):

/dev/mapper/datab_vg-lv_db  176594692 34629472 141965220  20% /var/postgres

How to get the right result using df or any alternative command ?


text:
Q: How do you generate a WHERE...IN clause using LINQ2SQL? Going backwards from SQL to LINQ2SQL is sometimes quite simple. The following statement
SELECT user FROM users WHERE lastname='jones'

translates fairly easily into
from u in users where u.lastname='jones' select u

But how do you get the following SQL generated?
SELECT user FROM users WHERE lastname IN ('jones', 'anderson')

A: I had to do a bit of searching to find this, and thought it might be useful to others.
List<string> names = new List<string>() { "jones", "anderson" };

from u in users where names.Contains(u.lastname) select u


text:
Q: How to assign an associative array to another variable in zsh? In zsh, is there a way to assign an associative array to another variable? I would like to to something like this:
typeset -A orig
orig=(key1 val1 key2 val2)
typeset -A other
other=$orig
print '$orig:  '$orig
print '$other: '$other
print '$orig[key1]: '$orig[key1]
print '$other[key1]: '$other[key1]

This will print:
$orig:  val1 val2
$other: val1 val2
$orig[key1]: val1
$other[key1]:

I want to be able to use $other[key1] and get val1.
I know I can iterate over the keys and copy it item by item, but I really want to avoid this. Also, eval is evil :)
I have tried other=($orig) and other variations, but this will get my values from orig and create as associative array like this
other=(val1 val2)

So other[key1] returns nothing and other[val1] returns val2, which is not what I want.
If I understand correctly, what is going on in every attempt of mine is that $other is getting an array of the values of $orig, without the keys. How can I make it receive both keys and values and have the correct association between them?
I'm not worried about null values, if that would even be a problem,
because I am sure $orig will be well behaved.
Thanks!

A: zsh: bad set of key/value pairs for associative array
Perfect world without escaping:
typeset -A old new
old=(k1 v1 k2 v2 k3 v3)
typeset old    # old=( k1 v1 k2 v2 k3 v3 )

...doesn't exist and your arrays usually include empty values:
old[k2]=
typeset old    # old=( k1 v1 k2 '' k3 v3 )

...therefore you need to use " (quoting), @ (escaping) and f (field separation):
typeset new    # new=( )
new=("${(@fkv)old}")
typeset new    # new=( k1 v1 k2 '' k3 v3 )

See man zshexpn for more on parameter expansion flags.

A: You have to delve into the wonderful world of parameter expansion flags :) The k and v flags can be used together to force an associative array to expand to both its keys and values.
$ typeset -A orig
$ orig=(key1 val1 key2 val2)
$ print ${(kv)orig}
key1 val1 key2 val2

Then you can use the set command to populate your copy with the alternating key/values produced by that expansion.
$ typeset -A other
$ set -A other ${(kv)orig}
$ print $other[key1]
val1

These and other flags are documented in man zshexpn under "Parameter Expansion Flags", which is one of my favorite zsh features.


text:
Q: Record Sounds from AudioContext (Web Audio API) Is there a way to record the audio data that's being sent to webkitAudioContext.destination?
The data that the nodes are sending there is being played by the browser, so there should be some way to store that data into a (.wav) file.

A: Currently, there's not a native way to do that, but as Max said in the comment above, Recorderjs does essentially this (it doesn't chain onto the destination, but is a ScriptProcessorNode you can connect other nodes to, and have its input recorded.  I built on Recorderjs to do a simple audio file recorder - https://github.com/cwilso/AudioRecorder.

A: Sine to opus file: https://developer.mozilla.org/de/docs/Web/API/AudioContext/createMediaStreamDestination

In the following simple example, we create a
  MediaStreamAudioDestinationNode, an OscillatorNode and a MediaRecorder
  (the example will therefore only work in Firefox at this time.) The
  MediaRecorder is set up to record information from the
  MediaStreamDestinationNode.

Chrome supports it, too: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder


text:
Q: Why a JQuery function fires only once on the same page I have a very simple JQuery that takes the user hit "enter" key as clicking a particular button:
$('#<%= txtSearch.ClientID %>').keyup(function (event) {
            if (event.keyCode == 13) {
                $('#<%= btnSearchByRef.ClientID %>').click();
            }
        });

The button click will trigger a postback and display the search result in the same page.
This works great only in the first time. After the first time, this function is never triggered.
Any idea what's wrong? Thanks.

A: Since you're using webforms, why not make use of the DefaultButton property?
<form runat="server">
    <asp:Panel runat="server" DefaultButton="button1">
        <asp:TextBox runat="server" />
        <asp:Button id="button1" Text="Default" runat="server" />
    </asp:Panel>
</form>

This property is used to specify which button gets clicked when the Panel control has focus and the enter key is pressed.

A: Maybe a delegated event handler would work?  Try this:
$('body').on("keyup",'#<%= txtSearch.ClientID %>', function(){
        if (event.keyCode == 13) {
            $('#<%= btnSearchByRef.ClientID %>').click();
        }
});

The explanation:
When you add an event handler, it will only bind to an element once.  If that element is refreshed, the binding is lost.
However, this is where delegated event handlers come in (really) handy.  Bind to an element that won't refresh (in this case, 'body').
In the code above, if I'm not mistaken, every time 'body' is clicked, it tests if '#<%= txtSearch.ClientID %>' exists.  Then if it does, it should execute your command.


text:
Q: Is it possible to use StratifiedKFold from sklearn in multi input Neural Networks? I have a dataset that can be passed to a multi input neural network in the shape of a python dictionary or a list:
Example:
#dict
{'input1': X1, 'input2': X2, 'input3': X3}, {'output': Y}
#list
[ X1, X2, X3], y

Now I would like to use K-fold cross validation to estimate the performance of my model. Do you think I can use StratifiedKFold from sklearn as in this mono-input example?
for train, test in kfold.split(X, Y):
  # create model
    model = Sequential()
    model.add(Dense(12, input_dim=8, activation='relu'))
    model.add(Dense(8, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    # Fit the model
    model.fit(X[train], Y[train], epochs=150, batch_size=10, verbose=0)
    # evaluate the model
    scores = model.evaluate(X[test], Y[test], verbose=0)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    cvscores.append(scores[1] * 100)

Otherwise, what would be the best way?

A: skf.split() returns you indices and it depends only on Y:
for train_index, test_index in skf.split(X, y):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]

So you can pass any X array here (even X1 for layer 1 converted to dataframe or synthetic X). Then you take your
train_index

and
test_index

and filter all your inputs.
Again, skf() depends on your Y only. So the goal is to pass proper Y and get indices.
Other way: union all you inputs in outputs in one dataframe and keep column names for each layer. In this case you have one 'big' X. Split it firstly train_index and test_index and then split into X1, X2 and X3 using column names you saved above.


text:
Q: How to access firebase data from wordpress hosted in a remote server? I have developed an android game, it stores user scores in firebase. How do I access the user scores from wordpress website?. Is it possible to create a login for my android app using play store account, and have the play store google account to login to my site to check their score?

A: Yes, you can retrieve data from Firebase and display it on the WordPress website.
https://firebase-wordpress-docs.readthedocs.io/en/latest/retrieve-data-from-firestore.html
There is also an option to log in with Google on a WordPress site, so the user will only see the data based on their security rule.


text:
Q: Android bluetooth IOException: read failed, socket might closed or timeout, read ret: -1 I have a problem with connecting my client socket in the Android bluetooth API.
I already read these posts: this one, this one, this one and this one
According to these posts I made my code like the following but it still not work:
class MainActivity : AppCompatActivity()
{
    private val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    private var connectThread: ConnectThread? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (bluetoothAdapter != null)
        {
            if (!bluetoothAdapter.isEnabled)
                bluetoothAdapter.enable()

            val devices = bluetoothAdapter.bondedDevices.toTypedArray()

            if (devices.isNotEmpty())
            {
                connectThread = ConnectThread(devices[0])
                connectThread!!.run()
            }
        }
        else
            Log.i("BluetoothTest", "No bluetooth supported")
    }

    override fun onDestroy()
    {
        super.onDestroy()

        connectThread!!.cancel()
    }

    private inner class ConnectThread(device: BluetoothDevice) : Thread()
    {
        //private val socket = device.createRfcommSocketToServiceRecord(UUID.fromString ("00001101-0000-1000-8000-00805F9B34FB"))
        private val socket = device.javaClass.getMethod("createRfcommSocket", (Int::class
            .javaPrimitiveType)).invoke(device, 2) as BluetoothSocket

        override fun run()
        {
            bluetoothAdapter.cancelDiscovery()
            socket.connect()
        }

        fun cancel()
        {
            socket.close()
        }

    }
}

Here is the logs with the returned error that comes on socket.connect():
--------- beginning of crash
05-15 15:59:19.553 24176-24176/com.bluetoothtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bluetoothtest, PID: 24176
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bluetoothtest/com.bluetoothtest.MainActivity}: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
    at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:685)
    at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:697)
    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:374)
    at com.bluetoothtest.MainActivity.onCreate(MainActivity.kt:36)
    at android.app.Activity.performCreate(Activity.java:6999)
    at android.app.Activity.performCreate(Activity.java:6990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)

It seems that the problem appeared after Android 4.3 because of the port value of the socket
I am on Android 7.1 and 8.1
Does someone knows how to make bluetooth work on Android ?

A: Finally, the root cause was because the socket's inputStream couldn't be read. That's because there was no open socket with the same UUID on the server side.
See https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/core/java/android/bluetooth/BluetoothSocket.java
So to fix the problem we need a listening socket with the same UUID on the other side, for me it was a raspberry in python:
from bluetooth import *

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "YOUR UUID"

advertise_service( server_sock, "SampleServer", service_id = uuid, service_classes = [ uuid, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROFILE ])

print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print("received [%s]" % data)
except IOError:
    pass

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")

from https://github.com/karulis/pybluez/blob/master/examples/simple/rfcomm-server.py


text:
Q: How to change color of TODAY in Calendar? How can I change the color of TODAY in Calender?

A: In OS X it's possible to change the highlight color. You can do this in the General ▸ Appearance panel in System Preferences.
Now you can enable the system highlight color for the today selection with the following command.
defaults write com.apple.ical CalUIUseSystemHighlightColorForToday -bool TRUE


text:
Q: GORM/Grails - add extra column to a joinTable expression I have a Domain Class setup similar to this
class NewsStory {
  String headline
  static hasMany = [channels:Channel]
  static mapping = {
      table 'NewsStory'
      addresses joinTable:[name:'Article_Channel', key:'ArticleId', column:'ChannelId']
  }
}

in the Article_Channel table i need to have an extra column populated called ArticleType say. Its value will always be the same e.g. 'news' for this domain class, but will be differnt for others e.g. 'blog'
Channel is just something like 'Security' etc
Is there a way?
Thanks

A: One option would be be to create your own many-to-many mapping class and add the field in there.
http://grails.org/Many-to-Many+Mapping+without+Hibernate+XML
So, for example:
class ArticleChannel {
    NewsStory newsStory
    Channel channel
    String articleType
}

Then, your NewsStory and Channel classes would hasMany the ArticleChannel class.


text:
Q: Envio de anexo com PHPMailer Estou usando o PHPMailer para enviar anexos via formulário de contato.
Front end do Formulário:
<form action="mail.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="tipo" value="trabalhe-conosco">
<input class="input_100 require" type="text" name="nome" placeholder="Digite o seu nome">
<input class="input_49_left require email" type="text" name="email" placeholder="Digite o seu e-mail">
<input class="input_49_right require fone" type="text" name="telefone" placeholder="Telefone">
<select class="input_49_left require" name="cargo">
    <option value="">Cargo</option>
    <option value="Comercial">Comercial</option>
    <option value="Administrativo">Administrativo</option>
</select>

    <input type="file" name="curriculo" class="upload" value="">

<textarea class="input_100 require" name="mensagem" cols="30" rows="10" placeholder="Mensagem"></textarea>

<button type="submit" formmethod="POST" class="bt-enviar">Enviar</button>

mail.php (action do formulario)
<?php

    $GetPost = filter_input_array(INPUT_POST,FILTER_DEFAULT);

    $Erro      = true;
    $Tipo      = $GetPost['tipo'];
    $Nome      = $GetPost['nome'];
    $Email     = $GetPost['email'];
    $Telefone  = $GetPost['telefone'];
    $Cargo     = $GetPost['cargo'];
    $Curriculo = $_FILES['curriculo'];
    $Mensagem  = $GetPost['mensagem'];

    include_once 'PHPMailer/class.smtp.php';
    include_once 'PHPMailer/class.phpmailer.php';

    $Mailer = new PHPMailer;
    $Mailer->CharSet = "utf8";
    $Mailer->SMTPDebug = 3;

    $Mailer->FromName = "Jogo Digital";
    $Mailer->From = "leo@jogo.digital";
    $Mailer->AddAddress("renata@jogo.digital");
    $Mailer->IsHTML(true);
    $Mailer->Subject = "Novo currículo \"Trabalhe Conosco\" - {$Nome}";
    $Mailer->AddAttachment($Curriculo);
    $Mailer->Body = "
    Novo currículo enviado por {$Nome}

    Tipo: {$Tipo}

    Dados:

    Email: {$Email}

    Telefone: {$Telefone}

    Cargo: {$Cargo}

    Mensagem: {$Mensagem}

    Curriculo: {$Curriculo['name']}
    ";

    if($Mailer->Send()){
        $Erro = false;
    }

    var_dump($Erro);

Quando envio não chega o anexo, e dá a seguinte mensagem:
2017-08-16 19:11:14 Could not access file: Array.
No corpo do e-mail o $Curriculo['name'] está retornando o nome do arquivo.
O que devo adaptar no código para dar certo?

A: Tente isto:
if (isset($_FILES['uploaded_file']) &&
    $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

Um exemplo basico pode ser encontrado aqui.
A declaração para a função AddAttachment é:
public function AddAttachment($path,
                              $name = '',
                              $encoding = 'base64',
                              $type = 'application/octet-stream')

A: Este exemplo é o que sempre uso quando preciso e possui o envio com anexos funcional, espero que lhe ajude
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Enviar e-mail com anexo</title>

<form id="form1" name="form1" method="post" action="?acao=enviar" enctype="multipart/form-data">

     Nome:
     <input type="text" name="nome" id="nome" />

     Assunto:
     <input type="text" name="assunto" id="assunto" />

     Mensagem:
     <textarea name="mensagem" id="mensagem" cols="45" rows="5"></textarea>

     Anexo:
     <input type="file" id="arquivo" name="arquivo" />

     <input type="submit" value="Enviar" />

</form>

<?php
if($_GET['acao'] == 'enviar'){
 $nome      = $_POST['nome'];
 $assunto   = $_POST['assunto'];
 $mensagem  = $_POST['mensagem'];
 $arquivo   = $_FILES["arquivo"];

 $corpoMSG = "Nome: $nome
 Mensagem: $mensagem";
 // chamada da classe
 require_once('class.phpmailer.php');
 // instanciando a classe
 $mail   = new PHPMailer();
 // email do remetente
 $mail->SetFrom('remetente@dominio.com.br', 'remetente');
 // email do destinatario
 $address = "destinatario@dominio.com.br";
 $mail->AddAddress($address, "destinatario");
 // assunto da mensagem
 $mail->Subject = $assunto;
 // corpo da mensagem
 $mail->MsgHTML($corpoMSG);
 // anexar arquivo
 $mail->AddAttachment($arquivo['tmp_name'], $arquivo['name']  );

 if(!$mail->Send()) {
   echo "Erro: " . $mail->ErrorInfo;
  } else {
   echo "Mensagem enviada com sucesso!";
  }
}
?>


text:
Q: which is better choice among J2ME and iPhone
Possible Duplicate:
what mobile platform should I start learning?

I am fresher to enter into IT industry. Which is better chioce for my career to enter into IT industry among J2ME ,iPhone ,Android.....Please give me the suggestion and help me for my better career

A: Some information about the various platforms:

*

*Android:

*

*Programming Language: Java

*Platform: A subset of the Java API plus Android-specific APIs

*Development Environment: Either commandline or Eclipse on Windows, Mac, or Linux

*Devices: Handsets from multiple manufacturers

*Licensing: Fully open source

*Deployment: However you choose

*Marketshare: According to recent reports, in 2nd place (behind Blackberry)

*iPhone:

*

*Programming Language: Objective-C

*Platform: CocoaTouch (A set of frameworks/libraries written in Objective-C)

*Development Environment: Xcode Developer Tools and iPhone SDK on Mac, only

*Devices: iPhone, iPad

*Licensing: Proprietary

*Deployment: Through the iTunes App Store (approval plus $100/yr required)

*Marketshare: According to recent reports, in 3rd place (behind Android)

Note that market share is subject to change and that Android and iPhone are currently quite close. Now, as for your question about entering the IT industry....
For entering the IT industry, you should really learn the basics of computer software engineering, first, and you should familiarize yourself with common industry-grade programming languages. If you take a look at Programming Language Popularity, you can see that Java, C++, and Python are all consistently ranked highly. I suggest that you start off with those languages. Once you are comfortable with those languages on a standard desktop platform, only then should you consider mobile app development. If you already know Java, then developing both for J2ME and Android should be easy. Note, though, that J2ME is much more limited in functionality than Android (Android supports a larger subset of the Java APIs than J2ME), and Android is most likely going to end up in a second or first place position in the mobile phone market (they recently overtook iPhone and are currently behind Blackberry as of this writing). If you are familiar with C and C++, then learning Objective-C and programming the iPhone is not too difficult, either. Note, though, that you need a Mac to develop for the iPhone. There are many similarities between C++, Java, and Python, so learning one once you understand the others is not all that difficult. For myself, I started with C++, then learned Java, then Python. On my website, I have listed the various online tutorials from which I taught myself C++... those are a pretty good start.

A: there is a very nice paper about mobile development, developing for different platforms, and platform choice called Mobile Developer's Guide to the Galaxy. it has a perfect answer to your question (p. 61):

Now what - which Environment Should I Use?
The short and crystal clear answer: it depends.
The longer answer: think about your target users, about their
needs, about their devices and their dataplans. And about your
vision and the requirements for your idea. Remember that you are
not necessarily restricted to a single application environment. A
practical approach is to use the environment that you are most
comfortable with and then move on to other environments for
increasing the market reach of your app. Sometimes it also makes
sense to combine different environments, for example by providing
a mobile website for casual users and a J2ME app for your
power users.

followed by a table providing a [very] rough overview about the individual strengths and limitations of each application environment.
much recommended.

A: My vote is for Android (or J2ME),
Android is going places, you may as well jump on the band wagon.  (sorry Apple) Plus it is just a lot more open and you can program in whicher enviroment you wish. I can't think of a single down side of choosing Android over the IPhone.  And there are plenty of advantages.


text:
Q: Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable Running into an issue and error when I go to run the mobile app. I think it has something to do with the cocoapods but I'm not sure. Can someone help me or give me a call?
Im building out the App.js file and creating a drawer navigation currently.

A: In my case what worked was:

*

*restarting the javascript bundler

   1. Ctrl + c
   2. npx react-native start --reset-cache

*restarting my emulator or simulator device

   1. npx react-native run-android


text:
Q: Why is my AWS RDS (postgres) at a high percentage of cpu with no active sessions? I have two postgres db, prod and dev.  Lately, dev has been really slow, so I checked into it, and it appears to be using CPU credits faster than I'm getting them.  I could not figure out why, so I checked the cpu usage history, and it appears that after a strange spike, the baseline has settled to twice the usage it was before:

I could not find any active sessions which would warrant such cpu usage, but just to be sure, I stopped the db, let it sit for a bit, then started it again.  Even after a fresh start, though, the cpu usage is still strangely high, even as compared to a very similar db:

How can I figure out what all of this usage is coming from?

A: I can't guarantee this will always work, but what managed to be effective for me was switching to a different instance, then switching back.
To do so, go up to Modify button in the RDS > Databases > [MY_DB} view, and then change your instance to any other instance type, wait for the update, then switch back.
I suppose I just had a bad ec2.mirco, and the method above got me a different (better) one which does not exhaust more cpu credits at idle than it gains.


text:
Q: c# создать таблицу в пустом файле accdb создал в проводнике пустой файл accdb. в программе выполняю
string createTableString = "CREATE TABLE IF NOT EXISTS people(id INTEGER PRIMARY KEY AUTOINCREMENT, name1 TEXT, name2 TEXT, name3 TEXT, birthdate TEXT, adress TEXT);";

OleDbCommand cmd = new OleDbCommand(createTableString, oleConnection);
cmd.ExecuteNonQuery();

Ошибка: Syntax error in CREATE TABLE statement.


text:
Q: Prove that a graph on $n$ vertices with $c$ components has at least $n-c$ edges. My question is about graph theory. Prove that a graph on $n$ vertices with $c$ components has at least $n-c$ edges.

A: Supose your graph has $c$ conected componentes, each with $n_1$, $n_2$, $\ldots$, $n_c$ vertices. Your graph as a whole has $n=n_1+n_2+\ldots+n_c$ vertices. Supose the components are conected by the fewest edges posibles. Any set of $k$ vertices can be conected by just $k-1$ vertices, as in path graphs, $K_{1,k-1}$ bipartite graphs, and so on; so the $i$-th component of your graph can be conected with at least $n_i-1$ edges. The sum of these numbers gives you a lower bound for the number of edges in the whole graph: $$\sum^{c}_{i=1}(n_i-1) =n_1+n_2+\ldots+n_c-c=n-c.$$

A: First we prove that if $c = 1$ (if the graph is connected) we have at least $n - 1$ edges.
A simple path with $n$ vertices has $n - 1$ edges, thus it's possible.
If $\delta \geq 2$, then we have at least $n$ edges, thus there is a node with $\delta = 1$. use induction on other vertices, so you have at least $n-2$ edges on other vertices of the graph and $n - 1$ edges on all vertices of the graph.
Now, we have $c$ connected components with $a_i$ vertices on $i^{th}$ component. thus we have at least $\Sigma_{i = 1}^c (a_i - 1) = n - c$


text:
Q: Is it correct to say "I didn't study this chapter in details"? My professor wants to ask me some questions about a chapter.
I want to tell him I didn't study it in details.
What should I say?

A: I'm sorry, but I did not study that chapter in detail.
Also, the moderators of this forum would suggest that you post this question in English Language Learners, as this forum is for serious English questions.


text:
Q: Can I deploy a slug to heroku without including the runtime I'm trying to follow this https://devcenter.heroku.com/articles/platform-api-deploying-slugs?preview=1 to create a slug of my node app and deploy to heroku. Given that heroku has a nodejs buildpack built into it I can't help thinking there must be a way to do so without including the node runtime as recommended, but it's not easy to find out how in the platform api docs.
Anyone have an ideas?

A: you can also create slugs programmatically using the Build API. See these guides

*

*Building and Releasing using the Platform API

*Programmatic builds on Heroku
This is also mentioned in the intro to the article you mentioned, but I'll make that clearer.
Feel free to get in touch at friis@heroku.com if you have any questions about how to use this.


text:
Q: Create enum using reflection Does C# offer a way to create Enum type from scratch using reflection?
Suppose, I have a collection of strings: {"Single", "Married", "Divorced"} and I'm willing to build the following enum type in runtime:
enum PersonStatus
{
    Single, Married, Divorced
}

Is this somehow possible?

A: Not without doing really gnarly things like generating assemblies using Emit.  How would you use such an enum anyway?  Whats the real goal here?
EDIT: Now that we know what you really want to do, this page suggests that you can acheive your goal using code like the following:
private void listViewComplex_CellEditStarting(object sender, CellEditEventArgs e)
{
    // Ignore edit events for other columns
    if (e.Column != this.columnThatYouWantToEdit)
        return;

    ComboBox cb = new ComboBox();
    cb.Bounds = e.CellBounds;
    cb.Font = ((ObjectListView)sender).Font;
    cb.DropDownStyle = ComboBoxStyle.DropDownList;
    cb.Items.AddRange(new String[] { "Single", "Married", "Divorced" });
    cb.SelectedIndex = 0; // should select the entry that reflects the current value
    e.Control = cb;
}

A:
Does C# offer a way to create Enum type from scratch using reflection?

Yes, it's possible. If you want to create types (including enums) at runtime you could use Reflection.Emit in order to emit the actual MSIL code.
Here's a concrete example of how to achieve that using the DefineEnum method.


text:
Q: I'm having an error: "TypeError: 'str' object is not callable" - Python I'm really confused. I made classes similar to this the one with this one with no errors. So I don't see the problem with this one. Please help!
class champ_info:
    def __init__(self, name):
        self.name = name

    def name(self):
        print({self.name}) #I also tried using it with out the {}

v = champ_info('henry')
v.name()

A: You have an attribute with the same name as a method. When you assign self.name its object shadows the function object you really wanted.
class champ_info:
    def __init__(self, name):
        self.name = name    # <-- this shadows the same-named method

v.name() translates to (1) get object referenced by "name" (its the string 'henry') and (2) call that object. You can't call a string, so boom.
To solve, just come up with a better name for the method, hopefully something that gives a good hint of what it does.
class champ_info:
    def __init__(self, name):
        self.name = name

    def print_me(self):
        print(f"{self.name}")

v = champ_info('henry')
v.print_me()


text:
Q: Is it possible to infer the first isomorphism theorem from the second one? While it's quite standard to infer the second isomorphism theorem from the first one, I've not seen the proof in reverse direction. Is it possible to infer the first isomorphism theorem from the second one? Thank you so much for your help!
I tried to let $S := G$ and $N := \ker(\varphi)$, but this leads to a trivial equality.

Here is first isomorphism theorem:

Let $\varphi: G \to H$ be a group homomorphism. Then $G/\ker(\varphi) \cong \operatorname{Im}(\varphi)$.

Here is second isomorphism theorem:

Let $G$ be a group, $S \le G$, and $N \trianglelefteq G$. Then $(S N) / N \cong S /(S \cap N)$.

A: To follow up on the comment of @RobArthan, here's part of the trouble.
What does it mean to "infer the first isomorphism theorem from the second"?
Perhaps it means that one accepts the second isomorphism theorem as an additional axiom of group theory, and in light of that one writes down a proof of the first isomorphism theorem. The trouble is, I could just ignore the light altogether and write down any proof of the first isomorphism theorem (in fact, I can even write a very short proof of the first isomorphism theorem, which ignores the light).


text:
Q: unity custom shader not receiving Shadow Shader "Custom/1_displayImageOnSlide" {
    Properties {
        _MainTex ("Texture", 2D) = "white" {}
        _CutoffX("CutoffX", Range(0.0,1.0)) = 1
        _CutoffY("CutoffY", Range(0.0,1.0)) = 1
    }

    Category {
        Cull off
        Blend SrcAlpha OneMinusSrcAlpha
        Lighting Off
    Fog { Mode Off }

        SubShader {
//      Tags {"LighMode"="ForwardBase"}
        Tags {"Queue"="Transparent" "RenderType"="Transparent"}
        //UsePass "VertexLit/SHADOWCOLLECTOR"
        //UsePass "VertexLit/SHADOWCASTER"

        CGPROGRAM
        #pragma surface surf Unlit
        //#pragma surface surf Lambert

        // Inside CGPROGRAM block.

        half4 LightingUnlit (SurfaceOutput s, half3 lightDir, half atten) {
                half4 c;
                c.rgb = s.Albedo;
                c.a = s.Alpha;
                return c;
        }

        sampler2D _MainTex;

        struct Input {
                float2 uv_MainTex;
                float4 color : Color;
        };

        fixed _CutoffX;
        fixed _CutoffY;

        void surf (Input IN, inout SurfaceOutput o) {

        half4 tex = tex2D(_MainTex, IN.uv_MainTex);

        o.Albedo = IN.color.rgb * tex.rgb;
        o.Alpha = IN.uv_MainTex.x > _CutoffX ? 0 : IN.uv_MainTex.y > _CutoffY ? 0 : IN.color.a*tex.a;
        }
    ENDCG
        }//sub Shader End
    }//Categoy End
     FallBack "VertexLit"    // Use VertexLit's shadow caster/receiver passes.
}

This is the code of my shader file and it is applied to a cube object. The problem is,  shader is casting correctly by  cube but cube is not receiving shader. Whats wrong in it?  I don't have enough knowledge about shader programming so it is requested to share you answer with description


text:
Q: GridBagLayout strategy in Java I'm struggling with putting vertical space between two components in my GridBagLayout and would like help
(1) successfully putting space between the first two components and
(2) understanding better a strategy for laying out my components based on the picture below.
Below is (a) what I have, (b) what I want, (c) what I've made in another tab, and (d) the code for the tab I'm having trouble with.
I have this and you can see there isn't space between the two lines.  I can't get the insets to work properly

I want this

I was able to make this, but think I did so inefficiently.

And here's the code for my Chinese Remainder Thm tab:
import java.awt.*;
import javax.swing.*;

public class CRTTab extends JPanel{

// for stackoverflow
public static void main(String[] args){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(200, 50);
    frame.setPreferredSize(new Dimension(600, 674));
    frame.add(new CRTTab());
    frame.pack(); //fit gui components nicely
    frame.setVisible(true);
}

/** Global Variables */

//entry labels & corresponding text field
// α ≡ i (mod m)
JLabel alphaLabel1; // α ≡
JFormattedTextField iEnter; // ENTER i
JLabel leftPar1; // (mod
JFormattedTextField mEnter; // ENTER m
JLabel rightPar1; // )

// α ≡ j (mod n)
JLabel alphaLabel2; // α ≡
JFormattedTextField jEnter; // ENTER j
JLabel leftPar2; // (mod
JFormattedTextField nEnter; // ENTER n
JLabel rightPar2; // )

//Solve/Import buttons & answer label
JButton solveButton;
JButton importButton;
JTextPane crtAnswer; // α ≡ _ (mod m*n)

//table (showing GCD computation) maintenance
JTable t;
JScrollPane scroller;

/**Construct CRT Tab
 */
CRTTab() {
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    // α ≡ i (mod m) in ROW 1 *****************************************************************

    //α ≡ label
    alphaLabel1 = new JLabel("α ≡", JLabel.CENTER);
    alphaLabel1.setFont(new Font("Arial", Font.PLAIN, 22));

    //constraints
    c.fill = GridBagConstraints.BOTH;
    c.anchor = GridBagConstraints.BASELINE;
    c.weightx = 0.01;
    c.weighty = 1;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(0, 40 , 0, 0); //top, left, bottom, right
    add(alphaLabel1, c);

    //enter i
    iEnter = new JFormattedTextField();
    iEnter.setFont(new Font("Arial", Font.PLAIN, 22));
    alphaLabel1.setLabelFor(iEnter);

    //constraints
    c.weightx = 35.0;
    c.insets = new Insets(0, 5 , 0, 0); //top left bottom right
    c.gridx = 1;
    add(iEnter, c);

    //(mod label
    leftPar1 = new JLabel("(mod");
    leftPar1.setFont(new Font("Arial", Font.PLAIN, 22));

    //constraints
    c.weightx = 0.01;
    c.gridx = 2;
    c.insets = new Insets(0, 10, 0, 0); //top, left, bottom, right
    add(leftPar1, c);

    //enter m
    mEnter = new JFormattedTextField();
    mEnter.setFont(new Font("Arial", Font.PLAIN, 22));
    leftPar1.setLabelFor(mEnter);

    //constraints
    c.weightx = 35.0;
    c.insets = new Insets(0, 10 , 0, 0); //top, left, bottom, right
    c.gridx = 3;
    add(mEnter, c);

    //) label
    rightPar1 = new JLabel(")");
    rightPar1.setFont(new Font("Arial", Font.PLAIN, 22));

    //constraints
    c.weightx = 0.01;
    c.fill = GridBagConstraints.REMAINDER;
    c.gridx = 4;
    c.insets = new Insets(0, 5, 0, 40); //top, left, bottom, right
    add(rightPar1, c);

    // ROW 2 ******************************************************************************************0

    //α ≡ label
    alphaLabel2 = new JLabel("α ≡", JLabel.CENTER);
    alphaLabel2.setFont(new Font("Arial", Font.PLAIN, 22));

    //constraints
    c.weighty = 3;
    c.gridx = 0;
    c.anchor = GridBagConstraints.BELOW_BASELINE;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(0, 40 , 0, 0); //top, left, bottom, right
    add(alphaLabel2, c);

    //enter j
    jEnter = new JFormattedTextField();
    jEnter.setFont(new Font("Arial", Font.PLAIN, 22));
    alphaLabel2.setLabelFor(jEnter);

    //constraints
    c.weightx = 35.0;
    c.insets = new Insets(20, 5 , 0, 0); //top left bottom right
    c.gridx = 1;
    add(jEnter, c);

    //(mod label
    leftPar2 = new JLabel("(mod");
    leftPar2.setFont(new Font("Arial", Font.PLAIN, 22));

    //constraints
    c.weightx = 0.01;
    c.gridx = 2;
    c.insets = new Insets(0, 10, 0, 0); //top, left, bottom, right
    add(leftPar2, c);

    //enter m
    nEnter = new JFormattedTextField();
    nEnter.setFont(new Font("Arial", Font.PLAIN, 22));
    leftPar2.setLabelFor(nEnter);

    //constraints
    c.weightx = 35.0;
    c.insets = new Insets(20, 10 , 0, 0); //top, left, bottom, right
    c.gridx = 3;
    add(nEnter, c);

    //) label
    rightPar2 = new JLabel(")");
    rightPar2.setFont(new Font("Arial", Font.PLAIN, 22));

    //constraints
    c.weightx = 0.01;
    c.fill = GridBagConstraints.REMAINDER;
    c.gridx = 4;
    c.insets = new Insets(0, 5, 0, 40); //top, left, bottom, right
    add(rightPar2, c);

}//end constructor

}


text:
Q: Hash Match inner join in simple query with in statement I am running the execution plan for the following query:
select m_uid from EmpTaxAudit
where clientid = 91682
and  empuid = 42100176452603
and newvalue in('Deleted','DB-Deleted','Added')

Here is the execution plan:

I have a non clustered index on EmpTaxAudit Table on ClientId and NewValue columns which shows above as 14.9% of the execution:
CREATE NONCLUSTERED INDEX [idx_EmpTaxAudit_clientid_newvalue] ON [dbo].

[EmpTaxAudit]
(
    [ClientID] ASC,
    [NewValue] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)

I also have a non clustered unique index PK as follows:
ALTER TABLE [dbo].[EmpTaxAudit] ADD  CONSTRAINT [PK_EmpTaxAudit] PRIMARY KEY NONCLUSTERED
(
    [ClientID] ASC,
    [EmpUID] ASC,
    [m_uid] ASC,
    [m_eff_start_date] ASC,
    [ReplacedOn] ASC,
    [ColumnName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)

Trigger code in source table EmpTax:
CREATE                trigger [dbo].[trins_EmpTax]
on [dbo].[emptax]
for insert
as
begin
  declare
    @intRowCount  int,
      @user          varchar(30)

  select @intRowCount = @@RowCount
  IF @intRowCount > 0
  begin
     select @user = suser_sname()

     insert EmpTaxAudit (Clientid, empuid,m_uid,m_eff_start_date, ColumnName, ReplacedOn, ReplacedBy, OldValue,dblogin,newvalue)
     select Clientid, empuid,m_uid,m_eff_start_date,'taxcode', getdate(),IsNull(userid,@user), '', Left(@user,15),'Added'
        from inserted i
         where m_uid not in (select m_uid from EmpTaxAudit
                    where clientid = i.clientid  and (newvalue = 'Deleted'
            or newvalue = 'DB-Deleted'
                        or newvalue = 'Added') and  empuid = i.empuid)
       and i.m_eff_end_date is null

     insert EmpTaxAudit (Clientid, empuid,m_uid,m_eff_start_date, ColumnName, ReplacedOn, ReplacedBy, OldValue,dblogin,newvalue)
     select Clientid, empuid,m_uid,m_eff_start_date,'taxcode', getdate(),IsNull(userid,@user), '', Left(@user,15),'Deleted'
        from inserted i
         where m_uid not in (select m_uid from EmpTaxAudit
                    where clientid = i.clientid  and (newvalue = 'Deleted'
            or newvalue = 'DB-Deleted'
                        or newvalue = 'Added') and  empuid = i.empuid)
       and i.m_eff_end_date is not null

  end
end

What can I do to avoid the high cost of Hash Match (Inner Join)?
Thanks!

A: For the 1st query, an index that uses all three columns from the WHERE clause and includes the column from the SELECT list would be much more useful:
-- index suggestion A
(clientid, empuid, newvalue) INCLUDE (m_uid)

or an index targeted specifically for this query:
-- index suggestion B
(clientid, empuid, m_uid)
WHERE newvalue in ('Deleted', 'DB-Deleted', 'Added')

Regarding the trigger, some comments:

*

*The first query you show does not appear in the trigger. What appears is a join from that table to the inserted rows to another table (which has the trigger).

*My suggestion B above seems better suited to be used by the trigger.

*The trigger has 2 almost identical insert statements. Why? I think they could be combined in one - and simpler - insert and using NOT EXISTS instead of NOT IN:
insert EmpTaxAudit
  ( Clientid, empuid, m_uid, m_eff_start_date, ColumnName,
    ReplacedOn, ReplacedBy, OldValue, dblogin,
    newvalue
  )
select
    Clientid, empuid, m_uid, m_eff_start_date, 'taxcode',
    getdate(), IsNull(userid,@user), '', Left(@user,15),
    case when m_eff_end_date is null
        then 'Added' else 'Deleted'
    end
from inserted i
where not exists
      ( select 1
        from EmpTaxAudit
        where m_uid = i.m_uid
          and clientid = i.clientid
          and empuid = i.empuid
          and newvalue in ('Deleted', 'DB-Deleted', 'Added')
      ) ;

A: Reason for Hash Match (inner join) :

"a Hash Match  join occurs when SQL Server joins two tables by hashing
  the rows from the smaller of the two tables to be joined, and then
  inserting them into a hash table, then processing the larger table one
  row at a time against the smaller hashed table, looking for  matches
  where rows need to be joined. Because the smaller of the tables
  provides the values in the hash table, the table size is kept at a
  minimum, and because hashed values instead of real values are used,
  comparisons can be made very quickly. As long as the table that is
  hashed is relatively small, this can be a quick process. On the other
  hand, if both tables are very large, a Hash Match join can be very
  inefficient as compared to other types of joins."

So clearly your smaller table return 16 rows and larger one return 1,41,000 rows.Here smaller table is hash which is quite good, now it will join to 1,41,000 rows so cost has to be more and execution time has to be slow.
you have to minimize number of rows return in large table.you are getting index seek in both case so index is being utilize.
I think you only need to rewrite trigger query.
CREATE  trigger [dbo].[trins_EmpTax]
on [dbo].[emptax]
for insert
as
begin

if @@rowcount = 0
        return
    set nocount on

  declare
    @intRowCount  int,
      @user          varchar(30)

  --select @intRowCount = @@RowCount
  if exists(select * from inserted)
  begin
     select @user = suser_sname()

     insert EmpTaxAudit (Clientid, empuid,m_uid,m_eff_start_date, ColumnName, ReplacedOn, ReplacedBy, OldValue,dblogin,newvalue)
     select Clientid, empuid,m_uid,m_eff_start_date,'taxcode', getdate(),IsNull(userid,@user), '', Left(@user,15)
     ,case when i.m_eff_end_date is null then 'Added' else 'Deleted' END
        from inserted i
         where not exists (select m_uid from EmpTaxAudit ETA
                    where i.m_uid=ETA.m_uid and  empuid = i.empuid and clientid = i.clientid
                    and newvalue in('Deleted','DB-Deleted' , 'Added')
                    )

     --insert EmpTaxAudit (Clientid, empuid,m_uid,m_eff_start_date, ColumnName, ReplacedOn, ReplacedBy, OldValue,dblogin,newvalue)
     --select Clientid, empuid,m_uid,m_eff_start_date,'taxcode', getdate(),IsNull(userid,@user), '', Left(@user,15),'Deleted'
     --   from inserted i
     --    where m_uid not in (select m_uid from EmpTaxAudit
     --               where clientid = i.clientid  and (newvalue = 'Deleted'
     --       or newvalue = 'DB-Deleted'
     --                   or newvalue = 'Added') and  empuid = i.empuid)
     --  and i.m_eff_end_date is not null

  end
end

Notice that you can correct condition inside NOT EXISTS clause which is minor,rest it will work perfect and perform better.
Also care to explain that what is clustered index on this table and why so many composite primary key.?

A: First critique: I don't think a PRIMARY KEY should consist of so many fields.  A primary key is just meant to be a simple identifier of uniqueness.  Arguably you could have two fields in your PK for many-to-many intersection tables, though I personally always have a single-field primary key, even for these.  So I'd say your PK PK_EmpTaxAudit really should be redefined as a unique index.
Then I would suggest adding newvalue to the INCLUDE fields of that index:
create unique index IX_EmpTaxAudit(
  [ClientID] ASC,
  [EmpUID] ASC,
  [m_uid] ASC,
  [m_eff_start_date] ASC,
  [ReplacedOn] ASC,
  [ColumnName] ASC
)
include (newvalue)

I suspect that will give you a neater execution plan.

A: First of all you should have a clustered index (with FILLFACTOR<=95) on the tables to avoid high IO. Because HEAP cause to more fragmentation. So, you can replace PK Non Clustered Index with Clustered.
Apart from that to avoid HASH_MATCH you should have all the columns being used in SELECT statement and WHERE clause should be within a index. So either you replace the non clustered index idx_EmpTaxAudit_clientid_newvalue with bellow one ore create new non clustered index.
    CREATE NONCLUSTERED INDEX [idx_EmpTaxAudit_clientid_newvalue] ON [dbo].

    [EmpTaxAudit]
    (
        [ClientID] ASC,
        [NewValue] ASC,
        [newvalue]
    )
    INCLUDE (m_uid)
    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)

Reason of HASH_MATCH
SQL Server Optimizer prefer to use index instead of HEAP. So, in your case requested data and columns in where condition lies on two different index. That's why SQL Server Optimizer used both indexes and performed HASH_MATCH.
Thanks


text:
Q: Own payment method in spree I want to add non gateway payment method other than of check.
As per my current scenario, I have my own payment server (other than of any payment gateway/check option) where I want to send the request for any product payment.
The only thing that is source which is getting nil. so do we any better way to achieving this scenario.


text:
Q: Git generated a file with a mysterious file name within visual studio code, what is this file? I found this generated file named "d" in my directory, it looks like the history of a git log output for a particular branch, but it could be something different, this is an example of one of the lines of the file, modified.
[02m789c537890fac34567f6a784374c58d943[m Committing our changes

Does anyone have an idea of what this is, and how it gets generated?


text:
Q: Removed/Re-Added file, now I get Undefined symbols for architecture arm64: In my app, I removed then re-added a class. The target membership for the .m file is checked and it appears under Build Phases->Compile Sources. "Build Active Architecture Only" is set to "No", and the "Valid Architectures" are "arm64 armv7 armv7s". I also tried clearing out the DerivedData folder. What other ways are there to fix this issue?

A: This worked for me:
ios sdk 9.3
into your build setting of app.xcodeproj valid architecture: armv7 armv7s Build Active architecture : No
Clean and build.

A: Pretty crazy stuff. Figured it out. Turns out the specific class I added calls some C++ functions, so I needed to change its file type to Objective-C++ in the Identity Inspector.


text:
Q: How to show image from cloudinary in android? I just want to show image from cloudinary in a imageView in android. I looked their documentations but I couldn't find how to show any image from cloudinary. In their github, they don't explain how to show images.
Map config = new HashMap();
config.put("cloud_name", "n07t21i7");
config.put("api_key", "123456789012345");
config.put("api_secret", "abcdeghijklmnopqrstuvwxyz12");
Cloudinary cloudinary = new Cloudinary(config);

so what?
Main activity :
package gc.x;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Transformation;
import android.widget.ImageView;

import com.cloudinary.Cloudinary;
import com.cloudinary.utils.ObjectUtils;

import java.util.Map;

import gc.x.mCloud.CloudinaryClient;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageView img = (ImageView)findViewById(R.id.iv1);

   // ??

    }
}

A: Use cloudinary URL to load images in your application using picasso or glide.
Using picasso your code will look something like this -
picasso.load("https://res.cloudinary.com/yourCloudName/image/upload/f_auto/v1525420575/yourImageName.jpg")
       .into(imageHolder)

You can add image modifications to this URL for quality management or to manage width and height of the image. Cloudinary provides multiple options to modify an image.
Hope this helps.


text:
Q: Why swapping between the derivative operator and this infinite sum leads to different results? While working on a mathematical physical problem, i came across seemingly contradictory results.
Notations
Let's consider $\mathbf{x}_1$ to be the origin of a spherical coordinate system and $\mathbf{x}_2$ a point located at the $z$ axis a distance $R$ from the origin, i.e. $R = \left| \mathbf{x}_2 - \mathbf{x}_1 \right|$.
We introduce the unit vector $\mathbf{d} = (\mathbf{x}_1 - \mathbf{x}_2)/R = -\mathbf{\hat{e}}_z$, where $\mathbf{\hat{e}}_z$ is the unit vector along the $z$ axis.
We denote by $s$ the distance from a given point $\mathbf{x}$ from $\mathbf{x}_2$ such that $s = |\mathbf{s}|$ with $\mathbf{s} = \mathbf{x} - \mathbf{x}_2$.
Problem statement

On the one hand, it can readily be checked that
  $$
\left( \mathbf{e} \cdot \mathbf{\nabla}_2 \right) \left( \frac{1}{s} \right) = \frac{\mathbf{e} \cdot \mathbf{s}}{s^3} \, , \tag{1}
$$

where $\mathbf{\nabla}_2$ denotes the gradient taken along $\mathbf{e}$ with respect to $\mathbf{x}_2$.

We note that  $\mathbf{e} \perp \mathbf{d}$.

On the other hand, by expressing $1/s$ in terms of harmonics based at $\mathbf{x}_1$ such that
$$
\frac{1}{s} = \sum_{n=0}^\infty  \frac{R^n}{r^{n+1}} \, P_n(\cos\theta)
$$
where $r = \left| \mathbf{x}-\mathbf{x}_1 \right|$, $\theta$ is the polar angle in spherical coordinates (physics convention), and $P_n$ denotes Legendre polynomial of degree $n$.
Then,
$$
\left( \mathbf{e} \cdot \mathbf{\nabla}_2 \right) \left( \frac{1}{s} \right)
= \sum_{n=0}^\infty -n R^{n-1} (\mathbf{e} \cdot \mathbf{d}) = 0 \, ,
$$
since we have imposed that $\mathbf{e} \perp \mathbf{d}$.
However, by direct calculation in Eq. $(1)$, the gradient does now necessarily vanish.
i have spend a couple hours today and most of the afternoon looking at this without understanding why.
In fact, i need the spherical harmonic representation for further calculations.
Any help or hint is highly appreciated.
Thank you,

A: The answer is straightforward. Here you have forgotten to take the derivative with respect to the spherical harmonic.
We have
$$
\frac{1}{s} = \sum_{n=0}^\infty R^n \frac{\left( \mathbf{d} \cdot \mathbf{\nabla} \right)^n}{n!} \frac{1}{r} \, .
$$
By noting that
$$
\left( \mathbf{e} \cdot \mathbf{\nabla}_2 \right) \mathbf{d}
= -(1/R) \mathbf{e} \, ,
$$
then
\begin{align}
\left( \mathbf{e} \cdot \mathbf{\nabla}_2 \right) \frac{1}{s}
&= \sum_{n=0}^\infty R^n \left( - \frac{\mathbf{e} \cdot \mathbf{\nabla}}{R} \right) n \,
\frac{\left( \mathbf{d} \cdot \mathbf{\nabla} \right)^{n-1}}{n!} \frac{1}{r} \, , \\
&= - \left( \mathbf{e} \cdot \mathbf{\nabla} \right)
\sum_{n=0}^\infty R^n \frac{\left( \mathbf{d} \cdot \mathbf{\nabla} \right)^n}{n!} \frac{1}{r}
\end{align}
leading to the desired result your equation (1).


text:
Q: Pass R variable to a sql statement Is there any way to pass a defined variable in R to the SQL statement within the sqldf package?
i have to run the code below and I passed the 'v' variable to sql select statement as '$v'
 for (i in 1:50){
          v <- i+ 450
          temp <- sqldf("select count(V1) from file_new where V1='$v' ")
        }

Although it runs, it returns wrong result. [The result should be 1000 but this code returns 0].
Hence, I think it doesn't pass the variable value.

A: If v is an integer then you don't want to enclose the $v with single quotes - that makes it a string value. Try without the single quotes.
temp <- fn$sqldf("select count(V1) from file_new where V1=$v ")


text:
Q: How to list AWS S3 objects and versions in a versioned bucket using Java I would like retrieve a list of all objects in a versioned bucket along with their versions in a list similar to how the AWS S3 Console does it:

I am able to list objects in a non-versioned bucket using the advice from this SO question.  However, it is not all that clear how to list them along with version IDs as S3ObjectSummary contains no versioning information.  It would seem cumbersome to make separate calls to versioning methods and then try to put them together with the information contained within an S3ObjectSummary

A: This looks like the closest answer I could find so far:
http://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html
The relevant code snippet is here:
    ListVersionsRequest request = new ListVersionsRequest()
        .withBucketName(bucketName)
        .withMaxResults(2);
        // you can specify .withPrefix to obtain version list for a specific object or objects with
        // the specified key prefix.

    VersionListing versionListing;
    do {
        versionListing = s3client.listVersions(request);
        for (S3VersionSummary objectSummary :
            versionListing.getVersionSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                    "(size = " + objectSummary.getSize() + ")" +
                    "(versionID= " + objectSummary.getVersionId() + ")");

        }
        request.setKeyMarker(versionListing.getNextKeyMarker());
        request.setVersionIdMarker(versionListing.getNextVersionIdMarker());
    } while (versionListing.isTruncated());


text:
Q: CoreData search too slow I am working on an iPhone app that searches through 91,000 entries. I am using CoreData, which works beautifully, except that it takes about 2 seconds to create the table of data. I have programmed it to do the search in the background, and added a spinner, but the user experience is still not ideal. I tried using FMDB which worked fine but wasn't any faster.
Essentially, I created my xcdatamodel in swift, added my entries to it, which works fine. (The code below is typed freehand, so sorry if there are typos)
I then create an NSFetchedResultsController:
let moc =(UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
searchText: String? = "name contains[c] \"seachText\""
nsfr = NSFetchRequest(entityName: "Example")
nsfr.fetchBatchSize = 20
nsfr.predicate = NSPredicate(format: searchText!)
nsfrc = NSFetchedResultsController(fetchRequest: nsfr, managedObjectContext: moc, sectionNameKeyPath: "section", cacheName: nil)

Then in my UITableViewController class (which conforms to NSFetchedResultsControllerDelegate):
nsfrc.delegate = self
nsfrc.performFetch()
self.tableView.reloadData()

Is there any way to speed up requests, like hashing the database? Any way to narrow search to the start of words? My data includes thousands of sentences, and I want to be able to search for parts of strings within. For example, "laz fo" should find "The lazy brown fox". Right now "azy own" will also find the string, which is not necessary. Any help would be appreciated! Even cutting the time in half would be wonderful.

A: FRC should perform very well with 100K records. However, string parsing is expensive, so depending on your data there could be performance issues.
You can try optimizing by replacing CONTAINS with BEGINSWITH although that will only match the beginning of the entire name string.
Alternatively, you can create a new entity Word and put them into a to-many relationship of Example (e.g. titleWords) and use a predicate like
NSPredicate(format: "ANY titleWords BEGINSWITH[c] %@", searchTerm)


text:
Q: Delay at end of page load when using mssql I have a working installation of mssql, php on Windows 2003, SQL Server 2008 express.  I finally got the connection working right, but now the connection to the database is really quick but its disconnection is slow.  This delays the final loading of my page by about 5 seconds, even though all the page is loaded in a few milliseconds.
I think this is something to do with php/mssql not releasing the connection to the database quickly.  The main problem here is that my javascript yui scripts wont run until the page thinks its fully loaded.
I've tried closing the connection immediately I don't need it to no avail.
Anyone know what setting I could set to fix it?

A: You can always call PHP flush() function to make any content generated by the script that is still in PHP or Apache buffer to be flushed.
Also, if you used mssql_pconnect to establish persistent connections to the MS SQL database, the connection is never closed when the PHP script exists, so I suppose mssql_close will not hold your script anymore.

A: I think the problem turned out to be incorrect DNS entries.  I changed the upstream DNS server being checked by the server and the lag went away.


text:
Q: error : display a red line under this statement _userFromFirebaseUser(userCredential.user); hi every one I'm trying making my app with flutter . it is contains a sign up page so I write the code and I'm retrieving an information from the firebase after I upload it .
the below code is the sign up code
UserModel? _userFromFirebaseUser(User userCredential) {
    return userCredential != null
        ? UserModel(
            id: userCredential.uid,
            bannerImageUrl: '',
            name: '',
            email: '',
            profileImageUrl: '')
        : null;
  }

  Stream<UserModel?> get userCredential {
    return auth
        .authStateChanges()
        .map((userCredential) => _userFromFirebaseUser(userCredential!));
  }

  Future SignUp(email, password) async {
    var formdata = formstate.currentState;

    if (formdata!.validate()) {
      print("valid");
      formdata.save();
      try {
        UserCredential userCredential =
            (await auth.createUserWithEmailAndPassword(
                email: myemail!, password: mypassword!));

        FirebaseFirestore.instance
            .collection('Users')
            .doc(userCredential.user!.uid)
            .set({'name': email, 'email': email});
        _userFromFirebaseUser(userCredential.user);

        return userCredential;
      } on FirebaseAuthException catch (e) {
        if (e.code == 'weak-password') {
          Navigator.of(context).pop();
          print('The password provided is too weak.');
        } else if (e.code == 'email-already-in-use') {
          Navigator.of(context).pop();
          print('The account already exists for that email.');
        }
      } catch (e) {
        print(e);
      }
    } else {}
  }

and the red line appears on this line   _userFromFirebaseUser(userCredential.user); as it is appears in the picture . please help me

A: userCredential.user      is User? not User

change the method parameter
UserModel? _userFromFirebaseUser(User? userCredential) {
    return ....
  }


text:
Q: RUBY - How to call a method from another class I'm new to ruby and programming in general and I'm having some issues getting methods to work from another class. The method I'm trying to get to work is new_employee and its option 2 if you run the business.rb
business.rb file contains class Business
  class Business
  attr_accessor :name

  def run
    self.welcome
  end

  def welcome
     while true
       puts "Welcome to Team Green Turf! What do you want to do today?"
       puts "1. Add new customer"
       puts "2. Add new employee"
       puts "3. View current revenue"
       choice = gets.chomp.to_i

      case choice
         when 1
           puts "hello!"
         when 2
           puts new_employee()
         when 3
           exit

      end
     end
  end
end

team_green_turf = Business.new
team_green_turf.run

---------------------------------
employees.rb file
require_relative 'business'

class Employees

  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def new_employee(name)
    puts "What is the employees name?"
    name = gets.chomp
    e1 = Employees.new(name)
  end

end

A: There are two main ideas:

*

*You need to ensure that the Ruby interpreter has loaded the file containing the method before you attempt to call it.  In your case, you are executing the code at the botton of business.rb before the employees.rb file has been fully loaded, so the Employee class and its methods will not be defined.  You could fix this in many different ways, but I suggest moving the last two lines of business.rb into their own file called run.rb and putting require_relative 'business' at the top of run.rb, and putting require_relative 'employees' at the top of business.rb, and removing the require_relative 'business' from the top of employees.rb.  (The Employees class does not actually use or depend on the Business class so it doesn't make sense to require it.)

*You need to provide the proper prefixes to the method to get it to be called.  In your case, you want to call the function from the Business class, you would write Employees.new_employee.  You would also need to change new_employee to be a class method by putting self. before its name when you are defining it:  def self.new_employee(name)....


text:
Q: How to reverse return value? var arr = [];

var a1;
arr.push( ( (a1 = [1, 2, 'random']).num = 5 ) && a1 )

Is there a way to not have to define the variable a1 and push the array a1 after setting the num property on it.
If I were to take out && a1 the number 5 would be pushed to arr. So anyways to push the array without having to define a1?

A: Why not define a helper function?
function set(obj, name, value) {
    obj[name] = value;
    return obj;
}

var arr = [];
arr.push( set([1, 2, 'random'], 'num', 5) );

For one instance even:
var arr = [];

var a1 = [1, 2, 'random'];
a1.num = 5;
arr.push(a1);

Would be more readable.

A: The only way I can shorten this code is by leaving off the variable declaration of a1 entirely:
var arr = [];
//var a1;
arr.push( ( (a1 = [1, 2, 'random']).num = 5 ) && a1 );

This actually works, but I think it's probably better to leave your variable definition.
You could do this:
var a1=( (a1 = [1, 2, 'random']).num = 5 ) && a1;
arr.push(a1);

At least now you don't have an empty variable declaration.
I ran a test on my second solution to see if a1 was in fact being defined globally before being stored in the local variable a1:
    var array=[];
    function scopeTest(){
        biff=10;// Global
        var a1 = (( a1 = [1, 2, 'random']).num = 5 ) && a1;// Private?
        array.push(a1);
    }
    scopeTest();

    alert("array: "+array);// 1,2,random
    alert("array[0].num: "+array[0].num);// 5
    alert("biff: "+biff);// 10
    alert("a1: "+a1);//a1 is undefined and therefore not global.

Defining a1 this way is totally fine!


text:
Q: Various User roles in Rails(specifically version 5) without using gems like devise or cancancan I am designing a fully-functional job boarding website on Rails 5 as a training project give by my company. I had no idea what Rails was until I read the Guide on Ruby on Rails and a book by Michael Hartl in Learn Enough Society.
I have a doubt regarding User model. I am not allowed to use any additional gems for Authentication or Authorization and there are three roles given to the user, that are, admin, recruiter and job-seeker.
I thought to use different models and controllers for all of them but it is not very helpful since there will further be controllers for Job application.This is also not beneficial since there are common attributes like name, email, password, contact etc which would be repeated as columns. Routing is also major concern for me.
I have another idea of having a User model with common attributes(and an attribute for role) and then having two other models for Recruiter and Job-seeker which would be inheriting from User model. I am unable to find relevant information.
Can I get any help from here? Thank you!


text:
Q: Ruby: How to set a default value for nil keys on a hash created via hash literal notation? In a free Ruby course I'm working through, I was shown the way to create a default value for a hash via constructor. And it looks like so:
no_nil_hash = Hash.new("default value for nil key")
puts no_nil_hash["non_existing_key"]

Which prints: default value for nil key
How would I go about this via the way of hash literal notation?
Did not find any answers via google and here are my futile attempts so far:

*

*via_hash_literal = {"default value for nil key"} but this is causing an error: syntax error, unexpected '}', expecting =>

*via_hash_literal = {=> "default value for nil key"} causing more errors:
syntax error, unexpected =>, expecting '}' via_hash_literal = { => "default value for nil key"} syntax error, unexpected '}', expecting end-of-input ...=> "default value for nil key"}

*via_hash_literal = {nil => "default value for nil key"} does not throw an error but then puts via_hash_literal["non_existing_key"] does not print the default key: default value for nil key, instead I get an empty row of line.

A: The {} syntax to generate a new hash in Ruby doesn't support setting a default. But you can use Hash#default= to set an default too:
hash = {}
hash.default = "default value"

hash[:foo]
#=> "default value"

A: It can be written as the following:
no_nil_hash = {}
no_nil_hash.default = "default value for nil key"
puts no_nil_hash["non_existing_key"]

Result in IRB:
irb(main):001:0> no_nil_hash = {}
=> {}
irb(main):002:0> no_nil_hash.default = "default value for nil key"
=> "default value for nil key"
irb(main):003:0> no_nil_hash["non_existing_key"]
=> "default value for nil key"

Read more: https://docs.ruby-lang.org/en/2.0.0/Hash.html


text:
Q: Using part of Text to control redirect using Protractor In our project, there are different urls assigned to different categories of product. If the product category is Cat1, click on edit button should take the user to the Cat1 page, and Cat2 should take the user to Cat2 page. However these categories are in a dynamic table so we can not use a fix reference for the edit buttons, and I am trying to make it dynamic. Below is my code snippet:
it('should take the user to appropriate page', function () {
    expect(globalVariables.Edit_Button_1.isDisplayed());

    // get rows
    var row_1 = globalVariables.tableData_Dashboard.all(by.tagName("tr")).get(1);

    // get cell values
    var cells = row_1.all(by.tagName("td"));

    var Cetegory = cells.get(3).getText().then(function (GL) {
        // console.log(GL)
        return GL;
    });

    globalVariables.Edit_Button_1.click();

    browser.wait(EC.invisibilityOf(globalVariables.Edit_Button_1), 25000, 'Edit button is not disappearing yet');

    if (Cetegory.endsWith('Cat1')){
        expect(browser.getCurrentUrl()).toEndWith("Cat1");
    }
    else {
        expect(browser.getCurrentUrl()).toEndWith("Cat2")
    }

The tests fails with the log "  Failed: Cetegories.endsWith is not a function ..
How can this be fixed?

A: Cetegory is a promise, not a string. Thus it does has function endsWith. You need to consume the promise eventual value in then() as following.
Cetegory.then(function(_Cetegory){
    if (_Cetegory.endsWith('Cat1')){
        expect(browser.getCurrentUrl()).toEndWith("Cat1");
    }
    else {
        expect(browser.getCurrentUrl()).toEndWith("Cat2")
    }
})


text:
Q: Weird behavior of spread operator in JSX Spread Operator in JS environment
let obj1 = {a:1,b:2}
let obj2 = {...obj1}
console.log(obj2)

Above code outputs {a:1,b:2} Which is a copy of obj1
Spread Operator in JSX
let us assume this.props = {lib:'react',lang:'js'}
<App {...this.props}/>
would be same as
<App lib={this.props.lib} lang={this.props.lang}>
As we know this.props is also an object just like obj1 why does JSX spreads like lib='react,lang='js' instead of lib:'react',lang:'js'?
Is there a difference between JSX Spread Operator and Javascript Spread Operator?
I'm really Confused

A:
As we know this.props is also an object just like obj1 why does JSX
spreads differently?

The {} syntax in JSX is used for JavaScript expressions, so when we use {} it isn't considered as an object literal.
That's the reason we use something like someProp={{bla: 'foo'}} when we want to pass an object because the outer pair is to tell that we will have an expression inside it.
In short, using {} in JSX doesn't create an object.
You can read more about spread attributes.

A: In both cases it is a spread operator only and Javascript spread operator only. There is no such thing as JSX spread operator.
When we do <App {...this.props}/>, it is same as <App a="1" b="2"/> in React.
And in React these are added to the prop object of App class. From that prop object, we get access to the values a and b respectively.
const App = (props)=>{
   const {a,b} = props; // Object De-structuring
}

We are basically spreading the props which means passing these values as Props to the App component, . This is same as passing values to function using spread operator.
Think of it this way: Think of App Component as a function, which is taking spreaded object as arguments.
const App= ({a,b})=>{ // Here we are De-Structuring from our props object
   console.log(a);
   console.log(b);
}

App({...obj1}); // This is same as App(a,b)

Codepen code : https://codepen.io/emmeiWhite/pen/poEREEx?editors=1111
Try above code in Javascript file
Spread ... operator can also be used to make a clone of the object when we do
let obj1 = {a:1,b:2}

let obj2 = {...obj1}

obj2 is clone of obj1. A complete new object. obj1 and obj2 are now two different objects in memory not just the references.