text:
Q: Anyone else having package-problems with their old Code on a new laptop? I am facing the following Problem. I am using a preambel in LaTex that I need for a specific Type of document for my university. However I am not able to use the exact same code on a different Laptop. I use MiKTeX together with TeXstudio. I uninstalled and installed both of them multiple times and tried to use the Code in TeXlive to no avail. I even set up a virtual machine with Ubuntu to determine if the error is a windows-problem. No its not. I get the exact same error message. I have multiple friend who use the same code as preambel and have no problems, just as me on my old laptop. The error is:
"Command \ifpdftex already defined. }"
I think there most have been a change in the packages I am using, so only old versions work ( which all of us are using, since we installed it 6 months ago ). The error seems to appear in pdfcprot.sty in line 703, which I cant remove since its appearently eesential. I am very new to the subject and really dont understand my mistake. Here is my preamble:

\documentclass[
    a4paper,
    12pt,
    twoside,
    headsepline,
    footsepline,
    captions=tableheading,
    numbers=endperiod,
]{scrartcl}
\brokenpenalty=10000

%\usepackage[style=chem-acs]{biblatex}
\usepackage{floatrow}
\floatsetup[table]{style=plaintop}
\floatsetup[longtable]{LTcapwidth=table}
\usepackage{siunitx}
\sisetup{exponent-product = \cdot, output-product = \cdot, separate-uncertainty=true}
\usepackage[ngerman]{babel}
\usepackage{grffile}
\usepackage{graphicx}
\usepackage[dvipsnames]{xcolor}
\usepackage{chemfig}
\definesubmol\nobond{-[3,0.2,,,draw=none]}
\usepackage{pgfplots}
\usetikzlibrary{babel}
\usepackage{amsmath}
\usepackage{calc}
\usepackage{FP}
\usepackage{placeins}
\usepackage{pgfplotstable}
\usepackage{verbatim}
% recommended:
\usepackage{booktabs}
\setlength\heavyrulewidth{0.4pt} %Dicke der Linien am Anfang und Ende jeder Tabelle
\setlength\lightrulewidth{0.4pt} %Dicke der Linien nach header
\usepackage{array}
\usepackage{colortbl}
\usepackage{csvsimple}
\usepackage{amssymb}
\usepackage{longtable}
\usepackage{geometry}
\usepackage{enumerate}
\usepackage{ae}
\usepackage[activate]{pdfcprot}
\usepackage{setspace}
\usepackage{fontspec}
%\usepackage[utf8]{inputenc}
\usepackage{scrlayer-scrpage}
\usepackage{mhchem}
\usepackage{subcaption}
\usepackage{caption}
\captionsetup{labelfont={bf,it},tablename=Tab.,figurename=Abb.}
\captionsetup[table]{singlelinecheck=false,justification=justified}
\captionsetup[figure]{justification=justified}

%\usepackage[nolist]{acronym}           Acronymverzeichnis
\usepackage{svg}

\renewcommand*\figureformat {\figurename~\arabic{section}.\arabic{subsection}.\thefigure.}
\renewcommand*\tableformat {\tablename~\arabic{section}.\arabic{subsection}.\thetable:}
\renewcommand*\captionformat {~}

\pgfplotstableset{
every head row/.style={before row=\toprule,after row=\midrule[0.4pt]},
every last row/.style={after row=\bottomrule}}

\let\oldcite\cite
\renewcommand*\cite[1]{\textsuperscript{\oldcite{#1}}}

\sisetup{group-digits=true,
    group-four-digits=true,
    group-separator = {\,},
    output-decimal-marker = {.}}

\pgfplotsset{
    siunitxlabels/.style={
        /pgfplots/typeset ticklabel/.code={\pgfmathparse{\tick}$\num[zero-decimal-to-integer]{\pgfmathresult}$},
    },
}

\makeatletter
\renewcommand*\bib@heading{\subsubsection{\bibname}
\@mkboth{\subsubsectionmarkformat \bibname}{\subsubsectionmarkformat \bibname}}
\makeatother
\addto\captionsngerman{\renewcommand*\bibname{Literatur}}

\usepackage{prettyref}                       x.x.# anpassen
%%% Für Abbildungen %%%
\newrefformat{fig}{Abb.~\arabic{section}.\arabic{subsection}.\ref{#1}}
%%% Für Tabellen %%%
\newrefformat{tab}{Tab.~\arabic{section}.\arabic{subsection}.\ref{#1}}
%%% Für Formeln
\newrefformat{eq}{Gl.~\arabic{section}.\arabic{subsection}.\ref{#1}}
%%% Für chem. Formeln
\newrefformat{ceq}{Gl.~\ref{#1}}

\usepackage[
    linkcolor=black,
    citecolor=black,
    urlcolor=black,
    colorlinks=true,
]{hyperref}
%\renewcommand\citeform[1]{[#1]}

\usepackage{titlesec}

\titleformat{\section}
{\normalfont\Large\bfseries}{\arabic{section}.}{1.5em}{}
\titleformat{\subsection}
{\normalfont\LARGE\bfseries}{\arabic{section}.\arabic{subsection}.}{1.2em}{}
\titleformat{\subsubsection}
{\normalfont\Large\bfseries}{\arabic{section}.\arabic{subsection}.\arabic{subsubsection}.}{0.75em}{}

\setkomafont{sectioning}{\bfseries}     %Serifenschrift in Überschriften
\setkomafont{section}{\LARGE}
\setkomafont{subsection}{\LARGE}
\setkomafont{subsubsection}{\large}
\pagenumbering{arabic}
\geometry{left=3cm, right=2cm, top=2.5cm, bottom=2cm}
\parindent 0pt
\setlength{\parindent}{0pt}
\parskip 12pt
\onehalfspacing
\pagestyle{scrheadings}
\headsep0.4cm
\footskip0.8cm
\urlstyle{same}

\RedeclareSectionCommand[
%runin=false,
afterindent=false,
beforeskip=\baselineskip,
afterskip=.5\baselineskip]{section}
\RedeclareSectionCommand[
%runin=false,
afterindent=false,
beforeskip=.75\baselineskip,
afterskip=.5\baselineskip]{subsection}
\RedeclareSectionCommand[
%runin=false,
afterindent=false,
beforeskip=.5\baselineskip,
afterskip=.25\baselineskip]{subsubsection}

I woul really appreciate any help. Thanks !
Best Regards


text:
Q: How can i summerize posts or news automatically in word press site? Is there any module or sample code for summerize post by intelligence algorithms?
I want to summerize 1000 last posts automatically

A: The Summy: Excerpt Extraction WordPress plugin has well documented code to use the Sum+my algorithms.
Instead of looking for a solution that is already used in WordPress, you might find more solutions by searching for PHP solutions that summarize articles and then integrating them into WordPress. WordPress provides a filter that can be used to edit the content for a summary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerShell :: click on href="javascript:;" and download document I'm writing a script in PowerShell that can allows me to login into this page and download a file.
The login is done, but I now have a new problem: the .zip file I want to download doesn't have a plain text URL but instead is generated by JavaScript. If I inspect the element this is what I see:
post_adressdaten 2021-09-07 == $0

That link doesn't has a Tag or an ID therefore I cannot click on it.
Even if I click on it then the browser will ask to save and I don't know how to proceed.
You can create an account and login to that page if you want to inspect by yourself.
Any help will be much appreciated.

A: The workaround was to search in the page for the text and click on it:
$link = $ie.Document.getElementsByTagName('A') | where-object {$_.innerText -like 'post_adressdaten*'}
$link.click()

This the whole


text:
Q: How to make Tiny MCE return empty string if textarea is left blank I am currently using Tiny MCE in one of my forms to enter information into a MySQL database and the textarea, replaced by the TinyMCE plugin, is optional so if the user doesnt have to fill it.
But checking the POST data sent, the textarea variable has default HTML tags, how can I configure Tiny MCE to return nothing if the textarea is left blank.
Thanks


text:
Q: How do I query with JSON function/operator where key is either not null or is null? I am looking for the active record version of the following sql code:
select *
from users
where (details->'email') is not null

Let's say that my User model has a json field called, details, and some records will have an email key-value and some will not. I'm trying to query the user records that have an email, key-value. I tried using the following, User.where("details->'email' is not null"), but my terminal prints out this:
PG::UndefinedFunction: ERROR:  operator does not exist: json -> boolean

I found this SO post, which attempts to do the opposite query, but the idea is the same. If someone can show me the Active Record version of querying where a json key is or is not present, I'd greatly appreciate it.

A: This worked for getting users with an email key:
User.where("(details->'email') is not null")

This worked for getting users without an email key:
User.where("(details->'email') is null")


text:
Q: Can I use 'a' instead of 'the' here? In this blog, there is a sentence as follows.

Here's an example of the low angle camera angle.

Can I change the word 'the' to 'a'? Which is better and why?

A: It depends. Both are possible, depending on the context. The question is whether we know which low camera angle is being referred to (requiring the) or whether it can be any low camera angle (requiring a). (You don't need to use angle twice.)
Look at the following illustrations:
Here is an example of a low camera angle that works well. Can refer to any low camera angle that works well.
Here is an example of the low camera angle used in the love scene. Refers to a particular angle that is identified.
Here is an example of a low camera angle, shot against a dark background. Can refer to any example.
Here is an example of the low camera angle used by director X in his movie. Refers to a specific angle.
So a low camera angle is any low camera angle; and the low camera angle is a particular low camera angle that is identified, either beforehand or in the sentence itself.


text:
Q: Calculating CPU Performance in MIPS i was taking an exam earlier and i memorized the questions that i didnt know how to answer but somehow got it correct(since the online exam using electronic classrom(eclass) was done through the use of multiple choice.. The exam was coded so each of us was given random questions at random numbers and random answers on random choices, so yea)
anyways, back to my questions..
1.)
There is a CPU with a clock frequency of 1 GHz. When the instructions consist of two
types as shown in the table below, what is the performance in MIPS of the CPU?
           -Execution time(clocks)- Frequency of Appearance(%)

Instruction 1         10                     60
Instruction 2         15                     40
Answer: 125
2.)
There is a hard disk drive with specifications shown below. When a record of 15
Kbytes is processed, which of the following is the average access time in milliseconds?
Here, the record is stored in one track.
[Specifications]
Capacity: 25 Kbytes/track
Rotation speed: 2,400 revolutions/minute
Average seek time: 10 milliseconds
Answer: 37.5
3.)
Assume a magnetic disk has a rotational speed of 5,000 rpm, and an average seek time of 20 ms.  The recording capacity of one track on this disk is 15,000 bytes.  What is the average access time (in milliseconds) required in order to transfer one 4,000-byte block of data?
Answer: 29.2
4.)
When a color image is stored in video memory at a tonal resolution of 24 bits per pixel,
approximately how many megabytes (MB) are required to display the image on the
screen with a resolution of 1024 x768 pixels? Here, 1 MB is 106 bytes.
Answer:18.9
5.)
When a microprocessor works at a clock speed of 200 MHz and the average CPI
("cycles per instruction" or "clocks per instruction") is 4, how long does it take to
execute one instruction on average?
Answer: 20 nanoseconds
I dont expect someone to answer everything, although they are indeed already answered but i am just wondering and wanting to know how it arrived at those answers. Its not enough for me knowing the answer, ive tried solving it myself trial and error style to arrive at those numbers but it seems taking mins to hours so i need some professional help....

A: 1.)
n = 1/f = 1 / 1 GHz = 1 ns.
n*10 * 0.6 + n*15 * 0.4 = 12 ns (=average instruction time) = 83.3 MIPS.
2.)3.)
I don't get these, honestly.
4.)

Here, 1 MB is 10^6 bytes.

3 Bytes * 1024 * 768 = 2359296 Bytes = 2.36 MB
But often these 24 bits are packed into 32 bits b/c of the memory layout (word width), so often it will be 4 Bytes*1024*768 = 3145728 Bytes = 3.15 MB.
5)
CPI / f = 4 / 200 MHz = 20 ns.


text:
Q: Get df subset based on condition applied to the list item I would like to loop over the group of items and use that to check condition for subsetting dataframe. My code throws error right now. I want to check if each item in en_nam1 passes en1$attributes == item. If it passes the condition then I want to select the row and add in another dataframe to return. Thank you.
A tibble: 3 x 2
  attributes models
  <chr>      <list>
1 AT01S      <chr [2]>
2 AT02S      <chr [2]>
3 AGG101     <chr [1]>
4 AGG102     <chr [1]>
5 AGG103     <chr [1]>
6 AGG104     <chr [1]>

en_nam1
[1] "AT01S"  "AT02S"  "AGG101"

My code:
 en_nam1 %>%
+ map(~subset(en1, en1$attributes == .x))

Expected result:
 A tibble: 3 x 2
  attributes models
  <chr>      <list>
1 AT01S      <chr [2]>
2 AT02S      <chr [2]>
3 AGG101     <chr [1]>

A: We don't need a loop here.  It is more direct with %in%
library(dplyr)
en1 %>%
  filter(attributes %in% en_nam1)

or subset in base R
subset(en1, attributes %in% en_nam1)


text:
Q: Extremely Slow Processing on Dataproc 9 hours vs 3 mins on local machine From the log I can see that there are 182k rows 70MB. It take 1.5 hours  load 70MB of data and 9 hours (Started at 15/11/14 01:58:28  and ended at 15/11/14 09:19:09) to train 182K rows on Dataproc. Loading the same data and running the same algorithm on my local machine takes 3 mins
DataProc Log
15/11/13 23:27:09 INFO com.google.cloud.hadoop.io.bigquery.ShardedExportToCloudStorage: Table 'mydata-data:website_wtw_feed.video_click20151111' to be exported has 182712 rows and 70281790 bytes
15/11/13 23:28:13 WARN akka.remote.ReliableDeliverySupervisor: Association with remote system [akka.tcp://sparkExecutor@rc-spark-poc-w-1.c.dailymotion-data.internal:60749] has failed, address is now gated for [5000] ms. Reason: [Disassociated]

15/11/14 01:58:28 INFO com.dailymotion.recommender.BigQueryRecommender: Fetching the Ratings RDD
15/11/14 01:58:28 INFO com.dailymotion.recommender.BigQueryRecommender: Transforming the video feature matrix
15/11/14 01:58:28 INFO com.dailymotion.recommender.BigQueryRecommender: Training ALS Matrix factorization Model

[Stage 2:=============================>                             (1 + 1) / 2]

15/11/14 09:19:09 WARN com.github.fommil.netlib.BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeSystemBLAS
15/11/14 09:19:09 WARN com.github.fommil.netlib.BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeRefBLAS

15/11/14 09:19:44 INFO com.dailymotion.recommender.BigQueryRecommender: Transforming the video feature matrix
15/11/14 09:19:44 INFO com.dailymotion.recommender.BigQueryRecommender: Transforming the user feature matrix

*

*Copied the data to local machine
r.viswanadha$ gsutil cp -r gs://<mycompany>-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000 .

Copying gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-0/data-000000000000.json...

Downloading ...201511132327_0000/shard-0/data-000000000000.json: 141.3 MiB/141.3 MiB

Copying gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-0/data-000000000001.json...

Copying gs://<mycompany>-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-1/data-000000000000.json...`

*Ran the same Algorithm. ALS Train step took ~3 mins
com.dailymotion.recommender.BigQueryRecommender --app_name BigQueryRecommenderTest --master local[4] --input_dir /Users/r.viswanadha/Documents/workspace/rec-spark-java-poc/input/job_201511132327_0000/shard-0/

First Run
15/11/14 13:19:36 INFO BigQueryRecommender: Training implicit features for the ALS Matrix factorization Model
...
15/11/14 13:22:24 INFO BigQueryRecommender: Transforming the video feature matrix

Second Run
15/11/14 13:29:05 INFO BigQueryRecommender: Training implicit features for the ALS Matrix factorization Model

...

15/11/14 13:31:57 INFO BigQueryRecommender: Transforming the video feature matrix

The DataProc cluster has  1 Master and 3 Slaves with 104GB (RAM) and 16 CPUs each.
My local machine has 8GB (RAM) and 2 CPU 2.7GHz Core i5
gsutil ls -l -r -h  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000

gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/:

gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-0/:

    0 B  2015-11-13T23:27:13Z  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-0/

    141.3 MiB  2015-11-13T23:29:21Z  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-0/data-000000000000.json

   0 B  2015-11-13T23:29:21Z  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-0/data-000000000001.json

gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-1/:

    0 B  2015-11-13T23:27:13Z  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-1/

    0 B  2015-11-13T23:28:47Z  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/shard-1/data-000000000000.json

   0 B  2015-11-13T23:27:09Z  gs://dailymotion-spark-rc-test/bqdata/hadoop/tmp/bigquery/job_201511132327_0000/

TOTAL: 6 objects, 148165416 bytes (141.3 MiB)

A: To recap some of the offline findings, when things are running orders of magnitude slower on the distributed cluster compared to a local setup, the main bottlenecks to look for are I/O round-trip-latency bottlenecks both in terms of cross-network service dependencies as well as disk and local I/O.
Things to look for in general (some of which may or may not be applicable to your specific case, but may be common to others encountering similar issues):

*

*Make sure the GCS bucket holding the data is in the same region as the GCE zone you've deployed your Dataproc cluster with gsutil ls -L gs://[your-bucket]. Cross continental traffic is not only significantly slower, but also may incur additional network costs in your project.

*If your job has any other network dependencies such as querying APIs or a separate database of some sort running on GCE, try to colocate them in the same zone; even within the same continent, GCE cross-region traffic could have tens of milliseconds of round-trip latency, which can add up significantly especially if there are per-record requests being made (for example, 30ms * 180k records comes out to 1.5 hours).

*Even though this may not have been applicable to your specific case this time, remember to avoid per-record round-trip I/O to GCS via Hadoop FileSystem interfaces if possible; overall throughput to GCS is very scalable, but by nature of remote storage, round-trip latencies are much slower than round-trip latencies you might measure on a local machine, due to local reads often hitting the OS buffer cache or if you're using a laptop with SSD being able to sustain high volumes of sub-millisecond round trips, compared to 30ms-100ms round-trips to GCS.

And in general, for use cases that can support very high throughput but suffer long round-trip latencies, make sure to shard out the data with something like repartition() if the data is small and doesn't naturally partition into sufficient parallelism already to ensure good utilization of your Spark cluster.
Finally, our latest Dataproc release fixes a bunch of native library configurations, so it may show much better performance for the ALS portion as well as other mllib use cases.

A: For anyone who hits something similar: when dealing with only a single small object in GCS (or a single shard with data from the BigQuery connector), you can end up with a single partition in your Spark RDD and as a result, end up with little or no parallelism.
While it results in an extra shuffle phase, the input RDD can be repartitioned right after reading from GCS or BigQuery to acquire the desired number of partitions. Whether the extra shuffle is beneficial is dependant on how much processing or IO is required for each record in an RDD.


text:
Q: Proving that every set in the Borel $\sigma$-algebra on $\mathbb{R}$ is Lebesgue-Stieltjes Measurable I am reading through Richard Bass's Real Analysis and on page 25 we have the following proposition, using $\alpha$ is a Stieltjes function and $m^*$ is the Lebesgue-Stieltjes outer measure on $\ell((a,b])=\alpha(b)-\alpha(a)$:

Proposition 4.7 Every set in the Borel $\sigma$-algebra on $\mathbb{R}$ is $m^*$-measurable.

The proof begins with:

It suffices to show that every interval $J$ of the form $(c, d]$ is $m^∗$-measurable. Let $E$ be any set with $m^∗(E) < \infty$; we need to show $$m^∗(E) \ge m^∗(E \cap J) + m^∗(E \cap J^c).$$ Choose $I_1, I_2, \ldots,$ each of the form $(a_i, b_i]$, such that $E \subset \cup_i I_i$ and $$m^∗(E) \ge \sum_i [\alpha(b_i) − \alpha(a_i)] − \varepsilon.\qquad(*)$$

Then via a series of calculations the proof concludes:

Thus $$m^∗(E \cap J) + m^∗(E \cap J^c) \le \sum_i m^∗(I_i) \le m^∗(E) + \varepsilon.$$ Since $\varepsilon$ is arbitrary, this proves $(*)$.

My problem with this proof is the existence of $I_1,I_2,\ldots$ that satisfy $(*)$. It seems to me that if $\varepsilon$ is sufficiently small that it may become the case that $(*)$ no longer holds for any $I_1,I_2,\ldots$.
Why is it valid to claim that we can have $I_1,I_2,\ldots$ satisfying $(*)$ for any $\varepsilon$? Or am I misunderstanding something else in this proof?
Thanks in advance.

A: This is really just a consequence of the definition of $m^*(E)$ the author gives on the page right before the theorem (all taken from the link you provided): it is defined as the inifimum over all such coverings by all such intervals. If you then assume the logical juxtaposition of (*). in other words that there is an
$\epsilon > 0$ such that
$$d:=m^∗(E) + \varepsilon \lt \sum_i [\alpha(b_i) − \alpha(a_i)] \quad (**)$$
for all such coverings, then certainly the infimum $I$ satisfies
$$m^∗(E) \lt d \le I,$$
in contradiction to the definition of $m^∗(E)$. Hence, (**) is wrong, and (*) is true.


text:
Q: InfluxDB: keep min/max values while downsampling I am pretty new to InfluxDB. I have an application that collects data with 20kHz, which is written to the database.
At some point I need to query/show this data. Currently I achieve this with:
from(bucket: "test-bucket")
   |> range(start: 0; stop: now())
   |> filter(fn: (r) => r["_field"] == "sensorValue")
   |> aggregateWindow(every: 1s, fn: mean, createEmpty: false
   |> yield(name: "mean")

The problem I do have is the mean function. I do have data, which might jump up and down quite fast. So calculating the mean value of each window is not good for me here, because it smoothes the data to much.
What I want to achieve is to get the min and max value (and its corresponding timestamp) from every window.
For example if the 'window' has the following data:
value: 10 11 10 12 13 27 10 2 10 11
time:   0  1  2  3  4  5  6 7  8  9

I want to get for max (27, 5) and for min (2,7). Is there any function doing this? Or even better, is there any other downsampling function that keeps local extreme values?
What I have tried so far:
data = from(bucket: "test-bucket")
   |> range(start: 0; stop: now())
   |> filter(fn: (r) => r["_field"] == "sensorValue")

minData = data
   |> aggregateWindow(every: 1s, fn: min, createEmpty: false)

maxData = data
   |> aggregateWindow(every: 1s, fn: max, createEmpty: false)

 |> yield()

This will draw 2 series. Is there any chance to merge them? Or is my approach just completly wrong?

A: There are two ways to do aggregateWindow for multiple functions.
One is to use reduce() to create a custom aggregate function that performs different aggregations. The problem here is that reduce() can't be pushed down and will be less performant.
The other is to create separate streams for each aggregation, AND union them together, and then pivot the data. Sample code is as below:
   data = from(bucket: "test-bucket")
       |> range(start: 0; stop: now())
       |> filter(fn: (r) => r["_field"] == "sensorValue")

   minData = data
       |> aggregateWindow(every: 1s, fn: min, createEmpty: false)

   maxData = data
       |> aggregateWindow(every: 1s, fn: max, createEmpty: false)

   union(tables: [minData, maxData])
       |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")


text:
Q: Game Center how to have two games use the same leaderboard I have a full version and a lite version of a game and i want them both to use the same leaderboard, can some one tell me how to accomplish this in iTunes connect. I've made another game using just one leaderboard but don't know how to have two games use the same leaderboard.

A: This is definitely possible, I have that with three pairs of games I have made. To this you need to go to iTunes Connect > go to your apps > go to the app > manage game center. There you will be able to add it to a group of apps. This will change the leaderboard identifier so that it has to start with "grp."
For developer information you can go to iTunes Connect Game Center Guide Groups


text:
Q: Opening facebook share dialog with populated text and url from a web-app via intent? I've been searching on Google, GitHub and StackOverflow for 2 days before I'm asking this question, but all the answers are old and outdated so I couldn't solve the problem.
For Twitter, Pinterest and Google+ I found the URL intents and they work just fine. So for example if I click this URL twitter://post?message=${fullMessage} in Safari, the native Twitter share dialog is opened with the link and the message.
Is there any documentation (from 2015-2016) that will work for the native Facebook iOS app in the same way?
Thanks!


text:
Q: Why does creating a C++11 thread cause a Fatal Signal? I want to create a C++11 thread that runs indefinitely, after a JNI call has been made. Why does this generate a Fatal Signal?
#include <thread>

static void teste()
{
    while(true)
        LOGI("IN TEST");
}

JNIEXPORT void Java_blahblah(JNIEnv *javaEnvironment, jobject self)
{
    std::thread t(teste);
    //t.join(); //I don't want to join it here.
}

I don't need the C++11 thread to call JNI or anything like that.

A: According to this answer, the destructor of the thread will call std::terminate if the thread is still joinable at time of destruction.
If you do not want to join the thread, you can fix this by detaching the thread instead.
std::thread t(teste).detach();


text:
Q: Disabling the initiation form when workflow is started manually in sharepoint 2010 I have a sharepoint site(sharepoint 2010).
I have created a custom action, on click of which will initiate the workflow associated to a list. When the user clicks on the custom action button, an initiation form will be shown which will have the Start and Cancel button. Only on click of this Start button, the workflow will Run. I want to avoid the last step of clicking on the Start button. What I want is "On click of Custom action, Workflow should Run. Initiation form should not come into picture at all". Is this possible ?

A: two solutions:

*

*Say it's good because you make sure the user didn't make a mistake

*Change the custom action form to a page where you start the workflow manually (via code) and then redirect the user to the home screen (you can also do that with a dialog and then there's no need for redirect)


text:
Q: Do we have a version of Grönwall lemma for $tLet $y(\cdot)$ be a continuous mappings defined on $[a,b]$ and $K\in (0,+\infty]$ a constant. An application of the Grönwall lemma is the following simple case: if we have for all $t\in[a,b]$
$$y(t)\leq K + \int_a^ty(s) ds ,$$
then we will have for all $t\in [a,b]$
$$y(t)\leq K e^{\int_a^tds}=Ke^{(t-a)}.
$$
My question is that do we still have such result if we change the order of the integral $\int_a^t ds$ to $\int_t^b ds$ in other words do we have the following implication:
$$\forall t\in [a,b]\; \;\;\; y(t)\leq K + \int_t^by(s) ds \implies \forall t\in [a,b]\; \;\;\;  y(t)\leq K e^{\int_t^bds}=Ke^{(b-t)}.$$

A: By taking : $z(t)=y(-t)$ for all $t\in [-b,-a]$, and changing the measure $ds=-d\tau$ we obtain
$$z(t)\leq K+\int_{-b}^t z(\tau)d\tau $$
and then by applying the classic Gronwall lemma we get that :
$$z(t)\leq Ke^{t+b} \;\; \forall t\in [-b,-a],$$
in other words
$$y(t)\leq Ke^{b-t} \;\; \forall t\in [a,b]$$


text:
Q: Como usar las rutas relativas en Linux para abrir el explorador de archivos o leer un fichero con java Hice un programa en java que puede abrir el explorador de archivos en la carpeta actual en la que se ejecuta el programa
En Windows funciona bien, el problema es que al usarlo en Linux me redirige directamente al home, y todas las rutas relativas las basa en el home.
Por ejemplo, en este codigo abro el explorador de windows en la carpeta actual donde se encuentra el archivo jar desde el que estoy ejecutando el programa:
En Windows Fuciona bien,pero en Linux solo me abre el home.
//metodo 1: usando getProperty para obtener la ruta desde la que se ejecuta el codigo
String sCarpetaActual = System.getProperty("user.dir");
File objetofile = new File(sCarpetaActual);
Desktop.getDesktop().open(objetofile);

//metodo 2: usando ruta relativa
String sCarpetaActual = ("./");
File objetofile = new File(sCarpetaActual);
Desktop.getDesktop().open(objetofile);

Lo mismo me pasa al leer o guardar ficheros, en windows me respeta las rutas relativas y guarda los ficheros dentro de la misma carpeta (o subcarpetas) pero en linux asume que se encuentra en el home.

A: Puedes utilizar un nuevo File de la siguiente manera.
File file = new File (".");

El "."  indica el directorio actual.


text:
Q: How AWS load balancer will behave in following scenario? We have two instances added to load balancer. Each instance have 2 different applications running on different app servers(port 80 & 443). We have listeners to forward request on LB's port 80 & 443 to instance port 80 & 443 respectively.
Load balancer health check is configured to ping on port 80.
Now if application running on port 443 died/crashed on instance 2, whether load balancer still continues to forward requests on port 443 of instance 2? (As instance will be in service because health check is configured for port 80)
Or
Will Load balancer come to know that no one is listening on port 443 for instance 2 and will it forwards all requests on port 443 to instance 1 from now?

A:
Load balancer health check is configured to ping on port 80

This sentence say it all. If you have configured load balancer to check for health on port 80 it will consider both the instances as healthy in the scenario you mentioned. It will keep on sending requests on port 443 of instance 2 and keep on getting error response.


text:
Q: Set a cookie from a php dynamic variable I have the below dynamic php variables.
responseId: <?php echo $checkAvailability->responseId?>

searchId: <?php echo $checkAvailability->searchId?>

totalFound: <?php echo $checkAvailability->totalFound?>

How can i post them to the next page ? I have tried the below code but the response is empty.
1st page:
<?php
$cookie_name = "searchID";
$cookie_value = "$checkAvailability->searchId";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

2nd page:
<?php
    echo "Value is: " . $_COOKIE[searchID];
?>

Could you please advise me on a safe & working method.
    - PS: i have fixed the initial issue by moving the set cookie code in the top page code.
Thank you.

A: First, you are going to want to verify that your browser's cookies are on and what not...
Secondly, if you are going to access the cookie via $_COOKIE[$cookie_name] - then you have to make sure that $cookie_name is set to the 'searchID' value which you created the cookie with.
When I run the above code, it works just fine...
You can also do things like print_r($_COOKIE); to see exactly what's going on with your cookie...
But, in some cases, you may find it more appropriate to use $_SESSION --- Remember, the values in cookies may be tampered with...

A: Solution found:
Use $_SESSION

Rules:On every page that you need to store/retrieve cookies put the start session code on the top of page code:
<?php
// Start the session
session_start();
?>

On the 1st page - Page from where we store the cookie:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>

<?php
// Set session variables
$_SESSION["searchId"] = $checkAvailability->searchId;
echo "Session variables are set.";
?>

On the 2nd page or on what page do you want to retrieve and use cookies :
<?php
    // Start the session
    session_start();
    ?>
    <!DOCTYPE html>

<?php
//in my case i wanted to use the cookies as a php variables
$searchId = $_SESSION["searchId"];
?>

http://www.w3schools.com/php/php_sessions.asp
Cheers.

A: From manual: cookies must be sent before any output from your script
http://php.net/manual/en/function.setcookie.php
Move setcookie code to the begin of script.


text:
Q: RefelectionException in Illuminate Container.php. Class Injection does not exist I was just importing this Lumen project from my local machine to an Ubuntu 14.04 VirtualBox. Both exact same code.
I've tried composer update, composer install. Also from other kind of simillar questions I've added this to the composer.json
"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
            "app/Library/recaptchalib.php",
            "app/Library/function.php"
    ],
    "classmap": [
        "database/"
    ]
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php" //added this
    ]
},

This is the full error log
ReflectionException in Container.php line 741:
Class injection does not exist

in /var/www/lumen_app_test/vendor/illuminate/container/Container.php line 741
at ReflectionClass->__construct('injection') in Container.php line 741
at Container->build('injection', array()) in Container.php line 631
at Container->make('injection', array()) in Application.php line 447
at Application->make('injection') in Pipeline.php line 123
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Application.php line 1439
at Application->sendThroughPipeline(array('injection', 'App\Http\Middleware\LanguageMiddleware', 'App\Http\Middleware\AssetVersionMiddleware'), object(Closure)) in Application.php line 1284
at Application->handleFoundRoute(array(true, array('as' => 'home', 'uses' => 'App\Http\Controllers\HomeController@index', 'middleware' => array('injection', 'language', 'asset_version')), array())) in Application.php line 1207
at Application->Laravel\Lumen\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Application.php line 1439
at Application->sendThroughPipeline(array('Illuminate\Cookie\Middleware\EncryptCookies', 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 'Illuminate\Session\Middleware\StartSession', 'Illuminate\View\Middleware\ShareErrorsFromSession'), object(Closure)) in Application.php line 1213
at Application->dispatch(object(Request)) in Application.php line 1153
at Application->run(object(Request)) in index.php line 29

The thing that made me confuse it that this app runs with no problem in my other machine.

A: Have you applied a middleware called injection anywhere? Or is it in the constructor of your HomeController? Looks like the container is looking for the definition of that middleware but can't find it (it would usually go in app/Http/Kernel.php.
If all else fails, delete /vendor and then run composer update to get a fresh copy of everything.


text:
Q: Как сделать, чтобы через определенное время генерировалось рандомное число? После загрузки страницы генерируется рамдомное число. Но мне нужно чтобы каждые 100ms оно менялось. Оно не меняется.

$(function() {
  function myRandom(from, to) {
    var empty = [];
    return Math.floor((Math.random() * (to - from + 1)) + from);
  }

  var ramd1 = myRandom(100, 1200);

  function myRandom2(from, to) {
    return Math.floor((Math.random() * (to - from + 1)) + from);
  }

  var ramd2 = myRandom2(100, 1200);

  setInterval(myRandom, 100);
  setInterval(myRandom2, 100);

  document.write(ramd1 + "
" + ramd2);
});

A: Во-первых, setInterval не умеет обрабатывать возврат функции.
Во-вторых, то что вы уже вывели в HTML не поменяется без вашего участия.
Пример, исправления кода:

$(function() {
  function myRandom(from, to) {
    return Math.floor((Math.random() * (to - from + 1)) + from);
  }

  function myRandom2(from, to) {
    return Math.floor((Math.random() * (to - from + 1)) + from);
  }

  document.write('
');

  setInterval(function(){ $('#ramd1').text( myRandom(100, 1200) ); }, 100);
  setInterval(function(){ $('#ramd2').text( myRandom2(100, 1200) ); }, 100);
});

A: попробуй так:

$(function() {
 var ramd1, ramd1;
 function myRandom(from, to, who) {
  if ( who == 1 ) {
   ramd1 = Math.floor((Math.random() * (to - from + 1)) + from);
  }
  else {
   ramd2 = Math.floor((Math.random() * (to - from + 1)) + from);
  }
 }

 setInterval( function () {
  myRandom(100, 1200, 1);
  myRandom(100, 1200, 2);
  document.write(ramd1 + "
" + ramd2);
 }, 100);
});


text:
Q: Single-precision arithmetic broken when running x86-compiled code on a 64-bit machine When you read MSDN on System.Single:

Single complies with the IEC 60559:1989 (IEEE 754) standard for binary
  floating-point arithmetic.

and the C# Language Specification:

The float and double types are represented using the 32-bit single-precision
  and 64-bit double-precision IEEE 754 formats [...]

and later:

The product is computed according to the rules of IEEE 754 arithmetic.

you easily get the impression that the float type and its multiplication comply with IEEE 754.
It is a part of IEEE 754 that multiplcation is well-defined. By that I mean that when you have two float instances, there exists one and only one float which is their "correct" product. It is not permissible that the product depends on some "state" or "set-up" of the system calculating it.
Now, consider the following simple program:
using System;

static class Program
{
  static void Main()
  {
    Console.WriteLine("Environment");
    Console.WriteLine(Environment.Is64BitOperatingSystem);
    Console.WriteLine(Environment.Is64BitProcess);
    bool isDebug = false;
#if DEBUG
    isDebug = true;
#endif
    Console.WriteLine(isDebug);
    Console.WriteLine();

    float a, b, product, whole;

    Console.WriteLine("case .58");
    a = 0.58f;
    b = 100f;
    product = a * b;
    whole = 58f;
    Console.WriteLine(whole == product);
    Console.WriteLine((a * b) == product);
    Console.WriteLine((float)(a * b) == product);
    Console.WriteLine((int)(a * b));
  }
}

Appart from writing some info on the environment and compile configuration, the program just considers two floats (namely a and b) and their product. The last four write-lines are the interesting ones. Here's the output of running this on a 64-bit machine after compiling with Debug x86 (left), Release x86 (middle), and x64 (right):

We conclude that the result of simple float operations depends on the build configuration.
The first line after "case .58" is a simple check of equality of two floats. We expect it to be independent of build mode, but it's not. The next two lines we expect to be identical because it does not change anything to cast a float to a float. But they are not. We also expect them to read "True↩ True" because we're comparing the product a*b to itself. The last line of the output we expect to be independent of build configuration, but it's not.
To figure out what the correct product is, we calculate manually. The binary representation of 0.58 (a) is:
0 . 1(001 0100 0111 1010 1110 0)(001 0100 0111 1010 1110 0)...

where the block in parentheses is the period which repeats forever. The single-precision representation of this number needs to be rounded to:
0 . 1(001 0100 0111 1010 1110 0)(001      (*)

where we have rounded (in this case round down) to the nearest representable Single. Now, the number "one hundred" (b) is:
110 0100 .       (**)

in binary. Computing the full product of the numbers (*) and (**) gives:
 11 1001 . 1111 1111 1111 1111 1110 0100

which rounded (in this case rounding up) to single-precision gives
 11 1010 . 0000 0000 0000 0000 00

where we rounded up because the next bit was 1, not 0 (round to nearest). So we conclude that the result is 58f according to IEEE. This was not in any way given a priori, for example 0.59f * 100f is less than 59f, and 0.60f * 100f is greater than 60f, according to IEEE.
So it looks like the x64 version of the code got it right (right-most output window in the picture above).
Note: If any of the readers of this question have an old 32-bit CPU, it would be interesting to hear what the output of the above program is on their architecture.
And now for the question:

*

*Is the above a bug?

*If this is not a bug, where in the C# Specifcation does it say that the runtime may choose to perform a float multiplication with extra precision and then "forget" to get rid of that precision again?

*How can casting a float expression to the type float change anything?

*Isn't it a problem that seemingly innocent operations like splitting an expression into two expressions by e.g. pulling out an (a*b) to a temprary local variable, changes behavior, when they ought to be mathematically (as per IEEE) equivalent? How can the programmer know in advance if the runtime chooses to hold the float with "artificial" extra (64-bit) precision or not?

*Why are "optimizations" from compiling in Release mode allowed to change arithmetics?

(This was done in the 4.0 version of the .NET Framework.)

A: I haven't checked your arithmetic, but I've certainly seen similar results before. As well as debug mode making a difference, assigning to a local variable vs an instance variable can make a difference too. This is legitimate as per section 4.1.6 of the C# 4 specification:

Floating point operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an "extended" or "long double" floating point type with greater range and precision than the double type, and implicitly perform all floating point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating point operations with less precision. Rather than require an implementation to forfeit performance and precision, C# allows a higher precision type to be used for all floating point operations. Other than delivering more precise results, this rarely has any measurable effects. [...]

I can't say for sure whether that's what's going on here, but I wouldn't be surprised.


text:
Q: Showing clicked product details and quantity to chat window I am working on an e-commerce project on Laravel, I want to show the details of the clicked product along with selected quantities on a real-time chat system developed using the pusher.
Scenario:
A customer visits the site(B2B E-commerce), clicks on a certain product, selects the quantity,
Clicks on (Ask Quotation button). Now I want, the chat windows to be opened with the above information

A: Be more precise in your question.
Do you want help with architecture definitions? Or do you already have something built, but with errors?
Don't get me wrong, but your question looks like you want something done.


text:
Q: Unit test for Expression tree in c# How do I write a unit test for a Expression tree in C#.
I have this class which needs to be tested. This method returns a Expression tree and also gets one as a parameter.
code:
public ExpressionStarter<SpecFinderDataModel> DoSearch(bool status, string searchValue, ExpressionStarter<SpecFinderDataModel> predicate)
{
    var localPredicate = predicate;
    if (status == false)
    {
        var searchTerms = searchValue.Split(' ').ToList().ConvertAll(x => x.ToLower());
        localPredicate = localPredicate.Or(s => searchTerms.Any(srch => s.ProductID.ToLower().Contains(srch)));
        localPredicate = localPredicate.Or(s => searchTerms.Any(srch => s.ISBN13.ToLower().Contains(srch)));
        localPredicate = localPredicate.Or(s => searchTerms.Any(srch => s.Title.ToLower().Contains(srch)));
    }
    return localPredicate;
}

Any advice would be helpful. Thanks.
Update #1
I have used LinqKit for ExpressionStarter

A: This shall be simple, though I will use the Expression<Func<SpecFinderDataModel,bool>> instead of LinqKit APIs, which is used internally, In the DoSearch method, you need Expression<Func<SpecFinderDataModel,bool>> as input, based on the method assuming following as the definition of the type SpecFinderDataModel
public class SpecFinderDataModel
{
    public string ProductID {get; set;}

    public string ISBN13 {get; set;}

    public string Title {get; set;}
}

Now you need to simply test various options, as done in regular unit test, a sample:
   // Initial Expression value constant false is the result
   Expression<Func<SpecFinderDataModel, bool>> expr = c => false;

    // SpecFinderDataModel Object
    var sfd = new SpecFinderDataModel
    {
     ISBN13 = "",
     ProductID = "Test A B C",
     Title = ""
    }

    // Call DoSearch and supply the sfd for testing
    var result = DoSearch(false,"Test",expr).Compile()(sfd);

    // Assert the result in the unit test to understand
    Assert.True(result,true);

Like this based on combinations of the DoSearch parameters and test object sfd, you can create any number of unit test cases to test your code


text:
Q: storing hierarchical application settings in web.config or app.config I need to store my application config settings in a hierarchical format in web.config or app.config. Is this possible? or I have to store it in some XML file or database and use it instead? plain name value pair format isn't enough for me.
    <appSettings>
        <Report1>
          <add key="SourceFilePath" value="value1" />
          <add key="DestinationFolderPath" value="value2" />
        </Report1>
        <Report2>
          <add key="SourceFilePath" value="value1" />
          <add key="DestinationFolderPath" value="value2" />
        </Report2>
   </appSettings>

It is a web-based reporting application and I need to store the file paths for the source files, SSIS packages, FTP server details etc.
Update: If I choose the custom config section option, can I store the settings in a separate file to keep the main web.config file clean from app settings?

A: You can't add custom elements to appSettings.
The best way to achieve a custom format it to write your own ConfigurationSettings class and use that in configuration.
This will allow you to store data in a strongly typed way as well as have meaningful element and attribute names.
See How to: Create Custom Configuration Sections Using ConfigurationSection on MSDN.

A: You can't do that as you suggest.
What you can do is to group by the key name the elements:
<appSettings>
      <add key="Report1:SourceFilePath" value="value1" />
      <add key="Report1:DestinationFolderPath" value="value2" />
      <add key="Report2:SourceFilePath" value="value1" />
      <add key="Report2:DestinationFolderPath" value="value2" />
</appSettings>

The best way though would be to define your own ConfigurationSection.
Here's some links about this:

*

*How to: Create Custom Configuration Sections Using ConfigurationSection

*Custom Configuration Sections in 3 Easy Steps

*Creating Custom Configuration Sections In ASP.NET

A: You can't store xml elements they way you suggested in appsettings.
If you need a hierarchy as you mentioned try one of the following approaches

*

*Store whole xml elements in appsettings an parse the xml
<appSettings>
  <add key="Report1" value="<Report1 SourceFilePath=""value1"" DestinationFolderPath=""value2"" />" />
  <add key="Report2" value="<Report2 SourceFilePath=""value1"" DestinationFolderPath=""value2"" />" />
</appSettings>

*Store the xml in config section (see answers above)

*Use the DslConfig project. Add it with NuGet and look add the AppSpike for examples.In your case you could create a class ReportConfig and use this class as configuration class. Example:
public class Report {
  string SourceFilePath { get; set; }
  string DesinationFolderPath { get; set; }
}

Create a config File entry in Variables.var
   import ReportClassNamespace from ReportClassAssembly

   Var["Report1"] = Report(SourceFilePath:"value1",DesinationFolderPath:"value2")
   Var["Report2"] = Report(SourceFilePath:"value1",DesinationFolderPath:"value2")

*

*Try the NConfig project

A: The best approach I know is to create your own Settings class and serialize/desiarilze it in order to read/write your app. settings.
Also you can use Admin. page of your website to save all settings into it.
May be in your case is better to use a database to keep all settings there as well.


text:
Q: one-to-many relationships with django I intend to create a teaming system, where each team may contain multiple contestants. The contestants is actually auth.User. Something similar to:
Team:
    Contestant1
    Contestant2
    .
    .
    ContestantN

Since a contestant is actually a user which I cannot modify to have a foreignkey to team. What is the best way to achieve this?
The ways I though was:

*

*Create a OneToOne profile for user which points to a team.

*Define a ManyToMany relationship between user and team where user has to be unique.

A Pause
I am redesigning the structure of my application, so I will rephrase the question again
Thanks for your replies, I will consider them and see if one of them fits.

A: You can do this:
class Team(models.Model):
    contestants = models.ManyToManyField(User, through='Contestant')

class Contestant(models.Model):
    team = models.ForeignKey(Team)
    user = models.ForeignKey(User)
    [here go Contestant data fields]

This allows one user to take part in different teams, but if you don't want to allow this, you can add unique=True to Contestant.user.

A: The best way would be to extend the functionality of default accounts and create a new user model. The new user model can then have a foreign key to team. Like this.
class UserExtended(models.Model):
    def __unicode__(self):
        return self.user.username

    user = models.OneToOneField(User, unique=True)
    team = models.ForeignKey(Team)

User.profile = property(lambda u: UserExtended.objects.get_or_create(user=u)[0])

Now you can use the "UserExtended" in place of normal User.

A: I would create a contestants field on the Team model like so:
from django.contrib.auth.models import User
contestants = models.ManyToManyField(User)

You can't specify unique=True on a ManyToManyField. The good news is that it won't add the same contestant to the same team twice so you won't need to check if the contestant is unique.

A: I would say your best bet is to create a Contestant model. You'll probably end up needing to store more information about a contestant that is team-specific but separate from a player (such as whether the contestant is a starter, the contestant's number, and so on). Creating a Contestant model allows you to store that information separate from the User, and you would have a ForeignKey in the Contestant model referencing Users, and another ForeignKey in the Contestant model referencing Teams.


text:
Q: Incomplete migration wordpress I have a website, and I had a problem with the server, I needed to migrate it, but my partner copied all the files from the FTP in a folder without doing a backup from the db, and the site I was working on is not even coded, is based on plugins, (I don't even know how it works, it is a theme and some plugins editing it).
Now the page only shows the basic theme without any of the information it has.
Is there any way to restore the site?


text:
Q: Set current system time from python on Linux and Solaris Using the below code, I can fetch the current date and time in python:
#!/usr/bin/python
import time

now = time.strftime("%c")
print "Current time %s"  % now

This will output:
Current time Mon Oct 24 09:25:17 2016

But, I need to change the system time to Mon Oct 24 11:25:17 2016 i.e. I need to set system date by adding 2 hours to existing time. Need to change the system date to 2 hours from now. (this question has been marked as duplicate, please check the question once)
This needs to be performed for Linux and Solaris hosts.
Please consider me as a python beginner and provide solutions.


text:
Q: Error: Expected resource of type anim [ResourceType] While Apk Generation While generating signed apk I got this error, When I follow the error path and found the warnings in concerned class;

and concerned animation stlye under drawable is

searched the similar topics but mine looks like a bit different how to fix it ?
I moved my animation xmls  under anim directory and fixed in every class but then I got

Error:(64) Error: Resources referenced from the manifest cannot vary by configuration (except for version qualifiers, e.g. -v21.) Found variation in tr [ManifestResource]
              android:value="@string/facebook_app_id" />

Well I fixed my problem with moving animation xmls to "anim" directory from "drawable" the following error with facebook_app_id was about the sdk version, my partner compiled it on Api 22 mine was 23 and he warned a bit late. We fixed the facebook id problem with direclty typing to the Manifest still dont understand why it causes error when I call  it "@strings/..


text:
Q: Trying to assign a string variable's value to another string variable in C# I'm new to C# and trying to code a random number generator with assigned variables. main problem is that I can't assign the value of a string variable to the other, probably because of format. (if this is long winded, sorry, it's my first time on stack overflow.) here's the code:
edit: Thanks for the help, I'll go move the variable declaration now.
using System.Collections;

internal class Program
{
    private static void Main(string[] args)
    {
        bool Running = true;
        while (Running)
        {

            string item1;
            string item2;
            string item3;
            string item4;
            string item5;
            string answer;

            item1 = "";
            item2 = "";
            item3 = "";
            item4 = "";
            item5 = "";
            answer = "";

            Console.Write("Enter item 1: ");
            item1 = Console.ReadLine();
            Console.WriteLine("Enter item 2: ");
            item2 = Console.ReadLine();
            Console.WriteLine("Enter item 3, or type null: ");
            item3 = Console.ReadLine();
            if (item3 == null) ;
            Running = false;
            Console.WriteLine("Enter item 4, or type null: ");
            item4 = Console.ReadLine();
            if (item4 == null) ;
            Running = false;
            Console.WriteLine("Enter item 5: ");
            item5 = Console.ReadLine();
            Running = false;

        }
        Random random = new Random();
        switch (random.Next(1, 6))
        {
            case 1:
                answer = item1;
                break;
        }
    }
}

A: you have a scope issue with you code, when you do a while loop (or any other function) the scope is set within the { }. This means that every variable declared within the {} of your loop is destroyed when the loop is done.
solution:
is to move declaration outside before the loop


text:
Q: What is missing in this soap request? I am trying to consume a SOAP API, here is the WSDL:http://clientes.tcc.com.co/servicios/informacionremesas.asmx?wsdl specifically the method called: ConsultarInformacionRemesasEstadosUEN
The problem is that when I make the request with a program called SoapUI I get the 200 response, but when I do it from my Laravel project I get an error. What am I doing wrong?
protected $pass ;
    protected $url;

    public function __construct($pass='APIKEY',$url="http://clientes.tcc.com.co/servicios/informacionremesas.asmx?wsdl")
    {
        $this->pass=$pass;
        $this->url=$url;
    }
    public function test()
    {
        try{
            $param=array('Clave'=>$this->pass,'numeroremesa'=>433654926,'unidadnegocio'=>1,'Respuesta'=>0);
            $client = new SoapClient($this->url,array('trace'=>TRUE));
            $response =$client->ConsultarInformacionRemesasEstadosUEN($param);
            dd($client->__getLastRequest());
            exit;
            // $array= json_decode(json_encode($response),true);
        }
        catch(Exeption $fault){
            return response()->json(['entro'=>'entro en la exepcion',"error"=>$fault->getMessage()],400);
        }
    }

I am getting the following 500 error
"message": "System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.NullReferenceException: Object reference not set to an instance of an object.\n   at ServiciosWeb.InformacionRemesas.ConsultarInformacionRemesasEstadosUEN(String Clave, List`1 remesas, List`1& remesasrespuesta, Int32& Respuesta, String& Mensaje) in C:\\TCC\\Proyectos\\Legacy\\WSNET\\2-Desarrollo\\3-Servicios\\ServiciosWeb\\ServiciosWeb\\InformacionRemesas.asmx.vb:line 443\n   --- End of inner exception stack trace ---",
    "exception": "SoapFault",
    "file": "C:\\xampp\\htdocs\\GirosYa\\app\\Http\\Controllers\\Api\\ExternalApis\\TccController.php",
    "line": 35,
    "trace": [
        {
            "file": "C:\\xampp\\htdocs\\GirosYa\\app\\Http\\Controllers\\Api\\ExternalApis\\TccController.php",
            "line": 35,
            "function": "__call",
            "class": "SoapClient",
            "type": "->"
        },

It works using SoapUI so I am not sure if that software is adding a header or something like that, thank you very much for your help.

A: Based on that WSDL and the error message, it looks like your 'numeroremesa'=>433654926,'unidadnegocio'=>1 needs to be wrapped in an array whose key in the main array is "remesas".  This means your $param should be as follows:
$param=array('Clave'=>$this->pass,'remesas' => array('numeroremesa'=>433654926,'unidadnegocio'=>1),'Respuesta'=>0)

The parts of the WSDL that indicate this are:
<s:element minOccurs="0" maxOccurs="1" name="remesas" type="tns:ArrayOfRemesaUEN"/>

...
<s:element minOccurs="0" maxOccurs="unbounded" name="RemesaUEN" nillable="true" type="tns:RemesaUEN"/>

...
<s:complexType name="RemesaUEN">
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="numeroremesa" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="unidadnegocio" type="s:string"/>
</s:sequence>
</s:complexType>

The part of the error message that indicates this is:

at
  ServiciosWeb.InformacionRemesas.ConsultarInformacionRemesasEstadosUEN(String
  Clave, List1 remesas, List1& remesasrespuesta, Int32& Respuesta,
  String& Mensaje)

Note the argument list shown for the function


text:
Q: In a DataFrame grouped by 2 fields, calculate difference between rows n and n-1 from 2nd grouping field inside the 1st grouping field Given the following dataFrame (subset of many areas and years, not the same years range per area) :

Area
Year
Food Aid (kg)
Population
Malnutrition
Malnutrition rate (%)

Afghanistan
2013
128238
32269.589
8600.00000
26.65000

2014
57214
33370.79400
8800.00000
26.37000

Algeria
2013
35234
38140.13300
1300.00000
3.41000

2014
18980
38923.69200
1300.00000
3.34000

2015
17424
39728.02500
1300.00000
3.27000

2016
9476
40551.39200
1300.00000
3.21000

Created with a groupby from a dataset which contained data for each country and each available year ; then added the calculated row :
df.groupby(['Area', 'Year']).agg(
    {
        'Food Aid (kg)' : 'sum',
        'Population' : lambda x: x.iloc[0],
        'Malnutrition': lambda x: x.iloc[0]
    })

df['Malnutrition rate (%)'] = round(((df.loc[:,'Malnutrition'] / df.loc[:,'Population']))*100,2)

I would like to add 2 aggregated columns as such. For a country, given a year N, the percentage of evolution since N-1 of :

*

*Food Aid

*Malnutrition

Something like :

Area
Year
Food Aid (kg)
Population
Malnutrition
Malnutrition rate (%)
Food Aid evolution (%)
Malnutrition rate evolution (%)

Afghanistan
2013
128238
32269.589
8600.00000
26.65000
---
---

2014
57214
33370.79400
8800.00000
26.37000
-55.38
-1.051

Algeria
2013
35234
38140.13300
1300.00000
3.41000
---
---

2014
18980
38923.69200
1300.00000
3.34000
-46.132
-2.053

2015
17424
39728.02500
1300.00000
3.27000
-8.198
-2.096

2016
9476
40551.39200
1300.00000
3.21000
-45.615
-1.835

I'm quite a beginner in Pandas. I've tried several things without much success. For example, this loop I'm not sure how to use to make things work:
for key, value in df:
    # key is an array of grouped keys. Examples: (Afghanistan, 2013), (Afghanistan, 2014)
    # value is a Series of the various cols for the current row

Question: in a dataframe grouped by 2 fields: how to add a new column which contains a calculation between the rows n and n-1 of the 2nd grouping field, inside the 1st grouping field ?

A: Look at pct_change
df.groupby(level=0).agg({'Food Aid (kg)': 'pct_change',
                         'Malnutrition rate (%)': 'pct_change'})*100

             Food Aid (kg)  Malnutrition rate (%)
Area
Afghanistan            NaN                    NaN
Afghanistan     -55.384519              -1.050657
Algeria                NaN                    NaN
Algeria         -46.131577              -2.052786
Algeria          -8.198103              -2.095808
Algeria         -45.615243              -1.834862

This assumes that the years you want to compare are ordered and sequential

A: Use pct_change:
new_cols = {'Food Aid (kg)': 'Food Aid evolution (%)',
            'Malnutrition rate (%)': 'Malnutrition rate evolution (%)'}

out = df.join(df.groupby('Area')[['Food Aid (kg)', 'Malnutrition rate (%)']]
                .pct_change().mul(100).rename(columns=new_cols))

>>> out[new_cols.values()]

                  Food Aid evolution (%)  Malnutrition rate evolution (%)
Area        Year
Afghanistan 2013                     NaN                              NaN
            2014              -55.384519                        -1.050657
Algeria     2013                     NaN                              NaN
            2014              -46.131577                        -2.052786
            2015               -8.198103                        -2.095808
            2016              -45.615243                        -1.834862


text:
Q: Understanding calculations about phase changes
Suppose mixture of 500g of water and 100g of ice that both are in thermic equilibrium. We then add 200g of steam which has a temperature of 100°C.
Calculate the equilibrium temperature and the composition of the final mixture.

Used formula's:
$Q = mL$ where Q = heat, m = mass, L = latent heat
$Q = mc\Delta t$ where m=mass, c=specific heat, $\Delta t$ = change in temperature
Given:

*

*$m_{\text{water}} = 500g$

*$m_{\text{ice}} = 100g$

*$m_{\text{steam}} = 200g$

*$T_{\text{water}} = 0°C$

*$T_{\text{ice}} = 0°C$

*$T_{\text{solid}} = 100°C$

*$L_{1,2} = 334J/g$ (latent het from solid to liquid state)

*$L_{2,3} = 2249J/g$ (latent heat from liquid to gas state)

1) Suppose $T_{final}$ = 0°C
Heat balance: $Q_{\text{Given By Steam}} = Q_{\text{Absorbed By Ice}}$
$m_{\text{solid}} L_{2,3} + m_{\text{solid}} C_{\text{water}}(T_{\text{solid}} - T_{\text{water}}) = m"_{\text{ice}}L_{1,2}$
after some calculations: $m"_{\text{ice}} = 1597,4g$
We conclude this supposition is wrong. We only have 200g of ice so there is no way 1597,4g which can melt.

2) Suppose $T_{\text{final}}=100°C$
Heat balance: $Q_{\text{Given By Steam}} = Q_{\text{Absorbed By Ice AND Water}}$
$m"_{\text{solid}}L_{2,3} = m_{\text{ice}}L_{1,2} + (m_{\text{ice}} + m_{water})c_{water}(T_{\text{solid}}-T_{\text{water}})$
after some calculations: $m"_{\text{solid}} = 126,5g$
This is not in contradiction with our supposition.
Solution:
We can now tell that
the final composition is 73,5g of steam, 726,5g of water and no ice.

My questions

*

*At the first supposition we suppose (and that is what is being used for the calculations):

$Q_{\text{given by steam}} = Q_{\text{absorbed by ice}}$
Why isn't it: $Q_{Given By Steam} = Q_{Absorbed By Ice AND Water}$ (like in the second supposition) as the ice and the water are both in thermic equilibrium?

*Why is at the first supposition the formula $Q=mc\Delta t$ associated with the heat given by the steam and at the second supposition with the heat absorbed by the ice and water?

Thank you very much,

A: It is simpler to first assume the water stays at 0 C while the ice melts (in equilibrium, that is what will happen). Once all the ice has melted, the remaining heat can be used to heat up the total mass of water - both that which started out as liquid, and that which started out as ice.
The second supposition asks whether there is enough heat to warm all the water to 100 C and still have heat left over in the steam. The answer is yes - again, this is just to make it easier to deal with the discontinuities that you would otherwise have in the equations. Perhaps a simple diagram makes this clear. See if you can calculate the breakpoints you would need here. Starting with a mixture of ice and water, we add heat (x axis). First, the ice disappears; eventually, some of the water evaporates. Does that help?


text:
Q: How can I put a shortcut to a file in the Unity launcher? Is it possible to put a shortcut to a file (like a application launcher but opens a file instead of launching a program) in the Unity launcher, and if so, how?

A: I only know a dirty way:

*

*Create a file ~/.local/share/applications/myfile.desktop

*Add the following to that file:
[Desktop Entry]
Name=MyFile
Exec=gedit /path/to/a/text/file
Icon=text
Terminal=false
Type=Application
StartupNotify=true

*Save it and make that file executable:
chmod +x ~/.local/share/applications/myfile.desktop

*Now browse to that file in Nautilus and drag it to the launcher.
This will add a launcher with a text icon, that opens /path/to/a/text/file with gedit:

Of course you need to change application/file/icon to whatever you want.


text:
Q: CSS: How can I show where a margin edge is to the user on a box-model Consider the following:

I am writing a debug class to show the position of elements on a page. I want to show the margin edge above (outside dashed line), but realise I can not use the border as this is the inside margin edge. How can I do this?

A: You're probably best off setting an outline in combination with an outline-offset. outline is like border, but doesn't take up any space in the layout and has a slightly different set of rules. Given a div with a 1px border and 10px margin, you'd add an outline like this:
div {
  border: 1px solid black;
  margin: 10px;
  outline: 1px solid red;
  outline-offset: 10px;
}

More info on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/outline-offset
Unfortunately outline-offset isn't supported in IE. If you need to support that then you'll have to go down the psuedoelement route as per the other answers.

A: The box model prevents this.
As you in your original post the margin of a box is not included in it's content size. Without changing your margin to padding this could only be done with pseudo elements.
http://jsfiddle.net/Fcwkw/1/
Since you mentioned it's a class you can simply get a div's margin with some Javascript and set the pseudo padding to the margin.

A: That's not how border's work, and your image is a perfect example of that. You could create a border with a second element or with the use of :after for example...

A: You can use :before/:after with position:absolute, border-left/right and height:100%


text:
Q: How to tabulate the means for multiple data files I have multiple data files formatted like so:
Condition    Score  Reqresponse
   Z          1         b
   Y          0         a

I want to read in multiple data files, get a mean score for each condition/reqresponse combo then tabulate that mean into a master table. I want each the means for each data file to populate a row in the master table (or list, whatever).
Here's what I've attempted
#loop reads data from source example with only 2 files named 1 and 2
for(i in 1:2)
{
n= paste(i,".txt", sep="")
data <- read.table(toString(n), header = TRUE, sep = "\t")

So far so good right? After this I get lost.
Score <- ave(x = data$Score, data$Condition, data$Reqresponse, FUN = mean)
table(Score)
}

This is all I've come up with. I don't know which cells in the table belong to which Condition x Reqresponse combo, or how to create a new row and then feed them into a master table.
By the way, if this is just a silly way to approach what I'm doing feel free to point that out >)

A: This should work, although it could be optimized quite a bit:
all_data<-data.frame() #make empty data.frame (we don't know the size)
for(i in 1:2){ #go through all files
  #add rows to the data frame
  all_data <- rbind(all_data,read.table(paste(i,".txt", sep=""),
              header = TRUE, sep = "\t"))
}
#use tapply to compute mean
Score<-tapply(all_data$Score,list(all_data$Condition,all_data$Reqresponse),mean)

EDIT: Better solution in terms of performance could be achieved by not making the master data frame at all (although I'm not sure about the efficiency of xtabs vs tapply):
#read the first file
data <- read.table(paste(1,".txt", sep=""),header = TRUE, sep = "\t"))
#number of 1's, formula is a equal to Score==1~Condition+Reqresponse
score1<-xtabs(xtabs(Score~.,data=data)
#number of 0's, formula is a equal to Score==0~Condition+Reqresponse
score0<-xtabs(!Score~.,data=data)
for(i in 2:n){ #go through the rest of the files

  data <- read.table(paste(i,".txt", sep=""),header = TRUE, sep = "\t"))

  #sum the number of combinations in file i.txt to previous values
  score1<-score1+xtabs(xtabs(Score~.,data=data)
  score0<-score0+xtabs(!Score~.,data=data)
}
#Compute the means
Score<-score1/(score0+score1)

A: The answer of @Hemmo involves growing an object sequentially. If the amount of files is large this can become really slow. A more R style approach is not to use the for loop, but to first create a vector of files, and then loop over them using an apply style loop. I'll use an apply loop from the plyr pacakge as this makes live a little easier:
library(plyr)
file_list = sprintf("%s.txt", 1:2)
all_data = ldply(file_list, read.table, header = TRUE, sep = "\t")

After that you can use another plyr function to process the data:
ddply(all_data, .(Condition, Reqresponse), summarise, mn = mean(Score))

You could also use base R functions:
all_data = do.call("rbind", lapply(file_list, read.table, header = TRUE, sep = "\t"))
# Here I copy the tapply call of @Hemmo
Score<-tapply(all_data$Score,list(all_data$Condition,all_data$Reqresponse),mean)


text:
Q: Multiple RTSPs receive method I am trying to code a project which I have at least 20 rtsp CCTV URL going to access at same time.
I tried to use ffmpeg to reach out my goal via multiple input method. However, there is a problem.
ffmpeg -i URL_1 -i URL_2 -

The command above is the example I tried. I wish that I can access two rtsps via ffmpeg and output them into two different queues for the future use. If I use this command and read bytes after that, I can not distinguish which bytes belongs to which input rtsp.
Is there any other way which I can access more rtsp at same time?
Edit: Adding Code
import ffmpeg
import numpy as np
import subprocess as sp
import threading
import queue
import time
class CCTVReader(threading.Thread):
    def __init__(self, q, in_stream, name):
        super().__init__()
        self.name = name
        self.q = q
        self.command = ["ffmpeg",
                        "-c:v", "h264",     # Tell ffmpeg that input stream codec is h264
                        "-i", in_stream,    # Read stream from file vid.264
                        "-c:v", "copy",     # Tell ffmpeg to copy the video stream as is (without decding and encoding)
                        "-an", "-sn",       # No audio an no subtites
                        "-f", "h264",       # Define pipe format to be h264
                        "-"]                # Output is a pipe

    def run(self):
        pipe = sp.Popen(self.command, stdout=sp.PIPE, bufsize=1024**3)  # Don't use shell=True (you don't need to execute the command through the shell).

        # while True:
        for i in range(1024*10):  # Read up to 100KBytes for testing
            data = pipe.stdout.read(1024)  # Read data from pip in chunks of 1024 bytes
            self.q.put(data)

            # Break loop if less than 1024 bytes read (not going to work with CCTV, but works with input file)
            if len(data) < 1024:
                break

        try:
            pipe.wait(timeout=1)  # Wait for subprocess to finish (with timeout of 1 second).
        except sp.TimeoutExpired:
            pipe.kill()           # Kill subprocess in case of a timeout (there should be a timeout because input stream still lives).

        if self.q.empty():
            print("There is a problem (queue is empty)!!!")
        else:
            # Write data from queue to file vid_from_queue.264 (for testingg)
            with open(self.name+".h264", "wb") as queue_save_file:
                while not self.q.empty():
                    queue_save_file.write(self.q.get())

# Build synthetic video, for testing begins:
################################################
# width, height = 1280, 720
# in_stream = "vid.264"
# sp.Popen("ffmpeg -y -f lavfi -i testsrc=size=1280x720:duration=5:rate=1 -c:v libx264 -crf 23 -pix_fmt yuv420p " + in_stream).wait()
################################################

#Use public RTSP Streaming for testing
readers = {}
queues = {}
dict = {
        "name1":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name2":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name3":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name4":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name5":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name6":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name7":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name8":{"ip":"rtsp://xxx.xxx.xxx.xxx/",
        "name9":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name10":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name11":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name12":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name13":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name14":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name15":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        }

for key in dict:
    ip = dict[key]["ip"]
    name = key
    q = queue.Queue()
    queues[name] = q
    cctv_reader = CCTVReader(q, ip, name)
    readers[name] = cctv_reader
    cctv_reader.start()
    cctv_reader.join()

A: You already have all the infrastructure in your previous question.
All you need to do is creating multiple objects of your 'CCTVReader' class.
Here is a working code sample, reading two streams:
import numpy as np
import subprocess as sp
import threading
import queue
import time

class CCTVReader(threading.Thread):
    def __init__(self, q, in_stream, chunk_size):
        super().__init__()
        self.q = q
        self.chunk_size = chunk_size
        self.command = ["ffmpeg",
                        "-c:v", "h264",     # Tell FFmpeg that input stream codec is h264
                        "-i", in_stream,    # Read stream from file vid.264
                        "-c:v", "copy",     # Tell FFmpeg to copy the video stream as is (without decoding and encoding)
                        "-an", "-sn",       # No audio an no subtitles
                        "-f", "h264",       # Define pipe format to be h264
                        "-"]                # Output is a pipe

    def run(self):
        pipe = sp.Popen(self.command, stdout=sp.PIPE, bufsize=1024**3)  # Don't use shell=True (you don't need to execute the command through the shell).

        # while True:
        for i in range(100):  # Read up to 100KBytes for testing
            data = pipe.stdout.read(self.chunk_size)  # Read data from pip in chunks of self.chunk_size bytes
            self.q.put(data)

            # Break loop if less than self.chunk_size bytes read (not going to work with CCTV, but works with input file)
            if len(data) < self.chunk_size:
                break

        try:
            pipe.wait(timeout=1)  # Wait for subprocess to finish (with timeout of 1 second).
        except sp.TimeoutExpired:
            pipe.kill()           # Kill subprocess in case of a timeout (there should be a timeout because input stream still lives).

#in_stream = "rtsp://xxx.xxx.xxx.xxx:xxx/Streaming/Channels/101?transportmode=multicast",

#Use public RTSP Streaming for testing
in_stream1 = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

in_stream2 = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

q1 = queue.Queue()
q2 = queue.Queue()

cctv_reader1 = CCTVReader(q1, in_stream1, 1024)  # First stream
cctv_reader2 = CCTVReader(q2, in_stream2, 2048)  # Second stream

cctv_reader1.start()
time.sleep(5) # Wait 5 seconds (for testing).
cctv_reader2.start()

cctv_reader1.join()
cctv_reader2.join()

if q1.empty():
    print("There is a problem (q1 is empty)!!!")
else:
    # Write data from queue to file vid_from_queue1.264 (for testing)
    with open("vid_from_q1.264", "wb") as queue_save_file:
        while not q1.empty():
            queue_save_file.write(q1.get())

if q2.empty():
    print("There is a problem (q2 is empty)!!!")
else:
    # Write data from queue to file vid_from_queue2.264 (for testing)
    with open("vid_from_q2.264", "wb") as queue_save_file:
        while not q2.empty():
            queue_save_file.write(q2.get())

Update:
I don't think you can use a syntax like ffmpeg -i URL_1 -i URL_2 -...
The code you have posted has few issues:

*

*The cctv_reader.join() must be in a second loop, because it waits for the thread to end, and blocks execution.

*Saving the data to files should be after all threads ended (it's just for testing).
In case you want to record the data, try saving each chunk right after grabbing it.

*Reduce size of bufsize=1024**3, try bufsize=1024**2*100.
In case OS actually allocate buffer size of 1GB per process, you might get out of memory.

Note: Python multi-threading performance is not so good, check the CPU load.
Here is a code sample (reading from files):
import numpy as np
import subprocess as sp
import threading
import queue

class CCTVReader(threading.Thread):
    def __init__(self, q, in_stream, chunk_size):
        super().__init__()
        self.q = q
        self.chunk_size = chunk_size
        self.command = ["ffmpeg",
                        "-c:v", "h264",     # Tell FFmpeg that input stream codec is h264
                        "-i", in_stream,    # Read stream from file vid.264
                        "-c:v", "copy",     # Tell FFmpeg to copy the video stream as is (without decoding and encoding)
                        "-an", "-sn",       # No audio an no subtitles
                        "-f", "h264",       # Define pipe format to be h264
                        "-"]                # Output is a pipe

    def run(self):
        pipe = sp.Popen(self.command, stdout=sp.PIPE, bufsize=1024**2*100)

        # while True:
        for i in range(100):  # Read up to 100KBytes for testing
            data = pipe.stdout.read(self.chunk_size)  # Read data from pip in chunks of self.chunk_size bytes
            self.q.put(data)

            # Break loop if less than self.chunk_size bytes read (not going to work with CCTV, but works with input file)
            if len(data) < self.chunk_size:
                break

        try:
            pipe.wait(timeout=1)  # Wait for subprocess to finish (with timeout of 1 second).
        except sp.TimeoutExpired:
            pipe.kill()           # Kill subprocess in case of a timeout (there should be a timeout because input stream still lives).

    def save_q_to_file(self, vid_file_name):
        # Write data from queue to file (for testing)
        if self.q.empty():
            print("There is a problem (q is empty)!!!")
        else:
            with open(vid_file_name, "wb") as queue_save_file:
                while not self.q.empty():
                    queue_save_file.write(self.q.get())

#in_stream = "rtsp://xxx.xxx.xxx.xxx:xxx/Streaming/Channels/101?transportmode=multicast",

#Use public RTSP Streaming for testing
#in_stream = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

#Use public RTSP Streaming for testing
readers = {}
queues = {}

# Read from file (for tesing)
dict = {
        "name1":{ "ip":"vid1.264",  "fname":"vid_from_q1.264"},
        "name2":{ "ip":"vid2.264",  "fname":"vid_from_q2.264"},
        "name3":{ "ip":"vid3.264",  "fname":"vid_from_q3.264"},
        "name4":{ "ip":"vid4.264",  "fname":"vid_from_q4.264"},
        "name5":{ "ip":"vid5.264",  "fname":"vid_from_q5.264"},
        "name6":{ "ip":"vid6.264",  "fname":"vid_from_q6.264"},
        "name7":{ "ip":"vid7.264",  "fname":"vid_from_q7.264"},
        "name8":{ "ip":"vid8.264",  "fname":"vid_from_q8.264"},
        "name9":{ "ip":"vid9.264",  "fname":"vid_from_q9.264"},
        "name10":{"ip":"vid10.264", "fname":"vid_from_q10.264"},
        "name11":{"ip":"vid11.264", "fname":"vid_from_q11.264"},
        "name12":{"ip":"vid12.264", "fname":"vid_from_q12.264"},
        "name13":{"ip":"vid13.264", "fname":"vid_from_q13.264"},
        "name14":{"ip":"vid14.264", "fname":"vid_from_q14.264"},
        "name15":{"ip":"vid15.264", "fname":"vid_from_q15.264"}
        }

for key in dict:
    ip = dict[key]["ip"]
    name = key
    q = queue.Queue()
    queues[name] = q
    cctv_reader = CCTVReader(q, ip, 8192)
    readers[name] = cctv_reader
    cctv_reader.start()

# Wait for all threads to end
for key in readers:
    readers[key].join()

# Save data for testing
for key in readers:
    fine_name = dict[key]["fname"]
    readers[key].save_q_to_file(fine_name)


text:
Q: Kotlin:java.lang.RuntimeException: Cannot create an instance of class com.app.datastorepreferences.MyViewModel I'm getting this error
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.app.datastorepreferences.MyViewModel
at com.app.datastorepreferences.MainActivity.onCreate(MainActivity.kt:16)
Caused by: java.lang.InstantiationException: java.lang.Class<com.app.datastorepreferences.MyViewModel> has no zero argument constructor
viewmodel
class MyViewModel(application: Application): AndroidViewModel(application) {
val kotlinDataStore = KotlinDataStore(application)

val readFromDataStore = kotlinDataStore.readPreferences.asLiveData()
fun sendName(name: String) = viewModelScope.launch(Dispatchers.IO){
    kotlinDataStore.writeToDataStore(name)
 }
}

Main Activity
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
    viewModel.readFromDataStore.observe(this, {myNAME ->
        textView.text = myNAME.toString()
    })
    button.setOnClickListener {
        val name = edit_text.text.toString()
        viewModel.sendName(name)
    }
}

Dependencies
 // ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
// Preferences DataStore
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"


text:
Q: How to determine which IAP was purchased? I'm writing some code in swift for handling an IAP. How do you determine which IAP was purchased inside the the paymentQueue function?
Here is the code I have so far:
func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!)    {

    println("Received Payment Transaction Response from Apple")

    for transaction:AnyObject in transactions {
        if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
            switch trans.transactionState {
            case .Purchased:
                println("Product Purchased");
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                break;
            case .Failed:
                println("Purchased Failed");
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                break;
            case .Restored:
                println("Product Restored");
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                // case .Restored:
                //[self restoreTransaction:transaction];
            default:

                break;
            }
        }
    }
}

A: SKPaymentTransaction instance's payment property's productIdentifier value gives you the related product.

you can read more about SKPaymentTransaction in its Class Reference.

A: From the transaction, you can get the payment, which contains the productIdentifier.
https://developer.apple.com/library/prerelease/ios/documentation/StoreKit/Reference/SKPaymentRequest_Class/index.html#//apple_ref/doc/c_ref/SKPayment


text:
Q: How to create thread according to integer value? I'm trying to create thread according to integer value. For example if the variable is '5', program should create 5 threads or variable is '2', program should create 2 threads, etc. But I can't understand which path I must follow.

A: It's just a matter of creating the Thread and start it. But I wouldn't suggest you to handle the thread explicitly, but to use Tasks or ThreadPool in order to execute multithreading work.
using System;
using System.Threading;

public class Program
{
    public static void Main()
    {
        int numberOfRequestedThreads = 3;
        for (int i = 0; i < numberOfRequestedThreads; i++)
        {
            var tempThread = new Thread(new ThreadStart(DoWork));
            tempThread.Name = i.ToString();
            tempThread.Start();
        }
    }

    public static void DoWork()
    {
        Console.WriteLine("Thread#{0} is now working!", Thread.CurrentThread.Name);
    }
}


text:
Q: Navbar links not getting smaller I am having an issue with my navbar, once I make the browser tab smaller, the text stays the same size but the logo gets smaller and smaller and disappears. How can I make it so everything gets smaller? If any more information is needed I will provide them. Here are some examples of my problem.
100% width page vs Page made smaller for smaller screens for example

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

/* custom scroll bar */

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #888;
}

::selection {
  background: rgb(0, 123, 255, 0.3);
}

.content {
  max-width: 1250px;
  margin: auto;
  padding: 0 30px;
}

/* Nav start*/

.navbar {
  position: fixed;
  width: 100%;
  z-index: 2;
  padding: 25px 0;
  transition: all 0.3s ease;
  background-color: black;
}

.navbar.sticky {
  background: black;
  padding: 10px 0;
  box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.1);
}

.navbar .content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar .logo a {
  color: #fff;
  font-size: 30px;
  font-weight: 600;
  text-decoration: none;
}

.navbar .menu-list {
  display: inline-flex;
}

.menu-list li {
  list-style: none;
}

.menu-list li a {
  color: #fff;
  font-size: 18px;
  font-weight: 500;
  margin-left: 20px;
  text-decoration: none;
  transition: all 0.3s ease;
}

.menu-list li a:hover {
  color: #007bff;
}

.banner {
  height: 100vh;
  background-position: center;
  background-attachment: fixed;
}

.about {
  padding: 30px 0;
}

.about .title {
  font-size: 38px;
  font-weight: 700;
}

.about p {
  padding-top: 20px;
  text-align: justify;
}

.icon {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  display: none;
}

.menu-list .cancel-btn {
  position: absolute;
  right: 30px;
  top: 20px;
}

@media (max-width: 1230px) {
  .content {
    padding: 0 60px;
  }
}

@media (max-width: 1100px) {
  .content {
    padding: 0 40px;
  }
}

@media (max-width: 900px) {
  .content {
    padding: 0 30px;
  }
}

@media (max-width: 868px) {
  body.disabled {
    overflow: hidden;
  }
  .icon {
    display: block;
  }
  .icon.hide {
    display: none;
  }
  .navbar .menu-list {
    position: fixed;
    height: 100vh;
    width: 100%;
    max-width: 400px;
    left: -100%;
    top: 0px;
    display: block;
    padding: 40px 0;
    text-align: center;
    background: #222;
    transition: all 0.3s ease;
  }
  .navbar.show .menu-list {
    left: 0%;
  }
  .navbar .menu-list li {
    margin-top: 45px;
  }
  .navbar .menu-list li a {
    font-size: 23px;
    margin-left: -100%;
    transition: 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  }
  .navbar.show .menu-list li a {
    margin-left: 0px;
  }
}

@media (max-width: 380px) {
  .navbar .logo a {
    font-size: 27px;
  }
}

.cta {
  padding: 9px 25px;
  background-color: rgba(0, 136, 169, 1);
  border: none;
  border-radius: 50px;
  cursor: pointer;
  transition: background-color 0.3s ease 0s;
}

.cta:hover {
  background-color: rgba(0, 136, 169, 0.8);
}

/* Nav end*/

Fireplaces

Floorings

IronWorks

Ornaments

Woodwork

Radiators

Luminary

Miscellaneous

A: I think you're using @media wrong.
@media (max-width: 868px)

indicates that these styles will be applied when it has a max width of 868px. So for small screens you need to decrease the font-size in there.
@media (max-width: 868px) {
    .navbar .menu-list li a{
         font-size: 16px; // for example
         margin-left: -100%;
         transition: 0.6s cubic-bezier(0.68, -0.55, 0.265,
         1.55);
    }
}

A: I see some issues in your styles that have proven to be problematic for your design. For sake of demonstrating the media-queries behavior, I have deleted all your media queries and made just one that points to your
 and your logo, which appears to be the focal point in this example.
Please see the CSS changes I made between /* Media Start & /* Media End */. Also, my suggestion, if you are flexing the navbar, would be to use display: flex; instead of inline-flex. Then you can add justify-content: space-between; to properly align your nav components. Next, this is just out of preference, but I wouldn't suggest spacing your li's with margin-left because then you get left margin on your "Fireplaces"
 which is just unnecessary margin. I used gap: 10px; as an alternative.
Please see the changes to the logo as well. With this correct structure for your media-queries, I believe it will be much easier for you to manipulate. Without being able to see your image or the size of it, it's challenging to give you an exact height & width so adjust the 25px around as necessary. Finally, setting font-sizes on logos or images won't be useful, unless there is a text element within the containing parent div of the image or logo.

* {
     margin: 0;
     padding: 0;
     box-sizing: border-box;
     font-family: 'Poppins', sans-serif;
}
/* custom scroll bar */
 ::-webkit-scrollbar {
     width: 10px;
}
 ::-webkit-scrollbar-track {
     background: #f1f1f1;
}
 ::-webkit-scrollbar-thumb {
     background: #888;
}
 ::selection{
     background: rgb(0,123,255,0.3);
}
 .content{
     max-width: 1250px;
     margin: auto;
     padding: 0 30px;
}
/* Nav start*/
 .navbar{
     position: fixed;
     width: 100%;
     z-index: 2;
     padding: 25px 0;
     transition: all 0.3s ease;
     background-color: black;
}
 .navbar.sticky{
     background: black;
     padding: 10px 0;
     box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.1);
}
 .navbar .content{
     display: flex;
     align-items: center;
     justify-content: space-between;
}
 .navbar .logo a{
     color: #fff;
     font-size: 30px;
     font-weight: 600;
     text-decoration: none;
}
 .navbar .menu-list{
     display: flex;
     justify-content: space-between;
     gap: 10px;
}
 .menu-list li{
     list-style: none;
}
 .menu-list li a{
     color: #fff;
     font-size: 18px;
     font-weight: 500;
     text-decoration: none;
     transition: all 0.3s ease;
}
 .menu-list li a:hover{
     color: #007bff;
}
 .banner{
     height: 100vh;
     background-position: center;
     background-attachment: fixed;
}
 .about{
     padding: 30px 0;
}
 .about .title{
     font-size: 38px;
     font-weight: 700;
}
 .about p{
     padding-top: 20px;
     text-align: justify;
}
 .icon{
     color: #fff;
     font-size: 20px;
     cursor: pointer;
     display: none;
}
 .menu-list .cancel-btn{
     position: absolute;
     right: 30px;
     top: 20px;
}
 .cta {
     padding: 9px 25px;
     background-color: rgba(0, 136, 169, 1);
     border: none;
     border-radius: 50px;
     cursor: pointer;
     transition: background-color 0.3s ease 0s;
}
 .cta:hover {
     background-color: rgba(0, 136, 169, 0.8);
}
/* Nav end*/

/* Media Start */

@media only screen and (max-width: 800px) {
  ul.menu-list li a {
    font-size: 10px;
  }

  .logo {
    width: 25px;
    height: 25px;
  }
}

/* Media End */

Fireplaces

Floorings

IronWorks

Ornaments

Woodwork

Radiators

Luminary

Miscellaneous

EDIT:
.navbar .content {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    align-content: center;
}

Then I would add two media queries like so :
@media only screen and (max-width: 1060px) {
    .menu-list li a {
      font-size: 13px;
    }
}

@media only screen and (max-width: 945px) {
    .menu-list li a {
       font-size: 11.5px;
    }
}


text:
Q: Get ip address from a request mvc I'm trying to get the ip address of the device that is making the request. This should work in both self hosted or hosted on a server with internet access.
I've tried this:
//Get Visitor IP address method
    public string GetVisitorIpAddress()
    {
        string stringIpAddress;
        stringIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
            stringIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //we can use REMOTE_ADDR
        else if (stringIpAddress == null)
            stringIpAddress = GetLanIPAddress();

        return stringIpAddress;
    }

    //Get Lan Connected IP address method
    public string GetLanIPAddress()
    {
        //Get the Host Name
        string stringHostName = Dns.GetHostName();
        //Get The Ip Host Entry
        IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
        //Get The Ip Address From The Ip Host Entry Address List
        System.Net.IPAddress[] arrIpAddress = ipHostEntries.AddressList;
        return arrIpAddress[arrIpAddress.Length - 1].ToString();
    }

But in both cases i get:  "::1".
What am I doing wrong?

A: In IPv6 ::1 is the same as 127.0.0.1 in IPv4. So when you run it from your local machine this is what you should be getting.
You can try to modify your hosts file, or try to access the application by it's IP http://192.168.0.1 (for example).


text:
Q: The terminal process failed to launch: A native exception occurred during launch (Cannot create process, error code: 998) I am trying to run java through VS code version 15.I have my jdk 13 installed but when I try to compile or run the program error pops up:
"The terminal process failed to launch: A native exception occurred during launch (Cannot create process, error code: 998)."

and after that another window with error shows up. It says:
JAVA.UTIL.CONCURRENT.TIMEOUTEXCEPTION:TIMEOUT.
Maybe there is something wrong with launch.json, but I don t know what.


text:
Q: What is Reactive Extensions used for An MVC 3 web site with some sections in Silverlight 5

*

*Can Rx be used in this scenario?

*If so, how and which components of the
application can benefit

A: The pre-release documentation for Rx has just been released, so I recommend that you take a look at that, and in particular this section: When Will You Use Rx.


text:
Q: Is there a way to mock non-global filters in a sub-flow using MUnit? I wanted to know if there was a way to mock a custom-filter that is within a sub-flow using MUnit.
I'm using Mule 3.4.0 and MUnit 3.4.0.M5.
The sample flow looks like the following.
<sub-flow name="a">
     <choice>
          <when expression="something...">
               <custom-filter doc:name="filter a">...</custom-filter>
          </when>
          <otherwise>
               ...
          </otherwise>
     </choice>
</sub-flow>

I've had to create a wrapper flow around the subflow because I get a NullPointerException whenever I try to hit the sub flow directly using the runFlow syntax. However, in doing so, I am unable to mock the custom-filter using the whenMessageProcessor syntax. Please see my attempt below.
whenMessageProcessor("custom-filter"
.withAttributes(attribute("name").ofNamespace("doc").withValue("filter a"))
.thenReturn(muleMessageWithPayload("some response");

This results in the message not being mocked.

A: There are to issues here mixed up.
You having to wrap you sub-flow is a MUnit/Mule issue as commented here:
How to mock a Java component within Mule Flow using MUnit
The second issue is filter mocking. Short answer is you can not, please check:
https://github.com/mulesoft/munit/issues/108
Conceptually  a filter is a shorthanded way of doing a choice (or an if in a normal language). One usually does not mock a choice/if it rather changes a value in a variable or in our case in the mule message payload. That's why the filter MP can not be mocked.
HTH