text:
Q: Email from Stack Exchange with a Python file attached I received an email from Stack Exchange with a Python file attached, and it seemed suspicious. I thought y'all would want to take a look.
email:
From: "Stack Exchange" <do-not-reply@stackexchange.com>
To: me Reply-To: do-not-reply@stackexchange.com
Subject: New questions in python filter for Aug 23 - Stack Exchange
Date: Thu, 23 Aug 2018 19:06:27 +0000
Content-Type: multipart/alternative;    boundary="----=_NextPart_000_1CCE_64CE4764.45758CD0"

------=_NextPart_000_1CCE_64CE4764.45758CD0 Content-Type: text/plain;   charset="UTF-8" Content-Transfer-Encoding: quoted-printable

***11 new questions in [python filter](<https://stackexchange.com/filters/1= 38574/python>) on stackexchange.com***

[AttributeError: 'str' object has no attribute 'export'](<https://stackover= flow.com/questions/51992674/attributeerror-str-object-has-no-attribute-expo= rt>)

from pydub import AudioSegment from pydub.silence import split_on_silence s= ound_file =3D AudioSegment.from_wav("file1.wav") audio_chunks =3D split_on_= silence(sound_file, # must be silent for at ...

Tagged: python-3.x

by [Allen](<https://stackoverflow.com/users/10266032/allen>) on <https://st= ackoverflow.com>

----------------------------

[Passing list to pool.map() function in Python returns each character for e= ach item in the list](<https://stackoverflow.com/questions/51992644/passing=
-list-to-pool-map-function-in-python-returns-each-character-for-each-it>)

This Python 2.7 script running on Windows is not outputting as I would expe= ct it to. from multiprocessing import Pool from multiprocessing.dummy impor= t Pool as ThreadPool def function1(): ...

Tagged: python

by [olaHalo](<https://stackoverflow.com/users/9976152/olahalo>) on <https:/= /stackoverflow.com>

----------------------------

[Calculating age of live person vs dead person](<https://stackoverflow.com/= questions/51992641/calculating-age-of-live-person-vs-dead-person>)

So, I've got a pandas dataframe that is the result of a MySQL query that se= arches for a person's name and then returns some information about them. On= e such piece of info is their age. The table ...

Tagged: python-3.x

by [adrysdale](<https://stackoverflow.com/users/10211367/adrysdale>) on <ht= tps://stackoverflow.com>

----------------------------

[Python ABC classes: One of multiple methods has to be overridden](<https:/= /stackoverflow.com/questions/51992631/python-abc-classes-one-of-multiple-me= thods-has-to-be-overridden>)

In Python, I have an abstract base class which has four methods, of which a= t least one has to be overridden. Is it possible to somehow implement this = with the @abstractmethod decorator or something ...

Tagged: python

by [MosteM](<https://stackoverflow.com/users/2609994/mostem>) on <https://s= tackoverflow.com>

----------------------------

[If dataframe length exceeds threshold, make a new row python](<https://sta= ckoverflow.com/questions/51992596/if-dataframe-length-exceeds-threshold-mak= e-a-new-row-python>)

I have a data frame with columns a,b,c,d a b c d 1 2 nan nan 2 3 4 5 4 5 na= n nan how do i reshape into 2 columns, when i am not aware of the number of=  rows that the result will give. (big data) ...

Tagged: python

by [aakash T.C.](<https://stackoverflow.com/users/4411700/aakash-t-c>) on <= https://stackoverflow.com>

----------------------------

[backward series in python where every next term is (prev1*prev2+prev3)](<h= ttps://stackoverflow.com/questions/51992569/backward-series-in-python-where=
-every-next-term-is-prev1prev2prev3>)

Please help to write pytnon code. The series goes like ....previous3, previ= ous2, previous1 Nth terms. And every next term is (previous1*previous2+prev= ious3). I have tried this n =3D int(input('Give ...

Tagged: python-3.x

by [hanifsm](<https://stackoverflow.com/users/10261288/hanifsm>) on <https:= //stackoverflow.com>

----------------------------

[Python - Sharing variables between different instances of different classe= s](<https://stackoverflow.com/questions/51992554/python-sharing-variables-b= etween-different-instances-of-different-classes>)

I have been searching for the next answer but for sure I have been searchin= g the wrong keywords. I used to develop with C++, passing pointers as refer= ences between objects. The case is, now I'm trying ...

Tagged: python

by [Cristo](<https://stackoverflow.com/users/10266397/cristo>) on <https://= stackoverflow.com>

----------------------------

[Automatic dictionary key resolution with nested schemas using Marshmallow]= (<https://stackoverflow.com/questions/51992551/automatic-dictionary-key-res= olution-with-nested-schemas-using-marshmallow>)

When using nested schemas in Marshmallow it is sometimes desirable to seria= lize objects using that are defined in a dictionary in another structure an= d to have the key automatically resolved when ...

Tagged: python

by [cdiggins](<https://stackoverflow.com/users/184528/cdiggins>) on <https:= //stackoverflow.com>

----------------------------

[Python Chirp.io app not responding to "chirps"](<https://stackoverflow.com= /questions/51992539/python-chirp-io-app-not-responding-to-chirps>)

I'm trying to build a chirp app that would just take a chirp and print the = data. I'm running the python app in my terminal and am able to send/ emit a=  chirp but am not getting any indication that my ...

Tagged: python

by [Jaylan](<https://stackoverflow.com/users/10266404/jaylan>) on <https://= stackoverflow.com>

----------------------------

[=D0=9E=D1=88=D0=B8=D0=B1=D0=BA=D0=B0 =D0=B2 =D0=BA=D0=BE=D0=B4=D0=B5
=D0=
=B4=D0=B5=D0=BB=D0=B0=D0=B5=D1=82 =D0=B8=D0=B7 =D0=BE=D0=B1=D1=8B=D1=87=D0=
=BD=D0=BE=D0=B3=D0=BE =D0=B1=D0=BE=D1=82=D0=B0 =D0=92=D0=9A =D1=84=D0=BB=D1=
=83=D0=B4=D0=B5=D1=80=D0=B0](<https://ru.stackoverflow.com/questions/872704= /%d0%9e%d1%88%d0%b8%d0%b1%d0%ba%d0%b0-%d0%b2-%d0%ba%d0%be%d0%b4%d0%b5-%d0%b= 4%d0%b5%d0%bb%d0%b0%d0%b5%d1%82-%d0%b8%d0%b7-%d0%be%d0%b1%d1%8b%d1%87%d0%bd= %d0%be%d0%b3%d0%be-%d0%b1%d0%be%d1%82%d0%b0-%d0%92%d0%9a-%d1%84%d0%bb%d1%83= %d0%b4%d0%b5%d1%80%d0%b0>)

=D0=9F=D1=80=D0=B8 =D0=BF=D0=BE=D0=BB=D1=83=D1=87=D0=B5=D0=BD=D0=B8=D0=B8 u= pdates =D0=B1=D0=BE=D1=82 =D0=BD=D0=B0=D1=87=D0=B8=D0=BD=D0=B0=D0=B5=D1=82 =
=D1=81=D0=BB=D0=B0=D1=82=D1=8C =D0=BE=D0=B4=D0=B8=D0=BD =D0=B8 =D1=82=D0=BE=
=D1=82 =D0=B6=D0=B5 =D0=BE=D1=82=D0=B2=D0=B5=D1=82(=D0=B2 =D1=81=D0=BE=D0=
=BE=D1=82=D0=B2=D0=B5=D1=82=D1=81=D1=82=D0=B2=D0=B8=D0=B8 =D1=81 answ[1]) =
=D0=B2=D0=BF=D0=BB=D0=BE=D1=82=D1=8C =D0=B4=D0=BE =D0=BE=D1=81=D1=82=D0=B0=
=D0=BD=D0=BE=D0=B2=D0=BA=D0=B8 =D1=81=D0=BA=D1=80=D0=B8=D0=BF=D1=82=D0=B0 =
=D0=9F=D0=BE=D0=BB=D0=BD=D1=8B=D0=B9 =D0=BA=D0=BE=D0=B4 - https://drive.goo= gle.com/open?id=3D12Bnha6V1sL3DObEsm9VLxYJO8PQ5BT-r
=D0=9D=D0=BE ...

Tagged: python

by [=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9](<https://ru.stackoverflow.c= om/users/307197/%d0%90%d0%bb%d0%b5%d0%ba%d1%81%d0%b5%d0%b9>) on <https://ru= .stackoverflow.com>

----------------------------

[monkeypatching not carrying through class import](<https://stackoverflow.c= om/questions/51992496/monkeypatching-not-carrying-through-class-import>)

I'm trying to test some code using pytest and need to change a function fro= m some module. One of my imports also imports that function, but this is fa= iling when I change the method using monkeypatch. ...

Tagged: python

by [BadAtTesting123](<https://stackoverflow.com/users/10266339/badattesting= 123>) on <https://stackoverflow.com>

----------------------------

[Unsubscribe from this filter](<https://stackexchange.com/email/unsubscribe=
-filter/366663/630686276?code=3DyKIvad76WjgGyKyQVvWaPWMykvcFJ4G0VqchgHoXuls= %3d>) or change your email preferences by visitingyour [filter subscription= s page on stackexchange.com](<https://stackexchange.com/users/2208803?tab=
=3Dsubscriptions>).

If you no longer want to receive mail from Stack Exchange, unsubscribe from=  all stackexchange.com emails <https://stackexchange.com/email/manage/22678= 0/dbf1aaad76103a2810d725a2c65de27958b70a5d2bc501a04b4b3f99bc106d1e> Questions? Comments? Let us know on our feedback site at <https://meta.stac= kexchange.com>.

Stack Exchange, Inc. 110 William St, 28th Floor, NY NY 10038

------=_NextPart_000_1CCE_64CE4764.45758CD0 Content-Type: text/html;    charset="UTF-8" Content-Transfer-Encoding: base64

DQo8IURPQ1RZUEUgSFRNTCBQVUJMSUMgIi0vL1czQy8vRFREIEhUTUwgNC4wMS8vRU4iICJodHRw
...[left the file out here]...
bGUgLS0+DQo8L2JvZHk+DQo8L2h0bWw+DQo=
------=_NextPart_000_1CCE_64CE4764.45758CD0--

Do all-a-y'all want me to post the attached file here?   I have added the email.  I was concerned that the python code might be harmful.

A: That looks like the kind of email you get when you've subscribed to notifications about questions in one or more tags on the Stack Exchange network. And indeed, you have set up a subscription for questions tagged [python] on Stack Overflow: https://stackexchange.com/users/2208803/ox?tab=subscriptions
Since these are questions about Python, it's expected that some of them contain code.
You say "with a Python file attached", but in the mail you posted, I only see a plain text and an HTML part. In particular, your [left the file out here] appears in the middle of the HTML version of the email. Are you sure you're not just seeing some Python code that is part of a Stack Overflow question?

A: Building on what balpha said, we've had issues with certain mail providers breaking in interesting ways when they tweak spam and virus filters. This is the first time I've seen it happen with Python, but even Gmail sometimes tries to convert Javascript snippets to attachments and complains about them being dangerous. It used to be alarmingly common, not too common these days, but still happens.
I envision this very hungry, very angry, very neurotic regular expression living in a lab petri dish somewhere having achieved sentience as a result of usenet cross posting, and the poor souls that have to 'update' it occasionally. That's the only explanation I've ever come up with as to why certain mail clients choke on semantically-correct HTML-ified code markup.
That email was supposed to be all shiny, exciting and enticing! Sorry that you got an awful mess, maybe report it to whatever service is handling your email?

A: I looked it over it again and noticed this in the email above:
This post is included in the email:
Ошибка в коде делает из обычного бота ВК флудера
it has a link to a google drive file, and gmail automagically converted it to a file attachment named 'bot.py'.
Interesting, curious if this could be exploited in other ways.  Thanks everyone!


text:
Q: Inno Setup: Different Serial keys with different options? How to provide multiple serial number with multiple options in Inno Setup?
I want to write different values in Registry, based on different serial keys I provide to customers.
ex different serial keys like
sKey1 = "A1AA-B2ACF-HEJUI-UYTER"
sKey2 = "A1BB-B2ACF-HEJUI-UYTER"
sKey3 = "A1CC-B2ACF-HEJUI-UYTER"

First 4 characters or different for different keys want to create in Registry
if (custInput.startwith ("A1AA") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Lite"}";
elseif  (custInput.startwith ("A1BB") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Pro"}";
elseif  (custInput.startwith ("A1CC") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Online"}";
endif

How to achieve this in Inno Setup? I used CheckSerial function below:
function CheckSerial(Serial: String): Boolean;
  begin
    Result := Serial = '{#SerialNumber}';
  end;

A: Use a scripted constant to programatically decide about the value to store to the registry:
[Setup]
UserInfoPage=yes

[Registry]
Root: "HKLM"; Subkey: "SOFTWARE\Version"; ValueType: string; ValueName: "Name"; \
    ValueData: "{code:GetEdition}";

[Code]

var
  Serials: TStrings;
  Editions: TStrings;

function CheckSerial(Serial: String): Boolean;
begin
  Result := (Serials.IndexOf(Serial) >= 0);
end;

procedure RegisterEdition(Serial: string; Edition: string);
begin
  Serials.Add(Serial);
  Editions.Add(Edition);
end;

function GetEdition(Param: string): string;
var
  Index: Integer;
begin
  Index := Serials.IndexOf(WizardForm.UserInfoSerialEdit.Text);
  if Index >= 0 then Result := Editions[Index];
end;

function InitializeSetup(): Boolean;
begin
  Serials := TStringList.Create;
  Editions := TStringList.Create;

  RegisterEdition('A1AA-B2ACF-HEJUI-UYTER', 'Lite');
  RegisterEdition('A1BB-B2ACF-HEJUI-UYTER', 'Pro');
  RegisterEdition('A1CC-B2ACF-HEJUI-UYTER', 'Online');

  Result := True;
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Product of Delta distributions of a submanifold I'm studying Kleinert theory and Delta functions of surfaces and curves, defined as
$\boldsymbol{\delta}_S(x)=\int_S \delta^{(3)}(x-y) dy$
Do you know some references about the extension of the Dirac Delta for generic submanifold? Specifically, I would need references related to the delta product.
$\int_V\boldsymbol{\delta}_S(x)\cdot \boldsymbol{\delta}_M(x) =\int_M \ \boldsymbol{\delta}_S(x) dy$
I found this work where there is a brief introduction
https://core.ac.uk/download/pdf/52922262.pdf
but it is not clear to me how they get to the result about the crossing and whether it is extendable to submanifolds that have not only a single common point


text:
Q: How to create a laravel relationship model with a SQL query like this I have query like this
SELECT * FROM 'discussions' INNER JOIN comments ON comments.commentable_id = discussions.id WHERE discussions.user_id = 1 ORDER BY comments.id DESC
How to create relationships in laravel models
Not with query builder like this
DB::table('discussions')
    ->join('comments', 'comments.commentable_id', '=', 'discussions.id')
    ->where('discussions.user_id', '=', 1)
    ->orderBy('comments.id', 'DESC')
    ->get();```

A: First you need to know what type of relationship it is.
One:One, One:Many, Many:Many, Many:One
After that you can take a look at the documentation
You create 2 models by calling to php artisan make:model <name> within your terminal, or by manually creating them.
After that you just do whatever documentation tells you to do.
Say you have one-to-many where one discussion has many comments, it is important you specify the foreign_key in the 2nd parameter if it's non-conventional naming.
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Discussion extends Model
{
    /**
     * Get the comments for the discussions post.
     */
    public function comments()
    {
        // Watch the foreign_key in this instance 'commentable_id'
        return $this->hasMany(Comment::class, 'commentable_id');
    }
}

After that you can call something like
$comments = Discussion::where('user_id', 1)->first()->comments

To get all comments belonging to that discussion
I don't want to be a jerk, but the documentation is truly a wonderful source of information. And I advice you to read everything before starting your development journey.


text:
Q: How To Quickly Switch Paths (in Bash) Sometimes, usually when installing packages with brew, I want to disable/remove certain parts of my path, and then later restore them. I haven't been able to find an easy way to do this, and while I could write my own bash script to do so, I'm wondering if there's an easier way.
Desired behavior (or something like it):
$ echo $PATH
/Users/mchenja/anaconda/bin:/usr/local/bin:/(and so on)
$ changepath "brew"; echo $PATH
/usr/local/bin:/(and so on)
$ changepath "anaconda"; echo $PATH
/Users/mchenja/anaconda/bin:/usr/local/bin:/(and so on)

Here, "brew" and "anaconda" are just user-defined keywords to manipulate a saved path.
Does bash offer a built-in method of doing this? What about an external add-on?

A: Swapping the contents of a variable is like the easiest thing to do in any language. There's no special facility in bash for swapping the contents of the PATH variable because swapping the contents of any variable is so darn easy to do.
For example, you could add this to the end of your favorite shell startup script:
DEFAULTPATH="$PATH"
alias dp="PATH=\"$DEFAULTPATH\""
alias ap="PATH=\"/Users/mchenja/anaconda/bin:$DEFAULTPATH\""
alias bp="PATH=\"/usr/local/bin:$DEFAULTPATH\""

Now, at runtime, you can just type ap, bp, or dp to switch between your anaconda, brew, and default PATHs, respectively.

A: Create individual files with the desired PATH variable and store them in a directory in your home folder.
Example:
cat ~/ch_path.d/brew

PATH="/usr/local/bin:/(and so on)"
export PATH

Then you can source whatever path you want
source ~/ch_path.d/brew

A: Depending on how complicated your use-case actually is, you can set and/or change a variable for just one command by prefixing the command with the variable's value. For example,
1 prompt> X=1
2 prompt> X=2 some_command arg1 arg2
3 prompt> echo $X

the variable X will be 2 inside some_command, but returned back to X=1 on line 3.  So you could temporarily change the PATH for just one command to strip out the matching prefix string (assuming your requirement is as simple as this), e.g.,
1 prompt> PATH=${PATH#/Users*:} brew ...args...

This will strip from the PATH the prefix starting with "/Users" ending at the first ":".  E.g., instead of /Users/foo/bar:/usr/bin/.... you'll just have /usr/bin/..... Whether this is easier than aliases is questionable, but it could be incorporated into your aliases/functions/scripts. Main advantage is that it dynamically modifies your PATH from whatever it's currently set to; but that's the main disadvantage, as well :-)


text:
Q: Updating an Uploaded Zip File without re-uploading the whole files Imagine I have uploaded a zip file which contains thousands of images and its size is about 2GB. Now I want to add 100 new pictures which their size is about 10MB. The only way I can imagine is that I add these images to my 2GB collection, then upload the whole collection AGAIN!!! But I'm looking for a way that I can inject only new files without re-uploading the whole collection. So is there any way to do this? any good way or software?

A: Do you have command line access to the server?  If you have or can install a zip utility on the server, you can unpack the zip on the server, upload the files to the directory, and then re-zip it.

A: Your answer would depend on how you are uploading the zip, and how you can manipulate it once its uploaded.
Unless you can add it directly to the zip, where you uploaded it, you would need to re-compress the images, then re-upload.


text:
Q: A density on the natural numbers invariant with respect to the multiplication The "classical Beurling density" of a subset of the natural numbers is $d(A)=lim_{n\rightarrow\infty}\frac{|A\cap[1,n]|}{n}$, when it exists. It defines a finitely additive probability measure on the natural numbers which is invariant with respect to the sum. Here is my question: does there exist a "nice formula" to describe a finitely additive probability measure on $\mathbb N$ which is invariant with respect to the multiplication?
A couple of remarks: I don't know if it is trivial that such a measure exists, but anyway it follows from the application of a general result of Vern Paulsen (on arxiv "Syndetic sets and amenability").
Another problem would be that of finding the measure of particular sets. What about the measure of {$1!,2!,3!,4!...$}? Sets with measure differente from 0 and 1? For example the set of numbers whose first digit through 4 to 9 seems to have measure $=\log_{10}4$... any other?
Thanks in advance, Valerio

A: The natural thing to do here is to replace the intervals $[1,n]$ (and $n = |[1,n]|$) in the definition of $d(A)$ with a sequence $F_n$ of subsets of $\mathbb{N}$ which is multiplicatively asymptotically invariant (or, in other words, a Folner sequence for the semigroup $(\mathbb{N},\cdot)$). For an exploration of this idea, as well as applications, see for instance this article by Vitaly Bergelson:
Multiplicatively large sets and ergodic Ramsey theory, Israel Journal of Mathematics 148 (2005), 23-40.
EDIT: One particular example (mentioned in the article) is to take $F_n$ to be the set of all positive integers which can be written as a product of powers of the first $n$ primes, where the powers are allowed to be any non-negative integer which is less than or equal to $n$. The motivation for choosing $F_n$ this way is that just as $1$ generates the additive semigroup $(\mathbb{N},+)$, the primes generate the multiplicative semigroup. Think of balls in the corresponding Cayley graphs with radius getting larger and larger. The article contains many other examples of such $F_n$, and each of them gives a notion of "multiplicative density" by setting $d(A) = \lim_{n \to \infty} \frac{|A \cap F_n|}{|F_n|}$ (if the limit exists. Otherwise one usually considers the limsup and liminf).

A: Here is an example.  Let $d(A)$ be as you define it in the question, namely $$d(A)=\lim_{n\to \infty} \frac{|A\cap [1,n]|}{n}.$$
Let $U_n=\{k\in\mathbb{N} \text{ such that } k \text{ is a mutiple of } n!\}$.  Then define $$\mu(A)=\lim_{n\to \infty} n!\cdot d(A\cap U_n).$$
Then I claim that $\mu$ is finitely additive and multiplicatively invariant.  Finite additivity is obvious.  For multiplicative invariance, note that for $s>k$, we have $(s+k)!\cdot d(kA\cap U_{s+k})=s!\cdot d(A\cap U_{s})$, unless I've screwed something up.
EDIT:  Note by the way that one can replace the limit in the definition with $d$ with the Cesaro mean, for example, giving a much broader class of sets with defined measure.  For example, with this addition, the set of natural numbers with a fixed leading digit in a fixed prime base $p$ has density $1/(p-1)$.

A: How about:
$$
\lim_{k\to\infty} \frac{|A \cap [1,k!]|}{k!}
$$
when it exists?


text:
Q: Getting error: " javascript error: Cannot read property" when tracking HTML video current Time using the combination of JavaScript and Selenium I would like in interval to track video play progress in a HTML video.
Based on the tutorial, the HTML video DOM timeupdate event can be achieved by something like below:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time

chrome_options = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path=r"\Browsers\chromedriver.exe",
                           options=chrome_options)

browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")

WebDriverWait(browser, 70).until(EC.element_to_be_clickable(
(By.XPATH, "//button[@aria-label='Play']"))).click()

javascript_to_execute = ' return document.getElementById("ytplayer").currentTime();'
for x in range(0, 2):
    time_current = browser.execute_script(javascript_to_execute)
    print(time_current)
    time.sleep(1)

However, I got the following error

Message: javascript error: Cannot read property 'currentTime' of null

May I know where did I do wrong. Appreciate for any  hint or help.
Thanks in advance

A: The following code should work thanks to the suggestion made from OP1.
To obtain the currentTime of a HTML video using JS, the following can be considered.
The JS code, to extract the video current time is
"return document.getElementsByTagName('video')[0].currentTime;"

The above JS can be executed using the method execute_script
   time_video = browser.execute_script("return document.getElementsByTagName('video')[0].currentTime;")

To investigate whether the above implementation is able to obtain the video timing, say, in the middle of the video. We first jump to a position, say 180 sec from the starting point using the code below.
player_status = browser.execute_script("document.getElementsByTagName('video')[0].currentTime += 180;")

The full code are as below;
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time

chrome_options = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path = r"some_path\Browsers\chromedriver.exe",
                           options = chrome_options)

browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")

WebDriverWait(browser, 70).until(EC.element_to_be_clickable(
    (By.XPATH, "//button[@aria-label='Play']"))).click()
print('Fast forward')
player_status = browser.execute_script("document.getElementsByTagName('video')[0].currentTime += 80;")
print('Get Current time')
time_video = browser.execute_script("return document.getElementsByTagName('video')[0].currentTime;")


text:
Q: GCP Cloud Shell Command Equivalent For Python SDK I have command to retrieve stackdriver logs in specific file and it is as below,
gcloud logging read "resource.type=\"bigquery_resource\" AND timestamp >= \"2019-12-03T00:00:00Z\" AND timestamp <= \"2019-12-04T05:30:00Z\" AND protoPayload.serviceData.jobCompletedEvent.job.jobStatistics.totalBilledBytes > 0" --format json > logs_data.json

Willing to know if their is any other way to do the same, using python script or python SDK for GCP.

A: You can find the sample python code example here. The REST API method used to retrieve log entries would be entries.list.
For more details on how to setup python to talk to GCP Stackdriver: https://cloud.google.com/logging/docs/quickstart-python
Hope this helps.


text:
Q: Cannot call DriveApp from Google sheet via onEdit() trigger I have noticed that I can execute calls to SpreadsheetApp using an onEdit() trigger until I make a call to DriveApp in which case no calls to the sheet after that are executed. But all lines of code are executed when I when i run onEdit() from within the script file. Wonder if anyone has overcome this obstacle. A code exammple can be created by running the code from this link:
https://gist.github.com/mesgarpour/07317e81e9ee2b3f1699
It runs fine when executed from within the script file by choosing Run => listFolers();
But if I try to trigger it from the spreadsheet itself by adding:
function onEdit() {
  listFolers();
}

and then make a change to any cell on the sheet, it doesn't execute.
Is this a bug in GAS? Has anyone been able to call DriveApp code using an onEdit() trigger and successfully write the results to the active sheet?


text:
Q: How to plot voltage vs current in HSPICE/MacSPICE? I have a transient simulation for a simple voltage divider for MacSPICE shown below. I'm able to plot certain variables under test vs. time. How can I do a current vs. voltage plot for the transient data?
Voltage Divider - Sine

vin 1 0 sin (0.0V 1.0V 50) ac 1.0 dc 0.0
r1 1 2 1.0K
r2 2 0 1.0k

.control
* dispose of any 'save' statements from previous runs
delete all
tran 0.1ms 20ms
plot v(1) v(2)
plot -i(vin)
.endc

.end

A: The command:
plot -i(vin) vs v(1)

is what you need.


text:
Q: Метод масштабирования текста для сайта Уважаемые, подскажите метод масштабирования текста для сайта.
A: Насколько я понял, вы имеете ввиду изменить размер текста. Ну а если вы имели ввиду другое, измените вопрос

Представим что у вас есть какой-нибудь блок с текстом (а если его нет, то надо создать). Выглядеть это дело должно так:

some text

Нам нужно добавить к блоку id:

some text

Теперь с помощью скрипта обращаемся к блоку и меняем font-size:
document.getElementById('1234').style.fontSize = 'необходимый_размер';

Размер нужно указывать согласно этим правилам
UPDATE1 Если нужно только 'подстраивание под экран' используйте js-код:
document.getElementById('1234').style.fontSize = screen.width / 500 + 'ex'

A: CSS Media Query вам в помощь.


text:
Q: OS X Bash, 'watch' command I'm looking for the best way to duplicate the Linux 'watch' command on Mac OS X. I'd like to run a command every few seconds to pattern match on the contents of an output file using 'tail' and 'sed'.
What's my best option on a Mac, and can it be done without downloading software?

A: Or, in your ~/.bashrc file:
function watch {
    while :; do clear; date; echo; $@; sleep 2; done
}

A: With Homebrew installed:
brew install watch

A: To prevent flickering when your main command takes perceivable time to complete, you can capture the output and only clear screen when it's done.
function watch {while :; do a=$($@); clear; echo "$(date)\n\n$a"; sleep 1;  done}

Then use it by:
watch istats

A: Use MacPorts:
$ sudo port install watch

A: You can emulate the basic functionality with the shell loop:
while :; do clear; your_command; sleep 2; done

That will loop forever, clear the screen, run your command, and wait two seconds - the basic watch your_command implementation.
You can take this a step further and create a watch.sh script that can accept your_command and sleep_duration as parameters:
#!/bin/bash
# usage: watch.sh <your_command> <sleep_duration>

while :;
  do
  clear
  date
  $1
  sleep $2
done

A: The shells above will do the trick, and you could even convert them to an alias (you may need to wrap in a function to handle parameters):
alias myWatch='_() { while :; do clear; $2; sleep $1; done }; _'

Examples:
myWatch 1 ls ## Self-explanatory
myWatch 5 "ls -lF $HOME" ## Every 5 seconds, list out home directory; double-quotes around command to keep its arguments together

Alternately, Homebrew can install the watch from http://procps.sourceforge.net/:
brew install watch

A: Try this:
#!/bin/bash
# usage: watch [-n integer] COMMAND

case $# in
    0)
        echo "Usage $0 [-n int] COMMAND"
        ;;
    *)
        sleep=2;
        ;;
esac

if [ "$1" == "-n" ]; then
    sleep=$2
    shift; shift
fi

while :;
    do
    clear;
    echo "$(date) every ${sleep}s $@"; echo
    $@;
    sleep $sleep;
done

A: It may be that "watch" is not what you want.  You probably want to ask for help in solving your problem, not in implementing your solution!  :)
If your real goal is to trigger actions based on what's seen from the tail command, then you can do that as part of the tail itself.  Instead of running "periodically", which is what watch does, you can run your code on demand.
#!/bin/sh

tail -F /var/log/somelogfile | while read line; do
  if echo "$line" | grep -q '[Ss]ome.regex'; then
    # do your stuff
  fi
done

Note that tail -F will continue to follow a log file even if it gets rotated by newsyslog or logrotate.  You want to use this instead of the lower-case tail -f.  Check man tail for details.
That said, if you really do want to run a command periodically, the other answers provided can be turned into a short shell script:
#!/bin/sh
if [ -z "$2" ]; then
  echo "Usage: $0 SECONDS COMMAND" >&2
  exit 1
fi

SECONDS=$1
shift 1
while sleep $SECONDS; do
  clear
  $*
done

A: I am going with the answer from here:
bash -c 'while [ 0 ]; do <your command>; sleep 5; done'

But you're really better off installing watch as this isn't very clean...

A: If watch doesn't want to install via
brew install watch

There is another similar/copy version that installed and worked perfectly for me
brew install visionmedia-watch

https://github.com/tj/watch

A: Here's a slightly changed version of this answer that:

*

*checks for valid args

*shows a date and duration title at the top

*moves the "duration" argument to be the 1st argument, so complex commands can be easily passed as the remaining arguments.

To use it:

*

*Save this to ~/bin/watch

*execute chmod 700 ~/bin/watch in a terminal to make it executable.

*try it by running watch 1 echo "hi there"
~/bin/watch
#!/bin/bash

function show_help()
{
  echo ""
  echo "usage: watch [sleep duration in seconds] [command]"
  echo ""
  echo "e.g. To cat a file every second, run the following"
  echo ""
  echo "     watch 1 cat /tmp/it.txt"
  exit;
}

function show_help_if_required()
{
  if [ "$1" == "help" ]
  then
      show_help
  fi
  if [ -z "$1" ]
    then
      show_help
  fi
}

function require_numeric_value()
{
  REG_EX='^[0-9]+$'
  if ! [[ $1 =~ $REG_EX ]] ; then
    show_help
  fi
}

show_help_if_required $1
require_numeric_value $1

DURATION=$1
shift

while :; do
  clear
  echo "Updating every $DURATION seconds. Last updated $(date)"
  bash -c "$*"
  sleep $DURATION
done

A: Use the Nix package manager!
Install Nix, and then do nix-env -iA nixpkgs.watch and it should be available for use after the completing the install instructions (including sourcing . "$HOME/.nix-profile/etc/profile.d/nix.sh" in your shell).

A: The watch command that's available on Linux does not exist on macOS. If you don't want to use brew you can add this bash function to your shell profile.
# execute commands at a specified interval of seconds
function watch.command {
  # USAGE: watch.commands [seconds] [commands...]
  # EXAMPLE: watch.command 5 date
  # EXAMPLE: watch.command 5 date echo 'ls -l' echo 'ps | grep "kubectl\\\|node\\\|npm\\\|puma"'
  # EXAMPLE: watch.command 5 'date; echo; ls -l; echo; ps | grep "kubectl\\\|node\\\|npm\\\|puma"' echo date 'echo; ls -1'
  local cmds=()
  for arg in "${@:2}"; do
    echo $arg | sed 's/; /;/g' | tr \; \\n | while read cmd; do
      cmds+=($cmd)
    done
  done
  while true; do
    clear
    for cmd in $cmds; do
      eval $cmd
    done
    sleep $1
  done
}

https://gist.github.com/Gerst20051/99c1cf570a2d0d59f09339a806732fd3


text:
Q: What's the function of `context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")` in python ssl coding? I follow a tutorial written a Python ssl demo.
import ssl
import socket
HOSTNAME = "www.cloudflare.com"

context = ssl.create_default_context()

context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
#context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=HOSTNAME)

conn.connect((HOSTNAME, 443))

# cert = conn.getpeercert()
#
# print(cert)

this line code I don't understand, what's the function?
context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")

and I run it in my macOS, I don't know which path I can access the ca-bundle.crt, and don't know the ca-bundle.crt's function.  Could you please help with these questions?

A: Do you know how certificates are verified? If no you can start with the Wikipedia page about PKI.
In brief. Certificates are signed by the certificate authorities. We trust those authorities in that they check all the claims in the certificated requests. As a resut, if a site provides a certificate for stackoverflow.com and signed by the trusted CA then we believe it is really Stackoverflow.
The set of trusted authorities is small. Several dozens. Theyr public keys are distributed  as certificates with operating systems, browsers, openssl distro. Those certificates are called root certificates.
The call context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") loads the list of root certificates of the CAs, that openssl maintaners trust. That list of certificates is stored in the file /etc/ssl/certs/ca-bundle.crt.
But in MacOS this call is not needed. Default OpenSSL distro loads the CA certificates from the operating sysem. The certificate for cloudflare.com is issued by DigiCert. This is a reputable CA that all browsers and operating systems trust. Their certificate is stored in MacOS and is loaded in your process when you intialize the default context.
FYI. The constant ssl.PROTOCOL_SSLv23 is a misnomer and was deprecated since python 3.6. Use ssl.PROTOCOL_TLS instead.


text:
Q: Adding Apache Camel custom component/endpoint in a Spring application I'm trying to implement a custom endpoint in a Spring Boot application.
Goal is to use routes as: from("...").process("...").to("my:...");
Now, I have 3 classes: a DefaultConsumer, a DefaultEndpoint, a DefaultComponent:
package com.my.endpoint;

import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.support.DefaultEndpoint;

public class MyEndpoint extends DefaultEndpoint {

    public MyEndpoint(String uri, MyComponent myComponent) {

    }
    ...
}

package com.my.endpoint;

import org.apache.camel.Endpoint;
import org.apache.camel.Processor;
import org.apache.camel.support.DefaultConsumer;

public class MyConsumer extends DefaultConsumer {

    public MyConsumer(Endpoint endpoint, Processor processor) {

        super(endpoint, processor);
    }
}

package com.my.endpoint;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;

import java.util.Map;

@Component("my")
public class MyComponent extends DefaultComponent {

    public MyComponent(CamelContext camelContext) {

        super(camelContext);
    }
    ...
}

Now: how can I register?
In a Spring configuration class, I have:
  @Override
  public void configure() throws Exception {

        camelContext.addComponent("my", new MyComponent(camelContext));

But is not working:
    Caused by: org.apache.camel.NoSuchEndpointException: No endpoint could be found for: my, please check your classpath contains the needed Camel component jar.

So, I added the META-INF file in services/org/apache/camel/component/my:
class=com.my.endpoint.MyComponent

But also this, is not working.
There is no complete tutorial on how to implement this.
Any help?
Note: I'm trying to implement an Endpoint because I need to integrate my systems using my data types. I tried using Transformer but failed because of this: Set a custom DataType in Apache Camel Processor
Before, I tried using data type converter, but failed because of this (marked duplicate because people are too lazy to really understand questions): Enforce type conversion on Rest consumer in Apache Camel
I've FULLY read "Apache Camel In Action, Second Edition" but, at the moment, I can't continue with my project because of?

A: This is because custom component must be annotated by @UriEndpoint annotation.

A: Another way to solve this problem: Set EndpointUri via Constructor or by implementing createEndpointUri() in MyEndpoint.
So easiest way might be changing your constructor to:
public MyEndpoint(String uri, MyComponent myComponent) {
 super(uri, myComponent);
}


text:
Q: Erase all traces of Windows 8 Just bought a new HP pavilion desktop with Windows 8.
I wish to totally remove Windows 8 and all data on the hard drive, remove any windows partitions, delete all data, and then install a fresh Linux.
Problem is I can seem to get to boot from USB or boot from CD.
It appears that Windows 8 added the following two "features":

*

*UEFI which substitutes what we have known as the BIOS

*Secure Boot which prevents anything but the installed operating system

How do I completely and totally erase all traces of Windows 8?  Is it still possible to reformat the hard drive?  I don't want a duel boot, I don't want to go back to Windows 7, I just want anything Windows gone.

A: You have at least three options to wipe those partitions:

*

*Turn off secure boot in the BIOS UEFI. After that you can boot from CD's/DVDs/USB.

*Boot from a disk with a valid safe boot signature. (E.g.  user88311's Fedora live disc or a windows 8 DVD)

*Remove the drive, connect it to another computer and wipe it from there.


text:
Q: MySQL - Get only the recent previous record but not all previous record I have this sample table:
id    room_id   gauge    date
1     1         10       2018-10-03
2     2         17       2018-10-03
3     1         16       2018-10-05
4     2         25       2018-10-05

I only wanted to get the recent ones which is the 2018-10-05 record to show it as my previous gauge. How will I do that?
My attempt:
SELECT * FROM sample WHERE date > (SELECT MAX(date) FROM sample)

A: Your should be asserting that the date equals the most recent date in the table:
SELECT * FROM sample WHERE date = (SELECT MAX(date) FROM sample);

A: Try this
SELECT * FROM sample WHERE date = (SELECT MAX(date) FROM sample)

the date you were trying to catch is GREATER THAN the max Date on your field.
So that the result will not be shown because the max date is 2018-10-05. meaning only the greater value will be retrieved.


text:
Q: Get the Text box and drop down value inside a Table which is created dynamically using JQuery Please help ,i am new to jquery . Have 3 tables which will fill the textboxes and  drop down "select" dynamically

The table can have so many text boxs and "select" drop down  that added dynamically by clicking "add more".
Actually i want to implement some thing like this from the textbox and select in that table
var array = [];
var j = 0;
$('#shareAddUserMember tr').each(function () {
    var memberID = ?  // Dynamic_textbox_value;
    var privilage = ? // Dynamic_drop_down_selected value ie type <select>
    if (memberID != "") {
        array[j] = memberID + ":" + privilage;
        j++;
    }
});

I have tried this to get the value of textbox ,i need select also
$('#shareAddUserMember tr').each(function () {
    $('input[type=text]').each(function (i, item) {
    var grade = $(item).val();
        alert(grade);
    });
});

But above code  will fetch all the input types in the page .I have more than one table .I need to fetch value in text boxes which is created dynamically(id is dynamically generated) inside the table shareAddUserMember  .
I need the value of textbox only inside the table having  id ="shareAddUserMember " not shareAddUserMemberA or shareAddUserMemberB.
$('#shareAddUserMember tr').each(function () {
     // ---what to write here  to fetch the textbox and drop down selected values-----------
});

Actually i want to implement some thing like this from the textbox and input type select  in that table
var array = [];
var j = 0;
$('#shareAddUserMember tr').each(function () {
    var memberID = ?  // Dynamic_textbox_value;
    var privilage = ? // Dynamic_drop_down_selected value ie type <select>
    if (memberID != "") {
        array[j] = memberID + ":" + privilage;
        j++;
    }
});

Inside the tr there is drop down and select sample DOM

      <input type="hidden" id="EmailUserMemberID1" name="EmailUserMemberID1" />

      <select style="width: 150px" name="select1" id="select1">
        <option value="">Select</option>
        <option value="1">Full Access </option>
        <option value="0">View Only</option>
      </select>

A: Iterate over each tr element inside #shareAddUserMember:
$("#shareAddUserMember tr").each(function() {
  // `this` refers to the current tr element

  // Get the input box and select that are inside the current tr element using
  // $(this).find()
  var memberID = $(this).find("input:text").val();
  var privilege = $(this).find("select").val();

  if (memberID !== "") {
    // ...
  }
});

Hope that helps or at least points you in the right direction.

A: Try this code:
$('#shareAddUserMember tr input[type=text]').each(function () {
     // do some of your magic in here :)
});

Since you have updated your answer you can try something like this (I didn't test this code)
$('#shareAddUserMember').each(function () {
        var memberID = $('#shareAddUserMember tr input[type=text]').val();
        var privilage = $("#shareAddUserMember tr select option:selected").text();
        if (memberID != "") {
            array[j] = memberID + ":" + privilage;
            j++;
        }
    });


text:
Q: speech_recognition is printing more information I need I am using speech recognition to send OSC messages. Actually, the code works fine sometimes, I had some errors, but I could solve them with
r.recognize_google(audio, language = "es_ES", show_all = True)
my problem now is that before show_all, I just got the word or phrases I was saying, and I could use that as information, but now I am getting this:
{'alternative': [{'transcript': 'vida', 'confidence': 0.96399021}], 'final': True}
and I just need the word 'vida', how can I print just that word, or how to get information, because later I am using:
if words == "vida":
msg01 = oscbuildparse.OSCMessage("/alturas", ",ii", arguments=(1, 0))
osc_send(msg01, "supercollider")
osc_process()
thanks and have a great day
WM


text:
Q: Как переименовать атрибут в MongoRecord? Пишу скрипт для миграции. Необходимо переименовать элемент коллекции(для сохранения старых данных, и проверки обращений к ним)
class NativeParams extends ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function collectionName() {
        return 'params';
    }

    /**
     * @inheritdoc
     */
    public function attributes() {
        return [
            '_id', 'input_data', 'old_input_data'
        ];
    }
}

Пробую так
$allParams = NativeParams::find()->all();

foreach ($allParams as $model) {
    $model->old_input_data = $model->input_data;
    //$model->input_data = null;
    unset($model->input_data);
    $model->save();
}

Элемент копируется. Но в базе остаётся старая копия. Как его полностью удалить? Пробовал присвоить ему NULL, но мне необходимо именно удалить его из базы а не присвоить другое значение.

A: Всё оказалось намного проще
NativeParams::getCollection()->update([], [
    '$rename' => [
        'input_data' => 'old_input_data'
    ]
]);


text:
Q: Windows 10 ignores setsockopt IP_TOS The short version: I am trying to set the IP_TOS field on the traffic my application is sending and even though setsockopt returns successfully and getsockopt returns the correct IP_TOS value, the traffic is untagged when leaving the Windows 10 box.
The longer version: I have an application that sends traffic that needs to have the IP_TOS field set and the IP_TOS value can be one in a range of values; it's an environment requirement so there is no way around it. The application also needs to be cross-platform (Windows 10 and Linux). Considering those requirements, we decided to just use boost asio and set the IP_TOS on the socket when it's created.
The Linux side works the way we want, socket is created, IP_TOS is set, data is sent, and tcpdump shows the data is correctly tagged on the send and receive sides.
The Windows side does everything except for actually tag the traffic. The socket is created, IP_TOS is set and read back to verify before sending, however wireshark/tcpdump shows that the traffic is not tagged at all (IP_TOS is 0). When we started to see issues with this, we created a simple test app using normal Windows TCP sockets, set and read IP_TOS using setsockopt and getsockopt and still had the same issues.
My google-fu can be weak at times, but information on Windows 10 support of IP_TOS seems rather sparse. I have one MSDN Doc say both to not use it (instead use the QoS API) but that it's supported in Windows 10 which I assumed meant it could be set. I also have an older support doc that says support has to be enabled, but I can't find a more recent document relevant to Windows 10. I did try the registry tweak, plus a second one (Do not use NLA) and that didn't help.
I'm at a bit of a loss now, so I'm hoping someone has dealt with this before and has a solution to setting IP_TOS on a socket. Really trying to avoid bringing in another API or making calls outside the application (netsh or group policy) to achieve something that should be simple.

A: TOS is disabled by default in OS(Imperfect)
To enable TOS use regedit: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DisableUserTOSSetting
Please see: Setting Type of Service (TOS) Bits


text: Q: connect to mysql database from remote server How can I connect to mysql database on Server2 from different server (Server 1). I have given the remote access to Server1 by specifying its domain name using CPanel of Server2. But when I try to run the PHP script from Server1. It does not connect.


text:
Q: Apache + Python Bottle : visitor IP always refers to 127.0.0.1 My server handles multiple websites, most of them with Apache, PHP, etc.
But one of them (www.mywebsite.com) uses a Python webserver, which listens on port 8092. Thus this Apache configuration:
<VirtualHost *:80>
  ServerName mywebsite.com
  ServerAlias *.mywebsite.com
  RewriteEngine On
  RewriteRule /(.*)           http://localhost:8092/$1 [P,L]
</VirtualHost>

Now when a user, coming from internet, connects to www.mywebsite.com, it works : Python handles it and everything is okay.
Problem: the IP that I get, in my Python code using bottle with :
ip = request.environ.get('REMOTE_ADDR')

is always 127.0.0.1.
How to get the real IP address of the visitor instead?

A: Your virtual host is using proxy rewriting.  The client connects to apache which opens a proxy connection to your application, rewrites the URL, and proxies the request.  There is no real connection between your application and the client.
Since there is not a direct connection between your application and the client, you cannot get the "real IP" unless you tell apache to send it to your application.  The usual approach is to set something like the X-Forwarded-For header.  You may have to explicitly use mod_proxy to do this though.


text:
Q: Bitmap not large enough to support new configuration I have a Bitmap and i want to configure it. I also set my bitmap to Mutable one that's not a problem but when i want to configure, it comes with a error that my bitmap is not large enough.
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.ic_cm);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888,true);
bitmap.setWidth(getWidth() / 2);


text:
Q: Passing the selected object to an Another Activity I have a news activity in which there is a list of news.I want a user to select a news from the list and direct him to the news_details page where I give the details about the selected news, however when the user selects the news, program goes quickly to news_details and comes back again to the news.
  News:

  public void Listen() {

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {  // ana sayfada herhangi bir item seçildiğinde
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
            Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
            i.putExtra("title", selectedNews.getTitle());
            i.putExtra("date", selectedNews.getNewsDate().toString());
            i.putExtra("image_id", selectedNews.getImageId());
            i.putExtra("text", selectedNews.getText());
            setResult(RESULT_OK, i);
            startActivity(i);

        }

    });
}

  News_Details:

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

    Intent i = new Intent(this,MainActivity.class);

    startActivityForResult(i, GET_NEWS);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GET_NEWS) {  // Check which request we're responding to

        if (resultCode == RESULT_OK) {  // Make sure the request was successful

            title.setText(data.getStringExtra("title"));
            date.setText(data.getStringExtra("date"));
            news_img.setImageResource(data.getIntExtra("image_id", 0));
            news_text.setText(data.getStringExtra("text"));

        }

    }
}
}

A: First of all, remove this line:
setResult(RESULT_OK, i);

Also, remove this line from newsdetails activity:
startActivityForResult(i, GET_NEWS);
Make changes as below:
public void Listen() {

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
            Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
            i.putExtra("title", selectedNews.getTitle());
            i.putExtra("date", selectedNews.getNewsDate().toString());
            i.putExtra("image_id", selectedNews.getImageId());
            i.putExtra("text", selectedNews.getText());
            startActivity(i);
        }

    });
}

Then, in your news details activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news__details);

    Intent i = getIntent();
    String title = i.getStringExtra("title");
    String date = i.getStringExtra("date");
    int imageId = i.getIntExtra("image_id");
    String text = i.getStringExtra("text");
}

OnActivityResult method is not required so simply remove it.
FYI:
startActivity and startActivityForResult both of them start new activities , but startActivityForResult as the name suggests that you are expecting a result from the activity you are starting. And this result shall be obtained in onActivityResult method.
Say for example, you want to start Activity2 from Activity1, and you want to pass some data back to Activity1 while finishing Activity2. You simply set the Result in Activity2 using setResult() method. and while Activity1 resumes again, its onActivityResult() will be invoked, you will override onActivityResult() in Activity1 to receive the Result set by Activity2.
Hope you are now clear on this.

A: Remove these lines
setResult(RESULT_OK, i);
Intent i = new Intent(this,MainActivity.class);
startActivityForResult(i, GET_NEWS);

Use google Gson for serializing the object.
    NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
    String strNews = new Gson().toJson(selectedNews);

    Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
                i.putExtra("news", strNews);
                startActivity(i);

On other hand News details onCreate() do this
    Bundle bundle = getIntent().getExtras();
    String newsStr = bundle.getString("news");
            Gson gson = new Gson();
            Type type = new TypeToken<NewsItem>() {
            }.getType();
            NewsItem selectedNews = gson.fromJson(newsStr, type);

A: to send string value
  NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
        Intent i=new Intent(MainActivity.this, News_Details_Activity.class);
        i.putExtra("title", selectedNews.getTitle());
        i.putExtra("date", selectedNews.getNewsDate().toString());
        i.putExtra("image_id", selectedNews.getImageId());
        i.putExtra("text", selectedNews.getText());
        startActivity(i);

to recieve in News_Details_Activity
    Intent i = getIntent();
    title = i.getStringExtra("title");
    date= i.getStringExtra("date");
    text= i.getStringExtra("text");

A: you can do it using Serializable by following way
public class News  implements Serializable{
String title;
String desc;
String time,imageUrl;

}
Then News List activity
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
        i.putExtra("news",newsObject);

and get it onCreate of NewsDetail
    News news=(News)  getIntent().getExtras().getSerializable("news");
and user it like  title.setText(news.getTitle());

A: make News class that implements Serialazable
Create new Object of News class , and put into intent as putSerialazable();
in your second activity just getIntent().getSerialazable("key") and set your data to views.


text:
Q: Qualcomm Atheros QCA6174 can't find channel 13 WiFi (Ubuntu Server 18.04.2 LTS) I want to enable WiFi channels 13 on UbuntuServer18.04.2LTS. I tried to change regulatory domain by running iw reg set JP (I am in Japan).
Regulatory domain changed but Ubuntu could not find channel 13 WiFi.
iw list | grep Freq -A 14
    Frequencies:
            * 2412 MHz [1] (20.0 dBm)
            * 2417 MHz [2] (20.0 dBm)
            * 2422 MHz [3] (20.0 dBm)
            * 2427 MHz [4] (20.0 dBm)
            * 2432 MHz [5] (20.0 dBm)
            * 2437 MHz [6] (20.0 dBm)
            * 2442 MHz [7] (20.0 dBm)
            * 2447 MHz [8] (20.0 dBm)
            * 2452 MHz [9] (20.0 dBm)
            * 2457 MHz [10] (20.0 dBm)
            * 2462 MHz [11] (20.0 dBm)
            * 2467 MHz [12] (disabled)
            * 2472 MHz [13] (disabled)
            * 2484 MHz [14] (disabled)

Ubuntu's statuses are as follows
$ uname -r
4.15.0-66-generic

$ lspci | grep Qualcom
04:00.0 Network controller: Qualcomm Atheros QCA6174 802.11ac Wireless Network Adapter (rev 32)

$ iw reg get
global
country JP: DFS-JP
    (2402 - 2482 @ 40), (N/A, 20), (N/A)
    (2474 - 2494 @ 20), (N/A, 20), (N/A), NO-OFDM
    (4910 - 4990 @ 40), (N/A, 23), (N/A)
    (5030 - 5090 @ 40), (N/A, 23), (N/A)
    (5170 - 5250 @ 80), (N/A, 20), (N/A), AUTO-BW
    (5250 - 5330 @ 80), (N/A, 20), (0 ms), DFS, AUTO-BW
    (5490 - 5710 @ 160), (N/A, 23), (0 ms), DFS
    (59000 - 66000 @ 2160), (N/A, 10), (N/A)
phy#0
country US: DFS-FCC
    (2402 - 2472 @ 40), (N/A, 30), (N/A)
    (5170 - 5250 @ 80), (N/A, 23), (N/A), AUTO-BW
    (5250 - 5330 @ 80), (N/A, 23), (0 ms), DFS, AUTO-BW
    (5490 - 5730 @ 160), (N/A, 23), (0 ms), DFS
    (5735 - 5835 @ 80), (N/A, 30), (N/A)
    (57240 - 63720 @ 2160), (N/A, 40), (N/A)

$ dmesg | grep ath
[    7.167872] ath10k_pci 0000:04:00.0: enabling device (0000 -> 0002)
[    7.168888] ath10k_pci 0000:04:00.0: pci irq msi oper_irq_mode 2 irq_mode 0 reset_mode 0
[    7.479266] ath10k_pci 0000:04:00.0: Direct firmware load for ath10k/pre-cal-pci-0000:04:00.0.bin failed with error -2
[    7.479292] ath10k_pci 0000:04:00.0: Direct firmware load for ath10k/cal-pci-0000:04:00.0.bin failed with error -2
[    7.487836] ath10k_pci 0000:04:00.0: qca6174 hw3.2 target 0x05030000 chip_id 0x00340aff sub 168c:3363
[    7.487838] ath10k_pci 0000:04:00.0: kconfig debug 0 debugfs 1 tracing 1 dfs 0 testmode 0
[    7.488472] ath10k_pci 0000:04:00.0: firmware ver WLAN.RM.4.4.1-00079-QCARMSWPZ-1 api 6 features wowlan,ignore-otp crc32 fd869beb
[    7.564222] ath10k_pci 0000:04:00.0: board_file api 2 bmi_id N/A crc32 4ed3569e
[    8.168203] ath10k_pci 0000:04:00.0: Unknown eventid: 118809
[    8.171207] ath10k_pci 0000:04:00.0: Unknown eventid: 90118
[    8.171838] ath10k_pci 0000:04:00.0: htt-ver 3.47 wmi-op 4 htt-op 3 cal otp max-sta 32 raw 0 hwcrypto 1
[    8.257109] ath: EEPROM regdomain: 0x0
[    8.257113] ath: EEPROM indicates default country code should be used
[    8.257113] ath: doing EEPROM country->regdmn map search
[    8.257115] ath: country maps to regdmn code: 0x3a
[    8.257116] ath: Country alpha2 being used: US
[    8.257116] ath: Regpair used: 0x3a
[    8.269422] ath10k_pci 0000:04:00.0 wlp4s0: renamed from wlan0


text:
Q: How to implement the theory of copy movement in Prolog? Using this input:
parse(Parse, [what,did,thomas,eat], [])
I want to produce this output:
sbarq(
whnp(
    wp(what)
    ),
sq(
    vbd(did),
    np(nnp(thomas)),
    vp(
        vb(eat),
        whnp(
            wp(what)
            )
      ) % this is not in the input, I need to copy the entire whnp here
)

with this code:
parse(Tree) --> sbarq(Tree).

% rules
sbarq(sbarq(WHNP, SQ)) --> whnp(WHNP), sq(SQ).
whnp(whnp(WP)) --> wp(WP).
sq(sq(VBD, NP, VP)) --> vbd(VBD), np(NP), vp(VP).
np(np(NNP)) --> nnp(NNP).
vp(vp(VB)) --> vb(VB).

% lexicon
wp(wp(what)) --> [what].
vbd(vbd(did)) --> [did].
nnp(nnp(thomas)) --> [thomas].
vb(vb(eat)) --> [eat].

how can I change my code to copy the whnp into the vp?

A: You can move WHNP to the desired location as shown below:

% rules

sbarq(sbarq(WHNP, SQ)) --> whnp(WHNP), sq(WHNP, SQ).
whnp(whnp(WP)) --> wp(WP).
sq(WHNP, sq(VBD, NP, VP)) --> vbd(VBD), np(NP), vp(WHNP, VP).
np(np(NNP)) --> nnp(NNP).
vp(WHNP, vp(VB, WHNP)) --> vb(VB).

% lexicon

wp(wp(what)) --> [what].
vbd(vbd(did)) --> [did].
nnp(nnp(thomas)) --> [thomas].
vb(vb(eat)) --> [eat].

Example:
?- phrase(sbarq(T), [what,did,thomas,eat]).
T = sbarq(whnp(wp(what)), sq(vbd(did), np(nnp(thomas)), vp(vb(eat), whnp(wp(what))))).


text:
Q: Scrapy - Connection lost in a non-clean fashion. Inconsistent across a single domain I have created a basic spider to scrape a small group of job listings from totaljobs.com. I have set up the spider with a single start URL, to bring up the list of jobs I am interested in. From there, I launch a separate request for each page of the results. Within each of these requests, I launch a separate request calling back to a different parse method, to handle the individual job URLs.
What I'm finding is that the start URL and all of the results page requests are handled fine - scrapy connects to the site and returns the page content. However, when it attempts to follow the URLs for each individual job page, scrapy isn't able to form a connection. Within my log file, it states:
[<twisted.python.failure.Failure twisted.internet.error.ConnectionLost: Connection to the other side was lost in a non-clean fashion: Connection lost.>]

I'm afraid that I don't have a huge amount of programming experience or knowledge of internet protocols etc. so please forgive me for not being able to provide more information on what might be going on here. I have tried changing the TLS connection type; updating to the latest version of scrapy, twisted and OpenSSL; rolling back to previous versions of scrapy, twisted and OpenSSL; rolling back the cryptography version, creating a custom Context Factory and trying various browser agents and proxies. I get the same outcome every time: whenever the URL relates to a specific job page, scrapy cannot connect and I get the above log file output.
It may be likely that I am overlooking something very obvious to seasoned scrapers, that is preventing me from connecting with scrapy. I have tried following some of the the advice in these threads:
https://github.com/scrapy/scrapy/issues/1429
https://github.com/requests/requests/issues/4458
https://github.com/scrapy/scrapy/issues/2717
However, some of it is a bit over my head e.g. how to update cipher lists etc. I presume that it is some kind of certification issue, but then again scrapy is able to connect to other URLs on that domain, so I don't know.
The code that I've been using to test this is very basic, but here it is anyway:
import scrapy

class Test(scrapy.Spider):

    start_urls = [
                    'https://www.totaljobs.com/job/welder/jark-wakefield-job79229824'
                    ,'https://www.totaljobs.com/job/welder/elliott-wragg-ltd-job78969310'
                    ,'https://www.totaljobs.com/job/welder/exo-technical-job79019672'
                    ,'https://www.totaljobs.com/job/welder/exo-technical-job79074694'
                        ]

    name = "test"

    def parse(self, response):
        print 'aaaa'
                yield {'a': 1}

The URLs in the above code are not being connected to successfully.
The URLs in the below code are being connected to successfully.
import scrapy

class Test(scrapy.Spider):

    start_urls = [
                    'https://www.totaljobs.com/jobs/permanent/welder/in-uk'
                    ,'https://www.totaljobs.com/jobs/permanent/mig-welder/in-uk'
                    ,'https://www.totaljobs.com/jobs/permanent/tig-welder/in-uk'
                        ]

    name = "test"

    def parse(self, response):
        print 'aaaa'
                yield {'a': 1}

It'd be great if someone could replicate this behavior (or not as the case may be) and let me know. Please let me know if I should submit additional details. I apologise, if I have overlooked something really obvious. I am using:
Windows 7 64 bit
Python 2.7
scrapy version 1.5.0
twisted version 17.9.0
openSSL version 17.5.0
lxml version 4.1.1

A: You can probably try setting a user agent and see if that changes things.
You might also try to do requests with bigger delays between them or with a proxy.
As it is a jobs website, I imagine they have some sort of anti-scraping mechanism.
This is not an amazing answer, but it is some insight I can share with you to maybe help you figure out your next steps.

A: This is a link to a blog I recently read about responsible web scraping with Scrapy. Hopefully it's helpful

A: In my case, it was caused by user agent got rejected. We should change the user agent for each request. For that, you should use scrapy fake user agent and then use this middleware to make sure it changes the user agent in each retry.
from scrapy.downloadermiddlewares.retry import *
from scrapy.spidermiddlewares.httperror import *

from fake_useragent import UserAgent

class Retry500Middleware(RetryMiddleware):

    def __init__(self, settings):
        super(Retry500Middleware, self).__init__(settings)

        fallback = settings.get('FAKEUSERAGENT_FALLBACK', None)
        self.ua = UserAgent(fallback=fallback)
        self.ua_type = settings.get('RANDOM_UA_TYPE', 'random')

    def get_ua(self):
        '''Gets random UA based on the type setting (random, firefox…)'''
        return getattr(self.ua, self.ua_type)

    def process_response(self, request, response, spider):
        if request.meta.get('dont_retry', False):
            return response
        if response.status in self.retry_http_codes:
            reason = response_status_message(response.status)
            request.headers['User-Agent'] = self.get_ua()
            return self._retry(request, reason, spider) or response
        return response

    def process_exception(self, request, exception, spider):
        if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
                and not request.meta.get('dont_retry', False):
            request.headers['User-Agent'] = self.get_ua()
            return self._retry(request, exception, spider)


text:
Q: XAML Binding Value from other Collection I really search the internet and could not find a answer.
Its hard for me to describe what i try to do. Maybe that is the reason i
could not find a answer on Stackoverflow and Google.
I have a ListBox in my Page which is bound to a ObservableCollection<Model>.
This Model has a property with a Id of another model. There is also
a Dictionary<int,SecondModel> containing the realted second models.
I could not add a property with the second model to the first model because this is a third party library.
Is it possible to get the Name property from the realated SecondModel using the collection?
Text="{Binding ???}"

Sample
public class Model
{
    public int Id { get; set; }
    public int SecondModelId { get; set; }
}

public class SecondModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SomeOtherModel
{
    public Dictionary<int,SecondModel> SecondModelCollection{ get; set; }
}

A: If you cannot play with the guts of Model class, I ll suggest wrapping the two models in a something like:
public class JoinedModel
{
  public Model FirstModel{ get; set; }
  public Model SecondModel{ get; set; }
}

 var secondModelCollection = SomeOtherModel.SecondModelCollection.Values;

 var joinedCollection = from model in firstModelCollection
                              join secondModel in secondModelCollection
                              on model.SecondModelId equals secondModel.Id
                              select new JoinedModel() { FirstModel = model, SecondModel = secondModel };

You can set the joinedCollection as the data source instead of the firstModelCollection which isgiven as ObservableCollection<Model> in the question.
Then in the binding, you can do a two level binding like Text="{Binding SecondModel.Name}"
... tho, I am assuming you can change the datasource of your view, I hope you can :)

A: I like zortkun's solution. You can also use an IValueConverter
<UserControl.Resources>
  <my:SecondValueConverter x:Name="SecondValueLookup" />
</UserControl.Resources>
  :
  :
<TextBlock Text="{Binding SecondValueId,
                  Converter={StaticResource SecondValueLookup},
                  ConverterParameter=Name}" />


text:
Q: Redirect user to another page - PHP I created a page, where user can register himself/herself. At the time of first login of user, user will redirect to add-profile page, where user can create his/her profile, after creation of profile user will redirect to another page which is account page where he/she can check his/her profile.
And my problem starts here, when the same user login his/her account second time, he/she will again redirect to add-profile page. But here i want to redirect user to account page, because user completed his/her profile page.
Does anyone know, how to achieve this? I mean what logic will be apply here.

A: There could be multiple possible solutions and it all depends on your project requirement.
A possible solution is, you can create a flag/status column in your table which says about the basic completion of user profile.
Means you can set its value to true when user has submitted some basic details that is mandatory for your project. In that case you can redirect user to some other page else redirect to add profile page.

A: The best way to achieve this is to add a new field and if the user completed the profile page set the field value as 1. After logging in you check the field and if it set to 1 redirect it to the account page. That is it

A: The solution is simple, you just have to create an extra column named as user_profile_complete in your user database table, which takes boolean values (i.e True/False). True value means user completed it's profile while False means not completed yet it's profile.By default , you have to set it's value as Flase.
So after user registeration, you know to redirect user to fill profile details page. But, when after user login,  first you have to check whether user completed it's profile or not by checking the user_profile_complete column (Note:- you can query to get user_profile_complete field value at login time or you can create separate query).If user_profile_complete is False , you have to redirect user to fill profile details page, otherwise redirect to it profile page.


text:
Q: Is there a for i in ("foo", "bar", "baz") construct in VBA? I have to iterate over a constant list of strings. As far as I know, there is no
for item in ("foo", "bar", "baz")
   doSth(item)
next item

I was wondering how I can elegantly program such a construct.

A: Elegantly? You decide.
Try:
Sub test()
    Dim x As Variant

    For Each x In Array("foo", "bar", "bas")
        Debug.Print x
    Next

End Sub

A: Your question is a bit generic, but yes, you can do that using For Each. I'll paste some code of my own, and you'll see how it can work:
Sub Example()
    Dim tempFolderStr As String
    Dim tempFullStr As String
    Dim objFolder As Object
    Dim objFile As Object
    Dim fs As Object

(...)

    Set objFolder = fs.GetFolder(tempFolderStr)

    For Each objFile In objFolder.Files
        tempFullStr = tempFolderStr & objFile.name
        Call Delete_File(tempFullStr)
    Next objFile

End Sub

This will iterate over every file it finds in the folder tempFolderStr.
I'll leave the link to the apropriate MSDN article: https://msdn.microsoft.com/en-us/library/5ebk1751.aspx


text:
Q: How to use OpenJDK 8 in Spring MVC application instead of Oracle JDK 1.8? I have developed a Spring MVC Application using the below tools and technologies and it is working fine without any issue.

*

*Spring Framework (Core, MVC & JDBC) 4.2.5.RELEASE

*Java 1.8

*Maven 3.3.9

*Eclipse IDE (Neon 2. Release 4.6.2)

*Oracle JDBC - ojdbc6 Version: 11.2.0.3

Now, I want to use OpenJDK-8 instead of Oracle JDK-8. How can we use OpenJDK in Spring MVC Project?

A: You just need to install OpenJDK on machines, where you want to build and run your projects, set JAVA_HOME to point to OpenJDK and that's it. Same for IDEs (Eclipse).
No need to change maven config since java version is not really depends on JDK vendor.


text:
Q: Ancient astronomers, planetary conjunctions, and epicycles How did ancient astronomers predict planetary conjunctions?  I know they used a system of epicycles to represent the path of planets, but finding the point and time of alignment of two planets still seems like a rather difficult problem.
Supposing just a model system of two planets each with a single epicycle (that is, they have the larger circular orbit and a smaller epicycle sub orbit), how would an ancient astronomer predict conjunctions (where their apparent positions in the sky are identical)?  That is, what algorithm were they using?  Are there any modern methods that make the problem easier (it doesn't seem to be a problem where a heliocentric solar system makes things easier).
I'm guessing that ancient mathematicians just had a lot of spare time to crunch numbers, and the algorithm was basically something primitive and numeric.  But I wonder if there's any clever mathematics involved, since there was at least 1000 years of smart guys working on the problem.

A: As explained in Wikipedia "Babylonian astronomers had developed arithmetical techniques for calculating astronomical phenomena and Greek astronomers such as Hipparchus had produced geometric models for calculating celestial motions". The oldest Astronomical Tables known were the Babylonian clay tablets which contained the future "Pythagorean theorem", the solar and lunar eclipses, the length of the year with an error of 0.001% only and so on. Hipparcus and the Greeks borrowed much from the Babylonians as well as Ptolemy after them. Ptolemy's very precise observations appeared in his famous Almagest (all the trigonometry required was in his books) and these precise tables were only superseded in 1551 by Kepler's Rudolphine Tables using Brahe's as well as his own observations and computations (reinterpreted with his three laws and introducing the recent logarithms). Of course exact Astrologic predictions required such tables! ;-) Titles of Ptolemy's book are revealing.
Concerning the Greeks some centuries B.C. they could have used the very interesting (Angela and pedja's link) Antikythera and other mechanisms.


text:
Q: Why is $\mathbb{E}\left(Z|X\right)$ a "fair" estimate for $Z$?
In statistics, a natural initial estimate for a random variable $Z$, is its conditional mean with some given random variable $X$ that is, $\mathbb{E}\left(Z|X\right)$.

With regard to why this is a "good enough" estimate, I am not sure what to make of the following- whether it is complete or even correct:
$$\mathbb{E}\left[\mathbb{E}\left(Z|X\right)\right]=\mathbb{E}\left(Z\right)$$
This is equivalent to saying that $\mathbb{E}\left(Z|X\right)$ is an unbiased estimate of $\mathbb{E}\left(Z\right)$.

A: This is called the law of total expectation. It is correct (provided $\Bbb E(Z)$ is defined).


text:
Q: Cannot get login button positioned correctly in navbar
The button that is labelled "Login" needs to be pushed to the right of the navbar and lined up properly with other buttons. Here is a jfiddle to see what it's doing. I am using bootstrap to design this and am having trouble with positioning of certain buttons.
 https://jsfiddle.net/sterlingmd17/tk17zjfq/1/

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Project name

 Home

 Order form

 About Swirlz

 Contact

            <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Login
            </button>

A: First, move the button div outside of the unordered list tags, then add the classes navbar-form and navbar-right to the button div.
It should look like this

 Home

 Order form

 About Swirlz

 Contact

    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Login
    </button>


text:
Q: what is the user agent string (github api) So, I'm attempting to make an HTTP request to github to return a list of all the issues on a particular github repository. I'm using coffeescript in my code below but it should be fairly self explanatory for any JS developer. my confusion is that if I enter "https://api.github.com/repos/username/repo-name/issues" into my browser I can retrieve all of the info that I'm looking for. I get an error saying "Missing or invalid User Agent string" when I try to make the request through my application with the request node library. Please let me know if you know how to properly structure a URL to actually retrieve information from the github API.
githubUrl = "https://api.github.com/repos/#{username}/#{repoName}/issues?state=open"

    request githubUrl, (error, response, body) ->

        console.log body

A: You need to pass a user agent string like it says :)  I just pulled one from chrome:
require( 'https' )
    .get({
         hostname : 'api.github.com'
        ,    path :'/repos/cwolves/jquery-imask/issues'
        , headers : {
            'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36'
        }
    }, function(res){
        res.on('data',function(data){
            console.log(data+'');
    });
});


text:
Q: Accessing ADLS Gen2 public container from the C# SDK I am unable to access a public container using the C# SDK, even though I have enabled "Allow Blob public access" in the storage account configuration.
var fileSystemClient = new DataLakeFileSystemClient(new Uri("https://somestorageaccount.dfs.core.windows.net/public"), new DataLakeClientOptions());
var paths = fileSystemClient.GetPaths();
foreach (var path in paths)
{
    Console.WriteLine(path);
}

This code throws the following exception:

Azure.RequestFailedException: 'Server failed to authenticate the
request. Make sure the value of Authorization header is formed
correctly including the signature.

Is there anything I can configure to make this work?

A: I tried in my environment and got below results:
Initially, I created ADLS gen2 container with public access level set to container level.
Portal:

When I try to access the file through browser, I got same error.
Browser:

When we are accessing through file system, Files kept in storage system are not accessible anonymously. It is necessary to authorize access even if it is public Access level. You are getting this error because you are attempting to access the resource without authorization.
If you need to access files, you need to authorize with SAS token.
I tried with File URL + SAS token in the browser. I can be able to access the file.
You can get SAS-token by clicking file with generate SAS token.

Browser:

If you need access path of data lake gen 2 in C#, you use the StorageSharedKeyCredential method by this link:
string storageAccountName = StorageAccountName;
string storageAccountKey = StorageAccountKey;
Uri serviceUri = StorageAccountUri;

StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);
DataLakeServiceClient serviceClient = new DataLakeServiceClient(serviceUri, sharedKeyCredential);
DataLakeFileSystemClient filesystem = serviceClient.GetFileSystemClient(Randomize("sample-filesystem-list"));
List<string> names = new List<string>();

foreach (PathItem pathItem in filesystem.GetPaths())
    {
     names.Add(pathItem.Name);
     }

Reference:
java - How to get list of child files/directories having parent DataLakeDirectoryClient class instance - Stack Overflow in java by Jim Xu.


text:
Q: How can I push a new value to a sub array in php? I have multiple posts with the same title but each one has a unique id. I am trying to make a new array with a title key and id key where id holds an array of the ids. My plan is to then loop over that new array to display my post data. I keep running into 2 problems:

Warning: array_push() expects parameter 1 to be array, null given in ..
Warning: Attempt to modify property 'ID' of non-object in ..

//args
    $args = array(
        'post_type' => 'event',
        'post_status' => 'publish',
        'posts_per_page' => -1,
    );

    // The Query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) {

        $stack = [];

        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $title= get_the_title();
            $id= get_the_ID();

            //logic not working
            if(!in_array($title, $stack)) {
                array_push ($stack, array(
                    'title' => $title,
                    'ID' => array($id)
              ));
            }

            if(in_array($title, $stack)) {
                array_push ($stack->ID, $id); //error here
            }
        }
        print_r($stack);
    }
    wp_reset_postdata()

A: // The Query
        $the_query = new WP_Query( $args );

        // The Loop
        if ( $the_query->have_posts() ) {

            $titles = [];
            $ids = [];
            $day_starts = [];
            $day_ends = [];
            $time_ends = [];
            $time_starts = [];
            $ods = [];
            $vids =[];
            $imgs = [];
            $links = [];
            $lss = [];
            $cats = [];

            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $title= get_the_title();
                $id= get_the_ID();
                $vid = 0;
                $od = 0;
                $ls = 0;
                $img = get_the_post_thumbnail_url();
                $link = get_the_permalink();
                $cat = get_the_terms($id, 'event-categories');

                $post_options = get_post_meta( get_the_ID(), 'post_options')[0];
                print_r($post_options);

                if(isset($post_options['on_demand'])){ $od = 1;}
                if(!isset($post_options['on_demand']) && $post_options['featured_video'] !== ''){ $ls = 1;}
                if($post_options['featured_video'] !== ''){ $vid = 1;}

                $startDate = /* str_replace('-', '',  */get_post_meta( get_the_ID(), '_event_start_date')[0];
                $startTime = /* str_replace(':', '',  */get_post_meta( get_the_ID(), '_event_start_time')[0];
                $endDate = /* str_replace('-', '',  */get_post_meta( get_the_ID(), '_event_end_date')[0];
                $endTime = /* str_replace(':', '',  */get_post_meta( get_the_ID(), '_event_end_time')[0];

                array_push ($titles,$title);
                array_push ($ids, $id);
                array_push ($day_starts, $startDate);
                array_push ($day_ends, $endDate);
                array_push ($time_starts, $startTime);
                array_push ($time_ends, $endTime);
                array_push ($ods, $od);
                array_push ($vids, $vid);
                array_push ($lss, $ls);
                array_push ($imgs, $img);
                array_push ($links, $link);
                array_push ($cats, $cat[0]->name);

            }
        }
        wp_reset_postdata();

        $unique = array_unique($titles);
if($unique){
        foreach($unique as $name){
            $data[] = array_merge(['title' => $name ], array(
                'ID' => array_merge(array_intersect_key($ids, array_intersect($titles, [$name]))),
                'vid' => array_merge(array_intersect_key($vids, array_intersect($titles, [$name]))),
                'od' => array_merge(array_intersect_key($ods, array_intersect($titles, [$name]))),
                'start_day' => array_merge(array_intersect_key($day_starts, array_intersect($titles, [$name]))),
                'end_day' => array_merge(array_intersect_key($day_starts, array_intersect($titles, [$name]))),
                'start_time' => array_merge(array_intersect_key($time_starts, array_intersect($titles, [$name]))),
                'end_time' => array_merge(array_intersect_key($time_ends, array_intersect($titles, [$name]))),
                'link' => array_merge(array_intersect_key($links, array_intersect($titles, [$name]))),
                'media' => array_merge(array_intersect_key($imgs, array_intersect($titles, [$name]))),
                'ls' => array_merge(array_intersect_key($lss, array_intersect($titles, [$name]))),
                'cat' => array_merge(array_intersect_key($cats, array_intersect($titles, [$name])))
            ));
        }
    }
?>


text:
Q: "For no other reason than" vs. "for no other reason that" vs. "for no other reason than that" I am looking for a comprehensive analysis of these three constructions:

*

*... for no other reason than X.

*... for no other reason that X.

*... for no other reason than that X.

Which is used when? Is this a question of register, dialect, style? How does the usage depend on what X is? Which of the constructions is the oldest, and what is the linguistic reasoning behind the other two variations coming about and happily co-existing — reanalysis, corruption, eggcorning?
I searched the Language Log, but to no avail. Google is of no real help, either — it returns few promising results, which upon closer examination turn out to be unrelated to the question at hand.

A: It seems to me that

For no other reason than

takes a nominal complement, and if what follows is a NP (eg your intransigence) it is simply used.
When the complement is a clause, it needs the complementiser "that", (eg that I want to)
Your number 2, on the face of it, makes no sense to me, but I would be quite prepared to believe that people say it for number 3.


text:
Q: Strange Logisim error; subcircuit does not work in main I have created a subcircuit that decides if a 3-bit signed binary digit A is larger than a 3-bit signed binary digit B. It works correctly in its subcircuit file.
It does not, however, work when added to my main. I have even added it to main and isolated it from the rest of the main circuit, and fed it inputs identical to the test inputs I tried in the subcircuit. in order to confirm it's not an error in my main, but this also does not give the right output.
I am using Logisim; is this potentially a Logisim error? The first picture is the subcircuit, the second is the subcircuit implemented in the main in isolation.

A: unfortunately I was not able to solve this error even after getting help from some people much more knowledgeable than me. I believe that logisim was acting up. Instead I re-built the circuit with an initial subcircuit that checks the most weighty position which is a sign. If the signs are euqal, it moves on to another subcircuit for comparing bits. Each subcircuit has three outputs, A>B, equal, and A<B. Depending on which outputs have a value, a series of AND and OR gates will determine if A>B such that the entire subcircuit only has that one output. Thank you for taking time to look this over!


text:
Q: Recovering Thunderbird mail after a Windows 7 upgrade I installed Windows 7 over Windows XP and forgot to backup my emails. I still have the Thunderbird profile folder saved in Documents and Settings though.
How do I go about recovering all my mail and messages from the profile folder?

A: Based on About.com's How to Restore a Mozilla Thunderbird Profile from a Backup Copy:
To restore your Mozilla Thunderbird Profile from a certain location:
First, create a new profile in Mozilla Thunderbird. You will overwrite this new profile with your  data you want to recover or copy. If your current default profile does not contain any data you want to preserve, this step is not necessary, and you can overwrite that profile

*

*Make sure Mozilla Thunderbird is not running.

*On Windows, select Run... from the Start menu and type "thunderbird.exe -profilemanager". Click OK.

*Click Create Profile....

*Click Next.

*Type "Restoration Profile" under Enter new profile name:.

*Note the path given under Your user settings, preferences, bookmarks and mail will be stored in:.

*Click Finish.

*Click Exit.

Now, it's time to copy the files:

*

*Open the folder containing your Mozilla Thunderbird profile backup.

*Highlight and copy all files.

*Open the desired new profile directory.

*

*Make sure you choose the folder noted when you created your restoration profile. The folder name should end in ".Restoration Profile" if you created a specific profile or ".default" if you want to overwrite your current default profile.

*Highlight all files and move them to the trash.

*Paste the files copied from your backup location.

If you created a special "Restoration Profile" profile, you can rename it after the process above.

A: I just had the same problem, I followed the indications in mozillazine:how to move your profile and worked wonderfully. Short version:

*

*Locate the data directory of your profile, usually in AppData\Local\Thunderbird\Profiles

*exit Thunderbird

*Launch the Thunderbird profile manager: Thunderbird -profilemanager

*Create profile -> choose folder, then select the one you located in point 1 and click finish

*Select the newly created profile and Start Thunderbird (or "Exit")

*You are good to go

Please note that if Thunderbird shows partial data or some folders appear empty when they shouldn't, it might be due to other reasons


text:
Q: Pandoc adds extra paragraph breaks I use pandoc to convert Markdown to Latex. My problem is that pandoc adds extra paragraph breaks around begin/end environments.
Source:
**First** phrase in a paragraph.
\begin{multline*}
some long formulae
\end{multline*}
Second phrase in a paragraph.

Doing pandoc my.md -o my.tex yields:
\textbf{First} phrase in a paragraph.

\begin{multline*}
some long formulae
\end{multline*}

Second phrase in a paragraph.

Clearly this is inappropriate behavior due to extra vertical space put by latex in resulting PDF when it sees extra blank lines around multline.
Is there a way to suppress extra blank lines in .tex output of pandoc?

A:

Modification:
**First** phrase in a paragraph.
\empty{
\begin{multline*}
some long formulae
\end{multline*}
}
Second phrase in a paragraph.

parses to
\textbf{First} phrase in a paragraph. \empty{
\begin{multline*}
some long formulae
\end{multline*}
} Second phrase in a paragraph.

A: What about:
**First** phrase in a paragraph. \begin{multline*}
some long formulae
\end{multline*} Second phrase in a paragraph.

pandoc -t latex with the above input and pandoc 2.2.1 gives:
\textbf{First} phrase in a paragraph. \begin{multline*}
some long formulae
\end{multline*} Second phrase in a paragraph.


text:
Q: What Is The PostgreSQL Equivalent To SQL Server NVARCHAR? If I have fields of NVARCHAR (or NTEXT) data type in a Microsoft SQL Server database, what would be the equivalent data type in a PostgreSQL database?

A: Standard TEXT datatype is perfectly fine for it.

A: I'm pretty sure postgres varchar is the same as Oracle/Sybase/MSSQL nvarchar even though it is not explicit in the manual:
http://www.postgresql.org/docs/7.4/static/datatype-character.html
Encoding conversion functions are here:
http://www.postgresql.org/docs/current/static/functions-string.html
http://www.postgresql.org/docs/current/static/functions-string.html#CONVERSION-NAMES
Example:
create table
nvctest (
utf8fld varchar(12)
);
insert into nvctest
select convert('PostgreSQL' using ascii_to_utf_8);
select * from nvctest;

Also, there is this response to a similar question from a Postgresql rep:

All of our TEXT datatypes are
  multibyte-capable, provided you've
  installed  PostgreSQL correctly.
  This includes: TEXT (recommended)
  VARCHAR CHAR

A: Short answer: There is no PostgreSQL equivalent to SQL Server NVARCHAR.
The types of NVARCHAR(N) on different database are not equivalent.
The standard allows for a wide choice of character collations and encodings/character sets. When dealing with unicode PostgreSQL and SQLServer fall into different camps and no equivalence exists.
These differ w.r.t.

*

*length semantics

*representable content

*sort order

*padding semantics

Thus moving data from one DB system (or encoding/character set) to another can lead to truncation/content loss.
Specifically there is no equivalent between a PostgreSQL (9.1) character type and SQL Server NVARCHAR.
You may migrate the data to a PostgreSQL binary type, but would then loose text querying capabilities.
(Unless PostgreSQL starts supporting a UTF-16 based unicode character set)

*

*Length semantics

N is interpreted differently (Characters, Bytes, 2*N = Bytes) depending on database and encoding.
Microsoft SQL Server uses UCS2 encoding with the VARCHAR length interpreted as UCS-2 points, that is length*2 = bytes length ( https://learn.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql?view=sql-server-2017 ):
their NVARCHAR(1) can store 1 UCS2 Characters (2 bytes of UCS2).
Oracle UTF-encoding has the same semantics ( and internal CESU-8 storage).
Postgres 9.1 only has a Unicode UTF-8 character set (https://www.postgresql.org/docs/9.1/multibyte.html) , which, like
Oracle (in AL32UTF8 or AL16UTF16 encoding) can store 1 full UCS32 codepoints. That is potentially up to 4 bytes (See e.g
http://www.oracletutorial.com/oracle-basics/oracle-nvarchar2/  which explicitly state the NVARCHAR2(50) column may take up to 200 bytes).
The difference becomes significant when dealing with characters outside the basic multilingual plane which count as one "char unit" in utf8 ucs32 (go, char, char32_t, PostgreSQL ), but are represented as surrogate pairs in UTF-16 which count as two units ( Java, Javascript, C#, ABAP, wchar_t , SQLServer).
e.g.
U+1F60A SMILING FACE WITH SMILING EYES  will use up all space in SQL Server NVARCHAR(2).
But only one character unit in PostgreSQL.
Classical enterprise grade DBs will offer at least a choice with UTF-16 like semantics (SAP HANA (CESU-8), DB 2 with collation, SQL Anywhere (CESU8BIN), ...)
E.g. Oracle also offers what they misleadingly call an UTF-8 Collation, which is effectivly CESU-8.
This has the same length semantics, representable content as UTF-16 (=Microsoft SQL Server) and is a suitable collation used by UTF-16 based enterprise systems ( e.g. SAP R/3 ) or under a Java application server.
Note that some databases may still interpret NVARCHAR(N) as a length in byte limitation, even with a variable length unicode encoding ( Example SAP IQ ).

*Unrepresentable content

UTF-16 / CESU-8 based system can represent half surrogate pairs, while
UTF-8/UTF-32 based system can not.
This content is unrepresentable in this character set, but are a frequent occurrence in UTF-16 based enterprise systems.
(e.g. Windows pathnames may contain such non-utf-8 representable characters, see e.g. https://github.com/rust-lang/rust/issues/12056).
Thus UTF-16 is a "superset" of UTF-8/UTF-16 which is typically a killer-criteria when dealing with data from enterprise/os-systems based on this encoding ( SAP, Windows, Java, JavaScript ). Note that Javascript JSON encoding took specific care to be able to represent these characters  (https://www.rfc-editor.org/rfc/rfc8259#page-10 ).
(2) and (3) are more relevant when migration queries, but not for data migration.

*Binary sort order:

Note that binary sort order of CESU-8/UTF-16 is different than UTF-8/UTF-32.
UTF-16/CESU-8/Java/JavaScript/ABAP sort order:
U+0041  LATIN CAPITAL LETTER A
U+1F60A SMILING FACE WITH SMILING EYES
U+FB03  LATIN SMALL LIGATURE ffi

UTF-8 / UCS-32 (go) sort order:
U+0041  LATIN CAPITAL LETTER A
U+FB03  LATIN SMALL LIGATURE ffi
U+1F60A SMILING FACE WITH SMILING EYES

*Padding semantics

Padding semantics differ on databases esp. when comparing VARCHAR with CHAR content.

A: It's varchar and text, assuming your database is in UNICODE encoding. If your database is in a non-UNICODE encoding, there is no special datatype that will give you a unicode string - you can store it as a bytea stream, but that will not be a string.


text:
Q: Is there a way to get extra warnings (perl-like runtime,) for Objective-C? I've been doing some programming in perl lately, and I found that it throws a really useful warning - "Use of uninitialized value" when you try to do a compare / print / regex etc with a value that you somehow didn't initialize yet, (along with a host of other things I always didn't mean to do) and it got me wondering if there is some kind of extension or something that can give me some extra useful warnings in Objective-C?
I know with things like swizzling it would be possible to generate some runtime warnings, maybe with some clever code magic you could find a way to make Nil yell at you from time to time even, although that's tough because nil pointers need to evaluate false.
Taking it to an extreme I even think (not to start a debate here) it would be great if I could get a warning when I don't have an "else" statement at the end of a decision structure.
So to put this in a bit of a two-part question, how much of this is possible, and how much of it exists?

A: Yes, it depends on the compiler.  Assuming you're using GCC, there's a host of warning options that you can enable.  Compiling with the -Wall -Wextra -pedantic options is a good choice—if your code compiles warning-free with those options, that's a great start (though of course it does not guarantee defect-free code).
If you're using Xcode as a frontend to GCC, then you can enable those warning options via the project settings.