text:
Q: May the name of a macro parameter be a keyword? I discovered something interesting while writing code. I defined a macro in my code and accidentally used the keyword int as the variable name of parameter of that macro. The code worked perfectly fine, but I'm a bit surprised about it. I have read that in C keywords are reserved words and cannot be used as variable names.
This is my code:
#include <stdio.h>

#define PRINT(int) printf("%d",int)

int main()
{
    int x=2;
    PRINT(x);
    return 0;
}

Can anyone explain me why is it working fine? Is it not true that keywords are reserved and cannot be used as variable names in C, or is this some exception in C for macros?

A: In this context, int is not a variable (more correct: parameter) name because of course PRINT is also not a function -- it's a preprocessor macro.
Whatever you write as part of a macro definition is only looked at by the preprocessor. By the time the compiler gets to see the processed source nothing remains of the "int" name.
This is similar to what happens with formal parameters of functions: the compiler gets to see those names, but after it's done with the source no trace of them remains in the compiled code (so you need to load debug symbols in the debugger to "get this information back").

A: The #define is replaced by the preprocessor before the C compiler ever sees it. What the compiler itself sees is this:
int main()
{
int x=2;
printf("%s",x);
return 0;
}

This is valid C code. Using a keyword as a variable name does give an error:
int main()
{
int float=2;
printf("%s",float);
return 0;
}

This will not compile.

A: During the preprocessing phases, keywords do not exist and are just seen as ordinary identifiers.

A: C standard section 5.1.1.2 defines nine phases of C translation. Preprocessing phase is number 4; keywords are recognized as such only in the phase 7; before that phase all keywords are considered regular preprocessing tokens. See the standard for further details.

keyword: one of
auto break case [...]
The above tokens (case sensitive) are reserved (in translation phases 7 and 8) for use as
keywords, and shall not be used otherwise.


text:
Q: Matrix inequality involving product to two positive definite matrices $(AA^T)(BB^T)$ Let $A \in \mathbb{R}^{m\times p}$ and $B \in \mathbb{R}^{p \times n}$
where $m > n > p$ and $A, B$ are full rank.
For $x \in \mathbb{R}^n$ with $\|x\|_2=1$, let us consider
$$
f(x) = x^T(A^TA)(BB^T)x.
$$
Can we conclude that
$$
f(x) \ge \sigma^2_{\min}(A^TABB^T)\|x\|^2 ? \quad \text{or} \quad
\ge \sigma_{\min}^2(A)\sigma_{\min}^2(B)\|x\|^2 ?
$$
or a lower bound which involves singular values of $A$ or $B$?
Here, for a matrix $M$ of size $s \times k$,
$\sigma_{\min}(M)$ is the $\min\{s,k\}$-th largest singular value of $M$.
Here is my attempt.
Since $BB^T$ is symmetric positive definite, we can write it as
$BB^T = R^{1/2}R^{1/2}$ where $R^{1/2}$ is a $p \times p$ symmeric matrix.
Since $R^{1/2}A^TAR^{1/2}$ is symmetric, it is diagonalizable. Thus we have
$$
A^TABB^T = R^{-1/2}(R^{1/2}A^TAR^{1/2})R^{1/2} = R^{-1/2}(Q\Sigma Q)R^{1/2},
$$
and
$$
f(x) = x^TA^TABB^Tx = (x^TR^{-1/2}Q)\Sigma (QR^{1/2}x).
$$
If $R^{-1/2} = (R^{1/2})^T$, $BB^T = I$ and the statement is obvious.
If $R^{-1/2} \ne (R^{1/2})^T$, I am not sure what would be a valid lower bound in terms of singular values of $A$ or $B$.
Any suggestions/comments/answers will be very appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automapper: Class and property with identical names not mapping Below is a barebones class setup for what I'm describing.
public class List
{
   public int Id {get;set;}
   public RecipientCount RecipientCount {get;set;}
   public RecipientCount SomeOtherName {get;set;}
}

public class RecipientCount
{
   public int Total {get;set;}
   public int Active {get;set;}
}

public class ListDto
{
   public int id {get;set;}
   public RecipientCountDto recipientCount {get;set;}
   public RecipientCountDto someOtherName {get;set;}
}

public class RecipientCountDto
{
   public int total {get;set;}
   public int active {get;set;}
}

public class AutoMapperConfiguration
{
    public void Init(AutoMapper.IConfiguration config)
    {
       config.CreateMap<RecipientCount,RecipientCountDto>();
    }
}

if I attempt to use this it throws a:
   The following property on Reachmail.Domain.Component.RecipientCountDto cannot
   be mapped:
   recipientCount
   Add a custom mapping expression, ignore, add a custom resolver, or modify the
   destination type Reachmail.Domain.Component.RecipientCount.
   Context:
   Mapping to property recipientCount of type Reachmail.Domain.Component.RecipientCountDto
   from source type Reachmail.Domain.Component.RecipientCount
   Mapping to type Reachmail.Web.UI.Controllers.ListDto from source type
   Reachmail.Domain.Contacts.Lists.List
   Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.

If however I remove RecipientProviderDto.recipientProvider it works fine. So it leads me to believe that its the fact that the class name and the property are the same that is causing an issue. Any insights on how to fix it or if its a bug?

A: try with UpperLetter:
public class ListDto
{
   public int Id {get;set;}
   public RecipientCountDto RecipientCount {get;set;}
   public RecipientCountDto SomeOtherName {get;set;}
}

public class RecipientCountDto
{
   public int Total {get;set;}
   public int Active {get;set;}
}

Hope it helps.


text:
Q: Using regular expression in Twitter API I am using Tweepy Library in Python to search for tweets. I am wondering, if I can use regular expression to search Tweets.
I am using the following code :
query = 'ARNOLD or SYLVESTER'
for tweet in tweepy.Cursor(api.search,
                            query,
                            count=100,
                            result_type="recent",
                            include_entities=True,
                            lang="en").items():

For instance, can I search for all tweets which uses 'ARNOLD' or 'SYLVESTER'  ( all capital/single word) an ignore all the other tweets.
I am currently processing the tweets after obtaining all the tweets consisting of Arnold or Sylvester and then checking if all the characters are in uppercase. I am wondering if it can be done through API search itself.
Thanks

A: There is now a full list of all available search operators in the Twitter API documentation.
https://developer.twitter.com/en/docs/tweets/rules-and-filtering/overview/standard-operators
I can't comment on the original answer, so thought this would be useful for future visitors arriving via Google, as it is not easy to find on the Twitter docs website.

A: Twitter unfortunately doesn't support searching of tweets using regular expressions which means that you do have to post process. There's not actually any official documentation from Twitter to that effect, but everyone who uses the Twitter search API post-processes their tweets using regex (including me).  Since there isn't a stated official position, I've tried just about every flavor of regex in search queries but I've had no luck. Per the Twitter search API documentation, queries must be:

A UTF-8, URL-encoded search query of 1,000 characters maximum, including operators. Queries may additionally be limited by complexity.

All queries are UTF-8 and are obviously searched as such.  It'd be nice if there was a regex parameter we could specify in the API search call but there isn't.
The reason behind this is likely the additional processing cost that running a regex search on all tweets would have for Twitter itself.


text:
Q: RegEx to split on commas, but excluding those within braces, brackets, and parenthesis I'm trying to parse a comma-separated list, while omitting commas that fall within inner structures defined by braces, brackets, or parenthesis. For example, this string:
'text:firstName,css:{left:x,top:y},values:["a","b"],visible:(true,false),broken:["str", 1, {}, [],()]'

Should split as:
text:firstName
css:{left:x,top:y}
values:["a","b"]
visible:(true,false)
broken:["str", 1, {}, [],()]

So far, I've got the following... which is close but breaks on nested structures:
[^,\[\]{}]+(({|\[)[^\[\]{}]*(}|\]))?

Any help would be greatly appreciated!

A: Unless you are willing to change your data format, or you can find an easy way to turn it into proper JSON after receiving, your best bet is parsing manually.
The simplest matcher (assumes "nice" values):
On ([{   - increment parens
On )]}   - decrement parens or emit error if parens is zero
On ,     - emit and reset the buffer if parens is zero (finish a match)
If not , - push into the output buffer

This doesn't work with "ugly" strings (quoted parens, escaped quotes, escaped escapes...). This parser should parse all valid input correctly, while still being relatively simplistic:
On ([{ - increment parens if the state is "start". Push to buffer.
On )]} - decrement parens if the state is "start" and parens is positive.
         Emit an error if parens is zero. Push to buffer.
On ,   - emit and reset the buffer if parens is zero and the state is "start"
         (finish a match). Push to buffer.
On \   - Push to buffer, and push and read the next symbol as well.
On '   - If the state is "start", change the state to "squote", and vice versa.
         Push to buffer.
On "   - If the state is "start", change the state to "dquote", and vice versa.
         Push to buffer.
On EOF - Emit error if parens is not zero or the state is not "start".

Here's a sketch of the implementation in Javascript:
function splitLiteralBodyByCommas(input){
  var out = [];
  var iLen = input.length;
  var parens = 0;
  var state = "";
  var buffer = ""; //using string for simplicity, but an array might be faster

  for(var i=0; i<iLen; i++){
    if(input[i] == ',' && !parens && !state){
      out.push(buffer);
      buffer = "";
    }else{
      buffer += input[i];
    }
    switch(input[i]){
      case '(':
      case '[':
      case '{':
        if(!state) parens++;
        break;
      case ')':
      case ']':
      case '}':
        if(!state) if(!parens--)
          throw new SyntaxError("closing paren, but no opening");
        break;
      case '"':
        if(!state) state = '"';
        else if(state === '"') state = '';
        break;
      case "'":
        if(!state) state = "'";
        else if(state === "'") state = '';
        break;
      case '\\':
        buffer += input[++i];
        break;
    }//end of switch-input
  }//end of for-input
  if(state || parens)
    throw new SyntaxError("unfinished input");
  out.push(buffer);
  return out;
}

This parser still has its flaws:
It allows closing parens with braces et al. To solve this, make parens a stack of symbols; if the opening and closing symbol don't match, raise an exception.
It allows malformed unicode-escaped strings. \utest is accepted by the parser.
It allows a top-level comma to be escaped. This is probably not a fault: \,,\, is a valid string, containing two top-level escaped commas separated by an unescaped one.
A trailing backslash produces unexpected output. Again, this would be fixed by reading the data we're escaping. An easier fix is buffer += input[++i] || '' (append an empty string instead of undefined, but that allows invalid input.
It allows all sorts of other invalid input: [""'']{'\\'}"a" is just an example. A fix would need a better (more comlex) grammar, and accompanyingly more complex parser.

having said that, isn't it better to just use JSON for transmitting the data?
Option 1: a real object: {"text":"firstName", "css":{...
Option 2 (only if you really wish so): an array of strings: ["text:firstName, css:{...
In both cases, JSON.parse(input) is your friend.

A: Using recursive matching:
(?>[^(){}[\], ]+:)?(?>(?>\([^()]*(?R)?[^()]*\))|(?>\[[^[\]]*(?R)?[^[\]]*\])|(?>{[^{}]*(?R)?[^{}]*})|(?>[^(){}[\], ]+))

The first part matches up to and including the colon:
(?>[^(){}[\], ]+:)?

The rest contains options for balanced (), [], {}, and anything else except comma or space:
(?>(?>\([^()]*(?R)?[^()]*\))|
(?>\[[^[\]]*(?R)?[^[\]]*\])|
(?>{[^{}]*(?R)?[^{}]*})|
(?>[^(){}[\], ]+))


text:
Q: Polyglot persistence in Android I wonder if there is a way of implementing Polyglot persistence in Android.
How would you implement it?
I'm looking for an Open Source sample project in order to dig deeper into the subject.


text:
Q: Reasons for the blue screen of death in Windows 7 logs Lately I see a blue screen of death a lot and want to know why it appears. Where should I gather the information so the problem can be diagnosed best?
Couldn't find anything in C:\Windows\Logs.

A: I really tend to be fond of whocrashed for analyzing BSODs, or you can use nirsoft's blue screen view - the former is easier to use, the latter lets you look at bluescreens. I believe both of these analyze the windows minidump file (often at %windir%/minidump) and MS has a knowledge base on reading it


text:
Q: How to find the number of combinations in which a class of elements always has to be included? Say I have a set $\{A, B, C, D, E, F\}$ and I have to find how many sets of four elements I can make from these that must include at least any two elements from the set $\{D, E, F\}$?
On a similar basis: How many ways can you form a committee of five from $6$ men and $4$ women such that in every of these committees there are at least $2$ women?
I seriously have no idea how to go about these.

A: In both of these problems it's easiest to count the sets that don't meet the requirement and subtract them from the total number of possible sets.
In the second problem, for instance, there are $\binom{10}5$ possible $5$-person committees altogether. $\binom65$ of them include no women, and $\binom64\binom41$ include just one woman, so there are $$\binom{10}5-\binom65-\binom64\binom41$$ committees that include at least two women. The first problem can be worked in similar fashion.


text:
Q: Compile libssh2 based C code (and generate the exe) on windows I could successfully build the libssh2 library for windows using Compiling libssh2 on windows. I am not able to figure out  the command to compile a simple C program on a windows system that uses libssh2 , say any example code from https://libssh2.org/examples/
My system: Windows Server 2019, Visual studio 2017.
Command I tried:
cl ssh2_exec.c
Error: cannot open include file : 'libssh2.h': no such file or directory

A: Try and type first:
set INCLUDE=%INCLUDE%;C:\path\to\libssh2-headers\folder

Then try again your cl ssh2_exec.c: that should be enough for cl to find where the header files are.


text:
Q: Как доработать запрос? Таблицы: объект, договор, договор-заказчик, заказчик.
Нужно вытянуть id, номер, наименование, дату закрытия объекта и первого заказчика в первом договоре.
Договор содержит id объекта. На 1 объект может быть несколько договоров. Первый договор ищу по самой ранней дате составления договоров.
Таблица дог-зак содержит заказчиков по договору. На 1 договор может быть несколько заказчиков. Первого заказчика определяю по минимальному ID в таблице дог-зак.
SELECT obj."ID", obj.nomob, zk.naimzak, obj.naimob, obj.datvk
FROM obekt obj
  INNER JOIN dogovor dgr ON (obj."ID" = dgr."IDobekt" AND dgr.deleted = false)
  INNER JOIN dogzak dz ON (dgr."ID" = dz."IDdogovor")
  INNER JOIN zakazchik zk ON (dz."IDzakazchik" = zk."ID")
WHERE
  obj.deleted = false

  AND dgr."ID" =
    (SELECT dogovor."ID" FROM dogovor
     WHERE dogovor."IDobekt" = obj."ID" AND dogovor."deleted" = false
     ORDER BY dogovor."fdatsost" LIMIT 1)

  AND dz."ID" =
    (SELECT min(dogzak."ID") FROM dogzak
     WHERE dgr."ID" = dogzak."IDdogovor");

Написал это, только есть проблема, не знаю как записать следующие условия:
В объекте может не быть договоров(соответственно и заказчика) - этот объект то же должен попасть в результат.
И в договоре может не быть заказчика(не будет записи в таблице дог-зак) - этот объект то же должен попасть в результат.
Подскажите, как доработать эти условия?

A: INNER JOIN - возвращает записи объединяемых таблиц по условию записанному после ON. Если в какой-либо из таблиц отсутствует запись соответствующая соседней, то в результат эта запись не попадет. Поэтому меняем INNER JOIN на LEFT JOIN.
LEFT JOIN - возвращает все данные из таблицы "слева", даже если не найдено соответствий в "правой" таблице.
Правка WHERE. Добавить IS NULL чтобы проверить, является ли какое-либо значение NULL.
Результат:
SELECT obj."ID", obj.nomob, zk.naimzak, obj.naimob, obj.datvk
FROM obekt obj
  LEFT JOIN dogovor dgr ON (obj."ID" = dgr."IDobekt" AND dgr.deleted = false)
  LEFT JOIN dogzak dz ON (dgr."ID" = dz."IDdogovor")
  LEFT JOIN zakazchik zk ON (dz."IDzakazchik" = zk."ID")
WHERE
  obj.deleted = false

  AND (dgr."ID" =
    (SELECT dogovor."ID" FROM dogovor
     WHERE dogovor."IDobekt" = obj."ID" AND dogovor."deleted" = false
     ORDER BY dogovor."fdatsost" LIMIT 1)
    OR dgr."ID" IS NULL)
  AND (dz."ID" =
    (SELECT min(dogzak."ID") FROM dogzak
     WHERE dgr."ID" = dogzak."IDdogovor")
     OR dz."ID" IS NULL);


text:
Q: How to programmatically ask if Mathematica is running as an Administrator To avoid execution problems in a program I need to know if Mathematica has been "Run as administrator".  What would be the cleanest way to programmatically getting this information?

A: It may suit your purpose to use the Windows API function IsUserAnAdmin.  It can be accessed through NETLink like this:
Needs["NETLink`"]
isUserAnAdmin = DefineDLLFunction["IsUserAnAdmin", "shell32.dll", "bool", {}];

isUserAnAdmin[]
(* True if Mathematica was launched elevated, False otherwise *)

It is also possible to to use the shell command whoami to determine the Mandatory Label which, in turn, can tell us if the current session is running elevated:
isElevated[] :=
  !StringFreeQ[
    Import["!whoami /groups | find \"Mandatory Label\"", "Text"]
  , "S-1-16-12288"|"S-1-16-16384"
  ]

isElevated[]
(* True if Mathematica was launched elevated, False otherwise *)

The magic strings in isElevated are the security identifiers (SIDs) denoting the elevated integrity levels.  This text-based solution has the advantage that it does not require NETLink to be loaded.  On the other hand, it is more brittle should the output format of whoami ever be changed.

A: The only method I am aware of is to attempt an operation that requires administrator-level permissions and look for a General::privv message:
Check[
  (CreateDirectory @ #; DeleteDirectory @ #) & @
   FileNameJoin[{$InstallationDirectory, "test"}]; True,
  False,
  General::privv
] // Quiet

This should return True if it is run with administrator control and False if not.


text:
Q: Gob Decode Giving "DecodeValue of unassignable value" Error I'm new-ish to Go and I'm having some trouble putting a gob on the wire. I wrote a quick test that I thought would pass, but the decode call is returning a "DecodeValue of unassignable value" error. Here's the code:
type tester struct {
    Payload string
}

func newTester(payload string) *tester {
    return &tester {
        Payload: payload,
    }
}

func TestEncodeDecodeMessage(t *testing.T) {
    uri := "localhost:9090"
    s := "the lunatics are in my head"
    t1 := newTester(s)
    go func(){
        ln, err := net.Listen("tcp", uri)
        assert.NoError(t, err)
        conn, err := ln.Accept()
        assert.NoError(t, err)

        var t2 *tester
        decoder := gob.NewDecoder(conn)
        err = decoder.Decode(t2)
        assert.NoError(t, err)
        conn.Close()
        assert.NotNil(t, t2)
    }()

    time.Sleep(time.Millisecond * 100)
    conn, err := net.Dial("tcp", uri)
    assert.NoError(t, err)

    gob.Register(t1)
    encoder := gob.NewEncoder(conn)
    err = encoder.Encode(t1)
    assert.NoError(t, err)
    conn.Close()
    time.Sleep(time.Millisecond * 100)
}

I suspect I'm missing something stupid here and appreciate any help that you're able to offer.

A: Had a friend take a look at this and he pointed out that gob doesn't let you assign to a nil pointer. From the gob package docs: "Nil pointers are not permitted, as they have no value." It looks like gob reflects on the fields of the struct that is passed in and attempts to assign values from the encoded stream. Changing this:
var t2 *tester

To this:
t2 := &tester{}

Makes the test pass.


text:
Q: Why should someone use decimal expansion of a real number when that decimal expansion is ITSELF a real number? EDIT: Is the cornell proof incomplete? Since it doesn't account for the two possible decimal expansions of a real number. For example, it says 1/2 = .5 but doesn't account for .49999999...
I'm looking at these two proofs - one from Cornell and one from Berkeley (example 3).
https://courses.cs.cornell.edu/cs2800/wiki/index.php/Proof:The_set_of_reals_is_uncountable
https://math.berkeley.edu/~arash/55/2_5.pdf
I understand Cornell's proof, but I'm confused about the Berkeley proof. Why does the Berkeley proof consider the decimal representation of real numbers between 0 and 1 and not just the real number itself, since it's already in decimal form (since it's between 0 and 1). Doesn't this just add potential holes in the argument, since there are either 1 or 2 possible decimal expansion forms?
I'm not comfortable with the real numbers or decimal expansions, so there's a good chance I'm missing something. My friend also wrote a proof that uses decimal expansion, but I'm not sure why. Basically, why should someone use decimal expansion? Is it because 5 is a real number but we want to represent it in decimal form so the decimal expansion of 5 is 5.00000... and 4.99999....? IN SHORT: Why should someone use decimal expansion of a real number when that decimal expansion is ITSELF a real number?
My friends proof:
Proceed by contradiction. Suppose there exists a surjection $f: \mathbb N \mapsto \mathbb R$. Consider the possible decimal expansions of $f(n)$ for any $n \in \mathbb N$; (there may be multiple). Consider the $n$th place after the decimal point, and let $S_n$ be the set of integers that appears in this $n$th place after the decimal point among the possible decimal expansions of $f(n)$.
Lemma: First fixing $n$ and $f$th, $S_n$ has at most two elements (give proof)
Now, for each $n$, pick $0 \leq a_n \leq 9$ an integer not in $S_n$ (can do that as $|S_n| \leq 2$). Consider a = $0.a_1a_2a_3\cdots$, i.e. the real number with decimal expansion given by $a_1$ in the tenths place, $a_2$ in the hundredths place, etc. Then $a \notin Im(f)$, i.e. $a \neq f(a)$ for any $n \in \mathbb N$ (give proof), so $f$ is not a surjection.

A: A decimal expansion is a sequence $u=(u_n)_{n>0} \in \{0;...;9\}^{\mathbb{N}^{>0}}$. You have a function $\sigma: \{0;...;9\}^{\mathbb{N}^{>0}} \rightarrow [0,1]$ which sends a decimal expansion $u$ to the sum $\sum \limits_{n>0}\frac{u_n}{10^n}$. Say that a decimal expansion $u$ is the decimal expansion of a number $x$ if $\sigma(u)=x$. Then it is known that each number $x\in [0,1]$ has exactly one or exactly two decimal representations: it has only one if it is not decimal or if $x \in \{0,1\}$, and it has two otherwise.
Writing a number in decimal form is not a mathematical statement, but an informal way to say "considering / computing the decimal expansion" of said number.


text:
Q: Why is it allowed for a list to append itself? I noticed by accident that in Python you can write something like the following:

l = list()
for i in range(5):
  l.append(l)

If I print out what l is it looks like this:
[[...], [...], [...], [...], [...]]

And now I can do things like:
l[0][0][0][0]...[0]

which will return still the exact same list.
The error I had made in my code was not detected by my linter and so might have been difficult to spot. So my question is: why is it allowed for a list to append itself? What use can you make of it?
If it's not useful it should probably be disallowed.

A: Your criteria for not allowing a list in a list is that it isn't useful. But it's hard to prove that's not true. Maybe nobody knows yet a use, but that doesn't someone won't in the future. In the meantime, there is added cost to the language both in terms of explaining what exceptions there are to adding an object to a list, and in implementing those exceptions.
If you could prove that it is harmful to allow adding a list to itself, then you would have a stronger case for making that change to the language. But "I accidentally typed the wrong variable name" is not a strong argument for harm.

A: Why is it allowed for list to append to itself?  Remember that in python, everything is a reference. A list is just a sequence of references to objects.  Since a list is an object, it can be referenced by another list.  When a list references an object, its not like that object is actually contained within the list now, its just that a single element of the sequence is now a reference to that object.  Though circular references are sometimes bad, they are sometimes useful, and nothing has actually been broken here. Remember, a list containing itself is actually just a list that has a reference to itself.

A: Why is it allowed for a list to append itself?
Your assumption that it's an error and should not be allowed is incorrect. It's up to us as engineers to decide if it's a good fit for the situation we have or not. I'll turn this question around, why do you think it should be disallowed?
What use can you make of it?
Adding arrays to arrays is actually pretty common. I could imagine a situation where you have to start with 5 identical arrays, perform different calculations on each one, then compare the results. This would be a way to accomplish that.


text:
Q: CrossGeolocator in Xamarin UWP project returns a wrong current location CrossGeolocator in my Xamarin UWP project returns a wrong current location. The location that it returns to me is Lakeville, Minnesota. But I am living much far away from it. Here is the code:
   var locator = CrossGeoLocator.Current;
   locator.DesiredAccuracy = 100;
   var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);

Where is the problem? Any suggestion?
Thanks!

A:
CrossGeolocator in Xamarin UWP project returns a wrong current location

If your device does not contain GPS sensor, CrossGeoLocator api will get current location with IP address preferentially. If your local network uses a VPN proxy, it will cause the map to find the corresponding location according to the proxy's ip address that will make the location deviation from actual location.

but right now I cannot try working without vpn.

If you can't use disable vpn. the better way is add the GPS sensor to your device. It has a higher priority.


text:
Q: Unable to get Last-Modified from PHP header in shell script I am using a bash shell script to retrieve the Last-Modified value from several webpages (Thanks Lri!).  Here is the code that I am using:
#!/bin/bash

url=http://www.mywebsite.com
tempdir=~/Library/Caches/scripts
temp=$tempdir/mywebsite
mkdir -p $tempdir
modified=$(curl -sI "$url" | grep ^Last-Modified)
if [[ -f "$temp" && "$modified" != "$(cat $temp)" ]]; then
terminal-notifier -message 'Example changed'
fi
printf %s "$modified" > $temp

When I run the script on index.html, the output is: Last-Modified: Wed, 06 Nov 2013 00:20:49 GMT (which is correct).
When I run the script against on index.php, I get no nothing in the output.
Could someone please explain to me the code that I need to include in the .php page or in the shell script to correct the problem?  Thanks!

A: The web server can determine the Last-Modified date based on the timestamp of the .html file.
This doesn't work for PHP files, since PHP pages are usually dynamic. In these cases, it's up to the developer to determine what constitutes a logical modification, and send an appropriate header.
Here's an example that just sets the last modified time to the current date:
<?PHP
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
?>

For a blog, you might instead want to set the Last-Modified date to be that of the most recently updated article displayed on the page. For a weather forecast, you could set it to the last time the source data was updated for the location you're currently looking at.


text:
Q: Full Disk Encryption, if my HDD isn't bootable? I want to find out how to encrypt my HDD, if I plan to boot live operating systems and just use it as storage.
  The operating systems in question will probably be some Debian-distro linux and Windows 8.1, if it matters at all.


text:
Q: custom dialog error: child already has parent I am trying to use a custom view on a Dialog. I keep getting the error
07-09 18:03:38.740: E/AndroidRuntime(22032): java.lang.IllegalStateException:
The specified child already has a parent. You must call removeView()
on the child's parent first.

Here is my code
LayoutInflater inflater = getLayoutInflater();
    View dialoglayout = inflater.inflate(R.layout.activity_mine1,
        (ViewGroup) findViewById(R.layout.mine1));
    mine1 = new AlertDialog.Builder(this);
    mine1.setView(dialoglayout);
    mine1.show();

How do I fix this? (Presumably all I have to do is remove view.)

A: Try this;
if(dialoglayout.getParent()!=null){
      ((ViewGroup) dialoglayout.getParent()).removeView(dialoglayout);
}

You can remove view with this one.


text:
Q: Calculate the the length of the curve $\gamma(t)=(\frac{t^{2}}{4},\frac{t^{3}}{3},\frac{t^{4}}{4})$ I just discovered that I have a Calculus 3 test on Thursday and my teacher posted a list of exercises for the test. As I'm a little desperate I thought about asking the question here and start studying in the process.
The question is the following:
Find the length:
$\int^{}_{\gamma} dt|\dot{\gamma}(t)|$
where $\gamma(t)=(\frac{t^{2}}{4},\frac{t^{3}}{3},\frac{t^{4}}{4})$
The biggest problem is that right now I'm not really familiar with the notation used or even the theory involved in the solution of the question. Any help is appreciated during the moment of desperation that I find myself in right now

A: Being sure that you did follow what Taby Mak answered, after computing $x'$, $y'$ and $z'$, you should arrive to
$$||\gamma'(t)|| = \int_a^b \sqrt{t^6+t^4+\frac{t^2}{4}}\,dt$$ and factoring, you should notice that
$$t^6+t^4+\frac{t^2}{4}=t^2 \left(t^2+\frac{1}{2}\right)^2$$ which then makes the problem vey simple.

A: From Paul's Online Notes and other sources:
From Calculus II, $||\gamma'(t)||$ represents the arc length of the curve. By converting $\gamma(t)$ into the parametric form  $x = f(t), y = g(t), z = h(t)$, we can extend this concept into three dimensions with the formula:
$$||\gamma'(t)|| = \int \sqrt{[f'(t)]^2 + [g'(t)]^2 + [h'(t)]^2}$$
The notation $\int_{\gamma}$ means to find the arc length function from $0$ to $t$, so in your case, you have to find:
$$||\gamma'(t)|| = \int_0^t \sqrt{\left[\frac{t^2}{4}'\right]^2 + \left[\frac{t^3}{3}'\right]^2 + \left[\frac{t^4}{4}'\right]^2}$$


text:
Q: Add SSL to heroku with SSL Endpoint I am trying to add SSL cert to heroku.
When I try to add a certificate
heroku certs:add server.crt server.key --type endpoint
I am getting following error.
Resolving trust chain... done
Adding SSL certificate to ⬢ myapp... !
Only one SSL endpoint is allowed per app (try certs:update instead).
And when I try to update certificate as below
heroku certs:update server.crt server.key --type endpoint
I am getting following error
myapp has no SSL certificates
And when I check for SSL certificates
heroku certs
Here's the output
myapp has no SSL certificates.
Use heroku certs:add CRT KEY to add one.
I am unable to add SSL certificate to heroku.
Please help me out. Thanks in advance.

A: You can add certificates directly from setting sub menu.

*

*Add domain

*Click on configure SSL

*Add priva6 key and crt

*If using pointdns update target values


text:
Q: Is $f(x)$ irreducible in $\mathbb{Q}[x]$? $f(x)=x^4+x^2+x+1$
Is $f(x)$ irreducible in $\mathbb{Q}[x]$?
My attempt:
Since $f(x)$ is monic, every rational root of $f(x)$ is an integer that divides the constant term. So, the only candidates for rational roots of $f(x)$ are $1$ and $-1$.
$f(1)=4$ and $f(-1)=2$.
So, $f(x)$ does not have any rational roots. So, it does not have any linear factors. But it could be a product of $2$ irreducible quadratics. How do I determine whether this is the case?

A: A simpler way: $\ f(2) = 23$ is prime so $f(x)$ is irreducible by Cohn's irreducibility test.

A: Working from the comment of @ThomasAndrews, I notice that if $f$ is product of two quadratics, they must be $x^2+ax+\varepsilon$ and $x^2-ax+\varepsilon$, where $\varepsilon$ is either $1$ or $-1$.
Reason? If the linear coefficients of the quadratic factors are $a$ and $b$, then the cubic coefficient of the product is $a+b$. In the same way, the product of the constant terms must be $1$, so they are inverses of each other and of absolute value $1$, thus equal.
But $(x^2+ax+\varepsilon)(x^2-ax+\varepsilon)=x^4+(2\varepsilon-a^2)x^2+1$, with no linear term. So $f$ is irreducible.


text:
Q: jQuery.post is being sent as HTTP GET on IE9 I'm using jQuery 1.8.2 to call some backend server api's via jQuery's ajax POST. The backend server and the webpage are both on the same domain.
In my js file, I'm simply calling $.post('/createAccount',data,function(e) { alert(e); });
In Fiddler, this request is being sent as a GET, in IE9.
GET http://[redacted]/createAccount HTTP/1.1
Accept: */*
Origin: [redacted]
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: [redacted]
Connection: Keep-Alive
Pragma: no-cache

The same page using Chrome (latest) returns the following in Fiddler:
POST http://[redacted]/createAccount HTTP/1.1
Host: [redacted]
Connection: keep-alive
Content-Length: 103
Origin: http://[redacted]
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: */*
Referer: http://[redacted]/builder?token=[redacted]
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

email=test123&token=[redacted]&company=tokentest1

Here is the code using $.ajax instead of $.post (same issue):
        $.ajax({
            url : '/createAccount',
            type : 'POST',
            data : obj,
            dataType : 'json',
            cache: 'false',
            success : function(data) {
                if(data.status === 'ok') {

                } else {
                    alert('error');
                }
            }
        });

A: This was a derp moment. I had some code else where that would fallback to MSFT's XDomainRequest, and in that code it was forcing all requests to get, instead of pulling the request type from the jQuery options object.


text:
Q: Illegal state exception in popBackStack In my application I'm using BottomBar Menu's. When quickly selecting menu's I'm getting following crash report on crashlytics(only in some devices).  Here is the stacktrace

Non-fatal Exception: java.lang.IllegalStateException: Can not perform
  this action after onSaveInstanceState
         at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
         at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
         at android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:781)
         at com.beco.ibeco.app.MainActivity$1.onMenuTabSelected(MainActivity.java:87)
         at com.beco.ibeco.app.views.bottombar.BottomBar.notifyMenuListener(BottomBar.java:1239)
         at com.beco.ibeco.app.views.bottombar.BottomBar.updateSelectedTab(BottomBar.java:1199)
         at com.beco.ibeco.app.views.bottombar.BottomBar.handleClick(BottomBar.java:1161)
         at com.beco.ibeco.app.views.bottombar.BottomBar.onClick(BottomBar.java:1149)
         at android.view.View.performClick(View.java:5076)
         at android.view.View$PerformClick.run(View.java:20279)
         at android.os.Handler.handleCallback(Handler.java:739)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5930)
         at java.lang.reflect.Method.invoke(Method.java)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
  And here is the code

protected void onCreate(Bundle savedInstanceState) {
        mActive = true;
        super.onCreate(savedInstanceState);
        initBottomBar(savedInstanceState);
        Intent intent = getIntent();
    }
private void initBottomBar(Bundle savedInstanceState) {
        mBottomBar = BottomBar.attach(this, savedInstanceState);
        mBottomBar.useFixedMode();
        mBottomBar.noTabletGoodness();
        mBottomBar.setItemsFromMenu(R.menu.bottombar_menu, new OnMenuTabClickListener() {
            @Override
            public void onMenuTabSelected(@IdRes int menuItemId) {

                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//line 87

                switch (menuItemId) {

                    case R.id.bottomBarHome:
                        showStoreList();
                        break;

                    case R.id.bottomBarMap:
                        showMap();
                        break;

                    case R.id.bottomBarDeal:
                        showDeals();
                        break;

                    case R.id.bottomBarSettings:
                        showSettings();
                        break;

                    case R.id.bottomBarNotification:
                        if (mNotificationBadge != null) {
                            mNotificationBadge.hide();
                            Beco.getApp().clearBadge();
                        }
                        showNotifications();
                        break;
                }
            }

            @Override
            public void onMenuTabReSelected(@IdRes int menuItemId) {
                switch (menuItemId) {
                    case R.id.bottomBarHome:
                        if (mCurrentTab != HOME)
                            showStoreList();
                        break;

                    case R.id.bottomBarMap:
                        if (mCurrentTab != MAP)
                            showMap();
                        break;

                    case R.id.bottomBarDeal:
                        if (mCurrentTab != DEAL)
                            showDeals();
                        break;

                    case R.id.bottomBarNotification:
                        if(mCurrentTab != NOTIFICATION) {
                            if (mNotificationBadge != null) {
                                mNotificationBadge.hide();
                                mNotificationBadge.setDealItemCount(0);
                                Beco.getApp().clearBadge();
                            }
                            showNotifications();
                        }
                        break;

                    case R.id.bottomBarSettings:
                        if (mCurrentTab != SETTINGS)
                            showSettings();
                        break;
                }
            }
        });

        mNotificationBadge = mBottomBar.makeBadgeForTabAt(3, R.color.beco_badge_color, Beco.getApp().getBadgeCount());
    }
@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mBottomBar.onSaveInstanceState(outState);
    }

How can I override this issue ?

A: Create a boolean and check if activity is not going to onpause
@Override
public void onResume() {
    super.onResume();
    mIsResumed = true;
}

@Override
public void onPause() {
    mIsResumed = false;
    super.onPause();
}

then while loading fragment check
if(mIsResumed){
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//line 8
}


text:
Q: How to get an array from ASP.Net WebMethod to Ajax using Jquery? I am calling an webmethod from ajax, and I want to return an array. I tried this below code:
$.ajax({
  type: "POST",
  contentType: "application/json;charset=utf-8",
  url: "adminCopyCrystalReport.aspx/getAllDirectoryNames",
  //data: JSON.stringify({
  //    //"dirLocation": $(this).children('.pathValue').text()
  //    "dirLocation": correctPath
  //}),
  dataType: "json",
  success: function (data) {
    alert('Success = ' + data.d);
  },
  error: function (result) {
    alert("Error");
  }
});

public static GetFolderDetails[] getAllDirectoryNames()
{
  string paths = "~CrystalReportFiles/";
  List<GetFolderDetails> details = new List<GetFolderDetails>();

  foreach (var dirr in new DirectoryInfo(System.Web.Hosting.HostingEnvironment.MapPath(@paths)).GetDirectories())
  {
    //dir.Add(dirr.Name);
  }

  GetFolderDetails fd = new GetFolderDetails();
  fd.fullFolder = "xxx";
  fd.folderName = "ccc";
  fd.urlPath = "eee";

  return details.ToArray();
}

It throws a 500 Internal Server Error. If I return a string I get the output

A: Try to serialize the array (using Newtonsoft) and use Response.Write():
using System.Web.Script.Serialization;

public void getAllDirectoryNames()
{
  string paths = "~CrystalReportFiles/";
  List<GetFolderDetails> details = new List<GetFolderDetails>();

  // Add items to details list

  // Serialize the list using Newtonsoft
  // var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(details);

  // Serialize the list using System.Web.Script.Serialization
  var jsonString = new JavaScriptSerializer().Serialize(details);

  // Send the response back to ajax success callback
  Response.Write(jsonString);
}

A: Maybe you are mising below configration
In Global.asax file inside Application_Start method comment below line
//RouteConfig.RegisterRoutes(RouteTable.Routes);

Make sure that you EnablePageMethods in your ScriptManager
<asp:ScriptManager runat="server" EnablePageMethods="true">


text:
Q: Documents List API client for C# timing out I'm working on a simple wrapper for the google docs api in c#. The problem I'm running into is my tests are timing out. Sometimes. When I run all of my tests (only 12 of them) then it usually hangs up on the 8th one, which is testing the delete function. After about 6.5 minutes, it continues on, but every test after it also times out after 6.5 minutes for each test. If I run the tests individually then it works fine every time.
Here is the first method that times out:
Updated to show exception handling
[TestMethod]
public void CanDeleteFile()
{
    var api = CreateApi();
    api.UploadFile("pic.jpg", "..\\..\\..\\pic.jpg", "image/jpeg");
    try
    {
        var files = api.GetDocuments();
        api.DeleteFile("pic.jpg");
        var lessFiles = api.GetDocuments();
        Assert.AreEqual(files.Count - 1, lessFiles.Count);
    }
    catch (Google.GData.Client.GDataRequestException ex)
    {
        using (StreamWriter writer = new StreamWriter("..\\..\\..\\errors.log", true))
        {
            string time = DateTime.Now.ToString();
            writer.WriteLine(time + ":\r\n\t" + ex.ResponseString);
        }
        throw ex;
    }

}

It times out on var lessFiles = api.GetDocuments(); The second call to that method. I have other methods that call that method twice, and they don't time out, but this one does.
The method that all the test methods use that times out:
    public AtomEntryCollection GetDocuments(DocumentType type = DocumentType.All, bool includeFolders = false)
    {
        checkToken();
        DocumentsListQuery query = getQueryByType(type);
        query.ShowFolders = includeFolders;
        DocumentsFeed feed = service.Query(query);
        return feed.Entries;
    }

It times out on this line DocumentsFeed feed = service.Query(query);. This would be closer to acceptable if I was requesting insane numbers of files. I'm not. I'm requesting 5 - 6 depending on what test I'm running.
Things I've tried:

*

*Deleting all files from my google docs account, leaving only 1-2 files depending on  the test for it to retrieve.

*Running the tests individually (they all pass and nothing times out, but I shouldn't have to do this)

*Checking my network speed to make sure it's not horribly slow (15mbps down 4.5mbps up)

I'm out of ideas. If anyone knows why it might start timing out on me? Any suggestions are welcome.
edit
As @gowansg suggested, I implemented exponential backoff in my code. It started failing at the same point with the same exception. I then wrote a test to send 10000 requests for a complete list of all documents in my drive. It passed without any issues without using exponential backoff. Next I modified my test class so it would keep track of how many requests were sent. My tests crash on request 11.
The complete exception:
Google.GData.Client.GDataRequestException was unhandled by user code
Message=Execution of request failed: https://docs.google.com/feeds/default/private/full
Source=GoogleDrive
StackTrace:
     at GoogleDrive.GoogleDriveApi.GetDocuments(DocumentType type, Boolean includeFolders) in C:\Users\nlong\Desktop\projects\GoogleDrive\GoogleDrive\GoogleDriveApi.cs:line 105
     at GoogleDrive.Test.GoogleDriveTests.CanDeleteFile() in C:\Users\nlong\Desktop\projects\GoogleDrive\GoogleDrive.Test\GoogleDriveTests.cs:line 77
InnerException: System.Net.WebException
     Message=The operation has timed out
     Source=System
     StackTrace:
          at System.Net.HttpWebRequest.GetResponse()
          at Google.GData.Client.GDataRequest.Execute()
     InnerException:

another edit
It seems that I only crash after requesting the number of documents after the second upload. I'm not sure why that is, but I'm definitely going to look into my upload method.

A: If your tests pass when ran individually, but not when ran consecutively then you may be hitting a request rate limit.  I noticed in your comment to JotaBe's answer you mentioned were getting request timeout exceptions.  You should take a look at the http status code to figure out what to do.  In the case of a 503 you should implement exceptional back off.
Updated Suggestion
Place a try-catch around the line that is throwing the exception and catch the Google.GData.Client.GDataRequestException.  According to the source there are two properties that may be of value to you:
    /// <summary>
    /// this is the error message returned by the server
    /// </summary>
    public string ResponseString
    { ... }

and
    //////////////////////////////////////////////////////////////////////
    /// <summary>Read only accessor for response</summary>
    //////////////////////////////////////////////////////////////////////
    public WebResponse Response
    { ... }

Hopefully these contain some useful information for you, e.g., an HTTP Status Code.

A: You can explicitly set the time-outs for your unit tests. Here you have extensive information on it:

*

*How to: Set Time Limits for Running Tests
You can include Thread.Sleep(miliseconds) in your unit tests before the offending methods. Probably your requests are being rejected from google docs for being too may in too short a time.


text:
Q: Swagger defination, how to specify that a file is returned? I want to download a file from the server, and I define the swagger file as follows:

swagger: '2.0'

################################################################################
# API Information
################################################################################
info:
  version: v0
  title: XXX REST API

host: api.xxx.io
basePath: /v0

schemes:
  - http
  - https
produces:
  - application/json

################################################################################
# Security
################################################################################

################################################################################
# Parameters
################################################################################
parameters:
  productId:
    name: productId
    in: path
    description: The product identifier
    type: string
    required: true

################################################################################
# Paths
################################################################################
paths:
  /products:
    get:
      description: Get the list of products
      operationId: getProducts
      responses:
        200:
          description: OK
          schema:
            type: array
            items:
              $ref: '#/definitions/Product'

  /resources/{productId}:
    parameters:
      - $ref: '#/parameters/productId'
    get:
      description: Get resources of a product
      operationId: getResourcesByProductId
      produces:
        - application/octet-stream
      responses:
        200:
          description: OK
          schema:
            type: file

################################################################################
# Definitions
################################################################################
definitions:
  Product:
    type: object
    required:
      - id
    properties:
      id:
        type: string
      name:
        type: string
      category:
        type: array
        items:
          type: string
      description:
        type: string
      price:
        type: number
      thumbnailUri:
        type: string
      previewUris:
        type: array
        items:
          type: string
      resources:
        type: array
        items:
          $ref: '#ResourceMeta'

And the api is as follows:

@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-24T17:56:03.446+08:00")

@Controller
public class ResourcesApiController implements ResourcesApi {

    public ResponseEntity<File> getResourcesByProductId(
@ApiParam(value = "The product identifier",required=true ) @PathVariable("productId") String productId

) {
        // do some magic!
        return new ResponseEntity<File>(HttpStatus.OK);
    }

}

My controller is as follows:

@Controller
public class ResourceController implements ResourcesApi {

    private final Logger logger = Logger.getLogger(ResourceController.class);

//    @RequestMapping(value="/resources/{productId}", method= RequestMethod.GET)
    public ResponseEntity<File> getResourcesByProductId(@ApiParam(value = "The product identifier", required = true) @PathVariable("productId") String productId) {
        String path = "resources" + File.separator + productId;
        File file = new File(path);
        FileSystemResource fileSystemResource = new FileSystemResource(file);
        InputStreamResource inputStreamResource = null;
        try {
            inputStreamResource = new InputStreamResource(fileSystemResource.getInputStream());
        } catch (IOException e) {
            logger.error(e.toString());
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .body(file);
    }

}

However, when I run the application, it return a file but only contains the metadata of the file instead of its content. How can I make it return the file content? Thanks!

A: Use the InputStreamResource to return the file contents:
return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK);


text:
Q: Execute a Shell Command until Successful I am installing a list of Jenkins plugins that are listed in a file, using the Jenkins CLI.
However, some installations fail in the first attempt. Once re-tried the installation is successful.
How can I ensure the command that invokes the CLI is tried again?
while read line; do
  xargs java -jar jenkins-cli.jar -s https://127.0.0.1:8443/ -noCertificationCheck install-plugin $line
done < plugins.txt

A: For retries you can use until loop, like this:
while read line; do
  until java -jar jenkins-cli.jar -s https://127.0.0.1:8443/ -noCertificationCheck install-plugin $line
  do
    echo "retry installing $line"
    sleep 1
  done
done < plugins.txt


text:
Q: The puts() only prints the last element of the text file I have a text file full of text that i want to store in the form of strings in S
FILE *fp;

char str[200];

char **S = malloc( 200000*sizeof( char ) );

int i=0, j;

fp = fopen("S.txt" , "r");

while( fgets (str, 200, fp)!=NULL )
{
    S[i] = str;
    i++;
}

for(j=0;j<i;j++)
    puts(S[j]);

fclose(fp);

But the problem is that the program only prints the last string of the list. I think that maybe i allocated the memory wrong(the malloc( 200000*sizeof( char ) ) its becouse the file contains up to 1000 strings of up to 200 characters)

A: FILE *fp;

char str[200];

/* <<<ATTENTION, READ HERE>>>
 * Here, the allocation size is incorrect, one of two:
 * You should use malloc( 200000 * sizeof (char *)); as you are
 *     allocating the pointers in the array, not the space for
 *     the strings
 * You express (always safe) malloc( 200000 * sizeof *S ); This is
 *     a fake expression (not evaluated but to get the sizeof only)
 */
char **S = malloc( 200000 * sizeof *S );

int i=0, j;

fp = fopen("S.txt" , "r");

while( fgets (str, 200, fp)!=NULL )
{

    /* <<<ATTENTION, READ HERE>>>
     * the strdup(str); allocates memory (calling malloc itself)
     * and copies the contents of the string in the allocated memory.
    S[i] = strdup(str);
    i++;
}

for(j=0;j<i;j++)
    puts(S[j]);

fclose(fp);

With those two modifications your program will run safe (considering that you cannot allow files of more than 200000 lines of no more than 200 characters)
Your problem, not strdup()ing the string is that you finally made all strings point to the buffer, so the contents of the buffer after reading all the lines where the contents of the last line read.  As all pointers pointed to the same place, you got as many copies of the last line (at double space, as fgets() doesn't take the \n off the string, but puts() does add a \n after printing the string passed.
NOTE
read how to create a minimum, complete and verifiable example, as you can easily eliminate the error if you decide to post just a snippet of code.  Also, it makes more difficult for us to verify and check your error, or detect what is a typo from what is an error.
NOTE2
In case you want to return all the memory allocated by your program, you can do the following:
for(j = 0; j < i; j++)
    free(S[j]); /* each malloc made inside strdup() */
free(S); /* the malloc you did at the beginning */


text:
Q: ATL COM+ Using Interface As Parameter My project has two interfaces IObjectContext and IObjectFactory.
One way to use Interface as parameter is:
interface IObjectFactory: IDispatch{
    [id(1)] HRESULT create([in] IObjectContext* context);
}
...
STDMETHODIMP CObjectFactory::create(IObjectContext* context)
{
    CObjectContext *ctx= dynamic_cast<CObjectContext*>(context);

    if(ctx!=NULL)
       ...
}

If I'm not mistaken, I read somewhere that using interface as parameter can cause security problems. I do not remember where I read.
Is it really possible?
Can be Interface used as a parameter or not recommended?
Articles are welcome.

A: If you pass a pointer to an interface as a parameter, the callee will have a reference to the object implementing that interface, and is free to store the pointer and call QueryInterface to get a pointer to any other interface implemented by that object.
The security implication is that if you don't trust the callee not to do that, you want to pass a proxy object that enforces the security constraints you need (i.e. does not support QI for any extra interfaces, and has a "shutdown" method to revoke access).
In your code, you use dynamic_cast<> on an interface pointer.
This is generally a bad idea:

*

*There is no guarantee that even in the same process or thread, you will actually be passed the same object. Some debuggers enforce process separation between apartments, in order to catch illegal accesses.

*Your implementation should not need to know about the implementation of CObjectContext. If it does, that is a sign that IObjectContext is missing functionality.

*If you directly access methods in the concrete implementation rather than going through COM, you may confuse the internal housekeeping, ending up with handles that are invalid in a certain thread context. Debugging these is hard.


text:
Q: Module not found: Can't resolve 'react-leaflet' While trying to run some example code, I get a compilation error;
"Module not found: Can't resolve 'react-leaflet' in 'C:\Users...\my-app\src\map'"

I'm trying to do this with react and typescipt, and use "react-leaflet"
I've already tried installing both types@react-leaflet and react-leaflet
Here are my dependencies:
"dependencies": {
    "@types/jest": "24.0.15",
    "@types/leaflet": "^1.4.4",
    "@types/node": "12.0.8",
    "@types/react": "16.8.20",
    "@types/react-dom": "16.8.4",
    "@types/react-leaflet": "^2.2.1",
    "leaflet": "^1.5.1",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1",
    "save": "^2.4.0",
    "typescript": "3.5.2"
  }

A: You haven't added the react-leaflet dependency, only the types.
Run npm i react-leaflet to install the actual package.

A: npm i leaflet
Run this command also in terminal and it will work


text:
Q: Конвейер команд cmd с командами docker Команда docker ps -a -q возвращает список идентификаторов всех имеющихся контейнеров. Я хочу подать этот список на вход команде docker rm, удаляющей контейнеры, ID которых переданы на вход, чтобы удалить все контейнеры разом. Делаю так:
docker ps -a -q | docker rm
В результате получаю:

"docker rm" requires at least 1 argument. See 'docker rm --help'.
Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]
Remove one or more containers

И, естественно, ни один контейнер не удаляется.
Просьба объяснить, что я делаю не так.
Уточню: я знаю про способ из документации к Docker. Однако мне интересно, почему не работает именно такое перенаправление? Все источники говорят, что оно должно работать именно так, как я от него и ожидал.


text:
Q: node.js then() not working I am new to node.js so I am trying to understand promises and wait on node.js. I want to print the file note.txt.
Here is my code
    var fs = require('fs');

    fs.readFile('note.txt','utf8').then(contents => console.log(contents))
    .catch(err => console.error(err));

When I run above code. I get the following error.
fs.readFile('note.txt','utf8').then(contents => console.log(contents))

    TypeError: Cannot read property 'then' of undefined
        at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
        at Module._compile (module.js:635:30)
        at Object.Module._extensions..js (module.js:646:10)
        at Module.load (module.js:554:32)
        at tryModuleLoad (module.js:497:12)
        at Function.Module._load (module.js:489:3)
        at Function.Module.runMain (module.js:676:10)
        at startup (bootstrap_node.js:187:16)
        at bootstrap_node.js:608:3

And I try another method for the same thing.
var fs = require('fs');

async function  read_file(){
  var file_data = await  fs.readFile('note.txt','utf8');
    return file_data;

}
console.log(read_file());

And I get following error
Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

I get the same error when I run with --harmony. I m not sure if there is bug on my code or what is wrong. Please help me understand.
My Environment
Node version: v8.9.0
node -p process.versions.v8: 6.1.534.46

A: You're getting errors because fs.readfile doesn't return a promise; hence then doesn't exist. For you to use the function as a promise, you will need to wrap it up as a promise; you could use something like bluebird or Q.

A: Thank you for the answers. I learned that function must return promise in order to use then() and catch(). So the code should be like this
var fs = require('fs');

  function  read_file(){
    return new Promise(function(resolve, reject) {
         fs.readFile('note.txt','utf8',function(err,file){
            if(err){
                return reject(err);
            }else{
                resolve(file);
            }
        });
    });

}

read_file().then(
    (data)=>{
        console.log('success: '+data);
    }
).catch((err)=>{
    console.log('error: ',err);
});

A: If you use NodeJs v10, try fs.promises:
var fs = require('fs').promises; // v10.0 use require('fs/promises')

fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));

If not, use readFileSync:
// This code can use for node v10 or lowwer
var fs = require('fs');

var data = fs.readFileSync('a.json');
console.log(data);

A: try to use the async await
function (async  err => {
    if (err) {
       console.err ....}

    await .... <other function included or comes after then .>
    await ... <other function included>
})


text:
Q: Second order logic - what does it mean following formula $\phi$? $E$ is edge relation, however $inc(u, e)$ guarantees that $u$ is end of edge $e$. $V$ is set of verticles.
$$\phi = \exists_{C\subseteq E} span(C)$$
$$span(C) = \forall_{X\subseteq V} [\exists_{u\in V}\exists_{v\in V} (u\in X \wedge v\notin X) \to(\exists_{e\in C}\ \ inc(u,e) \wedge\ inc(v, e))]$$
For me, it guarantees that each node is end at least of one edge in subset of edges $C$.  But, then I don't undersatnd why it is so complicated, it was sufficient to say:  $span(C) = \forall_{v\in V} \exists_{e\in C}(inc(v,e))$

A: I think that formula is even simpler. In the inner existential quantifier we can set $v = u$ thus:
$$\mathtt{span}(C) = \forall_{X\subseteq V} [\exists_{u\in V} (u\in X \land u\notin X) \to(\text{whatever})]$$
that is, the precondition of the implication is false, and the whole is true as long as $V \neq \varnothing$. Thus $\mathtt{span}(C) \iff V \neq \varnothing$ (or just say it's always true because $V \neq \varnothing$ is a sane assumption).
What I think the autor meant is:
\begin{align}
\mathtt{span'}(C) = &\forall_{X\subseteq V} \Bigg(\\
  &\Big(\exists_{u\in V}\exists_{v\in V} (u\in X \land v\notin X)\Big) \to\\
  &\Big(\exists_{u\in V}\exists_{v\in V}\exists_{e \in C} \big(u\in X \land v\notin X\land \mathtt{inc}(u,e) \land \mathtt{inc}(v, e)\big)\Big)\Bigg)
\end{align}
That formula says a subset of edges $C$ satisfies property $\mathtt{span'}$ iff:

*

*$\forall X \subseteq V$ — for all partitions (one part is $X$ the other one is $V \setminus X$),

*$\exists u,v \in V.\ (u \in X \land v \in V \setminus X) \to \ldots$ — if that partition is not trivial, then...

*$\exists_{u\in V}\exists_{v\in V}\exists_{e \in C} \big(u\in X \land v\in V\setminus X\land \mathtt{inc}(u,e) \land \mathtt{inc}(v, e)\big)$ — there is an edge in $C$ that crosses that partition.

In other words, $\mathtt{span'}(C)$ iff for any non-trivial partition $C$ has an edge that (somehow) connects these parts. If a subset has this particular property, people usually say that it spans the graph.
That property is much more that what you suggest. Take graph $K_4$ and let $C = \{(1,2), (3,4)\}$, that is:
\begin{align}
&V = \{1,2,3,4\}, \\
&E = \big\{\{u,v\} \mid u,v \in V, u\neq v\big\}, \\
&\mathtt{inc}(v,e) \iff v \in e,\\
&C = \big\{\{1,2\}, \{3,4\}\big\}.
\end{align}
It satisfies your property because
\begin{align}
&\mathtt{inc}\big(1,\{1,2\}\big) \\
&\mathtt{inc}\big(2,\{1,2\}\big) \\
&\mathtt{inc}\big(3,\{3,4\}\big) \\
&\mathtt{inc}\big(4,\{3,4\}\big) \\
\end{align}
but it does not satisfy $\mathtt{span'}$. Consider $X = \{1,2\}$. Then we can satisfy $\exists_{u\in V}\exists_{v\in V} (u\in X \land v\notin X)$ with $u = 1$ and $v = 3$, but there are no $u$ and $v$ that would make $$\exists_{u\in V}\exists_{v\in V}\exists_{e \in C} \big(u\in X \land v\notin X\land \mathtt{inc}(u,e) \land \mathtt{inc}(v, e)\big)$$ true.
I hope this helps $\ddot\smile$


text:
Q: To get nearest li class name on click of anchor tag element using jquery How to get the li class name on click of anchor tag

A: You can get parent li using jquery parent method and its class name by attr method.


text:
Q: How to open a file in Android via an Intent how can I open a file that has been previously stored in the "privat" filesystem? The file is being downloaded by a webservice and should be stored on local fs.
I got a "strange" error when trying to open the file via an Intent (Action_View). Although the file is present in the filesystem (saw the file in the file explorer in emulator/eclipse) it won't be shown in the calling galery activity that is launched. Instead of the picture the galery shows a black screen with not content in there (except the action bar). The same occurs when trying to open a pdf/movie/mp3 file via this method (pdf says for example that the file is corrupt).
BTW: The data that has been stored on the local fs is valid (not corrupt), I downloaded the files from debugger (via pull method) and the files can be opened on my workstation...
public void onAttachment(Context context, Attachment attachment) {
    try {
        //Attachment is a structured data object that contains of a byte[], filename and mimetype (like image/jpeg)
        FileOutputStream fos = FileOutputStream fos = context.openFileOutput(attachment.getAttachmentFileName(), Context.MODE_PRIVATE);
        fos.write(attachment.getBinary());
        fos.flush();
        fos.close();
        File f = context.getFileStreamPath(attachment.getAttachmentFileName());
        Uri uri = Uri.fromFile(f);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri,attachment.getAttachmentMimetype());
        context.startActivity(intent);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: You cannot open files that are not on the sdcard like that.
You'll need to copy the file to the sdcard and then opening it.

A: When setting the location to "openFileOutput("fileName", Activity.MODE_WORLD_READABLE)" it will work. Other apps cannot read the data (even for viewing) stored when setting to "Context.MODE_PRIVATE"
see other post on stackoverflow

A: What is the type of the Attachment in your code? Perhaps it returns wrong mime type?
This code works for me:
File file = new File("EXAMPLE.JPG");

// Just example, you should parse file name for extension
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".JPG");

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), mime);
startActivityForResult(intent, 10);


text:
Q: Permission denied (Errno 13) - wandb init - In docker container I am running a docker container on a cluster where I try to run an open source code : https://github.com/xinntao/BasicSR.  However I encounter the following error:
As I can see it's the package wandb that creates the error when initialized.
Traceback (most recent call last):
  File "/home/GAN/BasicSR-master/basicsr/train.py", line 251, in <module>
    main()
  File "/home/GAN/BasicSR-master/basicsr/train.py", line 152, in main
    logger, tb_logger = init_loggers(opt)
  File "/home/GAN/BasicSR-master/basicsr/train.py", line 72, in init_loggers
    init_wandb_logger(opt)
  File "/home/GAN/BasicSR-master/basicsr/utils/dist_util.py", line 81, in wrapper
    return func(*args, **kwargs)
  File "/home/GAN/BasicSR-master/basicsr/utils/logger.py", line 89, in init_wandb_logger
    import wandb
  File "/usr/local/lib/python3.9/site-packages/wandb/__init__.py", line 131, in <module>
    api = InternalApi()
  File "/usr/local/lib/python3.9/site-packages/wandb/apis/internal.py", line 17, in __init__
    self.api = InternalApi(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/wandb/sdk/internal/internal_api.py", line 73, in __init__
    self._settings = Settings(
  File "/usr/local/lib/python3.9/site-packages/wandb/old/settings.py", line 25, in __init__
    self._global_settings.read([Settings._global_path()])
  File "/usr/local/lib/python3.9/site-packages/wandb/old/settings.py", line 105, in _global_path
    util.mkdir_exists_ok(config_dir)
  File "/usr/local/lib/python3.9/site-packages/wandb/util.py", line 687, in mkdir_exists_ok
    os.makedirs(path)
  File "/usr/local/lib/python3.9/os.py", line 215, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/local/lib/python3.9/os.py", line 225, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/.config'

I tried to add a user in my Dockerfile but have the same error.
My Dockerfile:
FROM python:3

COPY requirements.txt /tmp/
RUN apt-get update
RUN apt-get install ffmpeg libsm6 libxext6 -y
RUN pip install pip --upgrade pip
RUN pip install imageio
RUN pip install matplotlib
RUN pip install numpy
RUN pip install opencv-python
RUN pip install pandas
RUN pip install Pillow
RUN pip install scipy
RUN pip install wandb
RUN pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
RUN pip install --requirement /tmp/requirements.txt

RUN useradd -ms /bin/bash admin
USER admin

ENV PYTHONPATH "${PYTHONPATH}:/home/GAN"

WORKDIR /home/
CMD /bin/bash

A: For the pip install wandb part, change it to:
pip install wandb --user


text:
Q: Why is apt no longer updating the kernel? Somehow I got a 12.04 server to stop updating the kernel.  It's stuck at 3.2.0-24-generic and doesn't want to fetch any new updates.  The new kernel at the moment is 3.2.0-29
apt-get clean && sudo apt-get autoremove
apt-get -f install
apt-get update
apt-get dist-upgrade

Shows "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded."  There were no failed installs.  /var/log/aptitude doesn't show any errors
My sources.list:
###### Ubuntu Main Repos
deb http://ca.archive.ubuntu.com/ubuntu/ precise main restricted
deb-src http://ca.archive.ubuntu.com/ubuntu/ precise main restricted

###### Ubuntu Update Repos
deb http://ca.archive.ubuntu.com/ubuntu/ precise-security main restricted
deb http://ca.archive.ubuntu.com/ubuntu/ precise-updates main restricted
deb-src http://ca.archive.ubuntu.com/ubuntu/ precise-security main restricted
deb-src http://ca.archive.ubuntu.com/ubuntu/ precise-updates main restricted

###### Ubuntu Partner Repo
deb http://archive.canonical.com/ubuntu precise partner
deb-src http://archive.canonical.com/ubuntu precise partner

Anyone know what's wrong?
Thanks

A: You have probably removed linux metapackage by accident. If so, that should be fixed by:
sudo apt-get install linux

Further explanation:
Because of technical reasons it's not wise for the kernels to be upgraded and replaced with the new one (i.e. let's say if the new one fails you may still boot into the old one).
Thus they are packaged under the names like linux-image-3.2.0-24-generic.
So, if you upgrade the system, technically there is no update to this version! Unless you install the linux metapackage which always depends on the latest kernel, meaning that whenever an update to the kernel is available, linux will change version, and it will depend on the newer kernel, and thus the new kernel will be automatically installed.
Remember that your older kernel won't be removed this way, which is a good thing. If you find anything odd you may boot into the old one (grub -> Previous versions or something like that) and remove the new kernel.


text:
Q: IsPointInsideSegment(pt, line) in Python Is there a nice way to determine if a point lies within a 3D line segment?
I know there are algorithms that determine the distance between a point and line segment, but I'm wondering if there's something more compact or efficient.

A: Given three points A, B, and C -- where AB is your line and C is your other point, you can also restate your problem as two lines, AB and AC.  If the angle between AB and AC is zero (i.e. if the area of the triangle ABC is zero) then your point C is on the line.
If you think about this in terms of angles, you can use the dot product of the two vectors (AB and AC) to find the angle between them.  Some quick googling turns up a couple of useful links:

*

*http://knol.google.com/k/koen-samyn/dot-product-cross-product-in-3d/2lijysgth48w1/10#

*http://www.jtaylor1142001.net/calcjat/Solutions/VDotProduct/VDPTheta3D.htm
The bonus of this method is that it's easy to define tolerances in terms of angles; e.g. you may want to consider any point that falls within 5 degrees of the line to be "on the line" even though there is strictly some distance between the line and the point.  Depending on your application, this may be more useful than an actual linear measurement.

A: One way to restate your question is to ask of the point is a solution to the equation which contains the line segment in question, and (if so) if it lies between the end points of the segment.
Since you don't describe the details of how you're representing your line segments and don't mention any modules or libraries that you're using I guess you'd have to code up the algebra yourself.  (It's not trivial and my algebra is too rusty in any event).
You might consider looking at a library that does the work for you (either to incorporate into your project or to study its code).  In this case I'd take a close look at:

*

*[PyEuclid]: http://code.google.com/p/pyeuclid/
... claims to be compatible with PyGame and supports objects for 2D and 3D vectors, rays, segments, and circles/spheres.  Basically if the distance between your point and your segment is less than epsilon (some threshold appropriate to your calculations) then you treat that as an intersection.
(Although it doesn't explicitly say so in the docs that I read, I'm guessing that they must handle floating point rounding issues in their code somewhere.  All of PyEuclid seems to be in a single 2200+ line .py file).

A: First, find the distance from the point to the line.  If the distance from the point to the line is zero, then it's on the line.


text:
Q: Glassfish v3 servlet container I'm wondering what is the servlet container in Glassfish. In some sources I saw that Glassfish uses something like Grizzly, but Grizzly is a web framework:

The Grizzly NIO and Web framework has been designed to help developers to take advantage of the Java™ NIO API. Grizzly's goal is to help developers to build scalable and robust servers using NIO and we are also offering extended framework components: Web Framework (HTTP/S), Bayeux Protocol, Servlet, HttpService OSGi and Comet.

What does it mean? Does Glassfish use Grizzly as web container. Or maybe Tomcat, and Grizzly as  an extension?

A: Grizzly is the HTTP connector. Glassfish uses a fork of Tomcat's engine (Catalina) as servlet container. An easy evidence is checking the stacktrace when some exception occurs in your business code. You'll see org.apache.catalina.* deep down in the trace, between the com.sun.grizzly.* lines and the lines of your own business code. It typically look like this:
...
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:680)

Glassfish is not the only which uses Catalina by the way, JBoss AS and IBM WebSphere also use it.


text:
Q: linear two-equation system, two variables to second derivative in both Forgive me if this is considered reposting, but I've been advised I might have given a bad format.
I'm trying to solve the two linear, second order differential equations. I want to break them into single order equations, but I can't see how as both variables have second order derivatives in both problems.
(m*a)u" + (I + m*a^2 )θ" + (d*a^2 )θ' + (K - m*g*a)θ = 0

(M + m)u" + (m*a)θ" = -F

I've gone to some lengths with both dsolve and ode45
This is my dsolve code:
M =70-5.876;
m =5.876;
a =(((0.05)^2)+((0.13^2))^0.5);
IG = 0.0233;
d = 500;
k = 500;
g = 9.81;
f = 628;

%y is u, x is theta

syms M m a IG d k g y(t) x(t)
Dy = diff(y);
Dx = diff(x);

eqn1 = (M+m)*diff(y,2) + M*diff(x,2) == -f;

eqn2 = m*a*diff(y,2) + (IG + m*a*a)*diff(x,2) + (d*a*a)*diff(x) + (k - m*g*a)*x == 0;

t=0:0.01:10;

z = dsolve(eqn1,eqn2, y(0)==0, Dy(0)==0, x(0)==0, Dx(0)==0, 't');

z.x
z.y

It does give me very, very long equations that I can't seem to plot with respect to time and I don't know why. If anyone can advise me I'd be very grateful. Thanks for looking!

A: In this case u" can be replaced out of the general equation with simple algebraic manipulation. The resulting equation will be of the order:
Eq1: K1*θ" + K2*θ' + K3*θ = -F
u can be solved directly with the solution of Eq1. Try to avoid placing u in the equation. If you must, you'll need to rewrite the equations so as to solve with the third differential of θ.


text:
Q: Is my program CPU bound or IO bound when dealing with subprocesses? Using Python, I am trying to figure out if I should use multiprocessing, threading, or asyncio, and the first step is to figure out if my program is CPU bound or IO bound.
The slowest part of my code is interacting with a subprocess that was created prior to the asyncronous programming. The relevant code is as follows:
    # First curl command to existing JS console running on my machine
    curl_command = <curl command here>
    cmd = shlex.split(curl_command)
    subprocess.Popen(cmd, stderr=subprocess.DEVNULL)

    # Different curl command
    self.other_command = self._other_curl_command()

    # Interact with an existing JS console running on my machine
    output_one = call_one()
    output_two = call_two()
    output_three = call_three()

It is important to note that these calls are to a JS console I have running on my machine. Are these I/O bound activities? If so, should I be using threading/asyncio?


text:
Q: Connection string for SAS token in Azure event hub python I am pretty new to event hub
https://learn.microsoft.com/en-us/azure/event-hubs/get-started-python-send-v2
based on the above link I am trying to implement a publisher for event hub.
Unfortunately the connection string is formed with Shared Access Key and not SAS (Shared Access Signature) as shown below
Endpoint=sb:///;SharedAccessKeyName=;SharedAccessKey=
I am unable to find a source that uses SAS token instead of the key.
Is this supported in the library or is there any other way to achieve this
Thanks!

A: Currently there is no support for SharedAccessSignature token. At the moment, this feature is discussed at https://github.com/Azure/azure-sdk/issues/1701#issuecomment-675855269


text:
Q: How to change javascript in woocommerce on add to cart? I've been trying to develop a theme/plugin in woocommerce and I've spend hours researching how to edit the hook / JS for notices in regards to products.
Ultimately I would like to remove the default notice and stop it from scrolling up to the top of the page. Instead, I would like the notice to show up with position:absolute near the top of the page.

In the image above I have added JS to my products listing page. Here is the code I have created for it. This works fine, but it is me making my own div rather than using woocommerces ajax built in notice. (I believe I should be using the notices as it's an important feature on woocommerce)
$('.atc').click(function(e){
    var productAdded = $(this).attr('aria-label');
    var productNumber = $(this).attr('data-product_id');
    var fixedPlacement = 'top';
    var bannerID = "cart-notice-" + productNumber;
    if($(window).width() <= 768) {
        fixedPlacement = 'bottom';
    }
    var addToCartButton = '

';
    addToCartButton += '

' + productAdded + '

';
    addToCartButton += '
View Cart
';
    addToCartButton += '

';
    var currentItemHeight = $(this).scrollTop();
    console.log(currentItemHeight);
    if($('#' + bannerID).length) {
        $('#' + bannerID).remove();
    }
    $('body').append(addToCartButton);

    //determine if mobile or desktop
    if($(window).width() <= 768) {
        console.log('mobile');
        $('#' + bannerID).css("bottom", 0);

    }
    else {
        //DESKTOP
        var windowHeight = $(window).scrollTop();
        if(windowHeight < 143) {
            windowHeight = 150 - windowHeight;
        } else {
            windowHeight = 10;
        }
        $('#cart-notice-' + productNumber).css("top", windowHeight);
    }
    $('#' + bannerID).delay(4000).fadeOut(800);
    e.preventDefault();

});

When looking into the code, I noticed the notice is loaded via do_action( 'woocommerce_before_cart' ); ?>  on the cart page. I am thinking wc_get_notices() hook is tied somewhere in there too. Additionally I have went deeper and brought in the add-to-cart.js into my theme using this in my functions.php
wp_deregister_script('wc-add-to-cart');
wp_register_script('wc-add-to-cart', get_template_directory_uri(). '/js/add-to-cart.js' , array( 'jquery' ), WC_VERSION, TRUE);
wp_enqueue_script('wc-add-to-cart');

The javascript file is now editable but I didn't find the notices in it, I know which hooks make my notices appear, but still have no idea how to change them. Any ideas how to customize the notices?
Update 1
I have used the updated_cart_totals event handler and intercepted it to be able to customize how it displays. However, for some reason my remove cart isn't working. It always refreshes the page. Below is the JS code to make it work on the cart page.
 $(document.body).on('updated_cart_totals, removed_from_cart',function(event){
                display_alert('.woocommerce-notices-wrapper');
                event.preventDefault();

            });
            function display_alert(alert_handle) {
                var fixedPlacement = 'top';
                if($(window).width() <= 768) {
                    fixedPlacement = 'bottom';
                }
                fixedPlacement = 'fixed-' + fixedPlacement;
                //determine if mobile or desktop
                if($(window).width() <= 768) {
                    console.log('mobile');
                    $(alert_handle).css("bottom", 0);

                }
                else {
                    //DESKTOP
                    var windowHeight = $(window).scrollTop();
                    if(windowHeight < 143) {
                        windowHeight = 150 - windowHeight;
                    } else {
                        windowHeight = 10;
                    }
                    $(alert_handle).addClass('position-fixed ' + fixedPlacement + ' container alert-primary p-3 add-to-cart-banner');
                    $(alert_handle).css("top", windowHeight);

                }
                $(alert_handle).show();
                $(alert_handle).delay(4000).fadeOut(800);
            }

A: I couldn't find a best way, as I tried really hard to instead of masking the code, to rebuild it, but I couldn't find any documentation on it. So I used woocommerce built in listeners to wait for certain actions (in this case updated_cart_totals) after this ajax function is triggered it then passes .woocommerce-notices-wrapper into my display_alert function which adds classes and CSS depending on the size of screen. The last problem I had was the scrolling up after updates, as I wanted that disabled. I used this code -
            $( document.body ).on( 'checkout_error', function() {
                $( 'html, body' ).stop();
            } );
            $( document ).ajaxComplete( function() {
                if ( $( 'body' ).hasClass( 'woocommerce-checkout' ) || jQuery( 'body' ).hasClass( 'woocommerce-cart' ) ) {
                    $( 'html, body' ).stop();
                }
            } );

Here is the full code I have created to solve this problem. but I am open to a cleaner way...
            $(document.body).on('updated_cart_totals',function(event){
                display_alert('.woocommerce-notices-wrapper');
                event.preventDefault();
            });
            function display_alert(alert_handle) {
                var fixedPlacement = 'top';
                //determine if mobile or desktop
                if($(window).width() <= 768) {
                    fixedPlacement = 'bottom';
                    console.log('mobile');
                    $(alert_handle).css("bottom", 0);
                }
                else {
                    //DESKTOP
                    var windowHeight = $(window).scrollTop();
                    if(windowHeight < 143) {
                        windowHeight = 150 - windowHeight;
                    } else {
                        windowHeight = 10;
                    }
                    $(alert_handle).css("top", windowHeight);

                }

                fixedPlacement = 'fixed-' + fixedPlacement;
                $(alert_handle).removeClass('position-fixed  fixed-top fixed-bottom container alert-primary p-3 add-to-cart-banner');

                $(alert_handle).addClass('position-fixed ' + fixedPlacement + ' container alert-primary p-3 add-to-cart-banner');

                $(alert_handle).show();
                $(alert_handle).delay(4000).fadeOut(800);
            }
            $( document.body ).on( 'checkout_error', function() {
                $( 'html, body' ).stop();
            } );
            $( document ).ajaxComplete( function() {
                if ( $( 'body' ).hasClass( 'woocommerce-checkout' ) || jQuery( 'body' ).hasClass( 'woocommerce-cart' ) ) {
                    $( 'html, body' ).stop();
                }
            } );


text:
Q: What jQuery event type is it when Ajax inserts data into an input field? I have an input field where the user enters an id#. I am using Ajax to check the database for that user's id# and afterwards populate the other input fields with that person's information from the database.
I am trying to run a series of validation statements after the information is inserted via Ajax into the input fields, but I can't figure out which event I need to use.
I am trying to do something like this:
$(.formfields).dataInserted(function() {
    if(costCenter == '') {
        $("#cost_center").after('
Your cost center number is required.
');
        hasError = true;
    }
}

I can't use keyup or change or anything like that, since there the user doesn't actually manually enter the data. What jQuery event type is it when Ajax inserts data into an input field?

A:
What jQuery event type is it when Ajax inserts data into an input field?

No event. Changing content from script does not fire any events(*). You must wire up your scripts to call you back when they've made a change.
If you really can't do that, you will need a poller interval to continually check the input for updates.
*: mostly. There are browser-specific hooks that you can use in some situations, but it's unpleasant and almost certainly better to fix the scripts to call you back instead. See this question for some discussion.


text:
Q: Sum over previous periods for each period for each subject - R A MWE is as follows:
library(dplyr)

Period <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)

Subject <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)

set.seed(1)
Values <- round(rnorm(n=9,mean=5,sd=1), digits = 2)

df <- bind_cols(Period = Period, Subject = Subject, Values = Values)
df
# A tibble: 9 x 3
  Period Subject Values
   <dbl>   <dbl>  <dbl>
1      1       1   4.37
2      1       2   5.18
3      1       3   4.16
4      2       1   6.6
5      2       2   5.33
6      2       3   4.18
7      3       1   5.49
8      3       2   5.74
9      3       3   5.58

I would like to have a variable sum_values that sums up all the previous values for each subject in each period. For example, for subject 1 in period 2, sum_values = 4.37, and it will be 4.37+6.6 = 10.97 in period 3.
I can do it with a for loop which would be very tedious that involves many if-else statements, but I believe that there's an easy way out in R. How can I achieve my purpose easier in R?

A: You may also use data.table to get this done.
library(data.table)

Period <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
Subject <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)
set.seed(1)
Values <- round(rnorm(n=9,mean=5,sd=1), digits = 2)

# create data.table
dt <- data.table(Period = Period, Subject = Subject, Values = Values)
# create cumsum by Subject
dt[,sum_values := shift(cumsum(Values),n = 1, fill = 0), by = Subject]

dt
#>    Period Subject Values sum_values
#> 1:      1       1   4.37       0.00
#> 2:      1       2   5.18       0.00
#> 3:      1       3   4.16       0.00
#> 4:      2       1   6.60       4.37
#> 5:      2       2   5.33       5.18
#> 6:      2       3   4.18       4.16
#> 7:      3       1   5.49      10.97
#> 8:      3       2   5.74      10.51
#> 9:      3       3   5.58       8.34

A: Arrange the data by Period and use cumsum to get cumulative sum of Values. Since you want to sum all the previous Values use lag.
library(dplyr)

df %>%
  arrange(Subject, Period) %>%
  group_by(Subject) %>%
  mutate(Values = lag(cumsum(Values), default = 0)) %>%
  ungroup

#  Period Subject Values
#1      1       1   0.00
#2      2       1   4.37
#3      3       1  10.97
#4      1       2   0.00
#5      2       2   5.18
#6      3       2  10.51
#7      1       3   0.00
#8      2       3   4.16
#9      3       3   8.34


text:
Q: android studio launch error: Missing MSCVR100.dll I am using Win 7 x64, I have installed Java SDK and Android Studio (both 64bit versions).
When I try to launch Android studio, I receive the error message:
    The program can't start because MSCVCR100.dll is missing from your computer....
I have run the Microsoft Visual C++ 2010 Redistributable Package (x64) but it hasn't fixed it.

A: I had the same problem, download the appropiate file for your version of Windows and just install it:

*

*Microsoft Visual C++ 2010 Redistributable Package (x86)

*Microsoft Visual C++ 2010 Redistributable Package (x64)


text:
Q: iOS 14: call controls not displayed in lock screen Seems like I'm missing something obvious but can't seem to find an answer.
Before upgrading to iOS 14, 3rd party apps like Teams would show call controls like mute, hang up etc, on the Lock Screen, while in a call. Now it seems the best I can do is click the green bar, unlock the phone, find the call controls I want inside the app somewhere.
I've tried changing the Incoming Calls setting to full screen, swiping every which way on the Lock Screen, no luck.
It looks like people have asked similar questions in the past when the call controls screen behavior changed in previous iOS releases...
iPhone SE 2020 with iOS 14

A: I found perfectly working WORKAROUND:
During Microsoft Teams meeting, just go to home screen, start dialing any number via built-in Phone app and stop even after 1 second. Your Teams meeting won't dissconnect, it will just pause. After that, when You go back to Teams and lock the screen, call controls will appear every time! Simple as that!!!
Of course You have to repeat those steps on every new Teams meeting.
I hope you find this guide useful.

A: I am seeing this issue with calls on third party apps, but the lock screen controls show for the native phone app. I haven't tried FaceTime audio or other Apple apps. It's possible that the third party apps need to be updated for iOS 14.

A: Having the same issue on my iPhone 11 but noticed something today - if I'm just on with 1 person (ie: someone calls me via Teams) and I lock my screen it does seem to show up as a phone call in the lock screen (as it used to). My sample size is 1 here as I haven't had a chance to try it again but it could just be an app issue as others have pointed out if it's somehow classifying "group" calls as something different in the new OS?


text:
Q: Testing a pirobox (lightbox like) modal with Watir I'm writing tests for www.offdesk.com and when "sign up" anchor is clicked, it opens a pirobox modal window, at this point my irb works fine but I can't set text into the inputtexts inside it.
I wrote:
browser.link(:id, 'lkNovaConta').click()
browser.text_field(:id, "usuario_nome").wait_until_present
browser.text_field(:id, "usuario_nome").set("Test user")

but never passes the until_present, so as I have a JS var with the html content, I thought I had an index probelm, so I tryed:
browser.link(:id, 'lkNovaConta').click()
browser.text_field(:id => "usuario_nome", :index => 1).wait_until_present
browser.text_field(:id => "usuario_nome", :index => 1).set("Test user")

also tryed with index = 2, index = 0... but all have failed
Do you have any idea how to test it or any suggest to make this feature testable?

A: This worked for me:
$ ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin10.8.0]

$ gem list watir
*** LOCAL GEMS ***
watir-webdriver (0.3.9)

$ irb

> require "watir-webdriver"
 => true

> browser = Watir::Browser.new
 => #<Watir::Browser:0x91f4b0ffb95e486 url="about:blank" title="">

> browser.goto "http://www.offdesk.com/"
 => "http://www.offdesk.com/"

> browser.a(:id => "lkNovaConta").click
 => []

> browser.text_field(:id => "usuario_nome").set "test"
Selenium::WebDriver::Error::ElementNotVisibleError: Element is not currently visible and so may not be interacted with
(...)

> browser.text_field(:id => "usuario_nome", :index => 1).set "test"
 => ""


text:
Q: How join two table or writing custom queries in Datatable php? I am using datatable to list data as server side scripting.
    // DB table to use
$table = 'enquiry';

// Table's primary key
$primaryKey = 'enquiry_id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array(
        'db' => 'enquiry_date',
        'dt' => 0,
        'formatter' => function( $d, $row ) {
            return date('jS M y', strtotime($d));
        }
    ),
    array('db' => 'parent_name', 'dt' => 1),
    array('db' => 'child_name', 'dt' => 2),
    array('db' => 'mobile', 'dt' => 3),
    array('db' => 'emirate', 'dt' => 4),
    array('db' => 'remarks', 'dt' => 5),
    array('db' => 'enquiry_status_id', 'dt' => 6),
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db' => 'lsn',
    'host' => ''
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( './server_side/scripts/ssp.class.php' );

echo json_encode(
        SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns)
);

This is my php server side scripting and working very fine for single table.
I want to join two table while listing table row. But I couldn't find any option for joining tables or writing custom queries.
how can I join table if it is possible?

A: here two table keyid same field and other field fetch
$sql_t="SELECT tabkey.keyid, table1.value, table2.value
FROM
(SELECT table1.keyid FROM table1
UNION
SELECT table2.keyid FROM table2) as tabkey
LEFT JOIN
table1 on tabkey.keyid = table1.keyid
LEFT JOIN
table2 on tabkey.keyid = table2.keyid;";

A: Step 1: open ssp.class.php
Step 2: locate this line.....               FROM '$table'
Step 3: remove single quotation....             FROM $table
Step 4: do the same to the other one .....       FROM   '$table' "
                                     FROM    $table"

Step 5: you can now add subquery to $table
example   $table="(select * from my_list join...)";
Step 6: Celebrate =)


text:
Q: insert and delete columns from a button I have a problem since 2 weeks with my JTable: I created a table with three buttons: "Insert new column", "delete new colunm", "add new column"; I managed to add lines but I can not insert or remove a column. Can you help me?

A: This is much easier if you extend a AbstractTableModel and use that to display your data. You can make an ArrayList of your data and add/remove from that. The TableModel will update the Table automatically when the ArrayList is changed. The ArrayList contains a class which has all the data that you would have in a row. See the Java Tutorials example from Oracle: http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableDemoProject/src/components/TableDemo.java
For custom cells, you can detect from the TableModel which column the cell is in and update its content accordingly.