text:
Q: Spark configuration for Out of memory error Cluster setup -
Driver has 28gb
Workers have 56gb each (8 workers)

Configuration -
spark.memory.offHeap.enabled true
spark.driver.memory 20g
spark.memory.offHeap.size 16gb
spark.executor.memory 40g

My job -
//myFunc just takes a string s and does some transformations on it, they are very small strings, but there's about 10million to process.

//Out of memory failure
data.map(s => myFunc(s)).saveAsTextFile(outFile)

//works fine
data.map(s => myFunc(s))

Also, I de-clustered / removed spark from my program and it completed just fine(successfully saved to a file) on a single server with 56gb of ram.  This shows that it just a spark configuration issue.  I reviewed https://spark.apache.org/docs/latest/configuration.html#memory-management and the configurations I currently have seem to be all that should be needed to be changed for my job to work.  What else should I be changing?
Update -
Data -
val fis: FileInputStream = new FileInputStream(new File(inputFile))
val bis: BufferedInputStream = new BufferedInputStream(fis);
val input: CompressorInputStream = new CompressorStreamFactory().createCompressorInputStream(bis);
br = new BufferedReader(new InputStreamReader(input))
val stringArray = br.lines().toArray()
val data = sc.parallelize(stringArray)

Note - this does not cause any memory issues, even though it is incredibly inefficient.  I can't read from it using spark because it throws some EOF errors.
myFunc, I can't really post the code for it because it's complex.  But basically, the input string is a deliminated string, it does some deliminator replacement, date/time normalizing and things like that.  The output string will be roughly the same size as an input string.
Also, it works fine for smaller data sizes, and the output is correct and roughly the same size as input data file, as it should be.

A: Would help if you put more details of what going on in your program before and after the MAP.
Second command (only Map) does not do anything unless an action is triggered. Your file is probably not partitioned and driver is doing the work. Below should force data to workers evenly and protect OOM on a single node. It will cause shuffling of data though.
Updating solution after looking at your code, will be better if you do this
val data = sc.parallelize(stringArray).repartition(8)
data.map(s => myFunc(s)).saveAsTextFile(outFile)

A: You current solution does not take advantage of spark.  You are loading the entire file into an array in memory, then using sc.parallelize to distribute it into an RDD.  This is hugely wasteful of memory (even without spark) and will of course cause out of memory problems for large files.
Instead, use sc.textFile(filePath) to create your RDD.  Then spark is able to smartly read and process the file in chunks, so only a small portion of it needs to be in memory at a time.  You are also able to take advantage of parallelism this way, as spark will be able to read and process the file in parallel, with however many executors and corse your have, instead of needing the read the entire file on a single thread on a single machine.
Assuming that myFunc can look at only a single line at a time, then this program should have a very small memory footprint.


text:
Q: Convert a list of maps by the values of the maps [clojure] I have a list filled with many maps (all of them have the same key), like this:
({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2})

I would like to convert it to a map that stores the occurrence of the value of each map. For exemple, the list above should return the following map:
{:1 2, :2 3, :3 1}

Any ideas on how can i do that?

A: (def m '({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2}))

(frequencies (map :a m)) ;; => {1 2, 2 3, 3 1}

Note the keys of the result are not keywords, as that would be an odd thing to do.

A: I would solve it like this:
(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(defn maps->freqs
  [maps]
  (frequencies
    (for [m maps]
      (second (first m)))))

(dotest
  (let [data (quote
               ({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2}))]
    (is= (maps->freqs data)
      {1 2, 2 3, 3 1})))

The above uses my favorite template project.  The best technique is to build it up slowely:
(defn maps->freqs
  [maps]
  (for [m maps]
    (first m)))

then (spyx-pretty (maps->freqs data)) produces
(maps->freqs data) =>
[[:a 1] [:a 1] [:a 2] [:a 2] [:a 3] [:a 2]]

modify it:
(defn maps->freqs
  [maps]
  (for [m maps]
    (second (first m))))

with result
(maps->freqs data) =>
[1 1 2 2 3 2]

Then use frequencies to get the final result.
Please be sure to read the list of documentation, especially the Clojure CheatSheet!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get questions' text using the stackr library for the API? Using stackr it is possible, with the following command, to list the questions from a specific user.
library(devtools)
devtools::install_github("dgrtwo/stackr")
library(stackr)
textques <- stack_users(712603, "questions", num_pages=10, pagesize=100)

Is it possible to have also the text of every question?
There is a body option but how could I use it with the previous command?
Also, I tried body equals true but it is not working:
textques <- stack_users(712603, "questions", body = "true", num_pages=10, pagesize=100)

A: Since the stack_users() and stack_GET() function both accept (and pass on) the ellipsis argument, you can add any parameter onto the end of the API call URL. This includes the filter parameter, where we can use the built-in withbody filter:
library(stackr)
questions <- stack_users(9371451, "questions", num_pages=10, pagesize=100, filter="withbody")
for (i in 1:nrow(questions)) {
    qtext <- questions$body[i]
    print(qtext)
}

Output:
[1] "
I would like to use the Stack Exchange API with a specific user id to get the text of a user's badges.
\n\n
I found the stackr library for the Stack Exchange API, and tried this:
\n\n
# install.packages(\"devtools\")\nlibrary(devtools)\ndevtools::install_github(\"dgrtwo/stackr\")\nlibrary(stackr)\nstack_users(712603)\n
\n\n
But that only gives the total number of every kind of badge. How can I take the text from each one?\nExample:
\n\n
gold silver bronze\nr     r      ggplot2\n
\n\n
I don't only want the total number of badges but also what the badges are.
\n"
[1] "
Using stackr it is possible with the following command to take the question from a specific user.
\n\n
library(devtools)\ndevtools::install_github(\"dgrtwo/stackr\")\nlibrary(stackr)\ntextques <- stack_users(712603, \"questions\", num_pages=10, pagesize=100)\n
\n\n
How is it possible to have also the text of every question?
\n\n
There is a body option but how could I use it with the previous command
\n\n
Also I tried body equals true but it is not working:
\n\n
textques <- stack_users(712603, \"questions\", body = \"true\", num_pages=10, pagesize=100)\n
\n"

A: I am not sure if the package provides a function to extract the question asked, but here's an approach based on rvest
for(i in 1:nrow(textques)){
  link <- textques$link[i]
  textques$qtext[i] <- read_html(link) %>% html_node("#question .post-text") %>% html_text()
}

This should add another variable to your existing dataframe with the text of the question in each link.


text:
Q: show that $d'(x,y) = |e^x - e^y|$ induces the same topology as the standard metric in R to prove that  I thought about doing this in two parts
first, prove that we can find an open Ball $B'_r(x)$ with $B'_r(x) := \{y \in \mathbb{R} . |e^x - e^y| < r\} $ which is a contained in the ball $B_r(x)$ with $B_r(x) := \{y \in \mathbb{R} . |x-y| < r\} $
so let $ y \in B'_r(x)\implies |e^x-e^y| < r$. the problem is how do I get from there to the fact that $|x-y| < r$ ?
and for the second part which is proving that the ball of the standard metric can be contained in a ball with $d'$ I think I have the same problem. can anybody help with that please? Thanks

A: It is enough to show that $y_n\rightarrow y$ in the metic $d'$ iff $y_n\rightarrow y$ in the standard metric.
This follows by continuity of the exponential function and its inverse.


text:
Q: RAM no longer working after adding a second stick I have a Dell XPS 15 9500, and I'm trying to add 8GB of RAM.
I have RAM stick 1 and RAM stick 2. RAM 1 came with the laptop, and RAM 2 I bought on amazon. Here's what's written on them:
RAM 1:

*

*MTA8ATF1G64HZ-3G2J1

*8GB 1RX8 PC4-3200AA-SA2-11

*DPAPTJM002

*2037

RAM 2:

*

*HMA81GS6DJR8N-XN NO AC

*8GB 1RX8 PC4-3200AA-SA2-11 <- This is what I matched because I have no idea what I'm doing

*2014

The problem is, I added RAM 2, and got the error code for RAM failure. Next, I took out RAM 2, still RAM failure. Then I tested RAM 2 alone in both slots and it works fine. RAM 1, which I've been using for over a year, now does not work in either slot.
Why isn't RAM 1 working anymore? I don't think I damaged it.

A:
Why isn't RAM 1 working anymore? I don't think I damaged it.

That is hard to say since you started back with the original memory.
The memory may not have been properly seated. Try once more to ensure the memory is properly seated.
Otherwise, at this point, you might see if you can return the memory and then get the computer serviced at your local shop. This is most likely the best course of action.


text:
Q: Permutation of index and permutation of vector of powers of monomial I am confused about the following easy stuff,
Let $$\mathbf{x} =\begin{bmatrix} x_1 & \cdots & x_n\end{bmatrix}^T .$$
Suppose I have the following monomial
$$\mathbf{x}^{\alpha}=x^{\alpha_1}_1 x^{\alpha_2}_2\cdots x^{\alpha_n}_n,$$ corresponding to $$\alpha = \begin{bmatrix} \alpha_1 & \cdots & \alpha_n\end{bmatrix}^T$$
Suppose there is a permutation $\gamma\in \Gamma$ ($\Gamma$ a symmetric group) acting on $\mathbf{x}$ such that $$(\gamma \mathbf{x})^{\alpha} = x^{\alpha_1}_{\gamma(1)} x^{\alpha_2}_{\gamma(2)}\cdots x^{\alpha_n}_{\gamma(n)}.$$

If we rearrange the order such that the index is increasing, i.e., $x_1x_2\ldots x_n$, then the new power $\alpha$, $\alpha'$ should be $$\alpha' = M_\gamma \alpha,$$ i.e., the multiplication of the matrix representation of $\gamma$ (permutation matrix corresponding to $\gamma$) and the vector $\alpha$.

For example $\gamma = (13)$ so $\gamma(1) = 3$ and $\gamma(3) = 1$, $$\mathbf{x}^\alpha = x_1^{\alpha_1}x_2^{\alpha_2}x_3^{\alpha_3}$$ $$M_\gamma = \begin{bmatrix} 0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0\end{bmatrix}^T$$
so $$(\gamma\mathbf{x})^\alpha = x_1^{\alpha_3}x_2^{\alpha_2}x_3^{\alpha_3}.$$
In this case $\alpha = \begin{bmatrix} \alpha_1 & \alpha_2 & \alpha_3\end{bmatrix}^T$ and $\alpha' = \begin{bmatrix} \alpha_3 & \alpha_2 & \alpha_1\end{bmatrix}^T$.

Does this result hold for any permutation? for example $(123)$ or general order.

A: Yes, the result is true in general. Writing everything out explicitly, your notation $\textbf{x}^\alpha$ can be written as
$$
\textbf{x}^\alpha:=\prod_{i=1}^n x_i^{\alpha_i}.
$$
Furthermore, $\gamma\textbf{x}$ can be written out explicitly as
$$
\gamma\textbf{x}:=\prod_{i=1}^n x_{\gamma(i)}.
$$
Your question is asking whether $(\gamma \textbf{x})^{\alpha}=\textbf{x}^{\alpha'}$
where $\alpha'=M_\gamma \alpha$ and you are using
$$
(M_\gamma)_{ij}=\begin{cases}1,&i=\gamma(j)\\0,&else.\end{cases}
$$

Proof that $(\gamma \textbf{x})^{\alpha}=\textbf{x}^{\alpha'}$.
First, observe that $\alpha'$ can be written as follows:
$$
\alpha'_i=\sum_{j}M_{ij}\alpha_j=\alpha_{\gamma^{-1}(i)}.
$$
Therefore,
$$
(\gamma\textbf{x})^\alpha=\prod_{i=1}^n x_{\gamma(i)}^{\alpha_i}
=\prod_{j=1}^n x_{j}^{\alpha_{\gamma^{-1}(j)}}=\textbf{x}^{\alpha'}.
$$
In the middle equality, we have reindexed the product using $j=\gamma(i)$, so that $i=\gamma^{-1}(j)$. This reindexing is valid since $\gamma$ is a permutation and the variables $x_i$ commute with one another, so the order the product is written in does not matter.


text:
Q: Is there a good way to replace values in classes for openpyxl in Python? I have extracted cell values from excel, placed them in classes, and want to replace the wrong values after a specific conversion factor.
I.e something like this at the bottom.
Any suggestions?
products = []

for row in sheet.iter_rows(min_row=8, max_row=3030, max_col=10, values_only=True):
    product = Product(id=row[PRODUCT_ID],
                      Molecule=row[PRODUCT_MOLECULE],
                      Pack_Size=row[PRODUCT_PACK_SIZE],
                      Pack_Quantity=row[PRODUCT_PACK_QUANTITY],
                      Product_Treatment=row[PRODUCT_TREATMENT])
    products.append(product)

print(products[1000])

for index, item in enumerate(products):
    if item != PRODUCT_PACK_QUANTITY * PRODUCT_PACK_SIZE / 1:
        products[index] = round(products[index]) - (products[index] PRODUCT_PACK_QUANTITY * PRODUCT_PACK_SIZE / 1)```


text:
Q: Distributing $x$ identical balls into $p$ distinct boxes, what is the probability that there are at most $n$ balls in any of the boxes? I'm trying to figure out this problem when distributing $x$ identical balls randomly into $p$ distinct boxes. How can we compute the number of ways that there are at most $n$ balls in any of the boxes?
It seems that if $n <= x/2$, I cannot simply calculating the solution by putting $n$ balls in some box and calculate $\binom{x - n + p - 1}{p - 1} * p$.
For example, if $x=8, p=4, n=3$, $\binom{8}{3} * 4$ = 224, but the total number of ways is $\binom{8+4-1}{4-1} = \binom{11}{3} = 165$. It seems that some of the combinations are double counted, but I can't figure out a simple formula for solving this problem. Can anyone help?

A: Suppose we are distributing $n$ balls  into $p$ bins with a maximum of
$m$ balls per bin. For the case with no maximum we get
$$[z^n] \frac{1}{(1-z)^p} =
{n+p-1\choose p-1},$$
which is stars-and-bars. With the restriction we get
$$[z^n] (1+z+\cdots+z^m)^p
= [z^n] \frac{(1-z^{m+1})^p}{(1-z)^p}
\\ = \sum_{q=0}^{\lfloor n/(m+1) \rfloor}
{p\choose q} (-1)^q [z^{n-q(m+1)}] \frac{1}{(1-z)^p}
\\ = \sum_{q=0}^{\lfloor n/(m+1) \rfloor}
{p\choose q} (-1)^q {n+p-1-q(m+1) \choose p-1}.$$
The probability is then given by
$$\bbox[5px,border:2px solid #00A000]{
{n+p-1\choose p-1}^{-1}
\sum_{q=0}^{\lfloor n/(m+1) \rfloor}
{p\choose q} (-1)^q {n+p-1-q(m+1) \choose p-1}.}$$
This closed form was verified with an enumeration routine, which helps
to clarify the problem definition that was used.

with(combinat);

ENUM :=
proc(n,p,m)
option remember;
local perm, pos, len, src, res;

    res := 0;
    src := [B$n, S$(p-1)];

    for perm in permute(src) do
        len := 0;

        for pos to n+p-1 do
            if perm[pos] = S then
                if len > m then
                    break
                else
                    len := 0;
                fi;
            else
                len := len + 1;
            fi;
        od;

        if pos = n+p then
            if perm[pos-1] = S or len <= m then
                res := res + 1;
            fi;
        fi;
    od;

    res;
end;

CFX := (n,p,m) ->
add(binomial(p,q)*(-1)^q*binomial(n+p-1-q*(m+1),p-1),
    q=0..floor(n/(m+1)));


text:
Q: When are subcategories of continuous functors reflective? Let $J$ be a collection of small categories (to be thought of as diagrams in a category). Let $C$ be a small category with all $J$-limits (i.e. for every $J_0 \in J$ and every functor $F:J_0\rightarrow C$, $\lim F$ exists in $C$). Let $D$ be any category with all $J$-limits (such as Set).
Consider the category $[C,D]_J$ of functors from $C$ to $D$ which preserve all $J$-limits, with natural transformations as morphisms.
Question: What conditions on $J$ must hold in order for $[C,D]_J$ to be a reflective subcategory of $[C,D]$ (the category of all functors from $C$ to $D$)?
I ran into this question when investigating the case of two collections of diagrams $J \subseteq J'$, so that $[C,D]_{J'} \subseteq [C,D]_J$ (assuming $C$ and $D$ have all $J'$-limits). Since all these categories are full subcategories, it turns out that $[C,D]_{J'}$ is a reflective subcategory of $[C,D]_{J}$ if $[C,D]_{J'}$ is a reflective subcategory of $[C,D]$. (if $U_2$ is fully faithful, and $U_3 = U_2 \circ U_1$ has a left adjoint $F_3$, then $U_1$ has a left adjoint: $F_3 \circ U_2$.

A: When $D$ has copowers, the reflectivity of continuous functors can be seen as a case of the orthogonal subcategory problem. This problem asks whether the full subcategory $\mathcal{X}_\Gamma$ of a category $\mathcal{X}$ on the objects orthogonal to a set of morphisms $\Gamma$ is reflective. There are many hypotheses that ensure a positive answer, a famous one being the condition that $\mathcal{X}$ is a locally presentable category and $\Gamma$ is a small set.
The problem so reduces because we can show that a  functor $G : C \to D$ preserves the limit of $F : J_0 \to C$ if and only if it is orthogonal in the functor category $[C,D]$ to the morphisms
$$\text{colim}_j C(Fj,-)\cdot d \longrightarrow C(\text{lim}_j Fj,-)\cdot d$$
for each $d\in D$. Letting $\Gamma$ be the set of these morphisms for all $F \in J$, we have therefore that the full subcategory $[C,D]_J$ of the $J$-continuous functors is the orthogonal subcategory $[C,D]_\Gamma$.
Hence (keeping your assumptions of smallness) the full subcategory $[C,D]_J$ is reflective in $[C,D]$ if $D$ is a locally presentable category and $J$ is a small set.
The classic paper on this subject is

Freyd, P. J.; Kelly, G. M. Categories of continuous functors. I. J. Pure Appl. Algebra 2 (1972), 169--191.

where more general hypotheses are considered,
and see

Kelly, G. M. A unified treatment of transfinite constructions for free algebras, free monoids, colimits, associated sheaves, and so on. Bull. Austral. Math. Soc. 22 (1980), no. 1, 1--83.

(in particular section 12) for a more complete and cleaner treatment.

A: This is heuristics only, not a rigorous argument, but I would strongly expect that if $D$ is sufficiently co-complete, then very little restriction on $J$ is needed.
The "moral adjoint functor theorem" says that if a functor preserves all limits, then it is probably a right adjoint.  The inclusion functor $[C,D]_J \to [C,D]$ creates (hence reflects) all or most limits that exist in $[C,D]$, since they're usually pointwise — always pointwise, if $D$ has a 1 and sufficient coproducts, since then we can run a version of the Yoneda lemma — and limits commute with limits.
So assuming some co-completeness for $D$ and smallness for either $J$ or $C$ (I guess something like "$J$ or $C$ is bounded by some $\kappa$, such that $D$ has all colimits of size $< \kappa$" should suffice), then one of the genuine adjoint functor theorems should imply that the inclusion of $[C,D]_J$ has a left adjoint.


text:
Q: How to access resource strings from enum's ToString in Android? In my app, I have a Spinner being filled from an enum:
ArrayAdapter<myEnum> enumAdapter = new ArrayAdapter<Stroke> (parentActivity.getApplicationContext(), R.layout.simple_spinner_item, myEnum.values());
enumAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
enumSpinner.setAdapter(strokeAdapter);

This uses an override of the enum's toString() method to get a friendly name for the enum values to display in the Spinner. Currently my enum has strings hardcoded for the friendly names but I'd like to move these to strings.xml to support localization.
However, toString doesn't have access to a Context so I'm not sure how to resolve the resource ids.
Is there any way of getting localised strings in the toString() method of an enum?

A: @Override
    public String toString()
    {
        return App.getContext().getString(id);
    }

It's important that your enum class doesn't have any ties to your activity because if you want to use it in another application then you won't be able to if you are referencing a static context.
So a better way would be to return the resource id of the string back to the activity and then let the activity grab the string using the id from there.
So from your enum class you would have a method looking something similar to this:
  public  int getResourceId()
  {
    return resourceId;
  }

Then in your activity I would build up a list containing an arraylist:
final List<String> enumList = new ArrayList<String>();
for ( final MyEnum status : MyEnum.values() )
{
  enumList.add( getString( status.getResourceId() ) );
}

Then you can use enumList with your ArrayAdapter. Bingo :)
So now you have no ties to the enum class, and so if you are building another app that needs to use the same enum class you can easily do so.

A: Use static Application is always a bad practice, because not only it breaks Instant Run, but also this is against the decoupling principle thus makes modularization difficult to implement. Not to mention Android actually supports multiple Applications in a single process.
For this reason, I'd suggest define an inner class for the enum as your adapter entries.
enum Example {
    A(R.string.label_a),
    B(R.string.label_b);

    Example(@StringRes int label) { mLabel = label; }
    private @StringRes int mLabel;

    class Entry {
        private final Context mContext;
        Entry(final Context context) { mContext = context; }
        @Override public String toString() { return mContext.getString(mLabel); }
    }
}

Then, build an array of Example.Entry for the adapter.
Arrays.stream(Example.values()).map(item -> item.new Entry(context)).toArray(Example.Entry[]::new)

A: If I understand this correctly, the real question here is how to get a Context from your enum, so that you can call Context.getString() to get localized versions of the Strings you need.
One approach, would be to set a static member variable of type Context in your application's onCreate() method, which is described in this answer. The idea here is that every time your application gets created or recreated, you'll hold on to the application context in a variable that's easy to get to.
Then, pass in the resource ID in the constructor of your enum values, and use the Context in your toString() method.
For example:
public enum Example {
    HELLO(R.string.hello),
    WORLD(R.string.world);

    private int mResourceId;

    private Example(int id) {
        mResourceId = id;
    }

    @Override
    public String toString() {
        return App.getContext().getString(mResourceId);
    }
}

A: I'm not 100% sure I understand what you are asking.

Is there any way of getting localised strings in the toString() method of an enum?

You can certainly @Override the toString() method inside of your myEnum to change how it is displayed:
public enum myEnum {
    ONE("1"),
    TWO("2");
    private String pretty;
    private myEnum(String pretty) {
        this.pretty = pretty;
    }
    @Override
    public String toString() {
        // you can localise this string somehow here
        return pretty;
    }
}


text:
Q: Changing profile path of windows 11 terminal I'm trying to setup shortcuts (command aliases) in Windows 11 terminal.
When I try to run the command:
echo $profile

It gives me the path:
C:\Users\ashut\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Now if I try to save aliases to this file, it says file is not digitally signed.
I need to set profile path to:
C:\Users\ashut\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

I tried to create new profile but couldn't found an option to set the path. It allowed only startup path to set.
I my previous computer, profile path was not pointing to OneDrive. How to fix this?

A: PowerShell's profile paths are not configurable.[1]
Since your OneDrive path should be considered a local path, the implication is that the effective execution policy is AllSigned.
If you don't want to sign your profile file, use a less restrictive execution policy; a good compromise is RemoteSigned (only scripts downloaded from the web then require a signature).
# Open a *new* PowerShell session afterwards.
Set-ExecutionPolicy -Force -Scope CurrentUser RemoteSigned

Note:

*

*Scoping the change to the current user obviates the need to run from an elevated (admin) session, but obviously only takes effect for the current user.

*If execution policies are set via GPOs (Group Policy Objects) in your organization, you will not be able to make this change.

[1] If you want a file at C:\Users\ashut\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 to also exist, you can define it as a symbolic link that points to C:\Users\ashut\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.


text:
Q: Does Microsoft releases patches/version upgrades for SCOM Agent specifically or is it only part of SCOM CU rollup? I want to use SCCM to roll out patches for SCOM Agent on all the servers which we are monitoring.
Can we do it?

A: Sorry, I think I have misunderstood your question.
Ordinarily, Microsoft recommend that you install the update rollup package by following these steps in the given order:

*

*Install the update rollup package on the following server infrastructure:
•Management servers
•Gateway servers
•Web Console Server role computers
•Operations Console role computers

*Apply SQL scripts.

*Manually import the management packs.

*Apply the agent update to manually installed agents, or push the installation from the Pending view in the Operations console.
Meanwhile, this is a separate KB for Microsoft Monitoring Agent (KB 3165492)
You could deploy the SCOM agent by SCCM.

Yes. You need to push the SCCM agent to the servers.
There are 2 ways to deploy software updates using SCCM 2012 R2, Manual and Automatic. In Manual software updates deployment, a set of software updates is selected the Configuration Manager console and these updates are deployed to the target collection whereas Automatic software updates deployment is configured by using automatic deployment rules. When the rule runs, the software updates that meet a specified criteria are added to a software update group, the content files for the software updates are downloaded and copied to distribution points, and the software updates are deployed to client computers in the target collection.
For a complete description of the steps mentioned above, check out the articles below:
Introduction to Software Updates in Configuration Manager
How To Deploy Software Updates Using SCCM 2012 R2


text:
Q: How to simulate a slow network condition to specific port numbers There's a couple of questions with answers on tools or settings to simulate slow network conditions on different OSes, like

*

*Network tools that simulate slow network connection

*How do I simulate a low bandwidth, high latency environment?
Unfortunately, the answers don't mention a solution for my case, so it's not redundant or a duplicate.
I'm developing a web application (locally, with Node.js / Express on macOS, but that doesn't matter much) using a Redis cache and a MySQL database.
In order to do some (performance) testing on my local machine, I want to put load on that application (for example with ab or JMeter). Obviously, because the Redis cache and the MySQL database are running on the same machine as the web application, I have a stellar network connection (as in: none) between these three components.
I want to simulate different network connections between these components -  as would be the case in a production setup with multiple servers - by downgrading the virtual 'connections' to Redis and MySQL (but with different latency and bandwidth settings per connection). The connections can be distinguished by the port numbers, but not by the hostname (which is localhost for all three).
How can I simulate different network connection conditions for specific port numbers on the same machine?

A: Maybe this will help you: http://intrarts.com/throttledcli.html
Actually what you are asking about is more or less QoS functionality.
But... in my opinion, it's not a very efficient way of testing network applications. What I do prefer in the first place is to mock the network interfaces in the application. This way you can control much more precisely all kind of timeouts, downtimes, connections breaks, synchronizations.


text:
Q: Does Kustomize require you specify an entire resource to change one value? I'd understood that Kustomize would be the solution to my Kubernetes configuration management needs where, for example, if I want maxReplicas for a resource to be 3 on my dev and test environments but 7 in production, I could do that easily. I imagined there'd be a base file, and then an overlay file that would respecify just the values needing changing. My goal is that if I have multiple configurations (configurations? nodes? clusters? I'm still having trouble with K8s terminology. I mean dev, test, prod.), any time a value common to all of them needed changing, I could change it in one place, the base configuration, instead of in three different config files. Essentially, just as in programming, I want to factor out what's common to all the environments.
But I'm looking at https://www.densify.com/kubernetes-tools/kustomize/ and getting a different impression. Here, the dev version of an hpa.yml file is only meant to change the values of maxReplicas and averageUtilization. So I'd thought the overlay would look as follows, in the same way that, in a .NET Core application, appsettings.dev.json only needs to specify the settings from appsettings.json that it's overriding:
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: frontend-deployment-hpa
spec:
  maxReplicas: 2
    target:
      averageUtilization: 90

instead of the whole definition that's in the example given. So, if I started with all instances having minReplicas = 1 and I wanted to change it to 3 for all of them, I'd have make that change in every overlay instead of just in the base.
Is this correct? If so, is there a tool that will allow configuration management to work as I'm looking to have it work?

A:
Is this correct?

No.
Kustomize does not require to specify the entire resource in order to change a single value; the entire point of Kustomize is its ability to transform manifests through patches and other mechanisms to produce the desired output.
For example, assume the following layout:
.
├── base
│   ├── deployment.yaml
│   └── kustomization.yaml
└── overlays
    ├── dev
    │   └── kustomization.yaml
    └── prod
        └── kustomization.yaml

In base/deployment.yaml we have:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: demo
spec:
  replicas: 1
  template:
    spec:
      containers:
        - name: web
          image: docker.io/traefik/whoami:latest

And in base/kustomization.yaml we have:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
commonLabels:
  app: kustomize-demo

resources:
- deployment.yaml

If in my dev environment I want to keep replicas: 1, I would create overlays/dev/kustomization.yaml like this:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base

This simply includes the resources from base verbatim.
On the other hand, if in my production environment I want to run with three replicas, I would patch the Deployment resource in overlays/prod/kustomization.yaml like this:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base

patches:
  - patch: |
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: demo
      spec:
        replicas: 3

This type of patch is called a "strategic merge patch"; you can also apply changes using "JSONPatch" patches. That might look like:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base

patches:
  - target:
      kind: Deployment
      name: demo
    patch: |
      - op: replace
        path: /spec/replicas
        value: 3

The kustomize documentation has a variety of examples of patching and other transformations. For example, the commonLabels directive I show in base/kustomization.yaml uses the labels transformer to produce this output:
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: kustomize-demo
  name: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kustomize-demo
  template:
    metadata:
      labels:
        app: kustomize-demo
    spec:
      containers:
      - image: docker.io/traefik/whoami:latest
        name: web

Notice how the labels defined in commonLabels have been applied both to:

*

*The top-level /metadata/labels element

*The /spec/selector/matchLabels element

*The /spec/template/metdata/labels element


text:
Q: Apache видит только корневой URL Клонировал репозиторий на сервер и настроил проект, но при попытке получить какую либо страницу, будь это login или register, получаю ошибку 404.

Все отлично работает локально(локально проект запущен через openserver с сервером apache), видит все страницы, но в продакшене не видет кроме корня ничего.
Прикладываю .htaccess

A: Надо поменять:
AllowOverride None

на:
AllowOverride All

Важно обратить внимание на путь, которому вы прописываете AllowOverride All, в моем случае, это var/www/, в котором располагался проект:


text:
Q: input not working while running in debug mode - eclipse cdt Standard input works fine when I run my program, but doesn't work when in debugging mode, although output works fine as well.
I'm running Eclipse Photon (4.8) with CDT and for my toolchain I use gcc provided by Cygwin and I use gdb as my debugger.
Output when I run the program without debugging
Output when I run the program with debugging, mind the variable watches and the console
The Cygwin toolchain is detected automatically because it is present in the PATH environment variable, I also reset the workspace, but that didn't help.
UPDATE: If I put multiple cin lines one after another, the first cin will return a number different from that in the input and every consecutive cin will return a zero as a value.
UPDATE2: I found a workaround. If you use an external console (cmd) instead of the one in Eclipse, then it works. Image


text:
Q: Is "bleed in a red" idiomatic? Is "bleed in a red" idiomatic?

His body bled in a bright red before losing consciousness due to blood
loss.

I almost find no instance of such a usage. Is this unidiomatic? I am pretty sure I've heard it a plenty of times, but I can't find any similar example on Google.

A: It's not an idiom. It's a literal description. The man was bleeding, and the blood was bright red.
It seems a slightly odd wording to me. I wouldn't say "bled in a bright red". I'd say, "He was bleeding bright red blood" or "His blood was bright red."

A: Not to dispute anything in previous answers, but they miss the semantic point of the quoted sentence.
To bleed in bright red is to bleed from an artery. Arterial blood is bright red because it is oxygenated and is en route to the body's tissues and organs to deliver that oxygen. Bleeding in bright red is a dire emergency due to the large amount of blood that can be lost from an artery. If not stopped through immediate first aid, there is a high likelihood of rapid unconsciousness and death.
To bleed in dark red (actually dark reddish-purple) is to bleed from a vein. Venous blood has already given up its oxygen to organs and tissues. Bleeding in dark red is a lesser emergency and is less likely to cause rapid unconsciousness and death.


text:
Q: Navigation Bar TintColor not working with UIColor initWithPatternImage iOS5 I am using iOS5 and I am trying to set a custom TintColor for my Navigation bar.
Code : This I am using in viewWillAppear:
[self.navigationController.navigationBar setTintColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"NavigationBarImage.png"]]];

The Image is 320 x 44 PNG image available in my application.
When I use
self.navigationController.navigationBar.tintColor = [UIColor orangeColor];

it displays the orange color but not for PatternImage.
What am I doing wrong?

A: You can use  an UINavigationBar category to set background image.
#import "UINavigationBar+Background.h"

@implementation UINavigationBar (Background)

- (void) drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"NavigationBarImage.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end


text:
Q: AngularJS, insert predefined DOM element into html I have an predefined Canvas element in every element of results array, which I use in ng-repeat. I need to place this canvas inside of every element of ng-repeat. {{result.canvas}} didn't work and gives an error.
Tried to insert canvas via directives, but without success.
Every element in results have a bunch of data and one Canvas DOM element. E.g.:
result.canvas = document.createElement("canvas");
And I need to insert this canvas into HTML:

      {{result.canvas}}

Which gives error: https://docs.angularjs.org/error/$interpolate/interr?p0=%0A%20%20%20%20%20%20%20%20%20%20%7B%7Bresult.canvas%7D%7D%0A%20%20%20%20%20%20%20%20%20%20&p1=TypeError:%20Converting%20circular%20structure%20to%20JSON
I need to know how to insert a DOM Element into HTML without getting this error.

A: Angular should have executed $interpolate to replace your double-curlies, and $interpolate in the docs says the parameter should be a string. But your canvas is not a string.
https://docs.angularjs.org/api/ng/service/$interpolate


text:
Q: curl returns blank from valid url I am trying to lookup a zipcode from usps using curl like so:
curl "https://tools.usps.com/go/ZipLookupResultsAction!input.action?resultMode=2&companyName=&address1=&address2=&city=&state=Select&urbanCode=&postalCode=11111&zip="

This url does return normal output from browser.

A: One needs to specify the User-Agent header (using the -A option) so that the request resembles a request from a browser. Also, due to the presence of ! in the URL, one has to use ' instead of ":
curl -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:48.0) Gecko/20100101 Firefox/48.0" \
    'https://tools.usps.com/go/ZipLookupResultsAction!input.action?resultMode=2&companyName=&address1=&address2=&city=&state=Select&urbanCode=&postalCode=10001&zip='


text:
Q: Sorting WTForms form.errors dict The forms.errors dict seems to be sorted on field name, and not on the
order they are declared in the form itself.
E.g.
class ProductForm(Form):
    code = TextField('Code', validators=[Required()])
    description = TextField('Description', validators=[Required(), Length(max=100)])
    amount = DecimalField('Amount', validators=[Required(), NumberRange(min=0.00, max=1000000.00)])
    vat_percentage = DecimalField('VAT %', validators=[Required(), NumberRange(min=0.00, max=100.00)])
    inactive_date = DateField('Inactive date', validators=[Optional()])

Which produces the form.errors like:
{'amount': ['Amount is required'], 'code': ['Code is invalid.'],
'description': ['Description is required'], 'vat_percentage': ['VAT % is required']}

What I would like to do is print the the errors in the order as they are
ordered in the form.
Is this possible?

A: Dictionaries are inherently unordered (in Python).  However, WTForms includes each field's errors on the field as well as the form and it does guarantee that the fields can be enumerated in declared order.  So rather than enumerating form.errors you can loop over form and then loop over each field.errors to get them in order:
for field in form:
    for error in field.errors:
        # Display error


text:
Q: execute Bash script on form submission through browser in php I am trying to execute bash command(to open an application in system) via a browser in php.
(Example) If I run the command in terminal it opens up Shotwell(image viewer) and displays the image.
I want to display image using shotwell in my system when I submit my form. How do I do this?
Here is my code. Why doesn't it work?
form.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
 if(isset($_POST['submit']))
 {
        exec('shotwell bike.jpg');
 }
}
?>

<form  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method=post>
  Store ID:

  <input type="text" name="username" required>

  Department ID:

  <input type="text" name="emailID" required>

  <input type="submit" name="submit" value="Submit">
</form>


text:
Q: How to create an IAsyncResult that immediately completes? I am implementing an interface which requires implementations of BeginDoSomething and EndDoSomething methods. However my DoSomething isn't really long-running.
For simplicity assume DoSomething only compares two variables and return whether a > b
So my BeginDoSomething should be like:
protected override IAsyncResult BeginDoSomething(int a, int b, AsyncCallback callback, object state)
{
     bool returnValue = a > b;
     return ...; //what should I return here?
     //The method actually already completed and I don't need to wait for anything
 }

I don't know what I should return. I only implement BeginDoSomething because I have to, not because my method is long-running. Do I need to implement my own IAsyncResult? Is there an implementation already in .NET libraries?

A: This is a little quick and dirty, but you can implement a class that implements IAsyncResult like so:
    public class MyAsyncResult : IAsyncResult
    {
        bool _result;

        public MyAsyncResult(bool result)
        {
            _result = result;
        }

        public bool IsCompleted
        {
            get { return true; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get { throw new NotImplementedException(); }
        }

        public object AsyncState
        {
            get { return _result; }
        }

        public bool CompletedSynchronously
        {
            get { return true; }
        }
    }

Then use it in your BeginDoSomething like this:
    return new MyAsyncResult(a > b);

A: The quick hack way of doing it is to use a delegate:
protected override IAsyncResult BeginDoSomething(int a, int b, AsyncCallback callback, object state)
{
     bool returnValue = a > b;
     Func<int,int,bool> func = (x,y) => x > y;
     return func.BeginInvoke(a,b,callback,state);
}

The downside of this approach, is that you need to be careful if two threads will be calling this method concurrently you'll get an error.

A: I am not sure if I am missing something but today you can just return Task.CompletedTask/Task.FromResult. Task implements IAsyncResult
protected override IAsyncResult BeginDoSomething(int a, int b, AsyncCallback callback, object state)
{
     return Task.FromResult(a > b);
}

The IAsyncResult.IsCompleted is rightly true here. The Func.BeginInvoke approach wouldn't result in true.

A: I'd suggest you follow the directions here to be able to create your implementations using Task based methods in case one of them does turn out to be long running.  If DoSomething is short running, you can block on it by creating a Task from its result
public IAsyncResult BeginDoSomething(int a, int b,
                                        AsyncCallback callback,
                                        object state)
{
   return Task.FromResult(DoSomething(a, b)).AsApm(callback, state);
}

public bool EndDoSomething(IAsyncResult asyncResult)
{
   return ((Task<bool>)asyncResult).Result;
}

bool DoSomething(int a, int b)
{
   return a > b;
}

public static IAsyncResult AsApm<T>(this Task<T> task,
                                    AsyncCallback callback,
                                    object state)
{
    if (task == null)
        throw new ArgumentNullException("task");

    var tcs = new TaskCompletionSource<T>(state);
    task.ContinueWith(t =>
                      {
                         if (t.IsFaulted)
                            tcs.TrySetException(t.Exception.InnerExceptions);
                         else if (t.IsCanceled)
                            tcs.TrySetCanceled();
                         else
                            tcs.TrySetResult(t.Result);

                         if (callback != null)
                            callback(tcs.Task);
                      }, TaskScheduler.Default);
    return tcs.Task;
}


text:
Q: C++ fmtlib : How to convert a double to existing wchar_t buffer? I'm considering transitioning from snprintf and its ilk to fmtlib.
Imagine this fictional code:
class CFoo
{
  size_t  m_szLen{0};
  wchar_t m_pwcDst[123]{};
  ...

public:
  void Bar(double dValue, uint8 u8TotDecimals)
  {
    m_szLen += swprintf_s(&m_pwcDst[m_szLen], _countof(m_pwcDst)-m_szLen, L"%.*f", u8TotDecimals, dValue);
  }
};

How would I convert this to fmtlib WITHOUT copying std::wstring or fmt_memory_buffer?
So, I want fmt::format_to to use my existing buffer.

A: The closest function there is to swprintf_s() in fmtlib is fmt::format_to_n(). However, it returns the number of characters that would have been written, so you have to take some care using it. Here is how it would look:
void CFoo::Add(double dValue, uint8 u8TotDecimals)
{
    if(pwcSrc) {
        auto space_left = _countof(m_pwcDst) - m_u32Len;
        auto result = fmt::format_to_n(&m_pcwDst, space_left, "{:.{}f}", u8TotDecimals, dValue);
        m_u32Len += std::min(result.size, space_left);
    }
}

However, if you want to do things the proper C++ way, then try to see if you can change the destination buffer to be a std::wstring, and just add directly to that, like so:
void CFoo::Add(double dValue, uint8 u8TotDecimals)
{
    if(pwcSrc)
        m_pwsDst += fmt::format(L"{:.{}f}", u8TotDecimals, dValue);
}

A: It's not as simple/clear as I would have hoped, so that's a shame. But, this might do what I want:
class CFoo
{
  size_t  m_szLen{0};
  wchar_t m_pwcDst[123]{};
  ...

public:
  void Bar(double dValue, uint8 u8TotDecimals)
  {
    m_pwcDst[m_szLen += std::min(_countof(m_pwcDst)-m_szLen-1, fmt::format_to_n(&m_pwcDst[m_szLen], _countof(m_pwcDst)-m_szLen, FMT_STRING(L"{:.{}f}"), dValue, u8TotDecimals).size)] = L'\0';
  }
};

A: {fmt}'s equivalent of swprintf_s is format_to_n which can be used as follows:
auto result = fmt::format_to_n(buffer, buffer_size, "{:.{}}", value, precision);

In your example value is dValue and precision is u8TotDecimals. result.out will give you the pointer to the end of the output and result.size the total output size if the output wasn't truncated (similarly to snprintf).


text:
Q: Uniform random distribution in java i'm generating Random values with range of 5.0 - 9.0, are the numbers generated still uniformly distributed theoretically ??
and how to implement the histogram, i mean what  values we need to implement the histogram  ??
import java.util.Random;

public class GenerateNumber {
    public static void main(String args[]) {

        Random randomGenerator = new Random();

        for (int i = 0; i < 11; i++) {
            double randomDou = randomGenerator.nextDouble() * (9 - 5 + 1) + 5;
            System.out.println(randomDou);
        }
    }
}

*

*i'm zero on math .., pls help me

A: You are on the righ path- scaling the numbers linearly is correct.
To test your logic, plug in 0.0 and 1.0 as values from nextDouble()
0.0 * (9 - 5 + 1) + 5 = 5, o.k.
1.0 * (9 - 5 + 1) + 5 = 10, not o.k.

This is a basic way to test your math.

A: Littile math bug
There is a little bug in the code. You want to have randomly generated numbers between 5.0 to 9.0 but the code you post will give you numbers between 5. and 10.0. So the code should be changed a little bit in the following way:
import java.util.Random;

public class demo {
    public static void main(String args[]) {

        Random randomGenerator = new Random();

        for (int i = 0; i < 11; i++) {
            double randomDou = randomGenerator.nextDouble() * (9 - 5) + 5;
            System.out.println(randomDou);
        }
    }
}

It should be (9 - 5) instead of (9 - 5 + 1) because the later one will give you a range from 5.0 (not included) to 10.0 (included).
Uniformity
Yes, the number will uniformally distributed in the way you did. The java.util.random generates uniformally distributed numbers [1]. Intuitively, aχ(x) + b(1) where a and b are both constants is also uniformally distributed if and only if χ(x) is uniformally distributed.
Back to the question, randomGenerator.nextDouble() * (9 - 5) + 5 is in the form of the Eq.(1) where

*

*(9 - 5) -> a

*randomGenerator.nextDouble() -> χ(x)

*5 -> b

So yes it is  uniformally distributed.
Sorry for the second question about the histrogram because it is not clear and confusing me.
Ref links: [1]:https://perso.ensta-paris.fr/~diam/java/online/notes-java/summaries/60mathsum.html


text:
Q: Azure function with blob storage binding returns 500 http response code if file does not exist I am implementing an Azure function that reads a file from the blob storage. The problem is that the Azure function returns a 500 http response error when the file does not exist in the blob storage. This is quite an undesired behaviour and I'd like to handle the exception and return a 404 error. Is it possible with bindings or should I move to SDK to access the blob storage
function.json
{
  "scriptFile": "__init__.py",
  "entryPoint": "app",
  "bindings": [
    {
      "name": "req",
      "direction": "in",
      "methods": [ "get" ],
      "route": "ReadFile/{filename:alpha?}",
      "type": "httpTrigger"
    },
    {
      "name": "blobstream",
      "type": "blob",
      "path": "files/{filename}",
      "connection": "STRATOS_SAMPLE_BLOB_STORAGE_CONNECTION_STRING",
      "direction": "in"
    },
    {
      "name": "$return",
      "direction": "out",
      "type": "http"
    }
  ]
}

__init__.py
import logging
import azure.functions as func
import json
import pandas as pd
import io

def app(req: func.HttpRequest, blobstream: func.InputStream) -> func.HttpResponse:
    filename = req.route_params.get('filename'):

...

Logs:
2020-10-15T07:34:58.967 [Error] Executed 'Functions.read_file' (Failed, Id=3c5f1534-fb65-4909-946f-e3a415197215)Result: FailureException: AttributeError: 'NoneType' object has no attribute 'type'Stack:   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 297, in _handle__invocation_requestargs[pb.name] = bindings.from_incoming_proto(File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/bindings/meta.py", line 63, in from_incoming_protoreturn binding.decode(datum, trigger_metadata=metadata)File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure/functions/blob.py", line 78, in decodedata_type = data.type
2020-10-15T07:34:58.982 [Error] Executed 'Functions.read_file' (Failed, Id=3c5f1534-fb65-4909-946f-e3a415197215)Result: FailureException: AttributeError: 'NoneType' object has no attribute 'type'Stack:   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 297, in _handle__invocation_requestargs[pb.name] = bindings.from_incoming_proto(File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/bindings/meta.py", line 63, in from_incoming_protoreturn binding.decode(datum, trigger_metadata=metadata)File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure/functions/blob.py", line 78, in decodedata_type = data.type
2020-10-15T07:34:59.001732137Z [41m[30mfail[39m[22m[49m: Function.read_file[0]
2020-10-15T07:34:59.001776638Z       Executed 'Functions.read_file' (Failed, Id=3c5f1534-fb65-4909-946f-e3a415197215)
2020-10-15T07:34:59.001788839Z Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.read_file
2020-10-15T07:34:59.001854541Z  ---> Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException: Result: Failure
2020-10-15T07:34:59.001860041Z Exception: AttributeError: 'NoneType' object has no attribute 'type'
2020-10-15T07:34:59.001920843Z Stack:   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 297, in _handle__invocation_request
2020-10-15T07:34:59.001926443Z     args[pb.name] = bindings.from_incoming_proto(
2020-10-15T07:34:59.001929743Z   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/bindings/meta.py", line 63, in from_incoming_proto
2020-10-15T07:34:59.001970645Z     return binding.decode(datum, trigger_metadata=metadata)
2020-10-15T07:34:59.001982945Z   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure/functions/blob.py", line 78, in decode
2020-10-15T07:34:59.001987145Z     data_type = data.type
2020-10-15T07:34:59.001990145Z
2020-10-15T07:34:59.002043347Z    at Microsoft.Azure.WebJobs.Script.Description.WorkerFunctionInvoker.InvokeCore(Object[] parameters, FunctionInvocationContext context) in /src/azure-functions-host/src/WebJobs.Script/Description/Workers/WorkerFunctionInvoker.cs:line 85
2020-10-15T07:34:59.002086349Z    at Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) in /src/azure-functions-host/src/WebJobs.Script/Description/FunctionInvokerBase.cs:line 85
2020-10-15T07:34:59.002091449Z    at Microsoft.Azure.WebJobs.Script.Description.FunctionGenerator.Coerce[T](Task`1 src) in /src/azure-functions-host/src/WebJobs.Script/Description/FunctionGenerator.cs:line 225
2020-10-15T07:34:59.002155151Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync(Object instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52
2020-10-15T07:34:59.002246954Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker, ParameterHelper parameterHelper, CancellationTokenSource timeoutTokenSource, CancellationTokenSource functionCancellationTokenSource, Boolean throwOnTimeout, TimeSpan timerInterval, IFunctionInstance instance) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 587
2020-10-15T07:34:59.002296856Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 532
2020-10-15T07:34:59.002400059Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, IFunctionOutputDefinition outputDefinition, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 470
2020-10-15T07:34:59.002505363Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 278
2020-10-15T07:34:59.002515663Z    --- End of inner exception stack trace ---
2020-10-15T07:34:59.002926676Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 325
2020-10-15T07:34:59.003123383Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsyncCore(IFunctionInstanceEx functionInstance, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 117
2020-10-15T07:34:59.069209972Z [41m[30mfail[39m[22m[49m: Host.Results[0]
2020-10-15T07:34:59.069229273Z Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.read_file
2020-10-15T07:34:59.069233173Z  ---> Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException: Result: Failure
2020-10-15T07:34:59.069300475Z Exception: AttributeError: 'NoneType' object has no attribute 'type'
2020-10-15T07:34:59.069305475Z Stack:   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 297, in _handle__invocation_request
2020-10-15T07:34:59.069308975Z     args[pb.name] = bindings.from_incoming_proto(
2020-10-15T07:34:59.069360577Z   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/bindings/meta.py", line 63, in from_incoming_proto
2020-10-15T07:34:59.069365777Z     return binding.decode(datum, trigger_metadata=metadata)
2020-10-15T07:34:59.069412379Z   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure/functions/blob.py", line 78, in decode
2020-10-15T07:34:59.069417379Z     data_type = data.type
2020-10-15T07:34:59.069420479Z
2020-10-15T07:34:59.069468581Z    at Microsoft.Azure.WebJobs.Script.Description.WorkerFunctionInvoker.InvokeCore(Object[] parameters, FunctionInvocationContext context) in /src/azure-functions-host/src/WebJobs.Script/Description/Workers/WorkerFunctionInvoker.cs:line 85
2020-10-15T07:34:59.069473881Z    at Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) in /src/azure-functions-host/src/WebJobs.Script/Description/FunctionInvokerBase.cs:line 85
2020-10-15T07:34:59.069518982Z    at Microsoft.Azure.WebJobs.Script.Description.FunctionGenerator.Coerce[T](Task`1 src) in /src/azure-functions-host/src/WebJobs.Script/Description/FunctionGenerator.cs:line 225
2020-10-15T07:34:59.069561684Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync(Object instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52
2020-10-15T07:34:59.069645886Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker, ParameterHelper parameterHelper, CancellationTokenSource timeoutTokenSource, CancellationTokenSource functionCancellationTokenSource, Boolean throwOnTimeout, TimeSpan timerInterval, IFunctionInstance instance) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 587
2020-10-15T07:34:59.069720789Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 532
2020-10-15T07:34:59.069760890Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, IFunctionOutputDefinition outputDefinition, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 470
2020-10-15T07:34:59.069877694Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 278
2020-10-15T07:34:59.069883894Z    --- End of inner exception stack trace ---
2020-10-15T07:34:59.069981998Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 325
2020-10-15T07:34:59.070037899Z    at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsyncCore(IFunctionInstanceEx functionInstance, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 117

A: Unfortunately there is no way in Binding to gracefully handle blob does not exist scenario at this moment. There are open github issues:

*

*https://github.com/Azure/azure-functions-python-worker/issues/670

*https://github.com/Azure/azure-webjobs-sdk/issues/1326
I think you are pretty much left with moving to SDK to access blob instead of binding if you want to handle it.


text:
Q: Посчитать количество слов в строке, которые начинаются на "t" Стоит задача, написать программу, пользователь вводит строку, на выводе программа показывает сколько слов в строке начинается с буквы "t", не работает счетчик, ничего не выводит. Подскажите, пожалуйста, где допустил ошибку.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    int c=0;
    char a[100] = {0};
    cout << "Vvedite stroky: ";
    cin.getline(a,100);
    if (a[100] == 't') {
     c++;
        for (int i = 0; i < strlen(a); i++) {
            if ((a[i] = ' ') && (a[i + 1] == 't')) {
                c++;

            }

        }
        cout << c;
    }

    system("pause");
    return 0;
}

A: У вас вся строка забивается пробелами.
if ((a[i] = ' ') && (a[i + 1] == 't')) {

Надо
if ((a[i] == ' ') && (a[i + 1] == 't')) {

A: Допустим, что вы уже исправили огрех с a[100] и теперь у вас
if (a[0] == 't') {
    c++;
    for (int i = 0; i < strlen(a); i++) {

И что происходит, если у вас первый символ - не t? ваша программа не делает в таком случае ничего.
Вы цикл-то вынесите из тела if...
О том, что в цикле вы портите строку, вместо чтоб сравнивать с пробелом, вам уже написали.
Ну и, конечно, лучше не выскакивайте за пределы строки :), хотя в вашем конкретном случае ничего страшного не происходит - просто бессмысленно смотреть последний символ в строке - понятно, что за ним t вы не встретите.
И еще три маленьких вопроса - вам нужны только слова именно с маленькой t? вам не мешает, что выводимое число сливается в одну строку с "Для продолжения..."? вы смотрите на предупреждения компилятора? уж о присваивании в условии if он должен был вас предупредить...


text:
Q: find general solution from linear equations reduced to row-echelon form $$\begin{pmatrix}
1&2&3&-2&4\\
2&4&8&1&9\\
3&6&13&4&14\\
\end{pmatrix}$$
i got $$\begin{pmatrix}
1&2&0&-19/2&5/2\\
0&0&1&5/2&1/2\\
0&0&0&0&0\\
\end{pmatrix}$$
so i have two equations $$X_1+X_2-19/2X_4+5/2X_5$$ and $$X_3+5/2X_4+X_5/2$$
but im not sure how to make these two into one general solution

A: Supposing you are dealing with the homogeneous system associated to the row-echelon reduced matrix
$$A\textbf X=\textbf 0,$$ we have to solve:
$$\begin{cases}
X_1+2X_2-\frac{19}2X_4+\frac52X_5=0\\
X_3+\frac 52 X_4+\frac 12 X_5=0
\end{cases}
$$
Therefore we can put $X_1, X_2, X_3$ as parameters, $X_1=t, X_2=s, X_3=v$ and solve the system in the two variables remaining $X_4, X_5$ by standards $2\times 2$ linear systems resolving methods.

A: Since $\dim\ker\begin{pmatrix}
1&2&3&-2&4\\
0&0&2&5&1\\
\end{pmatrix}=3$, personally I'd like to give some zeros and then calculate the others:

*

*finding $x=\begin{pmatrix}
a\\
b\\
0\\
0\\
0\\
\end{pmatrix}$, we get $a=2,b=-1$

*finding $x=\begin{pmatrix}
0\\
0\\
a\\
b\\
c\\
\end{pmatrix}$, we get $a=-22,b=5,c=19$

*finding $x=\begin{pmatrix}
0\\
a\\
b\\
c\\
0\\
\end{pmatrix}$, we get $a=19,b=-10,c=4$

Then$$\ker\begin{pmatrix}
1&2&3&-2&4\\
0&0&2&5&1\\
\end{pmatrix}=<\begin{pmatrix}
2\\
-1\\
0\\
0\\
0\\
\end{pmatrix},\begin{pmatrix}
0\\
0\\
-22\\
5\\
19\\
\end{pmatrix},\begin{pmatrix}
0\\
19\\
-10\\
4\\
0\\
\end{pmatrix}>$$


text:
Q: How does the double parenthesis construct work in bash? I read here that double parenthesis allows for C-style variable manipulation. However, it did not work as expected when I tried to compare strings:
(( "a" == "b" )) && echo yes || echo no
# shows yes

I am also confused as to how this works for using variables as booleans. Following the example in the linked answer, I tried the following:
true=1
false=0
a=true
(( a )) && echo yes || echo no
# shows yes
a=false
(( a )) && echo yes || echo no
# shows no

But wouldn't a be a string value of either true or false?
In addition, since a "no error" value (0) is taken as true and any "error" value (non-zero) is taken as false in bash, why does it look like the opposite convention is taken here?

A: The main thing to take note of is that the double-parenthesis construct allows for arithmetic evaluation and expansion, and is not an inline C interpreter. Thus, only the rules defined in  Shell Arithmetic applies, that is, only C operations on integer types work in the double parentheses.

First example: bash constructs expand first
Anything outside the arithmetic operators are expanded first according to bash rules, e.g. quotes, parameter expansion, bash range {1..5} and list{a,b} constructs, before the double parentheses evaluation starts.
In the first example, double quotes cause what's inside to be interpreted as a single word (no effect inside double-paren) and also evaluate things starting with $ (but there's none inside the quotes), so the first example simply becomes (( a == b )).
Thus, the best way to understand how (( )) works is to work out all the bash constructs first in your mind, then plugging it in. You can also write examples to test your assumptions.
Example with parameter expansion taking place:
a=1
b=2
(( a = $b )) # becomes (( a = 2 ))
(( a = b )) # straight arithmetic evaluation of a = b within the double parenthesis
# they produce the same result but how they arrive at the result is different
(( $a = b )) # becomes (( 2 = b ))
# syntax error as that's not a valid expression.

Notes
There are some peculiarities when you compare the closely related $(( )) and (( )) constructs. The former (Arithmetic Expansion) treats the expression as if the expression is within double quotes, while the latter does not, as explained above.

Second example: Variables in the rvalue position expand recursively
There are some subtle rules in Shell Arithmetic:

*

*"The value of a variable is evaluated as an arithmetic expression when it is referenced"

*"or when a variable which has been given the integer attribute using declare -i is assigned a value".

*"A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax"

After trying it out for a bit, you will see that this basically means that any variables in the rvalue will be evaluated recursively until it reaches a value that is either an integer, or is an undefined/null variable name:
b=c
c=d
(( a = b ))
echo $a
# gives 0
d=3
(( a = b ))
echo $a
# gives 3

unset d
declare -i a
a=b
echo $a
# gives 0
d=3
a=b
echo $a
# gives 3

You can also play tricks with putting expressions in variables and evaluating it later:
b=2
c=3
d=c
e=b+d
(( a = e ))
echo $a
# gives 5, as it unfolds like a=b+d; a=2+c; a=2+3

So in the example in the question, a evaluated to true, then evaluated to 1 to give the final result.

How does (( )) reverse the interpretation for true and false
(( 0 ))
echo $? # print the return code of the previous call
# prints 1, which indicates error/false in shell

(( 1 ))
echo $?
# prints 0, indicating success/true

(( 2 ))
echo $?
# prints 0

(( -1 ))
echo $?
# prints 0

So the behaviour inside the parentheses is consistent with the C interpretation for true and false, with 0 indicating false and non-zero indicating true. (( )) "converts" false to a return value of 1 and true to a return value of 0.


text:
Q: How can I completely disable all caching in Safari 4? I want Safari to always fetch resources, regardless of how old they are, rather than the current behaviour. So, it should never heed the HTTP headers or meta tags that dictate caching.
It would be sufficient for this to apply to a limited set of sites.
Is this possible? How?

A: You can enable the Developer menu (Safari, Preferences, Advanced, Show Develop menu in menu bar) and select Disable Caches there.
I'm using Safari 5, but according to here this menu is present in Safari since at least 3.0


text:
Q: Dúvidas com laço do-while Pessoal estou aprendendo programação e estou com dúvidas em relação ao laço do-while, estava resolvendo um exercício porém na hora de executar o código apresenta um problema: não encerra o loop, se eu digitar a opção correta ele informa opção inválida.
Este é o código, peço perdão pelos erros, mas como disse estou aprendendo e a única maneira que tenho para treinar é pelo celular, não tenho PC. Caso verifiquem erros (creio que deve ter vários) peço que informe esses erros e me expliquem o que ser melhorado.
#include <stdio.h>
int main (){
    int qtdf, qtdm, qtdp, qtdc, sexo, olhos;
    // As variáveis abaixo tive que dar valor a elas pois o compilador "exigiu".
    qtdf = 0;
    qtdm = 0;
    qtdp = 0;
    qtdc = 0;
    sexo = 0;

    do {
        printf ("Informe seu sexo:\n\n");
        printf (" 1 - Feminino 2 - Masculino\n\n");
        scanf (" %d", &sexo);
        printf ("Informe a cor dos seus olhos:\n");
        printf ("1 - Pretos 2 - Claros \n\n");
        scanf (" %d", &olhos);
        if (sexo == 1){
            qtdf = qtdf + 1;
        } else if (sexo == 2){
            qtdm = qtdm + 1;
        } else {
            printf ("Opção inválida\n");
        }
        if (olhos == 1){
            qtdp = qtdp + 1;
        } else if (olhos == 2){
            qtdc = qtdc + 1;
        } else {
            printf ("Opção inválida\n");
        }
    } while (sexo != 0);
    printf ("Total de sexo feminino: %d\n", qtdf);
    printf ("Total de sexo masculino %d\n", qtdm);
    printf ("Total de olhos pretos: %d\n", qtdp);
    printf ("Total de olhos claros %d\n", qtdc);
    return 0;
}

!

A: O problema é que sua condição de saída do do-while é 0. Esta entrada de 0, no seu programa, não é esperada nas condições de sexo, ou seja, acaba resultando em opção inválida.
Por isto, um jeito de fazer é quando digitado sexo = 0 você dar um break para sair do laço. Além do mais, se você não quer continuar, porque ter que digitar a cor dos olhos?
#include <stdio.h>
int main() {
    int qtdf, qtdm, qtdp, qtdc, sexo, olhos;
    // As variáveis abaixo tive que dar valor a elas pois o compilador "exigiu".
    qtdf = 0;
    qtdm = 0;
    qtdp = 0;
    qtdc = 0;
    sexo = 0;

    do
    {
        printf("Informe seu sexo:\n\n");
        printf(" 1 - Feminino 2 - Masculino\n\n");
        scanf_s(" %d", &sexo);
        printf("Informe a cor dos seus olhos:\n");
        printf("1 - Pretos 2 - Claros \n\n");
        scanf_s(" %d", &olhos);

        if (sexo == 1)
            qtdf = qtdf + 1;
        else if (sexo == 2)
            qtdm = qtdm + 1;
        // Como 0 é a condição para saída no seu do-while, fazemos um break quando digitado
        // Porque não faria sentido digitar a cor dos olhos sem querer continuar
        else if (sexo == 0)
            break;
        else if(sexo != 0)
            printf("Opção inválida\n");

        if (olhos == 1)
            qtdp = qtdp + 1;
        else if (olhos == 2)
            qtdc = qtdc + 1;
        else
            printf("Opção inválida\n");
    } while (sexo != 0);

    printf("Total de sexo feminino: %d\n", qtdf);
    printf("Total de sexo masculino %d\n", qtdm);
    printf("Total de olhos pretos: %d\n", qtdp);
    printf("Total de olhos claros %d\n", qtdc);
    return 0;
}

Outro problema é: se eu digitar opção inválida de sexo, a cor dos olhos ainda é solicitada e se eu digitar o sexo válido e a cor dos olhos não, ainda sim é somado ao final.
Por este motivo, eu pensaria em fazer da seguinte forma: solicita ambas as informações sem somar nada e checa por elas. Se alguma estiver inválida, não fazemos nada e continuamos o loop. Só fazemos ao final com tudo validado.
Só para exemplificar e você pegar a ideia
#include <stdio.h>

int main()
{
    int qtdf, qtdm, qtdp, qtdc, sexo, olhos;
    // As variáveis abaixo tive que dar valor a elas pois o compilador "exigiu".
    qtdf = 0;
    qtdm = 0;
    qtdp = 0;
    qtdc = 0;
    sexo = 0;

    do
    {
        printf("Informe seu sexo:\n\n");
        printf(" 1 - Feminino 2 - Masculino\n\n");
        scanf_s(" %d", &sexo);
        printf("Informe a cor dos seus olhos:\n");
        printf("1 - Pretos 2 - Claros \n\n");
        scanf_s(" %d", &olhos);

        if ((sexo == 1 || sexo == 2) && (olhos == 1 || olhos == 2))
        {
            if (sexo == 1)
                qtdf = qtdf + 1;
            else if (sexo == 2)
                qtdm = qtdm + 1;

            if (olhos == 1)
                qtdp = qtdp + 1;
            else if (olhos == 2)
                qtdc = qtdc + 1;
        }
        else if (sexo != 0)
            printf("Opção inválida\n");
    } while (sexo != 0);

    printf("Total de sexo feminino: %d\n", qtdf);
    printf("Total de sexo masculino %d\n", qtdm);
    printf("Total de olhos pretos: %d\n", qtdp);
    printf("Total de olhos claros %d\n", qtdc);
    return 0;
}

A: Olá, em minha opinião seu código está indo bem, o que aconselharia era mudar um pouco a posição e acrescentar um break para que ele saia do loop assim que o usuário der uma opção inválida:
int main (){

 int qtdf=0, qtdm=0, qtdp=0, qtdc=0, sexo, olhos;

do {
    printf ("Informe seu sexo:\n\n");
    printf (" 1 - Feminino 2 - Masculino\n\n");
    scanf (" %d", &sexo);
    if (sexo == 1){
        qtdf = qtdf + 1;
    } else if (sexo == 2){
        qtdm = qtdm + 1;
    } else {
        printf ("Opção inválida\n");
        break;
    }

    printf ("Informe a cor dos seus olhos:\n");
    printf ("1 - Pretos 2 - Claros \n\n");
    scanf (" %d", &olhos);
    if (olhos == 1){
        qtdp = qtdp + 1;
    } else if (olhos == 2){
        qtdc = qtdc + 1;
    } else {
        printf ("Opção inválida\n");
        break;
    }
} while (sexo != 0);
printf ("Total de sexo feminino: %d\n", qtdf);
printf ("Total de sexo masculino %d\n", qtdm);
printf ("Total de olhos pretos: %d\n", qtdp);
printf ("Total de olhos claros %d\n", qtdc);
return 0;
}

Dessa forma quando o usuário informar uma opção inválida no sexo por exemplo o programa já irá sair do loop sem perguntar outra opção e já irá mostrar a saída do programa.
O que estava acontecendo antes no seu código era que pela sequência do código ao informar um sexo inválido mesmo assim o programa continuava executando até o fim, onde existia a mensagem de código inválido, com a mudança na ordem do código assim que o usuário digitar algo inválido ele já sai imediatamente do loop e dá a mensagem.
Espero que tenha te ajudado amigo :).


text:
Q: Request goes into Keycloak even if configured as permitAll I have below WebSecurityConfigurerAdapter which is to authenticate using KeyCloak if it doesn't have specific path's in the URL. In my case it's except "/payment/**" everything should be bypassed. Only "/payment/**"should be authenticated using KeyCloak.
@Bean
@Override
@Primary
public KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {

    KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(
            authenticationManagerBean()
            , new RequestMatcher(new AntPathRequestMatcher("/payment/**"))
    );

    filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
    return filter;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.csrf().disable().cors().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.authorizeRequests()
            .anyRequest().permitAll()
            .antMatchers("/payment/**").authenticated();
    http.headers().addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy", "script-src 'self'"));
}

Actual: If I have hit @GET request /public/** with Bearer Token(only in the case of Bearer Toke as I have other request which has bearer token in it), it gives me following error

Error: o.k.a.rotation.AdapterTokenVerifier      : Didn't find publicKey for kid: RVH0bfDX6ZPkFkVBvCl5zV2BVPGMtvbhenA6dh9IDxs

Excepted: It should not invoke KeyCloak at all as request is other than /payment/**
Tried:  All the possible ways to negate(/payment/**) or only accept(/payment/**) in request filter. Though if it sees Authorization header it goes into KeyCloak for any request or path.
StackTrace:
2021-03-30 15:56:37.298 DEBUG 67688 --- [  XNIO-1 task-1] o.k.adapters.PreAuthActionsHandler       : adminRequest http://localhost:9090/api/public/orders/94
2021-03-30 15:56:37.299 DEBUG 67688 --- [  XNIO-1 task-1] o.k.adapters.PreAuthActionsHandler       : adminRequest http://localhost:9090/api/public/orders/94
2021-03-30 15:56:37.309 DEBUG 67688 --- [  XNIO-1 task-1] o.k.a.BearerTokenRequestAuthenticator    : Found [1] values in authorization header, selecting the first value for Bearer.
2021-03-30 15:56:37.309 DEBUG 67688 --- [  XNIO-1 task-1] o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
2021-03-30 15:56:37.318 DEBUG 67688 --- [  XNIO-1 task-1] o.keycloak.adapters.KeycloakDeployment   : Resolving URLs from https://keycloak-dev.deviceapi.com/auth/realms/admin/.well-known/openid-configuration
2021-03-30 15:56:38.018  INFO 67688 --- [  XNIO-1 task-1] o.keycloak.adapters.KeycloakDeployment   : Loaded URLs from https://keycloak-dev.deviceapi.com/auth/realms/admin/.well-known/openid-configuration
2021-03-30 15:56:38.128 DEBUG 67688 --- [  XNIO-1 task-1] o.k.a.rotation.JWKPublicKeyLocator       : Realm public keys successfully retrieved for client DEVICE-PROJECT-EVENT. New kids: [yUDSD-1WHU4B07pkSQZTfA7_XPGu4jeUdAZKPTBJT98]
2021-03-30 15:56:38.128 ERROR 67688 --- [  XNIO-1 task-1] o.k.a.rotation.AdapterTokenVerifier      : Didn't find publicKey for kid: RVH0bfDX6ZPkFkVBvCl5zV2BVPGMtvbhenA6dh9IDxs
2021-03-30 15:56:38.128 DEBUG 67688 --- [  XNIO-1 task-1] o.k.a.BearerTokenRequestAuthenticator    : Failed to verify token
2021-03-30 15:56:38.130 DEBUG 67688 --- [  XNIO-1 task-1] o.k.adapters.RequestAuthenticator        : Bearer FAILED

Why KeyCloak fetches value from Authorization Header as the request should be bypassed as it's other than /payment/**?

Found [1] values in authorization header, selecting the first value for Bearer.

Findings:

Request goes under
org.keycloak.adapters.BearerTokenRequestAuthenticator.authenticate(...)
Though it shouldn't, as request is from /public/**(With Authorization Header) and not /payment/**

Is there a way one can make such request in KeyCloak configuration which can accept only (/payment/**) with Authorization Token and ignores the rest?


text:
Q: Order of LIKE clause in query when wanting to use multiple terms I have the query
SELECT * FROM images WHERE tags LIKE '%example%hello%'

I would like the database to select rows which have 'example' and 'hello' in the 'tags' column in any order, as in:
A row with 'hello, test, example', also 'example, hello, test' or any other variation of this order.
Is this possible, even without using LIKE? The rows must all contain everything specified with LIKE.
EDIT: Such as, when I provide 'example' and 'hello' in the query, rows returned must contain both 'example' and 'hello'.

A: You could try a simple OR for a quick solution:
SELECT * FROM images WHERE tags LIKE '%example%' OR tags LIKE '%hello%'

EDIT
To address your edit, you can use AND instead:
SELECT * FROM images WHERE tags LIKE '%example%' AND tags LIKE '%hello%'

A: You could use FIND_IN_SET:
SELECT tags FROM images WHERE FIND_IN_SET('hello', tags) AND FIND_IN_SET('example', tags)

However, this requires that tags not have spaces after the comma (you will have to do replace on tags or more boolean checks in that case).  This might be faster than LIKE.  I'm not sure.


text:
Q: Error 0x80070570 while installing Windows 10 I'm following this answer to install Windows 10 on a new drive.
I created a bootable USB drive using the Win10_1803_English_x64.iso image, once with WoeUSB, and once manually, but the installation failed each time. The result was the following error message at around the 10% mark:
Windows cannot install required files. The file may be corrupt or missing. Make sure all files required are available, and restart the installation.
Error code : 0x80075070

The ISO file seems to be valid - I've checked its checksum.
How can I complete the installation?


text:
Q: remove white block of text I used codes below to display numbers on UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";

    TDBadgedCell *cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    [cell setText:[ NSMutableString  stringWithFormat:@"%d", [[aArray objectAtIndex:indexPath.row] intValue]]] ;

    [cell  setBackgroundColor:[UIColor clearColor]];

    return cell;

}

but the text of numbers have white block on background
how to remove these white blocks?
Welcome any comment

A: try [cell.textLabel setBackgroundColor:[UIColor clearColor]];
and [cell setText:] is deprecated,
use [cell.textLabel setText:]

A: try this
cell.textLabel.backgroundColor = [UIColor clearColor];

A: In your custom UITableViewCell, TDBadgedCell, you are probably adding a UILabel to the cell.  Your setText method is probably setting the UILabel text.  For this UILabel, set it's background color to clear like others have suggested.
You can set the UILabel background color to clear one time your initWithStyle: reuseIdentifier: method.


text:
Q: ValueError in text file after writing through one program and graphing through another So, I have a program that writes on to the txt file
 global v,t

    v=random.randint(1,4)
    txt=open('bv.txt','a')
    txt.write(str(v)+","+str(t) +"\n")
    t+=1
    txt.close()

after getting two values, I take these values and graph them through another program which i plan to integrate into my main GUI.
import matplotlib.pyplot as plt

def graph():

            x=[]
            y=[]

            readFile= open('bv.txt', 'r')

            sepFile = readFile.read().split('\n')

            readFile.close()

            for plotpair in sepFile:
                xAndY = plotpair.split(',')
                y.append((xAndY[0]))
                x.append(int(xAndY[1]))

            plt.plot(x, y)
            plt.show()

 graph()

So after doing this, it seems pretty staright forward, but I get an error stating that value cannot be added. I had initially used random.uniform but since it had a valueError that int cannot convert base 10 values, i eventually tried random.randint which gave int values yet it gave the same error.
The first time i had added my own valeus in the text file, it worked, yet after deleting those and inserting values through my program it just does not seem to work.
Please give your inputs for this.

A: if you don't mind using numpy, np.genfromtxt can do this a lot more simply:
import matplotlib.pyplot as plt
import numpy as np

def graph():
    x,y=np.genfromtxt('bv.txt',delimiter=',',unpack=True)
    plt.plot(x, y)
    plt.show()

graph()


text:
Q: Supporting multi google drive in one application? I have server which has credentials of several google drives(client_id, client_secret, refresh token for each google drive which generated from google console). I have clients. Whenever some client wants to upload, I choose one google drive, make authentication and send url with access token to a client, so it can upload. It works with single google drive. However if I want to give that time to some another client, another google drive's url for uploading, google does not allowing to do so. Below is log when client can not upload:
 "kind": "drive#permission",
 "etag": "\some_encrypted_string_here"\"",
 "id": "anyoneWithLink",
 "selfLink": "https://www.googleapis.com/drive/v2/files/folder_id/permissions/anyoneWithLink",
 "role": "reader",
 "type": "anyone",
 "withLink": true

Does google drive allows for one application at the same time make several authentication for several google drives, getting urls and use it by clients to upload file?
Any help kindly appreciated, thanks in advance

A: Does google drive allows for one application at the same time make several authentication for several google drives, getting urls and use it by clients to upload file?
Yes it does.


text:
Q: How do I rotate a 3D object relative to its orientation using quaternions? As a learning experience, I'm trying to build a simple 3D game without any libraries. I've managed to figure out rendering (for the most part), and I've gotten 4D matrix transforms to work well enough.
I'm having trouble rotating my player object relative to its own orientation; I want to build an arcade-like flight model, so that the object rolls, yaws, and pitches relative to its current orientation, not relative to the world space.
A few articles pointed me to quaternions as a better solution for rotation than the 4D matrix. After a little reading I thought I had it figured out, but in practice I can't get that approach to work. I think I'm either calculating the rotational axes incorrectly, or I'm applying them to the quaternions completely the wrong way.
I don't fully understand how the math works, so there could be something obvious here that I'm missing. I've read several articles on this topic, and read about quaternion math until my brain melted, so any help would be great!
Here are relevant parts of my code, a link to a JSFiddle demo, and two of the articles I found the most helpful in my research:
https://jsfiddle.net/peternatewood/guwd03et/
https://www.3dgep.com/understanding-quaternions/
http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/
var player = {
  // These keep track of player input: -1 and 1 are opposite directions, 0 is no input
  roll: 0, pitch: 0, yaw: 0,
  radians: [0, 0, 0], // X, Y, Z
  // Keep track of the rotational axes
  axisX: [1, 0, 0],
  axisY: [0, 1, 0],
  axisZ: [0, 0, 1],
  // 4D matrices
  scale: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,1
  ],
  trans: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,1
  ],
  rotX: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,1
  ],
  rotY: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,1
  ],
  rotZ: [
    1,0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,1
  ]
};

/*
  This also updates the player's radians, so I use it
  for both the matrix and quaternion transforms
  "mod" is a timing modifier to account for varying framerates
*/
function updateMatrix3D(mod) {
  var rad, sin, cos;

  if (player.yaw) {
    player.axisY[0] = Math.sin(player.radians[0]);
    player.axisY[1] = Math.cos(player.radians[1]);
    player.axisY[2] = Math.sin(player.radians[2]);

    rad = player.radians[1] + mod * player.yaw / 40;
    if (rad >= TAU) {
      rad -= TAU;
    }
    if (rad < 0) {
      rad += TAU;
    }
    player.radians[1] = rad;

    var sinY = Math.sin(-player.radians[1]);
    var cosY = Math.cos(-player.radians[1]);

    player.rotY[ 0] =  cosY;
    player.rotY[ 2] = -sinY;
    player.rotY[ 8] =  sinY;
    player.rotY[10] =  cosY;
  }

  if (player.roll) {
    player.axisZ[0] = Math.sin(player.radians[0]);
    player.axisZ[1] = Math.sin(player.radians[1]);
    player.axisZ[2] = Math.cos(player.radians[2]);

    rad = player.radians[2] + mod * player.roll / 40;
    if (rad >= TAU) {
      rad -= TAU;
    }
    if (rad < 0) {
      rad += TAU;
    }
    player.radians[2] = rad;

    var sinZ = Math.sin(player.radians[2]);
    var cosZ = Math.cos(player.radians[2]);

    player.rotZ[ 0] =  cosZ;
    player.rotZ[ 1] = -sinZ;
    player.rotZ[ 4] =  sinZ;
    player.rotZ[ 5] =  cosZ;
  }

  if (player.pitch) {
    player.axisX[0] = Math.cos(player.radians[0]);
    player.axisX[1] = Math.sin(player.radians[1]);
    player.axisX[2] = Math.sin(player.radians[2]);

    rad = player.radians[0] + mod * player.pitch / 40;
    if (rad >= TAU) {
      rad -= TAU;
    }
    if (rad < 0) {
      rad += TAU;
    }
    player.radians[0] = rad;

    var sinX = Math.sin(-player.radians[0]);
    var cosX = Math.cos(-player.radians[0]);

    player.rotX[ 5] =  cosX;
    player.rotX[ 6] =  sinX;
    player.rotX[ 9] = -sinX;
    player.rotX[10] =  cosX;
  }
}

// Quaternion => [scalar, x-value * i, y-value * j, z-value * k]
function transformQuat(v, q) {
  return [
    q[3]*q[3]*v[0] + 2*q[1]*q[3]*v[2] - 2*q[2]*q[3]*v[1] + q[0]*q[0]*v[0] + 2*q[1]*q[0]*v[1] + 2*q[2]*q[0]*v[2] - q[2]*q[2]*v[0] - q[1]*q[1]*v[0],
    2*q[0]*q[1]*v[0] + q[1]*q[1]*v[1] + 2*q[2]*q[1]*v[2] + 2*q[3]*q[2]*v[0] - q[2]*q[2]*v[1] + q[3]*q[3]*v[1] - 2*q[0]*q[3]*v[2] - q[0]*q[0]*v[1],
    2*q[0]*q[2]*v[0] + 2*q[1]*q[2]*v[1] + q[2]*q[2]*v[2] - 2*q[3]*q[1]*v[0] - q[1]*q[1]*v[2] + 2*q[3]*q[0]*v[1] - q[0]*q[0]*v[2] + q[3]*q[3]*v[2],
    1 // I set w to 1 because I don't need to scale anything
  ];
}

/*
quatX => Pitch
quatY => Yaw
quatZ => Roll
*/
function renderQuaternion() {
  var quatX = [
    player.axisX[0] * Math.sin(player.radians[0] / 2),
    player.axisX[1] * Math.sin(player.radians[0] / 2),
    player.axisX[2] * Math.sin(player.radians[0] / 2),
    Math.cos(player.radians[0] / 2)
  ];
  var quatY = [
    player.axisY[0] * Math.sin(player.radians[1] / 2),
    player.axisY[1] * Math.sin(player.radians[1] / 2),
    player.axisY[2] * Math.sin(player.radians[1] / 2),
    Math.cos(player.radians[1] / 2)
  ];
  var quatZ = [
    player.axisZ[0] * Math.sin(player.radians[2] / 2),
    player.axisZ[1] * Math.sin(player.radians[2] / 2),
    player.axisZ[2] * Math.sin(player.radians[2] / 2),
    Math.cos(player.radians[2] / 2)
  ];

  // Rendering happens here
}


text:
Q: How to import other python modules and packages I have the following project structure,
work_directory:
    merge.py
    a_package

(i.e. a python file merge.py and a directory a_package under the directory "work_directory")
I wrote a MapReduce job using MRJob in merge.py, in which I need to import a_package, like from a_package import something.
But I have difficulty uploading a_package into hadoop.
I have tried this method(https://mrjob.readthedocs.io/en/latest/guides/writing-mrjobs.html#using-other-python-modules-and-packages): I wrote
class MRPackageUsingJob(MRJob):
    DIRS = ['a_package']

and import code from inside a mapper
def mapper(self, key, value):
    from a_package import something

I also tried this one: https://mrjob.readthedocs.io/en/latest/guides/setup-cookbook.html#uploading-your-source-tree
But neither of them work, it keeps showing ImportError: No module named a_package.
What should I do?

A: You need just create empty file "__init__.py" in folder, what you want to use like a package.
For example:
work_directory:
  __init__.py
  merge.py
  a_package


text:
Q: REQUEST_URI is populated with default-file (DirectoryIndex) /index.html After a migration to a new server with Centos some behaviour changed.
The environment-variable REQUEST_URI contains '/index.html' when http://example.com is fetched (without the index.html).
I would expect:
REQUEST_URI is '/' when http://example.com is fetched.
REQUEST_URI is '/index.html' when http://example.com/index.html is fetched.
This has consequences in my .htaccess (rewriterules react on 'index.html' instead of 'empty string'), as well as in my scripts (Perl $ENV{'REQUEST_URI'})
How to provoke REQUEST_URI being populated with '/' when only http://example.com is fetched?

A: Try disabling DirectoryIndex and MultiViews, place this at the top of your .htaccess:
DirectoryIndex disabled
Options -MultiViews

A: Seems the problem only occurs when in Plesk 'Hosting settings' PHP Support is set to
'Run PHP as FPM application served by nginx'
when i change it to
'Run PHP as FPM application served by Apache'
or
'Run PHP as FastCGI application served by Apache'
there's no problem.


text:
Q: Creating Tabels Using T-SQL I'm reading Beginner ASP.NET MVC 4 and I have to create some tables using T-SQL. All works fine so far, but when I'm trying to copy this in T-SQL editor (in Visual Studio 2012)
ALTER TABLE [dbo].[UserProfile]
ADD
[FirstName] VARCHAR(150) NOT NULL,
[LastName] VARCHAR(150) NOT NULL,
[Email] VARCHAR(150) NOT NULL;

The error is :

In this context, you must specify columns by using a CREATE TABLE instead of by using ALTER TABLE statement

In other table I have following code:
...
REFERENCES **[UserProfile]** ([UserId])
...

but in book is no [UserProfile] table.
Can somebody help me with this ALTER TABLE?

A: ALTER TABLE will work only if that table exists in the database.
If you say there is no UserProfile table, then you should create it with:
CREATE TABLE [dbo].[UserProfile] (
  [FirstName] VARCHAR(150) NOT NULL,
  [LastName] VARCHAR(150) NOT NULL,
  [Email] VARCHAR(150) NOT NULL
)

A: The [UserId] column should be created before ALTER TABLE. And here the Alter Table is just add the column [FirstName],[LastName] and [Email].

A: First check if the table exists, if not create.
IF NOT EXISTS (SELECT 1 FROM sys.tables WHERE [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
    CREATE TABLE [dbo].[UserProfile] (
          [FirstName] VARCHAR(150) NOT NULL,
          [LastName] VARCHAR(150) NOT NULL,
          [Email] VARCHAR(150) NOT NULL
        )
END

Then check if each individual columns that you need exist and take care of those
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE [name] = 'FirstName' AND [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
    ALTER TABLE dbo.UserProfile
        ADD [FirstName] VARCHAR(150) NOT NULL
END

IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE [name] = 'LastName' AND [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
    ALTER TABLE dbo.UserProfile
        ADD LastName VARCHAR(150) NOT NULL
END

IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE [name] = 'Email' AND [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
    ALTER TABLE dbo.UserProfile
        ADD Email VARCHAR(150) NOT NULL
END

A: If you see this in Visual Studio, make sure your script file is not included in Build, right click on .sql file and see properties, set 'Build Action' to none. That will get rid of the error. This error broke the build in Jenkins and this solution fixed that for me.


text:
Q: Pass the result of a Velocimacro into another Velocimacro I have a few Velocity Macros (Velocimacros) I am using in some of my templates; I would like to pass the results of say a date format macro into another that pads string values. I am trying the following:
#pad(#dateFormat("my date"), 30)

I am getting an exception saying, "Invalid arg #0 in VM #pad..."
Is it not possible to pass the results of a macro into another macro? I tried to set the value of the "#dateFormat" macro into a variable using:
#set ($myParam = #dateFormat("my date"))

however, I am getting another exception.
Thanks.

A: Use string interpolation:
#pad( "#dateFormat('my date')", 30)

Only works for string values, but it's what works. :)


text:
Q: Product of distances to asymptotes in a rectangular hyperbola I need to prove that in a rectangular hyperbola, then the product of the distances of any point in the hyperbole to the asymptotes is a constant.
So I started by using the definition of a rectangular hyperbole.
this being $$b=a$$
So then the equations of the asymptotes are: $$y=x$$ and $$y=-x$$
From there I used the general formula of a hyperbole to get the formula for any point given an x coordinate, which was $$\left(x,\frac{\sqrt{x^2b^2}}{a}\right)$$
Then I applied the formula of distance from line to point using both asymptotes, and now I proceed to multiplying them. But I don't know if I'm going the right direction. Any help would be appreciated! (:

A: The asymptotes, as you've noted, are the lines $x\pm y=0$. The distances to these lines from an arbitrary point $(x,y)$ are given by the usual point-to-line distance formulas: ${|x \pm y| \over \sqrt2}$; their product is $\frac12|x^2-y^2|$. For a point on the hyperbola, $x^2-y^2=a^2$, therefore the product of the distances for any point on the hyperbola is $\frac{a^2}2$.
This generalizes to any hyperbola: Given a pair of intersecting lines $ax+by+c=0$ and $px+qy+r=0$, the family of hyperbolas with those asymptotes is given by the equations $(ax+by+c)(px+qy+r)=k$ for various values of the parameter $k$. However, the left-hand side of this equation is just the product of the numerators of the formulas for the distances of a point to these lines, and so the product of these distances for a point on the hyperbola is $$\left|{k \over \sqrt{(a^2+b^2)(p^2+q^2)}}\right|.$$ Indeed, we can drop the absolute value signs: the product of the signed distances for a fixed choice of orientation of the normals to the asymptotes is constant.


text:
Q: Use custom field value as href I created a custom field and would like to use its value as the href on a  tag that would go on my footer.
The custom field is on the Settings > General area of the dashboard and I used add_settings_field() in order to create it.
So, for example, the value inserted in my custom field is "https://www.google.com" and I would like that in my href. It would basically look like this:
Click Here

Is there any way to accomplish that?

A: To retrieve a value after using add_settings_field() you should use get_option().
So you could do something like this...
$value = esc_html(get_option('option_name'));

if ($value) {
    echo 'Click Here';
}

You just need to change option_name to your field name.  The code will grab the value and if it isn't false echo the link.  Also added the escaping.
*Updated after OP gave more details