text:
Q: how to convert format of my .pdf file to .txt in Django I am working on a Django web-application, where I want to convert .pdf and .docx files to .txt  .
I wrote a save() function where I want to get the file and then convert it into .txt format . But it is giving me the error that :

FileNotFoundError at /post/new/
[Errno 2] No such file or directory: 'Python String.pdf'

my models.py is :

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
import PyPDF2
import os
# Create your models here.
class FileUpload(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True)
    file = models.FileField(upload_to='files')

    def save(self, *args, **kwargs):
        if self.file:
            pdffileobj = open(str(self.file.name), 'rb') # this is where i want to get the file but it give me the error
            pdfreader = PyPDF2.PdfFileReader(pdffileobj)
            x = pdfreader.numPages
            pageobj = pdfreader.getPage(x + 1)
            text = pageobj.extractText()
            file1 = open(self.file.name.txt, "a")
            file1.writelines(text)
        super(FileUpload, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('home')

The conclusion is I want to convert my .pdf to .txt before saving it .
Thank you

A: i have not worked with django but this code might help:
use os for file path
os.path.join(os.path.dirname(os.path.dirname(__file__)),'filename')

source : https://stackoverflow.com/a/24971898/13319197


text: Q: how to hide php_self I am running my site on an Apache server with php. I use htaccess to hide informations from the URL and make them look good. But if I check the header of my website in browser, the php_self shows the actual path of the file opened. Is there a way to hide it or change its value?

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS and page resizing I`m setting up a simple page with a top section and
the portion below split into vertical sections.
The left section contains a site menu, the right section
holds verbiage and the middle is a space between left and
right (not needed?).
My issues:

*

*When the page is resized horizontally , the right
section moves over the left totally obscuring the site menu.

*Text in the right section wraps over into the left below
the site menu. I'd like the text in the right section to stay in the
right section.

.top {
  width: auto;
  height: auto;
  padding-bottom: 50px;
  background-color: white;
}

.ileft {
    width: 15%;
    float: left;
    background-color: white;
}

.imiddle {
    width: 5%;
    float: left;
    background-color: white;
}

.iright {
   width: 80%;
   float: left
   margin-left: 30px;
   background-color: white;
}

A: Please do as others said and use either flex or grid to create this layout.
But if you want to go with this setup for some reason, the problem with your code is that you have a missing ; after your float property in the .iright selector and you need to set your width to calc(80% - 30px) so it considers the margin-left property (or just remove the margin-left).

/* Added so you can see the output better */
div {
  height: 40px;
}

.top {
  width: auto;
  height: auto;
  padding-bottom: 50px;
  background-color: red;
}

.ileft {
    width: 15%;
    float: left;
    background-color: blue;
}

.imiddle {
    width: 5%;
    float: left;
    background-color: purple;
}

.iright {
   width: calc(80% - 30px);
   float: left;
   padding: left;
   margin-left: 30px;
   background-color: yellow;
}

Top

Left

M

Right

Please do as others said and use either flex or grid to create this layout.

A: -You can use "media queries" to re-adjust your content according to the size of the screen, in whichever way you want including font-size, for example: when it resizes itself to a smaller size using the media queries, the text won't wrap.
See:
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
-And you should also check alternative layout methods other than float such as:
https://developer.mozilla.org/en-US/docs/Web/CSS/flex
https://developer.mozilla.org/en-US/docs/Web/CSS/grid

A: Here you go. You may want to use a more flexible way to layout the page (flex, grids, ...)
Oh, and you are welcome about those delightful colors.

div {
  height: 100px;
}

.iLikeFlex {
 display: flex
}

header {
  background-color: MediumSlateBlue;
  height: 50px;
}

.ileft {
  /* Fixed width - 150px */
  flex: 0 0 150px;
  background-color: DeepPink;
}

.imiddle {
  /* Fills all remaining space */
  flex: 1;
  /* But you still can limit its min or max size*/
  min-width: 300px;
  background-color: PeachPuff;
}

.iright {
  /* Fixed width - 200px */
  flex: 0 0 200px;
  background-color: tomato;
}

A:

/* Column container */
.row {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

/* left column */
.side {
  -ms-flex: 20%;
  flex: 20%;
  background-color:green;
  padding: 20px;
}

/* Main column */
.main {
  -ms-flex: 80%;
  flex: 80%;
  background-color: blue;
  padding: 20px;
  float: center;
}

@media screen and (max-width: 700px) {
  .row {
    flex-direction: column;
  }
}


text:
Q: Inconsistencies in the definition of derivative of a polynomial over a field A problem I came across defines a particular differentiation operator $D$ over the set of polynomials $\{P\}$ over a field $F$ with "the normal formula; that is $D(\sum_{i=0}^n a_nx^i) = \sum_{i=1}^n na_nx^{i-1}$." However, there seem to be some problems with this definition. First, we cannot assume that $F$ contains the natural numbers as a subset. For example, what is $D(x^2)$ if $F = \mathbb{Z_2}$? Furthermore, the derivative may not be well-defined, depending on the definition of equality for polynomials. For example, if $F = \mathbb{Z_3}$, then $2x^2 + x = 0$ for $x \in \{0, 1, 2\}$, but $D(2x^2 + x) = 2(2)x+1 = x + 1 \neq 0 = D(0)$.
The problem then defines the derivative of rational functions $P/Q$ with the standard quotient rule formula $D(P/Q) = \frac{P'Q - PQ'}{Q^2}$ and then asks to prove that that definition is well-defined, but I can't do that without knowing that the derivative of polynomials exists and is well-defined. Can anyone shed some light on how to interpret the definition given, or what restrictions need to be made to make it work?

A: Several of the other answers have pointed out the danger of conflating a polynomial $p$ with a polynomial function.  When working over the real numbers this distinction isn't particularly important, as there is a one-to-one correspondence between the two types of objects, but over arbitrary rings (even other fields) the distinction is very important.  The definition of derivative given in the OP applies to polynomials, and one way of paraphrasing the question is to ask under what conditions it can be applied consistently to polynomial functions.
With that as framing, here are a couple of observations that (I think) have not yet been made by the other answers.
Let $R$ be any ring, and let $p \in R[x]$ be any polynomial with coefficients in $R$.  Note that we  are thinking of $p$ here as a formal expression of the form $a_n x^n + \cdots a_0$, where each $a_k \in R$, but we are not thinking of $p$ as a function on $R$.  However, $p$ does naturally induce a function $R \to R$, and it is useful to have a notation for that function, so let's call it $\hat{p}$.  We now have two different objects,
$$p \in R[x]$$
and
$$\hat{p} \in R^R$$
where $R^R$ denotes the set of all functions that map $R \to R$.  Both $R[x]$ and $R^R$ are rings:  in $R[x]$ the addition and multiplication operations are "formal" (i.e. you just use the distributive and associative properties to expand and simplify a combination of polynomials) whereas in $R^R$ the addition and multiplication operations are "pointwise" (e.g., if $f,g \in R^R$ then $f+g$ is defined to be the function that maps $r \in R$ to $f(r) + g(r)$).  One can now check that the association $p \mapsto \hat{p}$ is a ring homomorphism.
This homomorphism (which we can call the "functional interpretation map" and denote by $\Phi$) is not, in general, one-to-one.  For instance if $R=\mathbb{Z}_p$ for some prime $p$ then the kernel of $\Phi$ is generated by $x^p - x$.  This means that when $x^p - x$ is interpreted as a function, it "acts like" the (constant) zero function.  Put another way we can say that $x^p$ and $x$ are equivalent as functions even though they are distinct as polynomials.  More precisely, using the notation above we can write $\hat{x^p} = \hat{x}$ even though $x^p \ne x$.
This example also shows that the formal derivative rule in the OP does not "work" at the level of functions, because the formal derivative of $x^p$ is $p\cdot x^{p-1} = 0$, whereas the formal derivative of $x$ is $1$, so polynomials that are equivalent when interpreted as functions do not necessarily have equivalent derivatives.
(For the general question "When is $\Phi$ one-to-one?", see https://mathoverflow.net/questions/160986/rings-for-which-no-polynomial-induces-the-zero-function.)
So the other answers to this question, which point out that the formal derivative definition applies in the context of "formal polynomials" but not necessarily in the context of "polynomial functions", are spot on.  However, notwithstanding that it turns out that there is an alternative way to define the derivative of a polynomial with coefficients in an arbitrary ring that (a) directly engages with (rather than avoids) the interpretation of a polynomial as a function, and (b) generalizes the connection between derivatives and difference quotients,  but (c) avoids the need to use limits.  In the familiar context where $R=\mathbb{R}$, it reproduces the standard theory of differentiation; for general $R$, it reproduces the formal definition given in the OP.
Here's how it works:
Let $p \in R[x]$ be an arbitrary polynomial.  Choose any element $a \in R$.  Then we can formally divide $p$ by $x-a$ and obtain a quotient $q$ and a remainder $r$.  (We can determine $q$ and $r$ using either the long division or synthetic division algorithm -- they both work just fine over arbitrary rings.)  Note that $q,r \in R[x]$; we are not yet interpreting these as functions.  Furthermore since $r$ must be lower-degree than the divisor $x-a$, it must be a constant, i.e. an element of $R$ itself.  (Here I am using the natural embedding of $R$ as a subring of $R[x]$.)  We now have the relationship
$$p = (x-a)q + r$$
Where $p, q \in R[x]$ and $r \in R$.
Now let's apply the functional interpretation homomorphism $\Phi$ to this equation.  We find that for any $b \in R$,
$$\hat{p}(b) = (b-a)\hat{q}(b) + r$$
and in particular $$\hat{p}(a) = r$$
This is the analogue of what is called (in high school algebra) "the Remainder Theorem".  It tells us what we can rewrite the relationship between $p$ and $q$ as
$$p = (x-a)q + \hat{p}(a)$$
or as
$$p - \hat{p}(a) = (x-a)q$$
Interpreting the above as functions and acting on an arbitrary $b\in R$, we get
$$\hat{p}(b) - \hat{p}(a) = (b-a)\hat{q}(b)$$
Now it is very tempting to rewrite the equation above in the form $\hat{q}(b)=\frac{\hat{p}(b) - \hat{p}(a)}{b-a}$.  We can't really do that, since division is not defined in $R$.  If $b-a$ happens to be an invertible element then we can do it, and more generally if $R$ is an integral domain then we could embed $R$ as a subring of its field of fractions, but for arbitrary $R$ we need to be more careful.  However, the equation $\hat{p}(b) - \hat{p}(a) = (b-a)\hat{q}(b)$  does suggest that we can interpret $\hat{q}(b)$ as the "slope" of the "line" joining $\left( a, \hat{p}(a) \right)$ and $\left( b, \hat{p}(b) \right)$.
If we accept this interpretation as a plausible one -- and note that in the case where $R$ is a field it reduces to the standard idea that "slope is rise over run" -- then it is natural to identify $\hat{q}(a)$ as the slope of the "tangent line" to the graph of $\hat{q}$ at $a$.
If all of this seems overly abstract and formal, here are a few observations to set your mind at ease (each of these is easily verified):

*

*If $p=x^n$, so that $\hat{p}(a) = a^n$, then $\hat{q}(a) = n \cdot a^{n-1}$.  In other words the "normal" power rule is recovered under this definition.

*For any fixed $a$, the mapping  $p \in R[x] \mapsto  \hat{q}(a)$ is linear.  In other words the "normal" linearity of the derivative operation is preserved by this genralization.

*The product rule works, too -- although it is notationally hard to express it, and not particularly worthwhile.

A: *

*First Issues

If $F$ is a field, we always identify the natural number $n$ with the element
$$1+1+..+1 \in F$$
This definition can be extended easily to $\mathbb Z$.
So, to answer the question
$$D(x^2)=(1+1)x=x+x$$

*

*Second issue

First, $2x^2+x \neq 0$ when $x=2$.
Also, you are making a very common mistake here. Even if the corresponding functions would be the same, the polynomials $2x^2+x$ and $0$ would still be different polynomials over $\mathbb Z_3$, and hence their derivatives would not need be equal.
A polynomial is just an algebraic extension. Over infinite fields, polynomials correspond uniquely to a function, but over finite fields you cannot identify polynomials with their corresponding function, you have to think about them just as polynomials.

A: First of all, the formula you actually want is
$$
D\left(\sum_{i = 0}^n a_i x^i\right) := \sum_{i = 1}^n i a_i x^{i - 1}
$$
(you had $n$ in the index of the coefficients in the sum and $n$ instead of $i$ in the derivative). Now, to answer your questions:

First, we cannot assume that $F$ contains the natural numbers as a subset. For example, what is $D(x^2)$ if $F = \Bbb Z/(2)$?

Any commutative unital ring admits a unique map from $\Bbb Z$, determined by sending $1\mapsto 1$. So, if your field $F$ has characteristic $0$, $\Bbb Z$ can literally be thought of as a subset of $F$, via $n\mapsto\underbrace{1 + 1 + \dots + 1}_{n\textrm{ times}}$. If your field has characteristic $p$, then you may think of $\Bbb Z$ as mapping to the field, but the elements of $\Bbb Z$ become identified with their reductions modulo $p$. So if you wanted to be annoyingly precise, you could say let $\iota : \Bbb Z\to F$ be the unique ring homomorphism sending $1\mapsto 1$. Then
$$
D\left(\sum_{i = 0}^n a_i x^i\right) := \sum_{i = 1}^n \iota(i) a_i x^{i - 1}.
$$
So, $D(x^2) = \iota(2) x = 0$, since $2 \equiv 0\pmod{2}$, and the map $\Bbb Z\to\Bbb Z/(2)$ is reduction modulo $2$.

Furthermore, the derivative may not be well-defined, depending on the definition of equality for polynomials. For example, if $F=\Bbb Z/(3)$, then $2x^2+x=0$ for $x\in\{0,1,2\}$, but $D(2x^2+x)=2(2)x+1=x+1\neq 0=D(0)$.

The issue here is that you're identifying a polynomial in $F[x]$ with the function $F\to F$ it defines (via $\alpha\mapsto f(\alpha)$). A polynomial is simply a (finite) formal sum with coefficients in $F$, and two polynomials $\sum a_i x^i$ and $\sum b_i x^i$ are equal if and only if $a_i = b_i$ for all $i$. As you noted, two different formal sums may define the same function $F\to F$. However, any polynomial $f\in F[x]$ also defines a function $K\to K$ for any extension field $K$ of $F$, and once you pass to a suitable $K$, two polynomials will be equal if and only if they define the same function (taking $K$ to be the algebraic closure of $F$ will always do the trick, because a polynomial $f$ over a field has exactly $\deg f$ roots counted with multiplicity over the algebraic closure, and thus is determined by its value at $\deg f + 1$ elements of the algebraic closure). So a priori, a polynomial $f\in F[x]$ has more data than the function $F\to F$ it defines!


text:
Q: Swift How to add Title Text of UIRefreshControl in 2 rows I add a RefreshControl to View with long title text, but this title be hidden some word.
override func viewDidLoad()
    {
        super.viewDidLoad()

        self.refreshControl = UIRefreshControl()
        self.refreshControl.attributedTitle = NSAttributedString(string: "Last Updated at Some time...Pull to refersh your content")
        self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
        self.tableView.addSubview(refreshControl)
    }

A: You need to find the UILabel of the UIRefreshControl and set the number of lines to 0 to allow multiple lines. After that you can add \n to set a line break. (I didn't test this code. Check if the method to get the UILabel is correct. Maybe you have to alter it. I will update it later)
var titleLabel = self.refreshControl.subviews.firstObject.subviews.lastObject

if(titleLabel != nil){
  titleLabel.numberOfLines = 0
  var title = "Last Updated at Some time... \nPull to refersh your content"
  self.refreshControl.attributedTitle = NSAttributedString(string: title)
}


text:
Q: Why do I get a different result if instead of x I directly pass array element ar[0] in std::remove function? #include <iostream>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> ar = {1, 2, 2, 2, 3, 4, 5, 5, 5, 6, 7};
    vector<int> sum;
    int n = ar.size();
    for (int i = 0; i < n; i++)
    {
        int x = ar[0];
        int frq = count(ar.begin(), ar.end(), x);
        int q = frq / 2;
        sum.push_back(q);

        ar.erase(remove(ar.begin(), ar.end(), x), ar.end()); // Doubt
    }
    int count = 0;
    int n1 = sum.size();
    for (int i = 0; i < n1; i++)
    {
        count = count + sum[i];
    }
    cout << count;
}

Why do I get a different result if instead of x I directly pass ar[0] in the std::remove function?
x and ar[0] have the same value.

A: The reason is that std::remove takes the last parameter by reference. From cppreference:

Because std::remove takes value by reference, it can have unexpected behavior if it is a reference to an element of the range [first, last).

It is a bit tricky, because the paramter is passed as const reference:

template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );

However, just because ar[0] is passed as const reference does not imply that ar[0] cannot be modified by other means. In this case it is modified through first / last. Actually I cannot think of a case where it would be "ok" to have an element inside [first, last) as value.
For illustration, consider that you get the same wrong output with ar[0] as if you declared x as a reference:
int& x=ar[0];
ar.erase(remove(ar.begin(),ar.end(),x),ar.end());

Here x is passed as const reference, but the algorithm does modify ar[0].


text:
Q: Sun T2000 SC Log file Is there a SC log file for the Sun T2000?
I'm hoping to track down a possible power problem.  So if you have any suggestions outside of a log file... that would be great.
What makes me think its a power problem is that the T2000 turns off frequently.  We'll come back from the weekend and it will be sitting at the "ok>" prompt.
Thanks!

A: Yes, there are a few things you can look at in the SC.

*

*Show a summary of component status: sc> showenvironment

*Show the last 100 lines of the console history: sc> consolehistory -e 100

*Show the last 100 lines of the SC event history: sc> showlogs -e 100

*Show the hardware information, including event logs for many components: sc> showfru
In addition, Solaris itself keeps track of potential problems using FMA (Fault Management Architecture).

*

*See if Solaris has diagnosed an issue: # fmadm faulty

*Show the low level telemetry that may contribute to a fault status: # fmdump -e and # fmdump -eV

*Of course, check the log files such as /var/adm/messages as well.


text:
Q: PHP classes and static variables - Should I use __destruct()? I have a class that's similar to the following:
class Person
{
    private static $_sqlData;

    public function __construct($id)
    {
        if (!self::$_sqlData)
        {
        self::$_sqlData = // GET THE DB STUFF
        }
    }

    public function getName()
    {
        return self::$_sqlData['name'];
    }
}

This has been working fine until I needed to place it in a loop.
foreach ($ids as $id)
{
    $person = new Person($id);
    echo $person->getName();
}

This continues to return the first persons name rather than all the names for the given IDs. The reason being the static variable.
I've overcome this by adding in a __destruct() function to set $_sqlData to false then calling unset() on $person in the foreach() loop.
Is this a good way of handling this? Should I be approaching this differently?

A: Why are you using a static variable?  Is there something that you need this for?  It seems like not using a static var for the $_sqlData, just using an instance variable, would give you the same result, unless there is something your not showing us.
A instance variable will destruct, just like you are doing manually to your static variable.


text:
Q: Facebook mobile web returns 'Your link could not be found' when sharing a URL When users try to share a URL on facebook mobile web, sometimes the page returns the following message: 'Your link could not be found' and a text input to manually insert the URL

*

*Sharing URL that works:
https://m.facebook.com/sharer.php?u=http://dishenvy.com/dish/pollo-garnachas-gran-electrica-brooklyn

*Sharing URL that doesn't work:
https://m.facebook.com/sharer.php?u=http://dishenvy.com/dish/samgyupsal-hahm-ji-bach-new-york-
Code I'm using:
<a class="fb_share" name="fb_share" type="icon" share_url="<?php echo urldecode($shareUrl) ?>">
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>

A: Make sure the url you pass is accessible to Facebook. Not sure why, but their mobile site seems to validate the url but their non-mobile site does not seem to care.  If you have code generating the link you pass to facebook and the host corresponds to a server behind a firewall or private network (such as a test or dev server), this error will often happen.

A: According to the debugger the two url example that you posted work the same:

*

*First

*Second
So I don't know how to help you with that.
What I can tell you though is that you are using a deprecated api.
The facebook "sharer" is no longer supported as it states here:

The Share button has been deprecated in favor of the Like button, and
  will no longer be supported. Please use the Like button whenever
  possible to drive maximum traffic to your apps.

And here:

What happened to the old Share button?
We deprecated the Share Button when we launched the Like button,
  because the Like button improves clickthrough rates by allowing users
  to connect with one click, and by allowing them to see which of their
  friends have already connected.

That may be a cause for the inconsistency you are experiencing.
My advise to you is to stop using this deprecated api and move to the Like button.

A: I think facebook check your sharing page found or not on the server. Your first url found on the server (It means first url return the page). Second url doesn't return the page. The second url return the empty page for this reason facebook return this message. 'Your link could not be found'
Click the link :

*

*http://dishenvy.com/dish/pollo-garnachas-gran-electrica-brooklyn  =    Page found

*http://dishenvy.com/dish/samgyupsal-hahm-ji-bach-new-york-       =    Page not found

So share correct url on the facebook

A: https://m.facebook.com/sharer.php?m2w&u=http://dishenvy.com/dish/samgyupsal-hahm-ji-bach-new-york-
For mobile view you want to add m2w to the url.


text:
Q: onClick Navigation in React.js for Icons I have a component  which I want an icon to navigate to when it is clicked. The icon is present in an item tray as below.
  items = [
        {
          label: "Approve",
          Icon: <Checkmark/>,
          path:                //<SideLayer/> should be invoked from here
        },
        {
          label: "Reject",
          Icon: <Dislike/>,
          path: "/Dashboard"
        },
        {
          label: "Request Info",
          Icon: <Revert/>,
          path: "/History"
        }
      ];

SideLayer is an overlayer component and I do not want to go to any new page, the layer should get rendered on the same page. I have tried using "onCLick" and "onPress" instead of path but on clicking the icon, nothing works, there is no navigation. Is there a way to do it?


text:
Q: Scaffolding Error in ASP.Net MVC 3 when creating controller When I try to add a new controller using scaffolding, I get this message
"Unable to retrieve metadata for 'Model name'. Value cannot be null. Parameter name: key"

Can anyone help?
This is the Model use for scaffolding
public class Patient
    {
        [Key]
        public int PatientId { get; set; }
        public string FirstName { get; set; }
        public String LastName { get; set; }
        public int Phone { get; set; }
        public int FamilyPhone1 { get; set; }
        public int FamilyPhone2 { get; set; }
        public string Address { get; set; }

        public virtual ICollection<Drug> Drugs { get; set; }
        public virtual ICollection<Test> Tests { get; set; }
        public virtual ICollection<Alert> Alerts { get; set; }
        public virtual ICollection<Message> Messages { get; set; }
    }

A: public class Patient
{
    [Key]
    public int PatientId { get; set; }
    public string FirstName { get; set; }
    public String LastName { get; set; } ==> Replace String by string with a lower case
    public int Phone { get; set; }
    public int FamilyPhone1 { get; set; }
    public int FamilyPhone2 { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Drug> Drugs { get; set; }
    public virtual ICollection<Test> Tests { get; set; }
    public virtual ICollection<Alert> Alerts { get; set; }
    public virtual ICollection<Message> Messages { get; set; }
}


text:
Q: API Gateway: Can't Enable CORS I can't Enable CORS on my API Gateway instance, this is how it looks:
1. Settings:

2. Result:

I've tried a bunch of things like checking the DEFAULT 4XX and DEFAULT 5XX and manually inputting the Access-Control-Allow-Methods as suggested in some posts.
If I hover over the error I get: Invalid Response status code specified.
I'm able to GET using my browser but POST can only be done from Postman. My ReactJS website won't post either, throwing:
Access to XMLHttpRequest at <ENDPOINT> from origin <S3-REACT-BUCKET> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've read that I have my React app should send the CORS headers (haven't got to that) but I can't even Enable CORS in the API Gateway!

A:
That was because No Method Response

A: You shouldn't manually go on the console to enable CORS. Instead follow this guide from the serverless framework.
In short:

*

*set cors: true in your http event

*return {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Credentials': true} in your handler


text:
Q: Graphql Codegen - Enum with custom key => value I use graphql-codegen to generate type files.
As an example, let's say I have the following in my schema.graphql file:
enum cities {
 JOHANNESBURG
 CAIRO
 NEW_YORK
 LONDON
 BEIJING
}

The output in my generated-types.ts file is as follows:
export enum cities {
 Johannesburg = 'JOHANNESBURG'
 Cairo = 'CAIRO'
 NewYork = 'NEW_YORK'
 London = 'LONDON'
 Beijing = 'BEIJING'
}

Is there a way for me to 'override' the value of the enum before codegen runs? Perhaps something as follows (which I obviously tried):
enum cities {
 JOHANNESBURG: 'JNB'
 CAIRO: 'CAI'
 NEW_YORK: 'NYC'
 LONDON: 'LON'
 BEIJING: 'BEI'
}

which in turn should produce:
export enum cities {
 Johannesburg = 'JNB'
 Cairo = 'CAI'
 NewYork = 'NYC'
 London = 'LON'
 Beijing = 'BEI'
}

A: not sure if I'm too late, but you probably can use the enumValues to customize your internal enum values. Here is the documentation. For example:
./types.ts
export enum cities {
 Johannesburg = 'JNB'
 Cairo = 'CAI'
 NewYork = 'NYC'
 London = 'LON'
 Beijing = 'BEI'
}

./codegen.yml
generates:
  src/graphql.types.ts:
    config:
      useIndexSignature: true
      enumValues:
        cities: ./types#cities // path to your custom types
    plugins:
      - typescript
      - typescript-resolvers


text:
Q: OpenSSL encrypted streams Does anyone know a good implementation for encrypted C++ streams using OpenSSL ?
Something that extends or wraps std::istream and std::ostream ?
I know this could be done with boost (filtering stream) but I don't want to include boost just for that. Any non boost suggestions ?

A: Boost library provides ssl stream:
http://www.boost.org/doc/libs/1_47_0/boost/asio/ssl/stream.hpp
SO ref : HTTPS request with Boost.Asio and OpenSSL

A: I came across following implementations using std::istream and std::ostream.

*

*AES CTR-mode encryption/decryption

http://openssl.6102.n7.nabble.com/EVP-Decrypt-Final-ex-fails-on-larger-files-td2434.html

*

*Blowfish

http://openssl.6102.n7.nabble.com/EVP-Decrypt-Final-ex-fails-on-larger-files-td2434.html
Additionally, you can also look here:
http://www.appinf.com/docs/poco/Poco.Crypto.RSAKeyImpl.html
and here:
https://dev.marc.waeckerlin.org/projects/libpcscxx/browser/trunk/src/openssl.hxx?rev=60

A: If you want to do it yourself:
Subclass std::streambuf for use with TCP or SSL (they basically work the same once the socket is open.  Then you can make std::istream and std::ostream using that streambuf.  If you don't want std::iostream, you could make two streambufs, one for input and one for output.
std::streambuf docs (mostly just focus on overflow and underflow): http://www.cplusplus.com/reference/streambuf/streambuf/
And a small tutorial on how to use libssl directly.
http://www.ibm.com/developerworks/linux/library/l-openssl/index.html


text:
Q: How to add Country code(+852) before the phone number in a dataframe I have a CSV file and there is a column (Phone). However, there is no country code before the phone number. What is the syntax I should use in order to add +852 into every value under the "Phone" column?
Also, how could I remove the space within the phone number for every value under "Phone" column?
For example: Right now, the value is 9123 4567.
The value that I want afterwards is +85291234567.

A: Assuming your 'phone' column is in string format you could do the following commands:
a) use replace to remove the spaces (where df is the name of your datraframe)
df.phone = df.phone.apply(lambda x: x.replace(" ", ""))

b) concatenate the phone column with the country code
country_code = "+852"
df.phone = country_code + df.phone

In case the phone column is not in string format you will need to convert it.


text:
Q: jquery mobile javascript not being run when sing JQM pageContainer I'm new to JQM and trying to create a simple login app to learn with.
My login.html page calls the login.php page to verify.  If the user is verified then it returns a 200 and the login.js page moves to the next page which is called "menu.html".  THis is how I am moving to the next page
$.mobile.pageContainer.pagecontainer("change", "menu.html" );

When this page shows it does not execute the javascript inside menu.html?
However, if I press the "refresh" button in my browser to reload the menu.html page, it then runs the javascript.  I need the javascript for menu.html to run when the page is redirected, because the javascript for menu.html does a 2nd level security check using php $_sessions to prevent the user from directly calling menu.html trying to bypass the login process.
Any help is appreciated. thanks.


text:
Q: grep: highlight only first match of each line when using --color When I make grep highlight the matches like this:
echo hello hello | grep --color "hello"

I get highlighted all matches in the line, which in the above case is all the line:

hello hello

How can I get highlighted only the first ocurrence:

hello hello

I suppose I can do it with a complex regex but I wonder if there a simpler solution.

A: It can be easily done using sed:
sed 's/hello/\x1b[31m&\x1b[0m/' file

This will only color first match of hello word in each line. In replacement we are putting matched word back using & surrounded with escape code for color red.
Similarly you can do this in awk as well:
awk '{sub(/hello/, "\x1b[31m&\x1b[0m")} 1' file


text:
Q: Arrows between arrows Here is a fragment from MacLane's classic book "Categories for the working mathematician":

Here is another one that's a bit more complicated:

Is there a package that allows to (hopefully easily) typeset things of this kind?
PS: I've been using several packages for making commutative diagrams (amscd, tikz-cd), which is enough for a lot of stuff in category theory. But the picture above isn't really a "commutative diagram", it's something else. I don't even know how to call it, so looking it up on the web is kind of problematic. Thanks.

A: I think you can use tikz-cd for this kind of diagrams. For example, use
\documentclass[preview,border=1pt]{standalone}

\usepackage{tikz}
\usepackage{tikz-cd}

\begin{document}
%% Hint for the positions: L=left, R=right, U=up D=down
  \begin{tikzcd}
    C \arrow[bend left=80]{r}[name=LUU, below]{}
    \arrow{r}[name=LUD]{}
    \arrow[swap]{r}[name=LDU]{}
    \arrow[bend right=80]{r}[name=LDD]{}
    \arrow[Rightarrow,to path=(LUU) -- (LUD)\tikztonodes]{r}{\sigma}
    \arrow[Rightarrow,to path=(LDU) -- (LDD)\tikztonodes]{r}{\tau}
    &
    B
    \arrow[bend left=80]{r}[name=RUU, below]{}
    \arrow{r}[name=RUD]{}
    \arrow[swap]{r}[name=RDU]{}
    \arrow[bend right=80]{r}[name=RDD]{}
    \arrow[Rightarrow,to path=(RUU) -- (RUD)\tikztonodes]{r}{\sigma'}
    \arrow[Rightarrow,to path=(RDU) -- (RDD)\tikztonodes]{r}{\tau'}
    & A
  \end{tikzcd}
\end{document}

A: A solution using MetaPost could look something like this:
u:=1.8cm; % Horizontal scale
s:=6pt; % shift from letters
h:=10pt; % height

label(btex $C$ etex, (0,0));
label(btex $B$ etex, (u,0));
label(btex $A$ etex, (2u,0));

drawarrow ((s,0)--(u-s,0)) shifted (0,-h);
drawarrow ((s,0)--(u-s,0)) shifted (0,h);
drawarrow ((u+s,0)--(2u-s,0)) shifted (0,-h);
drawarrow ((u+s,0)--(2u-s,0)) shifted (0,h);

label.top(btex $\strut S$ etex, (0.5u,h));
label.bot(btex $\strut T$ etex, (0.5u,-h));

drawarrow ((0.5u,0.8h)--(0.5u,-0.8h));
label.rt(btex $\strut\tau$ etex, (0.5u,0));

label.top(btex $\strut S'$ etex, (1.5u,h));
label.bot(btex $\strut T'$ etex, (1.5u,-h));

drawarrow ((1.5u,0.8h)--(1.5u,-0.8h));
label.rt(btex $\strut\tau'$ etex, (1.5u,0));

The result looks like:

A: With stacks.
\documentclass{article}
\usepackage{graphicx}
\usepackage[usestackEOL]{stackengine}
\stackMath
\def\xtnd{-\kern-5pt-\kern-5pt}
\setstackgap{L}{.45\baselineskip}
\begin{document}
\[C
\mathop{\raisebox{1pt}{\Centerstack{
  S\\
  \xtnd\rightarrow\\
  \raisebox{.5pt}{$\scalebox{.8}{$\downarrow$}\scriptstyle\tau$}\\
  \xtnd\rightarrow\\
  T}}}
B
\mathop{\raisebox{1pt}{\Centerstack{
  S'\\
  \xtnd\rightarrow\\
  \raisebox{.5pt}{$\scalebox{.8}{$\downarrow$}\scriptstyle\tau'$}\\
  \xtnd\rightarrow\\
  T'}}}
A\]
\[C
\mathop{\Centerstack{
  \xtnd\rightarrow\\
  \raisebox{.5pt}{$\scalebox{.8}{$\downarrow$}\scriptstyle\sigma$}\\
  \xtnd\rightarrow\\
  \raisebox{.5pt}{$\scalebox{.8}{$\downarrow$}\scriptstyle\tau$}\\
  \xtnd\rightarrow}}
B
\mathop{\Centerstack{
  \xtnd\rightarrow\\
  \raisebox{.5pt}{$\scalebox{.8}{$\downarrow$}\scriptstyle\sigma'$}\\
  \xtnd\rightarrow\\
  \raisebox{.5pt}{$\scalebox{.8}{$\downarrow$}\scriptstyle\tau'$}\\
  \xtnd\rightarrow}}
A\]
\end{document}

A: Here is my version also using tikz-cd:
% arara: pdflatex

\documentclass{article}
\usepackage{tikz-cd}

\begin{document}
\[\begin{tikzcd}
C \ar[shift left=7pt, ""{name=UL, below}]{r}{S} \ar[shift right=7pt, ""name=LL]{r}[swap]{T\vphantom{'}} &
B \ar[shift left=7pt, ""{name=UR, below}]{r}{S'} \ar[shift right=7pt, ""name=LR]{r}[swap]{T'} &
A\\
\ar[from=UL, to=LL, "r", shorten <= -2pt, shorten >= -2pt]
\ar[from=UR, to=LR, "r\smash{'}", shorten <= -2pt, shorten >= -2pt]
\end{tikzcd}\]
\[\begin{tikzcd}
C \ar[shift left=10pt, ""{name=UL, below}]{r} \ar[shift right=10pt, ""name=LL]{r} \ar[""name=ML, ""{name=MLL, below}]{r} &
B \ar[shift left=10pt, ""{name=UR, below}]{r} \ar[shift right=10pt, ""name=LR]{r} \ar[""name=MR, ""{name=MLR, below}]{r} &
A\\
\ar[from=UL, to=ML, "\sigma", shorten <= -3pt, shorten >= -3pt]
\ar[from=UR, to=MR, "\sigma\smash{'}", shorten <= -3pt, shorten >= -3pt]
\ar[from=MLL, to=LL, "\tau", shorten <= -3pt, shorten >= -3pt]
\ar[from=MLR, to=LR, "\tau\smash{'}", shorten <= -3pt, shorten >= -3pt]
\end{tikzcd}\]
\end{document}


text:
Q: kivy scrolling in grid layout of n rows I have a grid layout inside of a relative layout that i would like to have a variable number of rows with each row having a fixed length. this would use a scroll bar so a large amount of items could be included.

Below is the relevant part of my kv file, at the moment I am manually adding items, ideally I would  not have this hard coded but i'm not sure how...
    RelativeLayout:
        size_hint: 0.35, 1
        pos_hint: {"x": 0, "y": 0}
        TextInput:
            id : inpSearch
            size_hint: 0.9,0.05
            pos_hint: {"x": 0, "y": 0.9}
        GridLayout:
            size_hint: 1, 0.8
            pos_hint: {"x": 0, "y": 0.1}
            cols: 2
            rows: 20

            Button:
                id : btnMov1
                text: 'Title'
            Button:
                id : btnRmv1
                text: 'Remove'
            Button:
                id : btnMov2
                text: 'Title'
            Button:
                id : btnRmv2
                text: 'Remove'
            Button:
                id : btnMov3
                text: 'Title'
            Button:
                id : btnRmv3
                text: 'Remove'
            Button:
                id : btnMov4
                text: 'Title'
            Button:
                id : btnRmv4
                text: 'Remove'
            Button:
                id : btnMov5
                text: 'Title'
            Button:
                id : btnRmv5
                text: 'Remove'
            Button:
                id : btnMov6
                text: 'Title'
            Button:
                id : btnRmv6
                text: 'Remove'
            Button:
                id : btnMov7
                text: 'Title'
            Button:
                id : btnRmv7
                text: 'Remove'
            Button:
                id : btnMov8
                text: 'Title'
            Button:
                id : btnRmv8
                text: 'Remove'
            Button:
                id : btnMov9
                text: 'Title'
            Button:
                id : btnRmv9
                text: 'Remove'
            Button:
                id : btnMov10
                text: 'Title'
            Button:
                id : btnRmv10
                text: 'Remove'
            Button:
                id : btnMov11
                text: 'Title'
            Button:
                id : btnRmv11
                text: 'Remove'
            Button:
                id : btnMov12
                text: 'Title'
            Button:
                id : btnRmv12
                text: 'Remove'
            Button:
                id : btnMov13
                text: 'Title'
            Button:
                id : btnRmv13
                text: 'Remove'
            Button:
                id : btnMov14
                text: 'Title'
            Button:
                id : btnRmv14
                text: 'Remove'
            Button:
                id : btnMov15
                text: 'Title'
            Button:
                id : btnRmv15
                text: 'Remove'
            Button:
                id : btnMov16
                text: 'Title'
            Button:
                id : btnRmv16
                text: 'Remove'
            Button:
                id : btnMov17
                text: 'Title'
            Button:
                id : btnRmv17
                text: 'Remove'
            Button:
                id : btnMov18
                text: 'Title'
            Button:
                id : btnRmv18
                text: 'Remove'
            Button:
                id : btnMov19
                text: 'Title'
            Button:
                id : btnRmv19
                text: 'Remove'
            Button:
                id : btnMov20
                text: 'Title'
            Button:
                id : btnRmv20
                text: 'Remove'

        Button:
            id : "btnAnm"
            text: "Add"
            size_hint: 0.5, 0.05
            pos_hint: {"x": 0, "y": 0.05}

I'm happy to keep this hard coded and have a fixed number of items but I would like to have a scroll bar so that I can fit more items in.

A: You can achieve what you are looking for by inserting the GridLayout into a ScrollView via add_widget()

main.py
import kivy
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.uix.gridlayout import GridLayout

class MyGrid(GridLayout):
    pass

class myApp(App):
    def build(self):
        layout = MyGrid(size_hint_y=None, size_hint_x=1)
        layout.bind(minimum_height=layout.setter('height'))
        root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
        root.add_widget(layout)
        return root

if __name__ == "__main__":
    myApp().run()

my.kv
<ScrollView>:
    canvas:
        Color:
            rgb: 0, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

<GridLayout>:
    canvas:
        Color:
            rgb: 1, 0, 0
        Rectangle:
            pos: self.pos
            size: self.size

    cols:2
    size: root.width, root.height

    TextInput:
        id : inpSearch
        size_hint: 1, None

    Label:
        text: ''
    Button:
        id : btnMov1
        text: 'Title'
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15
    Button:
        id : btnRmv1
        text: 'Remove'
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15
    Button:
        id : btnMov2
        text: 'Title'
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15
    Button:
        id : btnRmv2
        text: 'Remove'
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15
    Button:
        id : btnMov3
        text: 'Title'
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15
    Button:
        id : btnRmv3
        text: 'Remove'
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15

    Button:
        id : "btnAnm"
        text: "Add"
        size_hint: 1, None
        size: self.texture_size
        padding: 20, 15

Note that for the widgets to display correctly you must specify additional properties as shown in the example.


text:
Q: Elasticsearch: Alert on significant data change I have an index with exchange rates change log. Documents inside index look like this
    {
          "sourceId": "gh-ghs",
          "targetCountry": "gh",
          "targetCurrency": "ghs",
          "rate": 2.3,
          "modified": "2021-04-07T12:00:57.2760000Z",
    },
    {
          "sourceId": "gh-ghs",
          "targetCountry": "gh",
          "targetCurrency": "ghs",
          "rate": 2.5,
          "modified": "2021-04-06T12:00:57.2760000Z",
    },
    {
          "sourceId": "mx-mxn",
          "targetCountry": "mx",
          "targetCurrency": "mxn",
          "rate": 20.3,
          "modified": "2021-04-08T12:00:57.2760000Z",
    },
    {
          "sourceId": "mx-mxn",
          "targetCountry": "mx",
          "targetCurrency": "mxn",
          "rate": 2.2,
          "modified": "2021-04-07T12:00:57.2760000Z",
    },
    {
          "sourceId": "mx-mxn",
          "targetCountry": "mx",
          "targetCurrency": "mxn",
          "rate": 2.23,
          "modified": "2021-04-06T12:00:57.2760000Z",
    }

As you can see we have exchange rate change per destination (country+currency). Take a look mx-mxn documents. Last change was from 2.2 to 20.3. Probably it is human mistake, and we want to alert about such cases.
I tried to create following query to find significant changes
    {
      "query": {
        "bool": {
          "must": [],
            {
              "range": {
                "modified": {
                  "format": "strict_date_optional_time",
                  "gte": "now",
                  "lte": "now - 5h"
                }
              }
            }
          ],
          "should": [],
          "must_not": []
        }
      },
      "aggs": {
        "group": {
          "terms": {
            "field": "sourceId",
            "size": 1000
          },
          "aggs": {
            "2-metric": {
              "top_metrics": {
                "metrics": {
                  "field": "rate"
                },
                "size": 2,
                "sort": {
                  "modified": "desc"
                }
              }
            }
          }
        }
      }
    }

Using this query I managed to get to latest changes by destination. Response look like this
    {
      "aggregations": {
        "group": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "mx-mxn",
              "doc_count": 25,
              "2-metric": {
                "top": [
                  {
                    "sort": [
                      "2022-10-16T15:01:57.098Z"
                    ],
                    "metrics": {
                      "rate": 12
                    }
                  },
                  {
                    "sort": [
                      "2022-10-16T13:01:57.098Z"
                    ],
                    "metrics": {
                      "rate": 150
                    }
                  }
                ]
              }
            },
            {
              "key": "gh-ghs",
              "doc_count": 18,
              "2-metric": {
                "top": [
                  {
                    "sort": [
                      "2022-10-14T11:28:38.995Z"
                    ],
                    "metrics": {
                      "rate": 11.25
                    }
                  },
                  {
                    "sort": [
                      "2022-10-13T11:37:09.945Z"
                    ],
                    "metrics": {
                      "rate": 10.9609375
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }

So I managed to get two latest changes for each destination. But I want to setup alert for all buckets, where value changed more than on 10 percent. In this case it is mx-mxn. How can I do it in Elastic and Kibana ?

A: Tldr;
To gather the "detection" data:

*

*anomaly detection jobs

*derivative aggregation
To perform the alert:

*

*Kibana alerting with machine learning job.

*Watcher with elasticsearch query input.


text:
Q: Do something after leave page with JS I need to do some back-end process when user leaves my page. My JS code works fine:
if (window.addEventListener) {  // all browsers except IE before version 9
    window.addEventListener("beforeunload", OnBeforeUnLoad, false);
}
else {
    if (window.attachEvent) {   // IE before version 9
        window.attachEvent("onbeforeunload", OnBeforeUnLoad);
    }
}

function OnBeforeUnLoad () {
    return "Are you sure?";
}

But my OnBeforeUnLoad function must contain an $.ajax call to do something on server side when user press OK on dialog prompted by browser automatically. Doing it like this doesn't work:
function OnBeforeUnLoad () {
   if (confirm("Are you sure?")){
      $.ajax({
         type:       "POST",
         url:        "../wp-content/scripts/removedemo.php",
         data:       "s="+UserSession.encodedurl,
         success: function(data){}
      });
   }
}

Any help will be appreciated.

A: Use setimeout function to delay the execution for fraction of secs.Here is your code:
setTimeout(OnBeforeUnLoad, 10);

function OnBeforeUnLoad () {
if (confirm("Are you sure?")){
  $.ajax({
     type:       "POST",
     url:        "../wp-content/scripts/removedemo.php",
     data:       "s="+UserSession.encodedurl,
     success: function(data){}
  });
}
}


text:
Q: Neo4j-Ogm for dynamic domain object model I've started to use Neo4j-ogm inside my application and it works like charm for fixed object domain model. When I know which node type connected to another node with known type - it can be easily mapped.
However, in my opinion versitality of Neo4j graph database is also in an ability to work with un-typed (or dynamic) domain models and I'm having conceptual problem to understand how to achieve it with Neo4j-ogm.
Let me describe my problem with an example.
I have domain objects like: Message and Feature. Where Message can have multiple features and a Feature can be a part of many messages. It is completely ok to map with Neo4j-ogm.
Then what if user want to relate the message to some Task node type or refer it to some Contact node type ? In my application it is possible to have large (but limited) set of connection between nodes of various types. So I would like to be able to get all types of connections from a particular node, regardless of this connection types or endNode types?
Of course I can use cypher to create connections like this:
MATCH ($2911) WHERE id($2911)={$2911} MATCH ($2912) WHERE id($2912)={$2912} MERGE ($2911)-[_0:`part_of` {$aid} ]->($2912) RETURN id(_0) AS _0

but when I'm starting doing this - I would need a way how to convert results of this queries to and from relational entities myself.
Is there a gracefull way to do this using Neo4j-ogm. May be it is possible to create a comprehansive type heirarchy or something which will allow to use Neo4j-ogm together for fixed and dynamic domain object models.
Thank you in advance.

A: A fixed type hierarchy is supported by Neo4j OGM so if you are able to represent your domain in such a hierarchy, you should be able to fetch all connections from a single entity. This means that the end nodes must be also represented in this hierarchy.
Run time polymorphism is not supported in the current version- it's up for discussion though, so depending on how it goes, it might make it to a future release.


text:
Q: Puppet (err): Found 1 dependency cycle + cycles.dot file I am running this cmd:
puppet apply --environment split4 -l C:\Puppet_logs\log.log C:\ProgramData\PuppetLabs\code\environments\split4\manifests\bl.pp

This is the code which is running:
  service {
    $name :
      ensure => stopped,
      enable => true;
  } ->
 tidy { $bl_deployment_folder :
   rmdirs => true,
   recurse => 1,
  # notify => Service[$name],
   matches => ['*.dll','*.jar','*.exe','*.test','*.utd'];
  # subscribe   => File[$bl_deployment_folder];

} ->
file {
    #set the BL run time folder and update it according to the source folder
    $bl_deployment_folder :
      ensure    => directory,
      source    => $bl_source_folder,
      recurse   => true,
      ignore    => "AlisConfig.ini";
     }

According to this code, I would like to:

*

*Stop the tomcat service

*Clean the specific files that I mentioned

*copy files from source to my directory ($bl_deployment_folder)

Unfortunately, when I'm running it, it throws this error:
+0300 Puppet (err): Found 1 dependency cycle:
(File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll] => Tidy[\\my-server\C$\BL\ALIS_PUPPET] => File[\\my-server\C$\BL\ALIS_PUPPET] => File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll])
Cycle graph written to C:/ProgramData/PuppetLabs/puppet/cache/state/graphs/cycles.dot.
Puppet (err): Failed to apply catalog: One or more resource dependency cycles detected in graph

The circles.dot file is attached:

digraph Resource_Cycles { label = "Resource Cycles" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]"
-> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/obj_data_client.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]"
-> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/obj_data_policy.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]"
-> "File[//my-server/C$/BL/ALIS_PUPPET/obj_exceptions.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/obj_metadata.dll]"
-> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/obj_metadata_product.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]"
"File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/obj_services.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]"
-> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/objects.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]"
-> "File[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[//my-server/C$/BL/ALIS_PUPPET/xerces-c_2_6.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" "File[//my-server/C$/BL/ALIS_PUPPET/AAppData.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" -> "File[\\my-server\C$\BL\ALIS_PUPPET]"
-> "File[//my-server/C$/BL/ALIS_PUPPET/xmltools.dll]" -> "Tidy[\\my-server\C$\BL\ALIS_PUPPET]" }

What do I need to do to fix this problem?
I appreciate your help!
Thanks!

A: The problem here is that the tidy resource deletes files by creating file resources in $bl_deployment_folder. Each of those file resources will autorequire its parent directory file resource, in this case $bl_deployment_folder. The -> between the tidy and the directory file implies that $bl_deployment_folder requires the tidy file resources in it, and so you have a cycle.
Unfortunately, the upshot is that you can't have a file require a tidy on the same directory.
In this case, I'd suggest just removing the dependency and letting the tidy run in its own time.
I'd also note that this Puppet manifest feels very procedural. Puppet is really, really bad at "do this, then this, then that" type scripts. It wants to operate in a declarative "tell me what the final state is, and I'll sort it out" way. Trying to use it procedurally is just painful and isn't to be recommended.


text:
Q: Save and restore specific tables in an Oracle 11.2 Database, Enterprise Edition, we are running calculations divided into 3 different "modules". These modules can be started on their own, but not parallel, so in between users are able to confirm the calculations and proceed with the next step.
Now I want to find a proper way to "save" and "restore" the tables to allow "a rollback" to the definied start before the module.
I have read the Oracle-Documentation about (garantueed) restore points but i think its way too much. Within its time of usage the process is more or less exclusive, but not garantueed. So i cannot rollback the complete database.
I found some information about the OracleWorkspaceManager but I am not sure if this tool would be something I could use.
Finally, I simply want to save and maybe restore 6 or 7 different tables. Is there an "easy" way to do this? Alternatively I am thinking of materialized views to store the information "before" each step. But that would create dependencies into the workflow I cannot image right now.
Thank you for your help.

A: IF you just want to be able to restore a few tables and the volume is not to high, why not just make copies of them?
You do need to set up good auditing and security around all your tables to prevent data loss, in the event that users did manual updates on tables that are going to be restored because of a process failure or something similar.
It could be that despite that failure, the user modifications are still needed and valid.
Best would be to prevent any user changes in the period where processes run that could cause the need for a restore.


text:
Q: difference between $_SERVER and apache_note I need to get the user country code and I've managed this by using both
apache_note('GEOIP_COUNTRY_CODE')

and
$_SERVER['GEOIP_COUNTRY_CODE']

Is there any reason why I should use one of these over the other or are they both the exact same? They output the same result and as can be seen have the same index key so I assume it comes from the same place, is this correct?
I tried using the php function geoip_country_code_by_name($_SERVER['REMOTE_ADDR]) but it just returns null (geoip is installed) each time whereas the $_SERVER and apache_note have only not worked when I routed through switzerland.

A: It's better practice to use $_SERVER because if your application will scaled you might consider switching to nginx for performance and there apache_note function might not be available while $_SERVER will be available under every server.
From documentation:
The main use for apache_note() is to pass information from one module to another within the same request.


text:
Q: Is CAS (Centralized Authentication Service) dependent on cookie? If CAS is based on cookies, then will it work after disabling cookies? And can we manage CAS SSO using session management API?

A: Cookies are required for SSO. Not for authentication.


text:
Q: Laravel 5.4 - get entrys where column contains specific string I'm geting the following error if I try to get database entrys where the name contains a passed string.
Invalid argument supplied for foreach()

.
$search = $request['search'];
$key_search = explode(' ', $search);
$usergroups = Usergroups::whereIn('name', 'like', '%' . $search . '%')->paginate(3);

$key_search looks something like this: [0 => "Test", 1 => "Unicorn"];
Now I want to get every entry where the name column has data that contains the passed strings and get the query results with paginate();
I've also tried something like a foreach loop that pushes the entrys into another array but this haven't worked for me as well cause the entrys are Objects and not arrays. Thats why array_push coulnd't handle this.
Does someone know what I can do to get the entrys?
Thanks for your help and sorry for my bad english!

Based on answer:
Problem is that I get every entry in my database. At first the entrys that matches with the search keys and the last entrys doesn't match with the search keys at all.
example:
I'm passing "test" and "unicorn"
And I have 10 entrys in my database. For example:

*

*test dkkawdmawkdkaw

*mdkawdawtestdmwakdaw // test

*apples

*oranges

*anything

*Unicorn  /// Unicorn - U is uppercase

*more unicornsdawdawd //unicorn

*pizza

*testing

*i'm not creative

So I only want: 1,2,6,7 and 9. But I'm getting all of them sorted from high matches to doesn't match at all.

A: whereIn() can not be used for like query.
$usergroups = Usergroups::query();

foreach($key_search as $search) {
  $usergroups = $usergroups->orWhere('name', 'like', '%' . $search . '%')
}

$usergroups = $usergroups->paginate(3);

// Results in
// select * from `usergroups` where `name` like ? or where `name` like ?;

You can also try this.
$usergroups = Usergroups::where(function ($query) use ($key_search) {
                            foreach($key_search as $search) {
                              $query->orWhere('name', 'like', '%' . $search . '%');
                            }
                          })->paginate(3);

// Results in
// select * from `usergroups` where (`name` like ? or `name` like ?;

A: You can't use whereIn() like this. Use multiple orWhere() instead, for example:
$searchArray = explode(' ', $request->search);
$userGroups = Usergroups::query();
foreach ($searchArray as $searchValue) {
    $userGroups = $userGroups->orWhere('name', 'like', '%'.$searchValue.'%');
}
$userGroups = $userGroups->paginate(3);


text:
Q: Regex to get all "cells" form csv file row This is not duplicate! I'm asking for solution with regex. I can't use external libraries
I have csv file with [,] as separator and ["] as escape character.
I need regex to get all the "cells" from the row.
This row should be converted to:
This, Is, "Super Test", That, "Should, maybe work", Oh

1. This
2. Is
3. Super Test
4. That
5. Should, maybe work
6. Oh

I want to to be universal so I can't hardcode number of "cells".
Can you help me create regex for that?
What I tried?
I tried creating regex but failed.
P.S.
If you know other method that is nice or maybe faster I'd be happy to hear about it.


text:
Q: Tips and advice on how to make an eclipse source-to-source compiler plugin I have been searching for this but I could use a bit of help. I am not even sure if a plugin is the way to go with this.
Anyway, here is a description of what I want to do:
I have developed a Java project which is a source-to-source compiler. It translates Java files with jQuery blocks into Java-only files. It accepts a file from the cli arguments, transpiles it and outputs the result to a new file. I used ANTLR for this.
Now that the program is working, I would like to make some sort of plugin which makes use of it. Just like we can create a new Java project, code and run the program in eclipse, I would like to be able to create a new JavaWithJQuery project, be able to code, and when I run it with eclipse,  it would use the project I made to transpile it and run it directly, instead of outputting a file with Java-only.
Is this possible? I would appreciate some tips, and advice on how to get started.
Thanks in advance! :)


text:
Q: Why is my Deep Q Network not learning to play a simple game? So i have made a small python game where the player have to reach the end and avoid the traps, And it looks like this

I have tried many different batch sizes, Rewards, Input shapes, Amount of nodes in the hidden layer, But the network is still not training.
The current way i'm training it, Is using 64 batch size with 100000 memory size, The input is a 1D array representing the game state + the player's coordinates + the amount of moves left before the game ends, And the reward starts at -distanceFromEnd + maxDistance / 2, If you reach the end you get +500 reward and the game is done, If you touch a trap you get a -100 reward and the game is done, If the game is not done in 64 moves you get a -200 reward and the game is done.
i'm using AdamOptimizer and MSE loss function, And for the activation functions i'm using ReLU for all the layers except the last layer i'm using nothing.
the player, end, traps positions are all randomized after each episode
The average score (score is the sum of the rewards) for the last 100 games is around -30 even after 3000 episodes.
The DQN is working fine on the gym game LunarLander-v2.
And as i said i have been trying to tweak the values but it didn't help.
First here are the labels that i use in the state
  FLOOR = 1
  END = 2
  TRAP = 3
  PLAYER = 4

This is my step function
 def step(self, action):
isDone = False
if action == 0:
  # Move Up
  if self.playerY != 0:
    self.playerY -= 1
elif action == 1:
  # Move Down
  if self.playerY != 7:
    self.playerY += 1
elif action == 2:
  # Move Right
  if self.playerX != 0:
    self.playerX -= 1
elif action == 3:
  # Move Left
  if self.playerX != 7:
    self.playerX += 1

x = self.playerX - self.endX
x = x * x
y = self.playerY - self.endY
y = y * y

distance = math.sqrt(x + y)
reward = -distance + self.maxDist
#self.lastDist = distance

if self.state[self.playerX, self.playerY] == self.END:
  reward = 500
  isDone = True
elif self.state[self.playerX, self.playerY] == self.TRAP:
  reward = -100
  isDone = True

self.moves -= 1

if self.moves < 0:
  reward = -200
  isDone = True

return self.getFlatState(), reward, isDone, 0

State Getter function
  # Adding one to the players coordinates to avoid 0s as a try to fix the problem
  def getFlatState(self):
     return np.concatenate([np.ndarray.flatten(self.state), [self.playerX + 1, self.playerY + 1, self.moves]])

Here's the DQN/Agent script
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import load_model

class ReplayBuffer():
def __init__(self, max_size, input_dims):
    self.mem_size = max_size
    self.mem_cntr = 0

    self.state_memory = np.zeros((self.mem_size, *input_dims),
                                dtype=np.float32)
    self.new_state_memory = np.zeros((self.mem_size, *input_dims),
                            dtype=np.float32)
    self.action_memory = np.zeros(self.mem_size, dtype=np.int32)
    self.reward_memory = np.zeros(self.mem_size, dtype=np.float32)
    self.terminal_memory = np.zeros(self.mem_size, dtype=np.int32)

def store_transition(self, state, action, reward, state_, done):
    index = self.mem_cntr % self.mem_size
    self.state_memory[index] = state
    self.new_state_memory[index] = state_
    self.reward_memory[index] = reward
    self.action_memory[index] = action
    self.terminal_memory[index] = 1 - int(done)
    self.mem_cntr += 1

def sample_buffer(self, batch_size):
    max_mem = min(self.mem_cntr, self.mem_size)
    batch = np.random.choice(max_mem, batch_size, replace=False)

    states = self.state_memory[batch]
    states_ = self.new_state_memory[batch]
    rewards = self.reward_memory[batch]
    actions = self.action_memory[batch]
    terminal = self.terminal_memory[batch]

    return states, actions, rewards, states_, terminal

def build_dqn(lr, n_actions, input_dims, fc1_dims, fc2_dims):
model = keras.Sequential([
    keras.layers.Dense(fc1_dims, activation='relu'),
    keras.layers.Dense(fc2_dims, activation='relu'),
    keras.layers.Dense(n_actions, activation=None)])
model.compile(optimizer=Adam(learning_rate=lr), loss='mean_squared_error')

return model

class Agent():
def __init__(self, lr, gamma, n_actions, epsilon, batch_size,
            input_dims, epsilon_dec=1e-3, epsilon_end=0.01,
            mem_size=1000000, fname='dqn_model.h5'):
    self.action_space = [i for i in range(n_actions)]
    self.gamma = gamma
    self.epsilon = epsilon
    self.eps_dec = epsilon_dec
    self.eps_min = epsilon_end
    self.batch_size = batch_size
    self.model_file = fname
    self.memory = ReplayBuffer(mem_size, input_dims)
    self.q_eval = build_dqn(lr, n_actions, input_dims, 256, 128)

def store_transition(self, state, action, reward, new_state, done):
    self.memory.store_transition(state, action, reward, new_state, done)

def choose_action(self, observation):
    if np.random.random() < self.epsilon:
        action = np.random.choice(self.action_space)
    else:
        state = np.array([observation])
        actions = self.q_eval.predict(state)

        action = np.argmax(actions)

    return action

def learn(self):
    if self.memory.mem_cntr < self.batch_size:
        return

    states, actions, rewards, states_, dones = \
            self.memory.sample_buffer(self.batch_size)

    q_eval = self.q_eval.predict(states)
    q_next = self.q_eval.predict(states_)

    q_target = np.copy(q_eval)
    batch_index = np.arange(self.batch_size, dtype=np.int32)

    q_target[batch_index, actions] = rewards + \
                    self.gamma * np.max(q_next, axis=1)*dones

    self.q_eval.train_on_batch(states, q_target)

    self.epsilon = self.epsilon - self.eps_dec if self.epsilon > \
             self.eps_min else self.eps_min

def save_model(self):
    self.q_eval.save(self.model_file)

def load_model(self):
    self.q_eval = load_model(self.model_file)

A: The problem was that the goal state position and the initial position of the agent was not stationary. When they are fixed as reported by OP the agent starts winning consistently about "90% of the time".
Though far from perfect I wouldn't expect much from a naive DQN. Using more advanced techniques like A3C or even DDQN (Double Deep Q learning) should help you solve it. As we use a bit more advanced techniques to start to solve even more complex problems.
small and easy tasks with not much future planning could be done with some more diverse methods such as 'Monte-Carlo'. But the main problem here is that your obstacles are randomly generated and the simple DQN does not formulate in advance what path it should take to avoid the red areas which give a negative reward.
DQN is essentially Q-learning but values are stored in a more compressed state so to accommodate a bit more than possible. So it is not reliable for such complex solutions (as said before). So simply put the solution is to just use more complex and new methods, many of which I have mentioned.


text:
Q: Manually add files to Django's media folder and programmatically populate the database I am trying to production-deploy a Django project for the first time. My pre-Django implementation contains quite a bit of data (thousands of images, thousands of entries in the database). I have written a custom manage.py populate_db command that parses the dump of the old database and creates the new Django database based on my models. However I am stuck with adding all the files.
My initial deployment plan is to create the database locally once, sFTP-upload all images to the media folder on the server, do the same with the database and that's it. For this, I need the database to reference the image files in the media folder. As far as I understand, Django does it simply by filename. So far, I've been able to do this:
def _add_image_files(self, user: str):
    i = 0
    for f in local_files:
        i += 1
        photo = Photo(album=1, number=i, back=False, added_by=user)
        from django.core.files import File
        photo.image.save(f.name, File(open(f.path, 'rb')))

where Photo is defined as
class Photo(models.Model):
    album = models.IntegerField(null=True)
    number = models.IntegerField(null=True)
    image = models.ImageField(null=True, upload_to='photo_image_files')

However Django obviously duplicates every file by reading and writing it to the media folder. I don't need this duplication, I only want to add a reference to each file to the database.
How can I achieve it? Alternatively, if this is for some reason a poor approach, please let me know a better way. Thanks.

A: I have actually found the answer here: https://stackoverflow.com/a/12917845/674976 The "trick" is that ImageField can be simply populated with the image file name. Combined with bulk_create, I now get a reasonable execution time.
 photo_list = []
 for i in range(1000):
     photo = Photo(album=1, number=i, back=False)
     photo.image = 'photo_image_files/:filename_i.jpg'
     photo_list.append(photo)
 Photo.objects.bulk_create(photo_list)

I couldn't find any reference for this trick (assigning file name directly to ImageField), so if you could add one by editing or in comments, it would be a nice improvement to this answer.

A: django version: 3.2.4
Well, you may define your storage, which won't duplicate file, case it already exists.
Warning: this solution leads to problems when 2 processes will try to save file with same name. But it fits for programmatically populate the database.
models.py

...
from django.core.files.storage import FileSystemStorage
...
class NonDuplicateStorage(FileSystemStorage):
    OS_OPEN_FLAGS = os.O_WRONLY | os.O_CREAT | getattr(
        os, 'O_BINARY', 0)

    def exists(self, name):
        return False

non_duplicate_storage = NonDuplicateStorage()

class Photo(models.Model):
    ...
    image = models.ImageField(null=True, upload_to='photo_image_files', storage = non_duplicate_storage)

What's happened here:
let's open storage class
Lib\site-packages\django\core\files\storage.py
class FileSystemStorage(Storage):
    """
    Standard filesystem storage
    """
    # The combination of O_CREAT and O_EXCL makes os.open() raise OSError if
    # the file already exists before it's opened.
    OS_OPEN_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(
        os, 'O_BINARY', 0)

def _save(self, name, content):
...
        # There's a potential race condition between get_available_name and
        # saving the file; it's possible that two threads might return the
        # same name, at which point all sorts of fun happens. So we need to
        # try to create the file, but if it already exists we have to go back
        # to get_available_name() and try again.
...
        while True:
...
                    fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666)
...
            except FileExistsError:
                # A new name is needed if the file exists.
                name = self.get_available_name(name)
...

and self.get_available_name call
self.exists(), case file already exists - it will be renamed


text:
Q: How to calculate the limit: $\lim_{n\to\infty}\sum_{k=1}^n\big(\frac{k}{n}\big)^n$ How to calculate the following limit?$$\lim\limits_{n\to\infty}\sum\limits_{k=1}^n\left(\frac{k}{n}\right)^n$$
It is easy to seem the limit's existence.
But I don't know how to calculate its value.

A: Let $m$ be an arbitrary positive integer.  When $n>m$,
$$\sum_{j=0}^{m}\left(1-\frac{j}{n}\right)^n=\sum_{k=n-m}^{n}\left(\frac{k}{n}\right)^n\leq \sum_{k=1}^{n}\left(\frac{k}{n}\right)^n=\sum_{j=0}^{n-1}\left(1-\frac{j}{n}\right)^n\leq\sum_{j=0}^{n-1}e^{-j}<\frac{e}{e-1}.$$
Thus the limit is at most $\dfrac{e}{e-1}$, and taking limits in the inequality
$$\sum_{j=0}^{m}\left(1-\frac{j}{n}\right)^n\leq \sum_{k=1}^{n}\left(\frac{k}{n}\right)^n$$ yields $$\sum_{j=0}^me^{-j}\leq\lim\limits_{n\to\infty}\sum_{k=1}^{n}\left(\frac{k}{n}\right)^n.$$
Since the right-hand side does not depend on $m$, taking the limit as $m\to\infty$ yields
$$\frac{e}{e-1}\leq \lim\limits_{n\to\infty}\sum_{k=1}^{n}\left(\frac{k}{n}\right)^n.$$


text:
Q: Why does it keep outputing "0"? import java.util.Scanner;

class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
static int rank[];
int students;

public void save() {
    Scanner sc = new Scanner(System.in);

    System.out.println("Please input number of students");
    students = sc.nextInt();

    name = new String[students];
    korean = new int[students];
    math = new int[students];
    english = new int[students];
    sum = new int[students];
    average = new double[students];
    rank = new int[students];

    for (int i = 0; i < students; i++) {
        System.out.println("Name?");
        name[i] = sc.next();
        System.out.println("Korean Score :");
        korean[i] = sc.nextInt();
        System.out.println("Math Score :");
        math[i] = sc.nextInt();
        System.out.println("English Score :");
        english[i] = sc.nextInt();

        sum[i] = korean[i] + math[i] + english[i];
        average[i] = sum[i] / 3;
        }
  }
}

class DataOutput extends DataInput {

public void ranker() {
    for (int i = 0; i < students; i++){
        rank[i] = 1;
    }

    for (int i = 0; i < students; i++) {
        for (int j = i + 1; j < students; j++) {
            if (sum[i] < sum[j]) {
                rank[i] += 1;
            } else if(sum[i]>sum[j]){
                rank[j] += 1;
            }
        }
    }

}

}

public class Score {
public static void main(String[] args) {
    DataInput data = new DataInput();
    DataOutput out = new DataOutput();
    data.save();
    out.ranker();

    System.out.println();
    System.out.println("Name\t\tKorean  Math  English\tSum  Average  Rank");
    System.out
            .println("-------------------------------------------------------");

    for (int i = 0; i < data.students; i++) {
        System.out
                .println(data.name[i] + "\t\t" + data.korean[i] + "  "
                        + data.math[i] + "  " + data.english[i] + "\t"
                        + data.sum[i] + "  " + data.average[i] + "  "
                        + out.rank[i]);
    }
}

}

So, this is a little program I built. I think the logic is quite right, but when I run the program and type in all the variables, the ranks of students are all 0.
I can't figure out what's the problem. It would be really thankful if someone helps me.

A: Instead of average[i] = sum[i] / 3; - which does integer math; I think you really need average[i] = sum[i] / 3.0; which should give you a non-zero result.

A: When you call instantiate a new instance of Data output
    DataOutput out = new DataOutput();

it creates all new data. setting the number of students to zero.
Not Recommended
you should either pass in the number of students EDIT and other data
   DataOutput out = new DataOutput(students, otherData);

   //In Class Constructor

   DataOutput(int student, int ... otherData)
   {
       this.student = student;
       for(int i : otherData)
         //code
   }

Recommended
or you should put the ranker method inside of the dataInput class
   class DataInput
   {
         //code
        public int ranker()
        {
           //code
        }
   }

A: The data varible and out variable are "not linked". You call ranker on an "empty" class. Just because DataOutput extends DataInput doesn't mean those two instances are linked/related in anyway.
In the context of the code given: Move the ranker method into the DataInput class and just omit the DataOutput class. Then call ranker() on your data variable.

A: Use the same derived class object to hold the data on only one object. You are creating two objects.
With DataInput object, data is stored. When you create object for DataOutput, it is fresh object with all default values '0' in all arrays. So use the derived class object for both data storage and output.
out.save();
out.ranker();

System.out.println();
System.out.println("Name\t\tKorean  Math  English\tSum  Average  Rank");
System.out
        .println("-------------------------------------------------------");

for (int i = 0; i < out.students; i++) {
    System.out
            .println(out.name[i] + "\t\t" + out.korean[i] + "  "
                    + out.math[i] + "  " + out.english[i] + "\t"
                    + out.sum[i] + "  " + out.average[i] + "  "
                    + out.rank[i]);
}


text:
Q: There is no template in my dotnet I have installed dotnet-sdk-2.1.105 on my Ubuntu 18.04, but when I use command dotnet new, I found no template in there
The list of templates is at the bottom, but it's empty and no template in there

A: I've fixed my problem by using a previous version of dotnet sdk and dotnet runtime.


text:
Q: Find $\int \frac{{\rm d}x}{1+e\cos x}$
Find $$\int \frac{{\rm d}x}{1+e\cos x}$$

*

*When $e$ lies between $0$ and $1$

*When $e$ is greater than $1$

I got $\int \frac{dx}{1+e\cos x}$ when $e$ lies between $0$ and $1$, by substituting $\tan\frac{x}{2} =t$.
$$\int \frac{dx}{1+e\cos x} = \frac{2}{\sqrt{1-e^2}} \tan^{-1}\left( \frac{\sqrt{1-e}}{\sqrt{1+e}}\tan \frac{x}{2} \right) +C,$$
which will not be valid for $e >1.$
What different attempt we can do for $e>1$?

A: Substituting $t=\tan(\frac{x}{2})$ we obtain for $e\neq1$ (and the case $e=1$ gives $\int \frac{dx}{1+\cos x}=\tan(\frac{x}{2})+c_1$)
$$\int \frac{dx}{1+e\cos x}=\int \frac{2}{1+t^2+e(1-t^2)}dt$$
$$=\int\frac{2}{t^2(1-e)+(1+e)}dt=\int\frac{2}{(1-e)\left(t^2+\frac{1+e}{1-e}\right)}dt=\frac{2}{1-e}\int\frac{1}{t^2+\frac{1+e}{1-e}}dt$$
$\bullet$ Then for $0<e<1$ you can use the $\tan$ substitution to obtain $\arctan$ function (as you did).
$\bullet$ For $e>1$, you can use partial fractions decomposition to obtain logarithms. To make the calculations simpler, you can let $c^2=-\frac{1+e}{1-e}$, then you have $\int\frac{1}{t^2-c^2}dt$

A: \begin{align}
& \int \frac{dx}{1+e\cos x} = \int \frac{\frac{2\,dt}{1+t^2}}{1+e\cdot\frac{1-t^2}{1+t^2}} \\[8pt]
= {} & \int \frac{2\,dt}{(1+t^2) + e(1-t^2)} \\[8pt]
= {} & \int \frac{2\,dt}{(1+e) + (1-e)t^2} \\[8pt]
= {} & \frac 1 {1+e} \int \frac{dt}{1 + \frac{1-e}{1+e}\cdot t^2} \\[8pt]
& \text{Then if } e<1 \text{ we get this:} \\
= {} & \frac 1 {(1+e)\sqrt A} \int \frac{\sqrt A\,dt}{1+At^2}
\text{ where } A = \frac{1-e}{1+e} \\[8pt]
= {} & \frac 1 {(1+e)\sqrt A} \int \frac{du}{1+u^2} \text{ and so on.} \\[8pt]
& \text{If } e>1 \text{ then we have} \\[8pt]
& \frac 1 {1+e} \int \frac{dt}{1 - Bt^2} \text{ where } B=-A \\[8pt]
= {} & \frac 1 {1+e} \int \frac{dt}{(1 - t\sqrt B)(1 + t\sqrt B)} \\[8pt]
= {} & \frac 1 {1+e} \int \left( \frac C {1-t\sqrt B} + \frac D{1+t\sqrt B} \right) \, dt \\
& \text{and then you have to do} \\
& \text{some algebra to find $C$ and $D$.}
\end{align}


text:
Q: How to save dynamic changes to a Silverlight XAML file? In a scenario where the user created a textbox in the xaml page during runtime, I need to save his changes to the design of the XAML so that it is available when he opens it the next time.
I understand that XAMLWriter is only available for WPF, is there a way to do this in Silverlight ?


text:
Q: Numbering each value in a sequence Minimum Reproducible Example:
df = pd.DataFrame({'event_name': ['fulham','fulham','fulham','fulham','fulham','fulham'],
                      'batfast_id': ['bfs1', 'bfs1', 'bfs1', 'bfs1', 'bfs1', 'bfs1'],
                      'session_no': [1,1,1,1,1,1],
                      'overs': [0,0,0,0,0,0],
                      'deliveries_faced': [0,1,2,3,4,5],
                      'length/type': ['ES_LS_Y','ES_LS_Y','S_S_Y','ES_OS_Y','ES_LS_Y','ES_LS_Y']}, columns=['event_name', 'batfast_id','session_no','overs', 'deliveries_faced','length/type'])
df = df.set_index(['event_name', 'batfast_id','session_no','overs', 'deliveries_faced'],drop=True)
print(df)

There are 6 deliveries_faced in an over. I then produce a sequence column that gives the sequence of 6 length/type in each over using this code:
df['sequence'] = (df.groupby(["event_name", "batfast_id", "session_no", "overs"])["length/type"]
                       .apply(lambda x: ",".join(x)).loc[lambda x: x.str.count(",") == 5]

                   )

However I want to number each delivery in the sequence. eg 'ES_LS_Y1','ES_LS_Y2','S_S_Y3','ES_OS_Y4','ES_LS_Y5','ES_LS_Y6' or something along those lines that uniquely numbers each delivery.

A: You can try enumerating the x and then use the index in a format string, check the code below.
df['sequence'] = (df.groupby(["event_name", "batfast_id", "session_no", "overs"])["length/type"]
                   .apply(lambda x: ','.join(f'{val}_{i}' for i, val in enumerate(x)))
               )

A: Use enumerate:
out = df.groupby(level=df.index.names[:-1])['length/type'] \
        .apply(lambda x: ','.join(f"{v}{i}" for i, v in enumerate(x.tolist(), 1)))
print(out)

# Output:
                                                        length/type
event_name batfast_id session_no overs deliveries_faced
fulham     bfs1       1          0     0                    ES_LS_Y
                                       1                    ES_LS_Y
                                       2                      S_S_Y
                                       3                    ES_OS_Y
                                       4                    ES_LS_Y
                                       5                    ES_LS_Y


text:
Q: UNIX valid_password why in Cygwin Terminal - the if statement work
and ubuntu - unix - not working   for
this code :
#!/bin/sh
valid_password="pass"

echo "Please enter the password:"
read password

if [ "$password" == "$valid_password" ]
then
   echo "You have access!"
else
   echo "Access denied!"
fi

A: because the correct syntax to [ is:
[ a = b ]

From your error message it sounds like you wrote:
if ["$password" = "$valid_password" ]

change this to:
if [ "$password" = "$valid_password" ]

notice the space after [. if just takes a shell command, try to run it and depending if the exit code from the program is 0 it will run the commands inside the if statement.
In your terminal, write i.e.:
user@localhost$ true; echo $?
0

to test your if statement:
user@localhost$ pass=pass; valid=pass
user@localhost$ if [ "$pass" = "$valid" ]; then echo 'You have access!'; fi

As @nullrevolution said, the ! is evaluated if you use double quotes, it will try to run last command in your shell history, in this case that is matching u.
user@localhost$ uname
Linux
user@localhost$ !u
uname
Linux
user@localhost$ echo "!"
sh: !: event not found

This is because the ! is evaluated before the double quotes are matched, and echo is run. If you still want to use double quotes, you will have to escape the ! outside the quotes:
echo "Access denied"\!

@nullrevolution also said you could try with bash, which has a builtin syntax for the expression inside if statements.
#!/bin/bash

valid_password=pass

echo "Please enter the password:"
read password

if [[ "$password" == "$valid_password" ]]; then
    echo 'You have access!'
else
    echo 'Access denied!'
fi

Also in your program I guess you do not want to echo the password in the terminal, to turn off echo temporary change:
read password

to
stty -echo
read password
stty echo

if you forgot to write stty echo to turn on echo again, just write reset in your terminal, and it will reset the terminal to default settings.
A useful tutorial for bourn shell script can be found here:
http://www.grymoire.com/Unix/Sh.html

A: @emil pointed the answer:
if [ "$password" = "$valid_password" ]

instead of
if [ "$password" == "$valid_password" ]

Also: did you give the script executing permissions? Try
chmod +x script_name


text:
Q: Confused about equating random variables, vs. their distributions Let's say I have two random variables, $X$ and $Y$.
I know the relationship between their CDF's:
$$F_Y(y) = g(F_X(y))$$
For example, I could know that $F_Y(y) = F_X(y)^2$ or something like that.
What then can I say about relating $Y$ to $X$?  I am pretty sure I can't say that $Y = g(X)$... but I think there must be a relationship there.

A: As already explained by others, a functional equation between the CDF of two random variables $X$ and $Y$, such as the equation in this question, implies no almost sure relation whatsoever between $X$ and $Y$. A first reason is that $X$ and $Y$ may be defined on different probability spaces. A second reason is that, even if $X$ and $Y$ are defined on the same probability space, their CDF do not determine $X$ and $Y$, at all.
Basic examples to keep in mind in this setting might be $X$ uniform on $(0,1)$ and $Y=1-X$, or $X$ uniform on $(0,1)$ and $Y$ uniform on $(0,1)$ but independent on $X$. Both these $X$ and $Y$, at the level of their CDF, are indistinguishable from $X$ uniform on $(0,1)$ and $Y=X$.
However, a similar, but different, question might be of interest: consider a CDF $G$ and a function $g$ such that $g\circ G$ is also a CDF (hence $G$ replaces $F_X$ and $g\circ G$ replaces $F_Y$). Since every function which is nondecreasing and continuous on the right with limits $0$ and $1$ at $-\infty$ and $+\infty$ is a CDF, one way to ensure that $g\circ G$ is a CDF is to ask that $g$ is nondecreasing, continuous on the right, with limits $0$ and $1$ at $0$ and $1$. Assume that all this holds and that $X$ has CDF $G$, one can ask if there is a way to build a random variable with CDF $g\circ G$, using only $X$. The problem becomes:

Let $X$ with CDF $G$. Find a function $a$ such that the CDF of $a(X)$ is $g\circ G$.

Here is a fact:

If $U$ is uniformly distributed on $(0,1)$ and $G$ is a CDF, there exists a function, which we denote $G^\ast$, such that the CDF of $G^\ast(U)$ is $G$.

The function $G^\ast$ is a pseudo-inverse of $G$, defined as follows: for every nondecreasing and continuous on the right function $h$ and every real number $u$,
$$
h^\ast(u)=\inf\{x\mid G(x)\ge u\}.
$$
It is a nice analysis exercise to check that $h^\ast$ may also be defined by the equivalence
$$
h^\ast(u)\le x\iff u\le h(x).
$$
Consequences are that $h^\ast$ is nondecreasing and continuous on the right and that $(h_1\circ h_2)^\ast=h_2^\ast\circ h_1^\ast$. This answers a slightly easier question than ours:

Choose $U$ uniformly distributed on $(0,1)$ and consider the random variables $X=G^\ast(U)$ and $Y=(G^\ast\circ g^\ast)(U)$. Then the CDF of $X$ is $G$ and the CDF of $Y$ is $g\circ G$.

This also suggests that, to get $Y$ as a function of $X$, one could consider:

  $Y=a(X)$ with $a=G^\ast\circ g^\ast\circ G.$

With this definition, one sees that
$$
[Y\le y]=[g^\ast(G(X))\le G(y)]=[G(X)\le g(G(y))],
$$
hence the proof would be complete if one knew that
$\mathrm P(G(X)\le z)=z$ for every $z$ in the image of $g\circ G$ (note that to ask this for every $z$ is hopeless in general).
When $g$ is the identity, the problem itself becomes trivial (choose $Y=X$) but our function $a=G^\ast\circ G$ is not always the identity. In general, $G^\ast\circ G(x)\le x$ for every $x$ and it seems that
$$
(G^\ast\circ G)(x)=\inf\{z\le x\mid\mathrm P(z<X<x)=0\},
$$
which would imply that $(G^\ast\circ G)(X)=X$ almost surely.

A: There need not be any obvious relationship between $X$ and $Y$: even if $g(w)=w$, all you have are two identically distributed random variables, but they may be equal or independent or have some other relationship.
So all you have is a relationship between the distributions.  You can see that $g$ must be weakly increasing and that $g(0)=0$ and $g(1)=1$ (perhaps in some cases as limits).  But that is about it beyond repeating the equation in words or looking at specific examples.
Take $X$ having a uniform distribution on $(0,1)$: so $Y$ has CDF $g(y)$ on this support, and for example if $g(w)=w^2$ then $Y$ has a triangular distribution on $(0,1)$ with the mode at $1$. I also looked at $X$ being normally distributed and $g(w)=w^2$, and that made $Y$ have close to but not quite a normal distribution.

A: $X$ and $Y$ could be defined on completely different probability spaces.  Even if they are defined on the same probability space, there is no particular relationship between the events $X \le a$ and $Y \le b$: all you know about are their probabilities $F_X(a)$ and $F_Y(b)$.  So e.g. if $F_X(a) = 1/2$ and $F_Y(b) = 1/2$, $P(X \le a \text{ and } Y \le b)$ might be anything from $0$ to $1/2$.

A: Obviously this can work only if $g$ is a weakly increasing function from $[0,1]$ to itself and fixes $0$ and $1$.
One extreme case is that $Y$ is actually equal to $F_Y^{-1}(g(F_X(X)))$.  In that case, the random variable $X$ completely determines $Y$ and the relationship between the two cdf's is just the one you've written.  Qualification: provided $F_Y$ and $g$ are invertible, thus strictly increasing.
The opposite extreme case is that $Y$ is independent of $X$ and has the particular probability distribution that you've given.


text:
Q: Dependent Prefect flow runs across multiple instances I have two physical machines. I would like Prefect to automatically execute a flow run on machine B once a flow run on machine A finishes. What's the most lightweight way to do this?
In other words, I want to run a flow of flows, in which the flows are executed on different physical devices.
Why do I need this? Some of the data is sensitive so they are only accessible on a particular machine.

A: The most lightweight version would be to leverage the orchestrator pattern - the same applies to both Prefect 1 and Prefect 2.
For Prefect 2, check out: https://discourse.prefect.io/t/how-to-create-a-flow-run-from-deployment-orchestrator-pattern/803
For Prefect 1, check out: https://discourse.prefect.io/t/can-i-run-a-flow-of-flows-that-triggers-each-child-flow-on-a-different-machine/180


text:
Q: Photos saved to iOS from Google Drive randomly downsized in resolution Anybody experienced this please? How can I always have the original resolution?
Since these photos are exported from a raw to a gif on my laptop, they are around 4000x of resolution.
Sometimes they are saved to my camera roll in the original resolution and sometimes they are downsized to about 1000x.
In both cases I'm using the same saving process from Google Drive to iOS.
Thanks for your help!


text:
Q: Apache cxf delete request error I'm trying to use @DELETE request after a made some simple web application which I've tested using soapui. With this application I can add and get users/book to database. Now I'm trying to made a @DELETE request but I can't make it. Here is the code:
//UserServiceImpl

    @PersistenceContext
    private EntityManager em;

    @Override
    public void deleteUser(Long id) {
        if (null == id || id.longValue() < 1) {
            throw new IllegalArgumentException(" User id can not be null or less than zero. ");
        }

        User u = em.find(User.class, id);
        em.remove(u);

    }

//UserResource

    @Autowired
    private UserService userService;

    @DELETE
    @Path("/delete/{id}")
    public Response deleteUser(@PathParam("id") String id) {
        Response response;
        try {
            User user = userService.deleteUser(Long.valueOf(id));//here is the error
            if (user != null) {
                response = Response.status(HttpServletResponse.SC_OK).entity(user).build();
            } else {
                response = Response.status(HttpServletResponse.SC_NOT_FOUND).build();
            }
        } catch (IllegalArgumentException e) {
            response = Response.status(HttpServletResponse.SC_NOT_FOUND).build();
        }
        return response;
    }

A: I`ve fix my problem. The delete method which is in UserServiceImpl must not be void.... it must be public User deleteUser(Long id). The other delete method in Resource class ... just need to be of void type. There i do not use Response and i simply print the result like this:
System.out.print(Response.status(HttpServletResponse.SC_OK).entity(user).build());


text:
Q: "Accept-language" not set in the request header while using URLConnection in android? I am using URLConnection to download the html file from an android app. But I want the HTML content based on the device-locale.
Suppose user send the request from German locale then response should be in german language. I am expecting that URLConnection should send accept-language according to device-locale, similar to ajax calls. But accept-language header is not present in the request made by URLConnection.
Do I need to set request header explicitly or are there any alternative?
Thanks in advance.

A: You can use any of following to get the device locale language in your format -
Locale.getDefault().getLanguage()       ---> en
Locale.getDefault().getISO3Language()   ---> eng
Locale.getDefault().getCountry()        ---> US
Locale.getDefault().getISO3Country()    ---> USA
Locale.getDefault().getDisplayCountry() ---> United States
Locale.getDefault().getDisplayName()    ---> English (United States)
Locale.getDefault().toString()          ---> en_US
Locale.getDefault().getDisplayLanguage()---> English

Source - Refer here
You can give Accept-Language header in your request like -
URL url = new URL("website url");
URLConnection urlconnection = url.openConnection();
urlconnection.setRequestProperty("Accept-Language", "en-GB");


text:
Q: scipy.signal.cwt is getting a value error in correlate() I'm getting a weird error when attempting to use scipy.signal.cwt:
I have some list c, and I want to take the continuous wavelet transform like this:
scipy.signal.cwt(np.array(c), scipy.signal.morlet, np.arange(.01,.1,.01))

and I get a weird error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-5af5e14b96cd> in <module>()
----> 1 sig.cwt(a, sig.morlet, np.arange(.01,.1,.01))

/usr/local/lib/python2.7/site-packages/scipy/signal/wavelets.pyc in cwt(data, wavelet,     widths)
    359         wavelet_data = wavelet(min(10 * width, len(data)), width)
    360         output[ind, :] = convolve(data, wavelet_data,
--> 361                                               mode='same')
    362     return output

/usr/local/lib/python2.7/site-packages/scipy/signal/signaltools.pyc in convolve(in1,     in2, mode)
    270
    271     if np.iscomplexobj(kernel):
--> 272         return correlate(volume, kernel[slice_obj].conj(), mode)
    273     else:
    274         return correlate(volume, kernel[slice_obj], mode)

/usr/local/lib/python2.7/site-packages/scipy/signal/signaltools.pyc in correlate(in1, in2, mode)
    129         in1zpadded = np.zeros(ps, in1.dtype)
    130         sc = [slice(0, i) for i in in1.shape]
--> 131         in1zpadded[sc] = in1.copy()
    132
    133         if mode == 'full':

ValueError: could not broadcast input array from shape (66467) into shape (66466)

What's causing this error?

A: the third argument of scipy.signal.cwt is widths, which must larger than 1, so change your code to:
scipy.signal.cwt(np.array(c), scipy.signal.morlet, np.arange(.01,.1,.01) * len(c))


text:
Q: gdb debugger quits prematurely on popen(), 'signal SIGTRAP, Trace/breakpoint trap'? The following code works in stand alone (non-debugging) mode. However gdb debugging stops when I tried to step over popen(), meaning a breakpoint at the fgets() can never be reached.
#include <stdio.h>

int main()
{
    char buff[10];
    FILE *f = popen("echo blah", "r");
    // program and debugger exit before this line
    // so that fgets() and printf() were never called
    fgets(buff, 5, f);
    printf("%s\n", buff);
}

GDB reports Program terminated with signal SIGTRAP, Trace/breakpoint trap. I dug into glibc's popen() and this is where it quits,
// internal-signal.h
/* Block all signals, including internal glibc ones.  */
static inline void
__libc_signal_block_all (sigset_t *set)
{
  INTERNAL_SYSCALL_CALL (rt_sigprocmask, SIG_BLOCK, &sigall_set, set,
             __NSIG_BYTES);
}

Does anyone knows what is going on here? thanks!

A: Turned out to be a kernel issue, at least when I reverted back from 5.15.x to 5.14.x, the issue went away. I thought kernel update were never meant to break userspace.