text:
Q: Do I need ConcurrentQueue in this case of using Task.WhenAll? I'm reading from 4 XML files asynchronously and want to combine the results into one results file. I'm using ConcurrentQueue but I'm not sure if I need to.
Is the fact that I'm adding to a single collection within a Task.WhenAll might cause a concurrency problem? Is the ConcurrentQueue the only way to solve this problem?
Data File Sample (1 of 4)
<?xml version="1.0" encoding="utf-8" ?>
<states>
  <state id="11" Name="Georgia" Abbrev="GA" Capital="Atlanta" region="" />
  <state id="12" Name="Alabama" Abbrev="AL" Capital="Montgomery" region="" />
  <state id="13" Name="Mississippi" Abbrev="MS" Capital="Jackson" region="" />
  <state id="14" Name="Arkansas" Abbrev="AK" Capital="Little Rock" region="" />
  <state id="15" Name="South Carolina" Abbrev="SC" Capital="Columbia" region="" />
</states>

Code
namespace ConsoleApp1
{
    class Program
    {
        static string[] _regions = new[] { "ResourceMidwest.xml", "ResourceRockyMountains.xml", "ResourceSoutheast.xml", "ResourceSouthwest.xml" };

        static void Main(string[] args)
        {
            var results = GetLocations().GetAwaiter().GetResult();
        }

        static async Task<statesState[]> GetLocations()
        {
            ConcurrentQueue<statesState> toReturn = new ConcurrentQueue<statesState>();

            var w = await Task.WhenAll(_regions.Select(async region =>
            {
                var r = await GetLocationServices(region);
                var r2 = DeserializeResponse<states>(r);

                foreach (var item in r2.state)
                {
                    toReturn.Enqueue(item);
                }
                return toReturn;
            }));

            return toReturn.ToArray();
        }

        static async Task<string> GetLocationServices(string filename)
        {
            var results = await File.ReadAllTextAsync(filename);

            return results;
        }

        static T DeserializeResponse<T>(string r)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(T));

                using (TextReader reader = new StringReader(r))
                {
                    return (T)serializer.Deserialize(reader);
                }
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}

A: You don't need a to mutate shared state in the concurrent tasks at all.  Instead just return the data and aggregate it in the main thread after all the tasks have run.  eg
var states = await Task.WhenAll(_regions.Select(async region =>
{
    var r = await GetLocationServices(region);
    var state = DeserializeResponse<State>(r);
    return state;
}));

foreach (var s in states) ...


text:
Q: How to solve API fetch and type error in React I have an error when I call an API, I think this error is failed to compile, because this error indicates to me:
Cannot read property 'type' of undefined in line 18

I run fetchCoins in useEffect, how to I can solve this error?
I dont know why fetchCoins is undefined!?
import './App.css';
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Coin from './Coin';
import Pagination from 'react-js-pagination'

const App = () => {

  const [coins,setCoins] = useState([]);
  const [search , setSearch] = useState('');

  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(10);

useEffect(() => {
  const fetchCoins = () => {
    setLoading(true);
    axios.get('https://api............')
    .then(res => { setCoins(res.data)})
    .catch(err => console.log(err))
    setLoading(false);
  };
  fetchCoins()
}, [])

  const handleChange = e => {
    setSearch(e.target.value)
  }

  const filteredCoins = coins.filter(coin =>
    coin.name.toLowerCase().includes(search.toLowerCase())
    );

  console.log(fetchCoins())

  return (

      <form>
        <input type="text" placeholder="search" className="coin-input" onChange={handleChange} />
      </form>

    {filteredCoins.map(coin => {
        return (
          <Coin
            key={coin.id}
            name={coin.name}
            price={coin.current_price}
            symbol={coin.symbol}
            marketcap={coin.total_volume}
            volume={coin.market_cap}
            image={coin.image}
            priceChange={coin.price_change_percentage_24h}
          />
        );
      })}

  );
}

export default App;

A: You don't have access to fetchCoins outside useEffect because of cost block scope. Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block
You can fix that bit via the below code.
Your error around line 18 is not in this file and likely unrelated to your question.
import "./App.css";
import React, { useState, useEffect } from "react";
import axios from "axios";
import Coin from "./Coin";
import Pagination from "react-js-pagination";

const App = () => {
  const [coins, setCoins] = useState([]);
  const [search, setSearch] = useState("");

  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(10);

  useEffect(() => {
    const fetchCoins = () => {
      setLoading(true);
      axios
        .get("https://api............")
        .catch((err) => console.log(err))
        .then((res) => {
          setCoins(res.data);
          setLoading(false); // note I moved this in here
        });
    };
    fetchCoins();
  }, []);

  const handleChange = (e) => {
    setSearch(e.target.value);
  };

  const filteredCoins = coins.filter((coin) =>
    coin.name.toLowerCase().includes(search.toLowerCase())
  );

  console.log(coins); // you don't have access to fetchCoins here due to block scope limitations

  return (

        <form>
          <input
            type="text"
            placeholder="search"
            className="coin-input"
            onChange={handleChange}
          />
        </form>

      {filteredCoins.map((coin) => {
        return (
          <Coin
            key={coin.id}
            name={coin.name}
            price={coin.current_price}
            symbol={coin.symbol}
            marketcap={coin.total_volume}
            volume={coin.market_cap}
            image={coin.image}
            priceChange={coin.price_change_percentage_24h}
          />
        );
      })}

  );
};

export default App;

redpajama_set_name: RedPajamaStackExchange


text:
Q: django - any prebuilt authentication signal receivers? I'm writing a custom logout view since the Django built in logout function wipes out all the sessions when it calls the request.session.flush(). I have some sessions variables that I would like to keep even though the user has logged out.
I was thinking to use a signal to notify all the web site that I've logged out.
Does the Django 1.2.4 authentication system  have any built signal receivers to send a signal to so the other pages on the web site will be "informed" that I've logged out?

A: No, Django 1.2.4 doesn't provide authentication signals, but they were added in trunk, so the next release probably will include them.
http://docs.djangoproject.com/en/dev//topics/auth/#login-and-logout-signals


text:
Q: Asymptotics of sequence depending on Tricomi's function I'm dealing with the following sequence
$$ p_n = U(a, a - n, 1)$$
where $a > 0$ and $U$ is Tricomi's function.
I suspect that asymptotically when $n \to \infty$ its behaviour is a power law (evidence)
$$ p_n \sim 1/n^a $$
but I cannot arrive to anything with known properties (I've already checked the NIST handbook).
Any ideas are welcome, thanks in advance.
EDIT: Found stronger evidence: $\beta=a$
EDIT: Specified which asymptote

A: There are some details in the following derivation which will be omitted to keep this answer at a reasonable length.  What follows is a set of clotheslines on which a rigorous proof can hopefully be hung.
We will use the integral representation
$$
\begin{align}
U(a,a-n,1) &= \frac{1}{\Gamma(a)} \int_0^\infty e^{-t} t^{a-1} (1+t)^{-n-1}\,dt \\
&= \frac{1}{\Gamma(a)} \int_0^\infty \exp f_{a,n}(t)\,dt.
\end{align}
$$
(see equation 13.2.5 in Abramowitz and Stegun).  The function $f_{a,n}(t)$ critical points at $t \approx -n$ and $t \approx \frac{a-1}{n}$, so in the domain of integration the function will be maximized at $t=0$ if $a>1$ for $n$ large enough.  One can check explicitly that this is also true when $a=1$.  If $a>1$ then $f_{a,n}(t)$ is maximized at the point $t \approx \frac{a-1}{n}$.
Let's consider the case $0 < a \leq 1$.  We have
$$
\begin{align}
f_{a,n}(t) &= -t + (a-1)\log t - (n+1)\log(1+t) \\
&= -t + (a-1)\log t - (n+1)t + O(nt^2) \\
&\approx (a-1)\log t - (n+2)t,
\end{align}
$$
near $t=0$, so that as $n \to \infty$ the Laplace method yields
$$
\begin{align}
\int_0^\infty \exp f_{a,n}(t)\,dt &\sim \int_0^\infty \exp\Bigl[(a-1)\log t - (n+2)t\Bigr]\,dt \\
&= \frac{\Gamma(a)}{(n+2)^a} \\
&\sim \frac{\Gamma(a)}{n^a}.
\end{align}
$$
Now let's consider $a>1$.  In this case the function $f_{a,n}(t)$ has a maximum inside the range of integration at $t = t^* \approx \frac{a-1}{n}$.  Explicitly this is
$$
\begin{align}
t^* &= \frac{-n+a-3}{2}+\frac{1}{2}\sqrt{n^2+(-2a+6)n+a^2-2a+5} \\
&= \frac{-n+a-3}{2}+\frac{n}{2}\sqrt{1+\frac{-2a+6}{n}+\frac{a^2-2a+5}{n^2}} \\
&= \frac{-n+a-3}{2}+\frac{n}{2}\left[1+\frac{1}{2}\left(\frac{-2a+6}{n}+\frac{a^2-2a+5}{n^2}\right) \right. \\
&\qquad\qquad \left.- \frac{1}{8}\left(\frac{-2a+6}{n}+\frac{a^2-2a+5}{n^2}\right)^2 + O\left(\frac{1} {n^3}\right)\right] \\
&= \frac{-n+a-3}{2}+\frac{n}{2}\left[1 + \frac{-a+3}{n} + \frac{2a-2}{n^2} + O\left(\frac{1} {n^3}\right)\right] \\
&= \frac{-n+a-3}{2} + \frac{n}{2} + \frac{-a+3}{2} + \frac{a-1}{n} + O\left(\frac{1} {n^2}\right) \\
&= \frac{a-1}{n} + O\left(\frac{1} {n^2}\right),
\end{align}
$$
where we used the fact that $\sqrt{1+x} = 1 + \frac{x}{2} - \frac{x^2}{8} + O(x^3)$ to get the third equality.  We then have
$$
\begin{align}
f_{a,n}(t) &= -t + (a-1)\log t - (n+1)\log(1+t) \\
&= \alpha(a,n) + \beta(a,n)(t-t^*)^2 + \text{higher order terms},
\end{align}
$$
and we calculate
$$
\alpha(a,n) = (a-1)\Bigl[\log(a-1)-\log(n)-1\Bigr] + o(1)
$$
and
$$
\beta(a,n) = -\frac{n^2}{2 (a-1)} + O(n).
$$
By the Laplace method we conclude that
$$
\begin{align}
\int_0^\infty \exp f_{a,n}(t)\,dt &\sim e^{\alpha(a,n)} \int_{-\infty}^{\infty} \exp\Bigl[ \beta(a,n) t^2 \Bigr]\,dt \\
&\sim \exp\Bigl\{(a-1)\Bigl[\log(a-1)-\log(n)-1\Bigr]\Bigr\} \int_{-\infty}^{\infty} \exp\Bigl[ -\frac{n^2}{2 (a-1)} t^2 \Bigr]\,dt \\
&= e^{1-a} \sqrt{\frac{2\pi}{a-1}} \left(\frac{a-1}{n}\right)^a.
\end{align}
$$
In summary,

If $0 < a \leq 1$ then
  $$
U(a,a-n,1) \sim \frac{1}{n^a}
$$
  and if $a > 1$ then
  $$
U(a,a-n,1) \sim \frac{e^{1-a}}{\Gamma(a)} \sqrt{\frac{2\pi}{a-1}} \left(\frac{a-1}{n}\right)^a.
$$


text:
Q: SSH and SSHPASS Condition if machine online or offline I need to make bash file for remote backups. If remote machine is down i would like to send reminder by email. So this script needs to test if remote machine has ssh on if so do backup, otherwise send mail.
sshpass -p pass ssh -l root $host
this give me connection timed out if remote machine is down and ok wheen it is online

1condition, do it when machine is on
.....rsync backup....

2condition, do it wheen machine is down
...sending mail....

A: I think you're over-complicating this; what you really care about is the backup -- and if it succeeds or fails.
Try this:
rsync -avz /local/path root@$host:/remote/path || echo "failed" | mail -s "Backup failed" username@machine

The important part is the || that executes the remainder of the line if the exit code from the rsync command indicates failure -- for any reason.


text:
Q: Apache MiNiFi compatibility with jre-1.7 I am working on integration of Minifi and Nifi.currently i am working with Minifi version-0.1.0(java - 1.8).I tried working with Minifi 0.1.0 in a server which has java-1.7.But when i tried running any minifi commands like:
    bin/minifi.sh status.
    But getting this error:
    Java home: /usr/local/java/default
    MiNiFi home: /opt/minifi-0.0.1
Bootstrap Config File: /opt/minifi-0.0.1/conf/bootstrap.conf

Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/nifi/minifi/bootstrap/RunMiNiFi : Unsupported major.minor version 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

I think by default Minifi has been configured to run with Java-1.8
So i also tried with Minifi(version-0.0.1),facing same issues.
I want to know which minifi version is compatible with jre-1.7.
I would be grateful for any answers.
Thank you

A: You just need to upgrade your Java to 1.8 and will fix your problems

A: Initial development on Apache MiNiFi was started in 2016, at which time Java 1.7 was over four years old and Java 1.8 had been released for ~2 years. As Apache NiFi 1.0.0 and following versions removed backward compatibility with Java 7 in August 2016, the foundation for MiNiFi Java 0.0.1 was not designed to have Java 7 compatibility. There is no version of MiNiFi which was developed to be compatible with Java 7.


text:
Q: VBScript enable editing in Excel file & save as Set obj = CreateObject("Excel.Application")
obj.Visible = False
Set objwbk = obj.Workbooks.Open("File Link")
obj.DisplayAlerts = False
objwbk.SaveAs "C:\Data.xlsx"
Set obj1 = obj.Workbooks.Open("C:\Data.xlsx")
obj1.Visible = True

I have the above code to create a copy of the file on SharePoint. I am able to open the file but it does not make a copy because the file is opened in readonly mode. I am unable to figure out how to use the ActiveProtectedWindow.edit method here to be able to successfully achieve my objective.

A: Maybe something like this:
Set obj = CreateObject("Excel.Application")
obj.Visible = False
obj.DisplayAlerts = False

Set objwbk = obj.Workbooks.Open("File Link")
If objwbk.Application.ProtectedViewWindows.Count > 0 Then
    objwbk.Application.ActiveProtectedViewWindow.Edit
End If
objwbk.SaveAs "C:\Data.xlsx"
Set obj1 = obj.Workbooks.Open("C:\Data.xlsx")
obj1.Visible = True


text:
Q: Add in routerLink params only if it's not null or undefined? How can I add in router link params but only if it's not null or undefined?
Something like this:
<a [routerLink]="['/user/bob']" [queryParams]="{test? test:test : '', test2?test2:test2:''}" queryParamsHandling="merge">
  link to user component
</a>

I have multiple values so all of them I need to check if they are not null or undefined to add them in params


text:
Q: Call a concrete method on an concrete object which current type is an abstract object I have the following abstract class which ensures that all subclasses contain the method eval().
public abstract class ExpressionTreeNode {
        abstract double eval();
}

I would like to create several concrete classes which inherit from ExpressionTreeNode, like the class Addition. Theses concrete classes contain two other concrete classes (right and left), which inherit from ExpressionTreeNode. Since there might be different concrete classes I defined the variable type as ExpressionTreeNode.
Furthermore I would like to call the eval() method from these concrete classes. But Eclipse says at this point (e.g. double arg1 = right.eval();):

The method eval() is undefined for the type ExpressionTreeNode

Why is it undefined? There can't be a object which is only of the type ExpressionTreeNode and therefore it will contain the eval() method.
public class Addition extends ExpressionTreeNode {

    ExpressionTreeNode left;
    ExpressionTreeNode right;

    public double eval() {
        double arg1 = left.eval();
        double arg2 = right.eval();

        return arg1+arg2;
    }
}

How can I solve this problem (without using an interface instead of the abstract class)?

A: As @daniu notes in the comments, this is likely due to not making your method public.
Here's a working example that shows your basic architecture is valid:
public class TreeClasses {
    public static abstract class ExpressionTreeNode {
        public abstract double eval();
    }

    public static class Addition extends ExpressionTreeNode {

        ExpressionTreeNode left;
        ExpressionTreeNode right;

        public Addition(ExpressionTreeNode left, ExpressionTreeNode right) {
            this.left = left;
            this.right = right;
        }

        public double eval() {
            double arg1 = left.eval();
            double arg2 = right.eval();

            return arg1+arg2;
        }
    }

    public static class Constant extends ExpressionTreeNode {
        double val;

        public Constant(double val) {
            this.val = val;
        }

        @Override
        public double eval() {
            return val;
        }

    }

    public static void main(String[] args) {
        ExpressionTreeNode tree = new Addition(new Constant(1),new Constant(2));
        System.out.println(tree.eval());
    }
}


text:
Q: Weird behavior with Python os.system and mysqldump When I try and do a mysqldump on a remote host using the command line it will work perfectly
mysqldump -alv -h some_ip_here -Psome_port -usome_user some_db_name > /tmp/dumps/some_dump_file.sql

However, when I try the same thing in Python using os.command, I get a weird access denied error.
import os

command = 'mysqldump -alv -h some_host_ip -Psome_port -usome_user some_db_name > /tmp/dumps/some_dump_file.sql'

os.system(command)

Any ideas what is going on here?
Error message of the Python implementation below
-- Connecting to some_host_ip...
mysqldump: Got error: 1045: Access denied for user 'some_user'@'some_other_host_ip' (using password: YES) when trying to connect


text:
Q: extract a list of values from a variable, based on a list of indices, in R I have a list of row indices for an R dataframe (dat). What function can I use to extract the corresponding values for a target variable (dat$id)?
set.seed(42)  ## for sake of reproducibility
n <- 6
dat <- data.frame(id=c("s1","s2","s2","s3","s4","s4"),
                  date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
                  visit=1:2,
                  age=sample(18:30, n, replace=TRUE))
#dat
# id       date visit age
# 1 s1 2020-12-26     1  18
# 2 s2 2020-12-27     2  22
# 3 s2 2020-12-28     1  18
# 4 s3 2020-12-29     2  26
# 5 s4 2020-12-30     1  27
# 6 s4 2020-12-31     2  21

listindex->c(2,4,6)
#target variable is dat$id

desired_output:
s2
s3
s4

A: You can use [] to subset the id values by row index.
dat$id[listindex]
#[1] "s2" "s3" "s4"


text:
Q: Select statement is not working and cannot read from SQL database in Visual Basic After the button click event I wrote this:
Dim dbo As New Class1
dbo.connect()
dbo.objcomm.CommandText="select * from Employee where Emp_Code ="' &TextBox1.Text&"'"
dbo.objread .Read()
TextBox2.Text=dbo.objread.GetValue(1)
End Sub

What it should do is that it should take the second value in the Employee and display it in the textbox after clicking on the buttton.
However, nothing happens when I click.
I'm sure that the code is correct and that nothing is missing so what could possibly be the reason that the code is not working?
I have tried it in other applications and it worked fine. Now it is not.


text:
Q: Why is this regexp returning an empty item at the beginning of the array? I've got a javascript string I'm trying to split, but I'm getting an empty element at the beginning of the returned array, and I can't figure out why.

var split_in_el = in_el.split(/(#|\.|\[)/);

where split_in_el is either first,#last, or [color:red].
the returned arrays I'm getting (in Node.js, but shouldn't matter) are

.first //split_in_el
[ '', '.', 'first' ]  //returned
#last //split_in_el
[ '', '#', 'last' ] //returned
[color:blue] //split_in_el
[ '', '[', 'color:blue]' ] //returned

Here's a jsfiddle showing the issue.

A: This is how split() works in general, let's say we are splitting the following on the dot .:
Hello.World
     ^
----- -----

Then the returned array would be: ["Hello", "World"].
Now what if the previous line were like this:
    .World
    ^
  -- -----

Then we get an array like this: ["", "World"], the split() method returns everything before the dot . and everything after the ., nothing exists before the dot . here so it returns empty string "".
In a larger example:
.Hello.World.From.

It would return: ["", "Hello", "World", "From", ""].
Now the confusing part in your situation shouldn't be how you are getting the empty string, but rather how are you getting the character which you are splitting about in the resulting array.
For example, there is a dot . when you split around the dot . in .first, and there is a pound sign # when you split around the pound sign # in #last, etc ..
This can become obvious when you look at the documentation of split() method:

If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array.

The separator in your case is a regular expression /(#|\.|\[)/ that matches (or splits around) either a dot ., pound sign # or a colon : inside a capturing group, so they are added to the resulting array.
/(#|\.|\[)/
 ^       ^
 ---------
 These parentheses are used to create the capturing group

You can solve this by converting the capturing group into a non-capturing one like this:
/(?:#|\.|\[)/
  ^^
Notice the syntax

Finally I want to add one thing: in situations like .first and #last you probably don't want to use split(), but rather RegExp.exec() or String.match() to look for a particular match using a given pattern.
For example if you want to retrieve the word after a . character like .first then you can do:
var matches = ".first".match(/\.\w+/);


text:
Q: alternative way of blades @extends via controllers? Every view that I create I have to use @extends('my.layout.path'). Is there a way I can just tell the controller what layout the following views in the controller will be using?

A: First thing on the Templates docs page:

One method of using templates in Laravel is via controller layouts. By specifying the layout property on the controller, the view specified will be created for you and will be the assumed response that should be returned from actions.

class UserController extends BaseController {

    /**
     * The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Show the user profile.
     */
    public function showProfile()
    {
        $this->layout->content = View::make('user.profile');
    }
}

A: nm, i figured it out for anyone else this is what i did:
class MyController extends basecontroller
{
    protected $layout = 'layouts.admin';
}

class DashboardController extends AdminBaseController
{
    public function index()
    {
        $this->layout->content = View::make('admin.dash');
    }
}

then in the view i just have
@section('content')
... some html
@stop


text:
Q: Swagger nested parameter object I'd like to make a swagger endpoint thats request body is a product object with 2 integar fields and an options object with 2 more fields, I'm using rswag as a ruby gem
In my spec
      parameter in: :body, schema: {
        type: :object,
        properties: {
            product_id: { type: :integer },
            quantity: { type: :integer },
            options: {
                properties: {
                  color: { type: :string },
                  size: { type: :string },
                }
            },
          }
      }

However, in my ui I have no fields for color or size, just a text field for options, how can i fix this?

A: Try this :
  parameter in: :body, schema: {
    type: :object,
    properties: {
        product_id: { type: :integer },
        quantity: { type: :integer },
        options: {
            type: :object,
            properties: {
              color: { type: :string },
              size: { type: :string },
            }
        },
      }
  }


text:
Q: Separate "for" loop iterations How would I go about making each iteration of my four loop be random. The outcome as of now makes all 20 sentences put the same output, although it is choosing random words each time from the four arrays created in static class OuterWord. I have omitted the parts of the code that I don't think are necessary including the getMethods created for each array and sentence, hopefully that will not negatively effect my question.
`public class SentenceMaker {
static class OuterWord {
    //arrays
    String [] article = {"the", "a", "one", "some", "any"}; //array for articles
    String [] noun = {"boy", "girl", "dog", "town", "car"}; //array for nouns
    String [] verb = {"drove", "jumped", "ran", "walked", "skipped"}; //array for verbs
    String [] preposition = {"to", "from", "over", "under", "on"}; //array for prepositions

}
static class OuterSentence {
   int random = (int) (Math.random()*5);
    OuterWord word = new OuterWord();

    //sentence structure article-noun-verb-preposition-article-noun
    //StringBuilder with append, attempts to concatenate with .append
    //This code works as well
    StringBuilder sentence = new StringBuilder()
                    .append(word.article[random].substring(0, 1).toUpperCase())
                    .append(word.article[random].substring(1))
                    .append(" ")
                    .append(word.noun[random])
                    .append(" ")
                    .append(word.verb[random])
                    .append(" ")
                    .append(word.preposition[random])
                    .append(" ")
                    .append(word.article[random])
                    .append(" ")
                    .append(word.noun[random])
                    .append(".");
}

public static void main(String args[]) {
    //random element from arrays
    //int random = (int) (Math.random()*5);

    //instantiation of the Word and Sentence classes
    OuterWord word = new OuterWord();
    OuterSentence s = new OuterSentence();

    //loop initializer
    int counter = 0;

    //for loop for 20 iterations
    for(int i = 0; i < 20; i++){
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence.);
    }
}

}`

A: I would start by moving everything into a single class, your code is needlessly complicated by the way you have organized it.
private static String[] article = { "the", "a", "one", "some", "any" };
private static String[] noun = { "boy", "girl", "dog", "town", "car" };
private static String[] verb = { "drove", "jumped", "ran", "walked", "skipped" };
private static String[] preposition = { "to", "from", "over", "under", "on" };

Next, I would write a method to get the title case of a given word. You only need to capitalize the first character, but a StringBuilder is great for that.
private static String getTitleCase(String w) {
    StringBuilder sb = new StringBuilder(w);
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    return sb.toString();
}

Then building a sentence, I would move that to a method. You currently only get a single random index and build a single sentence. Instead, get a random value appropriate to each array length and I would use a StringJoiner to simplify adding the spaces between words. Like,
private static String buildSentence() {
    Random rand = ThreadLocalRandom.current();
    StringJoiner sj = new StringJoiner(" ");
    sj.add(getTitleCase(article[rand.nextInt(article.length)]));
    sj.add(noun[rand.nextInt(noun.length)]);
    sj.add(verb[rand.nextInt(verb.length)]);
    sj.add(preposition[rand.nextInt(preposition.length)]);
    sj.add(article[rand.nextInt(article.length)]);
    sj.add(noun[rand.nextInt(noun.length)]);
    return String.format("%s.", sj);
}

Finally, call the above method twenty times
public static void main(String[] args) {
    for (int i = 0; i < 20; i++) {
        System.out.println(buildSentence());
    }
}

A: Just move the OuterSentence object to for loop.
for(int i = 0; i < 20; i++){
        OuterSentence s = new OuterSentence();
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence);
    }

The above one is much readable or the other way is to just create the new object in the System.out.println statement like as follows:
System.out.println("Sentence " + counter + ": " + new OuterSentence().sentence);

In both the ways we are creating a new object for every statement so that new random will get generated so that new sentence will be formed.


text:
Q: Mod Rewrite ignore url I am creating a site where instead of using GET variables I will just be looking at the url. How would you create a mod_rewrite rule that no matter what directs the user to index.php(Or some page)?
EX:
User enters: www.example.com/blog/programming/postName
User still sees www.example.com/blog/programming/postName in the adress bar but www.example.com/index.php is shown

I have tried:
RewriteRule    ^([a-z]+.)?$    /index.php    [NC,L]

But that only changes the page for one directory(only worked for www.example.com/worksNow/

RewriteRule    ^(.*)    /Blog3/index.php    [NC,L]

But It got a server error

A: You can use this rule:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L]

This means if any request that is not for a file or directory then internally rewrite that to /index.php
Reference: Apache mod_rewrite Introduction

A: This behavior/recipe doesn't require mod_rewrite, see FallBackResource.
http://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource


text:
Q: Какое отличие состояния от характеристики в Java? Какое отличие состояния от характеристики в Java?
Класс - некая абстракция, логическая структура, описывающая поведение и характеристики.

Разве описывающая поведение и характеристики, разве не состояние?

Какое вообще отличие характеристики от состояния?

A: Характеристика это свойство, а состояние - конкретное значение этого свойства.
Примеры:
характеристика - состояние
-----------------------------
 скорость(м/с) -    10
     цвет      -  зеленый
    масса(г)   -    13
 угол(радиан   -    0.5


text:
Q: How to split an existing eclipse dynamic web project into web, jar, and webservice I have la large Eclipse project ( Dynamic Web Pages, using tomcat), and need to split it in three projects with dependencies:

*

*The application proper, providing web pages through tomcat

*A relatively static part, shared with other projects, preferably becoming a JAR (sort of framework)

*A web service, publishing some of the application functionality, through axis14 and tomcat

My question is how to define these three projects so that dependencies are handled automatically by eclipse, while being able to debug them combined ?
-- I'm using Eclipse Helios Java EE R1 in windows vista 32bits


text:
Q: time data '2022-11-27T23:40:26' does not match format '%Y-%m-%d %H:%M:%S' how can chnge this format my df['time'] is 2022-11-27T23:40:26 this format i want to change in %Y-%m-%d %H:%M:%S this format
how can i do
Need solution in above problem/sformat

A: *

*First make your datetime string to a pandas datetime type with pd.to_datetime()

*Then convert it back to any other datetime string you like using pd.Series.dt.strftime()
Your code could look like this:
import pandas as pd

data = {"time": ["2022-11-27T23:40:26", "2022-12-28T10:12:26"]}
df = pd.DataFrame(data)

df["time"] = pd.to_datetime(df["time"])
df["time_formatted"] = df["time"].dt.strftime("%Y-%m-%d %H:%M:%S")


text:
Q: The procedure to matching words from a list to words in a line The following are two examples of many lines that I need to analyze and extract specific words from.
[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.

The coordinates and numbers are ignored
The case is to find how many of the words in each tweet line are present in this keywords list:
['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.
For example, for the sentence
'I hate to feel lonely at times'

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.
I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.
What I want to find out is the sum of sentiment values of the keywords found in each line and how many words there were in each line
Appreciate your insight in advance!! :)
My Code:
try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()

A: If your tweets are in a .txt like this file and pattern of lines of tweets are same as you described in the question then you can try this approach:
import re
import json
pattern=r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)'
sentiment_dict={'hate' :1,'hurt':1,'hurting':1,'like':5,'lonely':1,'love':10}

final=[]
with open('senti.txt','r+') as f:
    for line in f:
        data = []

        match=re.finditer(pattern,line)
        for find in match:
            if find.group(1).split():
                final.append(find.group(1).split())

line=[]

for item in final:
    final_dict = {}

    for sub_item in item:
        if sub_item in sentiment_dict:
            if sub_item not in final_dict:
                final_dict[sub_item]=[sentiment_dict.get(sub_item)]
            else:
                final_dict[sub_item].append(sentiment_dict.get(sub_item))

    line.append((item,len(item),{key: sum(value) for key,value in final_dict.items()}))

result=json.dumps(line,indent=2)

print(result)

output:
[
  [
    [
      "Sometimes",       #tweets line or all words
      "I",
      "wish",
      "my",
      "life",
      "was",
      "a",
      "movie;",
      "#unreal",
      "I",
      "hate",
      "the",
      "fact",
      "I",
      "feel",
      "lonely",
      "surrounded",
      "by",
      "so",
      "many",
      "ppl"
    ],
    21,                   #count of words in tweets
    {
      "lonely": 1,        #sentiment count
      "hate": 1
    }
  ],
  [
    [
      "I",
      "wish",
      "I",
      "could",
      "lay",
      "up",
      "with",
      "the",
      "love",
      "of",
      "my",
      "life",
      "And",
      "watch",
      "cartoons",
      "all",
      "day."
    ],
    17,
    {
      "love": 10
    }
  ],
  [
    [
      "I",
      "hate",
      "to",
      "feel",
      "lonely",
      "at",
      "times"
    ],
    7,
    {
      "lonely": 1,
      "hate": 1
    }
  ]
]

Options for regex if one pattern doesn't work for your file:

*

*r'[a-zA-Z].+'   #if you use this change find.group(1) to find.group()

*r'(?<=\d.\s)[a-zA-Z].+'   #if you use this change find.group(1) to find.group()

*r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)'

*r'\b\d{2}:\d{2}:\d{2} (.+)'  #group(1)

A: The simplest approach is to use word_tokenize from nltk library on a per tweet basis.
from nltk.tokenize import word_tokenize
import collections
import re

# Sample text from above
s = '[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl'
num_regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
# Removing the numbers from the text
s = num_regex.sub('',s)
# Tokenization
tokens = word_tokenize(s)
# Counting the words
fdist = collections.Counter(tokens)
print fdist

`


text:
Q: make does not realize that a relative path name dependency is the same as an absolute pathname target The following is a simplified makefile for a problem I'm having:
all: /tmp/makey/../filey
    @echo All done
/tmp/filey:
    @echo Filey

When I run make it says:
make-3.79.1-p7: * No rule to make target /tmp/makey/../filey', needed byall'.  Stop.
Clearly it does not realize that /tmp/makey/../filey is the same as /tmp/filey.  Any ideas how I can make this work?
Thanks
Ciao
-- Murali

A: Newer versions of GNU make have $(abspath ...) and $(realpath ...) functions you can apply to your prerequisites and targets to resolve the paths to the same string.  If you've constructed these names yourself (for example, $(PREFIX)/../filey) then you can use $(dir $(PREFIX))filey instead.
Other than that, there's no way to solve this problem.  Make uses string matching on targets and if the strings are not identical, they don't match (there's a special case to ignore the simple prefix ./)  Even if make understood this distinction (by applying abspath itself to each target name, maybe) it would still not help in the face of symbolic links for example.
The only "real" answer would be for make to understand something about the underlying file system (device IDs and inodes for example) that let you talk about files without referring to their pathname.  However, in a portable program like make doing this is problematic.


text:
Q: C++ Linker error in Xcode for a Static Method I'm sure this is bone-headly simple but I just can't see it.  I'm getting the following linker error in C++ Xcode.
Undefined symbols for architecture x86_64:
"Random::NextInt(int, int)", referenced from:
Helpers::MakeData(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, int) in Helpers.o

Helpers::MakeData
#include "Helpers.h"
#include "Random.h"

void Helpers::MakeData(string dataFile, int numLines)
{
    vector<double> weights = { -0.1, 0.2, -0.3, 0.4, -0.5,
    0.6, -0.7, 0.8, -0.9, 1.0,
    -1.1, 1.2, -1.3, 1.4, -1.5,
    1.6, -1.7, 1.8, -1.9, 2.0,
    -0.5, 0.6, -0.7, 0.8, -0.9,
    1.5, -1.4, 1.3,
    -1.2, 1.1, -1.0,
    0.9, -0.8, 0.7,
    -0.6, 0.5, -0.4,
    0.3, -0.2, 0.1,
    0.1, -0.3, 0.6 };

    NeuralNetwork * nn = new NeuralNetwork(4, 5, 3);
    nn->SetWeights(weights);
    ofstream myFile;
    myFile.open(dataFile);
    for (int i = 0; i < numLines; ++i)
    {
        vector<double> inputs;
        for (int j = 0; j < inputs.size(); ++j)
            inputs[j] = Random::NextInt(10, 1);

        vector<double> outputs = nn->ComputeOutputs(inputs);

        string color = "";
        int idx = Helpers::IndexOfLargest(outputs);
        if (idx == 0) { color = "red"; }
        else if (idx == 1) { color = "green"; }
        else if (idx == 2) { color = "blue"; }

        myFile << inputs[0] << " " << inputs[1] << " " << inputs[2] << " " << inputs[3] <<      " " << color;
    }
    myFile.close();
} // MakeData

Random.h
#ifndef __NeuralClassificationProgram__Random__
#define __NeuralClassificationProgram__Random__

#include <iostream>
class Random{

public:
    static double NextDouble();
    static int NextInt(int high, int low);
};

#endif /* defined(__NeuralClassificationProgram__Random__) */

Random.cpp
#include "Random.h"
#include <time.h>
#include <stdlib.h>

double NextDouble()
{
    double rnd;
    srand(static_cast<unsigned int>(time(NULL)));
    rnd = rand() % 1+0;
    return rnd;
}

int NextInt(int high, int low)
{
    int rnd;
    srand(static_cast<unsigned int>(time(NULL)));
    rnd = rand() % high + low;
    return rnd;
}

A: You did not include the class name qualifier in the implementation, so those "static methods" are being compiled as simple global functions.
For example, you have:
int NextInt(int high, int low)

But you need:
int Random::NextInt(int high, int low)

A: It's because you never defined Random::NextInt(int, int), you defined NextInt(int, int).
In other words, you forgot the class scope operator.
Try
int Random::NextInt(int high, int low)
{
    return rand() % high + low;
}

Oh, and don't call srand more than once in your program.


text:
Q: phone field is not displaying in stripe checkout page javascript strikeCheckout.open({
  name: this.product.product_name,
  description: 'Payment widgets',
  amount: +amount * 100,
  phone:'',
  address: {
    mode: 'shipping',
  },
  currency:'inr'
});

I am using this code base all fields are visible except phone, i want to display phone field in my stripe checkout configuration page aswell

A: trikeCheckout.open({
name: this.product.product_name,
description: 'Payment widgets',
amount: +amount * 100,
phone:'',
address: {
mode: 'shipping',
},
currency:'inr'
});**
**
strong text

A: It looks like you might be using the Legacy checkout.js integration pattern, which has been deprecated for several years. You should look at migrating to the modern Checkout flow, which supports phone number collection.


text:
Q: Failing to understand Devise after sign in redirect with Rails I'm a bit of a rails/devise newbie and I have done months of searching on this and haven't found a solution.
What I'm trying to do seems simple: Redirect a user to the previous page after a successful sign in event using Rails and the Devise gem (v 3.2.3), but instead all of my sign in redirects are going to the root path. It's annoying because if I send someone a link to a specific page within which they have to authenticate, it redirects them to the home page again.
I'm aware that other questions on SO ask this, but I think I'm asking a higher level question about the code in Devise.
So my overall question is this: Is my understanding of the problem and solution correct? In order to solve, I need to:

*

*Store the users previous page from their session

*Redirect to that location in the after_sign_in_path function

I'm looking at some code comments in Devise lib/devise/controllers/helpers.rb on line 177:
# The default url to be used after signing in. This is used by all Devise
  # controllers and you can overwrite it in your ApplicationController to
  # provide a custom hook for a custom resource.
  #
  # By default, it first tries to find a valid resource_return_to key in the
  # session, then it fallbacks to resource_root_path, otherwise it uses the
  # root path. For a user scope, you can define the default url in
  # the following way:

Then on line 204 of that file:
def after_sign_in_path_for(resource_or_scope)
  stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
end

which lead me to the stored_location_for method in store_location.rb:
def stored_location_for(resource_or_scope)
  session_key = stored_location_key_for(resource_or_scope)
  if is_navigational_format?
    session.delete(session_key)
  else
    session[session_key]
  end
end

So code in sessions#create is being called when a new user logs in:
# POST /resource/sign_in
def create
  self.resource = warden.authenticate!(auth_options)
  set_flash_message(:notice, :signed_in) if is_flashing_format?
  sign_in(resource_name, resource)
  yield resource if block_given?
  respond_with resource, location: after_sign_in_path_for(resource)
end

And that calls after_sign_in_path_for(resource) which I pasted above. My question is this: Is this everything I need to be able to redirect someone to the previous page instead of the root path? Is there something missing that I need to add? How can I test that after_sign_in_path_for(resource) is not nil? Anyone else have experience with this?
Just for reference here is my routes file:
Rails.application.routes.draw do
  get 'orders/index'
  resources "orders", :controller => :my_orders, :as => :orders
  get 'faq/index'
  resources "faq", :controller => :faq, :as => :faq
  get 'guidelines/index'
  resources "guidelines", :controller => :guidelines, :as => :guidelines
  get 'terms_of_use/index'
  resources "terms-of-use", :controller => :terms_of_use, :as => :terms_of_use
  get 'privacy_policy/index'
  resources "privacy-policy", :controller => :privacy_policy, :as => :privacy_policy

  # This line mounts Spree's routes at the root of your application.
  # This means, any requests to URLs such as /products, will go to Spree::ProductsController.
  # If you would like to change where this engine is mounted, simply change the :at option to something different.
  #
  # We ask that you don't use the :as option here, as Spree relies on it being the default of "spree"
  mount Spree::Core::Engine, :at => '/store'

# Need to adjust this for FB authentication
  devise_for :users, controllers: { registrations: 'users/registrations', passwords: 'users/passwords' }

  devise_scope :user do
    get 'register', to: 'devise/registrations#new', as: :register
    get 'signin', to: 'devise/sessions#new', as: :signin
    get 'logout', to: 'devise/sessions#destroy', as: :logout
    get 'edit', to: 'devise/registrations#edit', as: :edit
    put "update" => 'devise/registrations#update', as: :updateprofile
  end

  get 'welcome/index'

  get '/sell' => 'sell#index'

  get '/:id', to: 'profiles#show', as: :profile

  root 'welcome#index'

  # for setting up the stripe webhook
  post '/hooks/stripe' => 'hooks#stripe'

end

I will happily reveal more of my code if it's useful.
Thank you in advance,

*

*Brandon

EDIT
Did some more digging to narrow this down. I commented out a lot of the code in store_location.rb to see what the session key. Commented out the if/else statement since it was a navigational format, apparently (what does that mean anyway?):
  def stored_location_for(resource_or_scope)
    session_key = stored_location_key_for(resource_or_scope)
    puts "session_key = #{session_key}"
    puts "session = #{session}"
    puts "session[session_key] = #{session[session_key]}"
    # if is_navigational_format?
    #   puts "is navigational"
    #   session.delete(session_key)
    # else
    #   puts "is not navigational"
    puts "session[session_key] = #{session[session_key]}"
    session[session_key]
    # end
  end

and I added some put statements in this method which is bound to session_key.
  def stored_location_key_for(resource_or_scope)
    scope = Devise::Mapping.find_scope!(resource_or_scope)
    "#{scope}_return_to"
  end

Here's the output in the command line:
Started POST "/users/sign_in" for 127.0.0.1 at 2015-05-03 22:34:31 -0500
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"/Xjy/neoPX2nGqpz+FtACjtTx4nnkhiRuVln44Zi4qI=", "user"=>{"email"=>"brandon.a.hay@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."email" = 'brandon.a.hay@gmail.com'  ORDER BY "users"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.3ms)  UPDATE "users" SET "current_sign_in_at" = ?, "last_sign_in_at" = ?, "sign_in_count" = ?, "updated_at" = ? WHERE "users"."id" = 7  [["current_sign_in_at", "2015-05-04 03:34:31.179646"], ["last_sign_in_at", "2015-05-04 03:32:08.608830"], ["sign_in_count", 65], ["updated_at", "2015-05-04 03:34:31.181312"]]
  Spree::Role Load (0.1ms)  SELECT  "spree_roles".* FROM "spree_roles"  WHERE "spree_roles"."name" = 'admin' LIMIT 1
  SQL (0.1ms)  INSERT INTO "spree_roles_users" ("role_id", "user_id") VALUES (?, ?)  [["role_id", 1], ["user_id", 7]]
   (1.5ms)  commit transaction
session_key = user_return_to
session = #<ActionDispatch::Request::Session:0x007fc7c4af34b0>
session[session_key] =
stored location =
session_key = user_return_to
session = #<ActionDispatch::Request::Session:0x007fc7c4af34b0>
session[session_key] =
Redirected to http://localhost:3000/

So, stored_location_key_for returns the user class and binds that to the scope. session_key returns "user_return_to", session returns an action dispatch request session, and session[session_key] is nil. Can someone help make sense of this to me?

A: The answer from this post solved my problem: redirect back to current page using omniauth and devise
I had to add a store location call back in my application controller:
#application_controller.rb
before_filter :store_current_location, :unless => :devise_controller?

def store_current_location
  store_location_for(:user, request.url)
end

A: You need to redirect routes in your controller, like this
class HomeController < ApplicationController
    def index
        if user_signed_in?
            redirect_to blogs_index_path
        end
    end
end

go to terminal and type rake routes and find the path you want and redirect it there. hope this helps!

A: It looks like attempted location is never stored or stored in a wrong place. Look at this code https://github.com/plataformatec/devise/blob/v3.2.3/lib/devise/failure_app.rb
Failure app is always called when authentication fails. You can see that on line 57 it stores accessed uri. You can try to debug in this place.
I can think of few reasons why this doesn't work:

*

*you are using different failure app which doesn't store location

*session key is incorrect in failure app

*there is some code that clears stored location

If you cannot find what problem causes this you can try to copy code from devise failure app to your application controller. Use prepend_before_filter to store location before any other before_filters.


text:
Q: Error deleting tabs in envelope I'm having an issue when trying to delete a tab using the REST API which fails at the following URL:
https://demo.docusign.net/restapi/2/accounts/{accountID}/envelopes/{envelopeID}/recipients/1/tabs
DELETE with body {"checkboxTabs":[{"tabId":"168229c3-d717-436f-b6a9-5f014d1817bb"}]} gets:
{
  "checkboxTabs": [
    {
      "selected": "false",
      "requireInitialOnSharedChange": "false",
      "recipientId": "1",
      "tabId": "168229c3-d717-436f-b6a9-5f014d1817bb",
      "errorDetails": {
        "errorCode": "INVALID_TAB_OPERATION",
        "message": "The Tab specified is not valid for the requested operation."
      }
    }
  ]
}

It's unclear what the problem is and I cannot find a good example of the correct usage.  Is it possible that the tab wasn't found to delete?
UPDATE
I also tried an UPDATE instead of a DELETE and I got the following response body (interestingly the response shows textTabs instead of checkboxTabs):
{
  "textTabs": [
    {
      "requireAll": "false",
      "concealValueOnDocument": "false",
      "disableAutoSize": "false",
      "documentId": "1",
      "recipientId": "1",
      "tabId": "00000000-0000-0000-0000-000000000000",
      "errorDetails": {
        "errorCode": "INVALID_TAB_OPERATION",
        "message": "The Tab specified is not valid for the requested operation.  The Tab specified is not valid for the requested operation. Recipient not in state that allows correction."
      }
    }
  ]
}

However this time the error message also contained "Recipient not in state that allows correction" which means I'm attempting an invalid operation as the recipient had already signed?  If someone can clarify that would help my understanding.
It would be very useful if the DELETE method also contained a similar message.

A: That error should appear if the tabID does not exist. I'd recommend a double check the tabID by performing a GET against the same URL.

A: I believe you'll get that error if ANY of the tab properties you specify are incorrect.  For instance, you might be referring to the correct tabId but if the tab in question is on document 2 (for example) and you are referencing documentId = 1 in your request you'll get that error.
I recommend that right before you send the DELETE request to first do a GET on the tab and then inspect all the properties returned and verify that they all match what you are sending out in your delete request.

UPDATE
I just realized what you're probably running into.  The EnvelopeTabs: delete API request you are trying to make says this for the description
"Deletes one or more tabs associated with a recipient in a draft envelope."
I believe this is only for DRAFT envelopes.  Once you have sent the envelope you need to do an envelope correction if you want to change aspects about it.  Your error message is also referencing this
"Recipient not in state that allows correction"


text:
Q: How to replace text inside braces using Powershell? I have the following powershell script running over a C# class in order to replace the constructor with an empty constructor. I am doing this over a number of files that were autogenerated.
$nl = [Environment]::NewLine
foreach($item in Get-ChildItem $path) {
        if($item.extension -eq ".cs") {

            $name = $item.name
            $name = $name.replace('.cs', '')
            $reg = '(public ' + $name + '\(.*?\})'
            $constructorString = [regex]$reg
            $emptyConstructor = 'public ' + $name + '()' + $nl + '{' + $nl + '}' + $nl

            Get-Content $item.fullname -Raw | Where-Object { $_ -match $constructorString } | ForEach-Object { $_ -replace $constructorString, '$1'}
        }
}

The classes have a form of
public Bar()
{
    this.foo = new Foo();
}

This results in no matches, let me know if more information is required.

A: There is no need to convert the pattern to a regex.  Try this:
$item | Get-Content -raw | Where {$_ -match "(?s)(public\s+${name}\s*\(.*?\})"} | ...

I believe the issue you are running into is that although you've read the C# file as a single string using the -Raw parameter, there are line breaks in the string that .* won't traverse unless you use singleline mode in the regex.  That is what the (?s) does.
Also, if you are on PowerShell V3 you can use basename instead of replace e.g.:
$name = $item.basename

BTW have you looked at Roslyn as an alternative to the regex search/replace approach?  Roslyn will build an AST for you for each source file.  With that you could easily find default constructors and replace it with an empty constructor.


text:
Q: SharePoint site style Is there a way to edit the master page without using SharePoint Designer?
I tried to use the Oslo theme but it doesn't show on my site, i looked in the internet and using Desinger may be the only solution.

A: You can edit a master page with any text editor of your choice.
For example: I always download the default master page (seattle.html or oslo.html) and do my stuff with notepad++. After that just rename the file so I don't overwrite the default file and upload it.
After that just publish master page so it will be converted to .master-file.
You can also check if anything is right with your new master page by calling
https:///_layouts/15/previewwithstatus.aspx?Url=%2F%5Fcatalogs%2Fmasterpage%2FNameOfYourFile%2Ehtml

A: You can download the file from the Page Layouts and Masterpage gallery. After you have obtained it from the website, you can edit it in any text-editor you like (notepad, VSCode, etc.). When you are done you can upload the file again and see your changes.
Same question for your reference:
How to edit a sharepoint master page without using sharepoint designer?


text:
Q: Upper bound in bayesian regression setting Let $y_i = x_i^\top  \beta + \epsilon_i$, $i=1,\ldots,n$; where $\epsilon_i$ are i.i.d. following a distribution with mean zero and unit variance, i.e., $\epsilon_i \sim P_{\epsilon_i}(0,1)$, $i=1,\ldots,n$, $\beta \sim N(0, (1/\lambda) I)$ and is p-dimensional vector, for some fixed $\lambda > 0$, and $x_i$ is also a p dimensional vector . Let the SVD of $X$ be $US^{1/2}V^\top$. Now, I am trying to find an upper bound on $\|y^\top UR\|_2^2$ where $s_i$ is $i^{th}$ diagonal element of $S$ and $R$ is zero matrix having same size as $S$ but with diagonal elements of $S$ inverted and each element is raised to the power half. My first attempt is below
\begin{align*}
\|y^\top UR\|_2^2 & = \|(X\beta + \epsilon)^\top UR \|_2^2 \\
& = \| \beta^\top (US^{1/2}V^\top)^\top UR + \epsilon ^\top UR\|_2^2 \\
& \leq 2 (\| \beta^\top V\|_2^2 + \|\epsilon ^\top UR\|_2^2) \\
& \leq 2 (\|\beta\|^2_{2} + \| \epsilon R\|^2_{2}).
\end{align*}
But, I am trying to find stricter bound for it and remove $\epsilon$, how can I use expectations or concentration inequalities here? Also, is it possible to use a trace of the covariance of $\epsilon$?


text:
Q: lastKnownLocation is always returning null when gps is off I am using Google Service API , LocationServices.FusedLocationApi to find user's current and then updated Location. I have tested on emulator as well as on actual device and I have found that if I turn off GPS LocationServices.FusedLocationApi.getLastLocation() always returns null, however I get a valid value if I turn on the GPS. Here is the code which I am using:
private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
mLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

if (mLastKnownLocation != null) {
    Log.i(TAG, String.valueOf(mLastKnownLocation.getLatitude()));
    Log.i(TAG, String.valueOf(mLastKnownLocation.getLongitude()));
}

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), this);

Am I missing something here?
Thanks in advance.

A: I think u should check if the your device has a GPS first by using this:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();
        }

 private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

And then use the LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient).
For more info and code please refer here.


text:
Q: What sample rate do I need to analyze usb 2 with a analyzer? What is the sample rate needed for a logic analyzer to be able to analyze a 480 Mbps USB 2 bus?

A: Nyquist basically says you need at least double the bandwidth (aka the highest frequency component of interest) in your signal to get a sampled waveform unique to your signal. Unique is not the same as accurate. Draw a sine wave with just two points per cycle, then 4, then 8, then 16. You can intuitively see why. Your square wave's fundamental is around 480MHz but the edges of a square wave contains frequencies many times that. But you know it is a square wave so you can weed out things like edges that don't seem to be exactly where they should be if your sample rate isn't many times faster than double.
It is the difference between having a discernible or identifiable picture vs a clear, highly detailed picture. Sometimes, discernible is enough though, especially if you already know what it is you are supposed to be looking at.

A: USB 2.0 HS signal has the main frequency of 240 MHz, but the signal UI (unit interval) is 2.083 ns. So you need few samples per UI to identify the bus state and its transitions.
There are software processing packages for high-speed oscilloscopes that provide USB protocol post-processing and decoding. For example, Tektronix offers USB decoder starting with mid-level scopes as
4 Series MSO Mixed Signal Oscilloscope, see this reference

In this example the default sampling rate for a straightforward signal decoding is 6.25 Gsps, but 3.125 Gsps is also doable. For more details of scope-based decoding see this article.
However, normal USB protocol analyzers don't use the raw data sampling; they use the same high-speed grade USB PHYs as in normal USB devices, they just use a weak non-invasive high-impedance sniffers with wide-band amplifiers to restore the signal and feed the PHY. The PHY does all this oversampling (internally), clock-data extraction, and provide an output in digital format to FPGA-based buffers and event triggering.

A: Since USB 2.0 hast a frequence of 480MHz you need more than the Double of this (Shannon-Theorem).
Neverthrless most often the 10 times of the frequence is recommended. So around 4800Mhz.


text:
Q: the closure of subgroup of $\mathrm{GL}(n,\mathbb{R})$ is a subgroup? I have read the following sentece on a lecture notes:

If $G\subset\mathrm{GL}(n,\mathbb{R})$ is a subgroup then its
topological closure $\overline{G}$ is a topologically closed subgroup.
$\overline{G}$ is obviously topologically closed, and I'm
claiming that it's still a subgroup.

Now, I guess the topology is a metric topology (on $\mathrm{GL}(n,\mathbb{R})$ all metrics  are equivalent), but I cannot see how it is true: as it is, it seems a false statement to me.
For example, if $G=\mathrm{GL}(n,\mathbb{R})$ then its closure is all the space of $n\times n$ matrixes, which is not a group.
Or if I consider the subgroup of diagonal matrix of the form $\lambda\mathrm{Id}_n$, $0\neq\lambda\in\mathbb{R}$, then the zero matrix is in the closure so it is not a group (with respect to the matrix multiplication).
I would need the assumption that $\overline{G}\subset\mathrm{GL}(n,\mathbb{R})$ to prove that it is a subgroup.
Am I missing something?

A: You are missing the fact that, when the author of those notes wrote about $\overline G$, what it was meant was its closure in $GL(n,\Bbb R)$.
Besides, it is not true that, in $GL(n,\Bbb R)$ all metrics are equivalent. The usual metric that it is used on $GL(n,\Bbb R)$ is the one for which$$d\bigl((a_{ij})_{1\leqslant i,j\leqslant n},(b_{ij})_{1\leqslant i,j\leqslant n}\bigr)=\sqrt{\sum_{i,j=1}^n(a_{ij}-b_{ij})^2}.$$


text:
Q: How to merge different rows in Excel based on a condition? How do I merge different rows in an Excel sheet into one row without losing any data by testing if the content of one of the column is equal. Also the merged rows should be treated as one single row. For example:
  row  Title1   Title2
   1     1        sdf
   2     1        dsf
   3     2        dsf
   4     3        dsaf
   5     3        asd

I want the above Excel sheet to become like so:
  row  Title1   Title2
   1     1        sdf
                  dsf
   2     2        dsf
   3     3        dsaf
                  asd

A: =IF (Logic_Test, Value_if_True, Value_if_False) so for you it would be something like this in the D column =IF(A1=A2, "=A1&B1&C1" , NA())


text:
Q: Multilingual Messages I have written the following code to show server side error messages on client side
messages.error(request , 'Authentication Failed.')

Which works file. I would like to load the message from Message file to keep all the messages in one place also I want to load images based on the language.
I explored Message File option in DJango but it looks like it translates the string by itself but I want to define myself and load them. How to achieve it?

A: I'm not sure I completely understood your question, but an example for you could be this:
# file text_messages.py
from django.utils.translation import ugettext as _

MY_MESSAGE = _('Auth failed')

Then in the script where you should use that message:
import text_messages

messages.error(request, text_messages.MY_MESSAGE)

This is all in the docs
Then, of course, you need to run django-admin.py makemessages --locale=en,de and provide a way to switch correctly languages in your views. Is this what you where after?


text:
Q: Trying to join two function returns in Angular.js or JavaScript I have the following Angular controller. I want to take items from both x and y variables and show them on the web page. Right now, the web page only shows items from the y variable. I try to use .push() to put the two function result sets together into the PremByClass array. Any help or direction on how to do this would be greatly appreciated.
app.controller('PremByClass', ['$scope', '$http', 'policyApi', 'lookupApi', function ($scope, $http, policyApi, lookupApi) {
    $scope.model = {};
    $scope.load.then(function () {
        function formatDate(value) {
            return value.getMonth() + 1 + "-" + value.getDate() + "-" + value.getFullYear();
        }
        $scope.PremByClass = [];
        policyApi.policy.get().then(function (t) {
            if (t) {
                policyApi.class.get().then(function (x) {
                    if (x) {
                        //Put x into $scope.PremByClass
                        $scope.PremByClass.push(x);
                        var dtEff = formatDate(t.DateEffective);
                        for (var i = 0, e = null; e = x[i]; i++) {
                            lookupApi.WCClassDesc.get(e.GovState, e.classCode, e.DescCode, dtEff).then(function (y) {
                                //This seems to wrok correctly however it seems that $scope.PremByClass forgets about x
                                //The web page only shows stuff from y
                                $scope.PremByClass.push(y);
                            })
                        }
                    }
                })
            }
        })
    });
}]);

A: As it seems that your x variable is an array, I guess you should be showing it in your page as a list or table of objects with something like :

    {{item.GovState}} // {{item.classCode}}

I used the index 0 on PremByClass because your x variable is the first item you push into the PremByClass array. Although, I would make that part of the code more maintainable by setting the x variable into a more meaningful scope property.
You could replace this line in your controller:
$scope.PremByClass.push(x);

with this line:
$scope.policies = x;

and then simply rewrite your ng-repeat block to use policies:

    {{item.GovState}} // {{item.classCode}}

the variable/array PremByClass would then contain only results from your lookupApi.WCClassDesc service or factory and you should be able to render them on screen using the same ng-repeat code as above simply replacing policies with PremByClass.


text:
Q: How do I get a Bootstrap container to stay inline with another div? Currently, the top of my web page looks like this:

I'm trying to use Bootstrap instead of CSS as I was told it was simpler (however so far I'm struggling to bend it to my will just as much as CSS). I have a div containing the logo and title, and a Bootstrap container with a list group of buttons to share the website. I want the buttons to appear on the right hand side of the page inline with the logo.
HTML:

FACTorFICTION

CSS:
.list-group-horizontal .list-group-item {
display: inline-block;
}
.list-group-horizontal .list-group-item {
    margin-bottom: 0;
    margin-left:-4px;
    margin-right: 0;
}
.list-group-horizontal .list-group-item:first-child {
    border-top-right-radius:0;
    border-bottom-left-radius:4px;
}
.list-group-horizontal .list-group-item:last-child {
    border-top-right-radius:4px;
    border-bottom-left-radius:0;
}

.headerDiv {
    float: left;
    padding-top: 10px;
    padding-left: 10px;
    padding-right: 10px;
    margin-bottom: 5px;
    margin-right: 5px;
}

.headerDiv div {
    display:table-cell;
}

.titleDiv {
    position: relative;
    top: 30px;
    width:100%;
}

I have tried putting the two divs inside another, however for some reason this causes my buttons to be vertical, and still beneath the logo.
I'm open to all suggestions, including telling me that I'm going about this completely wrong. Thanks in advance.

A: Bootstrap is easy as long as you understand the fundamental concept and basic structure. It general has a structure of a container with rows and within each row, you could have several cols. With that in mind, it is as easy as this:

Company Name

With minimum styling as:
.headerDiv {
  display:inline;
  float:left;
}
h1#title {
  display:inline;
}
.list-group {
  float: right;
}

You can style the rest of margins and alignment of text as you need.


text:
Q: Extract Lat/Long/Value data from TIF without Rasterio I would like to extract Lat/Long/Value Data from a Tif document. Unfortunately I cannot install Rasterio and only use GDAL for this.  So far I have written the following code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from osgeo import gdal
from numpy import linspace
from numpy import meshgrid
import pandas as pd

Basemap = Basemap(projection='tmerc',
              lat_0=0, lon_0=3,
              llcrnrlon=1.819757266426611,
              llcrnrlat=41.583851612359275,
              urcrnrlon=1.841589961763497,
              urcrnrlat=41.598674173123)

ds = gdal.Open('Tif_file_path')
data = ds.ReadAsArray()
x = linspace(0, Basemap.urcrnrx, data.shape[1])
y = linspace(0, Basemap.urcrnry, data.shape[0])
xx, yy = meshgrid(x, y)
xx, yy = Basemap(xx, yy)
xx, yy = Basemap(xx,yy,inverse=True)

dfl = pd.DataFrame({
    'Latitude': yy.reshape(-1),
    'Longitude': xx.reshape(-1),
    'Altitude': data.reshape(-1)
    })

dfl.to_csv('C:/Users/Oliver Weisser/Desktop/Bachelor/Programm/Daten/Daten/elevation.csv')

my data: https://wetransfer.com/downloads/924bb5b5a9686c042d33a556ae94c9c020220621143611/6c3e64
Is there a good way to extract the data without using Rasterio or creating the data incorrectly?
But now I want to extract the Lat/Long data with the lines:
xx, yy = meshgrid(x, y)
xx, yy = Basemap(xx, yy)
xx, yy = Basemap(xx,yy,inverse=True)
...

However, I get quite strange results (see below) as well as a csv. File with 2.4 GB which I cannot open.
>>> print(xx)
[[1.81975727 1.81975778 1.81975829 ... 1.84184992 1.84185043 1.84185094]
 [1.81975725 1.81975777 1.81975828 ... 1.84184991 1.84185042 1.84185093]
 [1.81975724 1.81975775 1.81975826 ... 1.8418499  1.84185041 1.84185092]

Is there a good way to extract the data without using Rasterio or creating the data incorrectly?

A: if you only need height data and don't want to use tiffs I would recommend using NetCDF data. Like the ones from the site: https://www.ngdc.noaa.gov/mgg/global/relief/ETOPO1/data/bedrock/grid_registered/netcdf/
These NetCDF data are well known and often used in geosciences! You can extract this data according to the example: https://earthscience.stackexchange.com/questions/23904/etopo1-region-selection-in-python/23924#23924
I know this doesn't quite answer your question but the result is the same without having to install rasterio or GDAL.


text:
Q: Error 128 al tratar de instalar un repositorio con npm Descargue el repositorio con el que voy a trabajar y en el package.json quiero instalar un repositorio privado de Gitlab y me muestra el siguiente error:
npm ERR! Error while executing:
npm ERR! C:\Users\Bec\Documents\Bec\Soft\cmder\vendor\git-for-windows\cmd\git.EXE ls-remote -h -t ssh://git@gitlab.com/xxxx/xxxxx.git
npm ERR!
npm ERR! git@gitlab.com: Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR! exited with error code: 128

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Bec\AppData\Roaming\npm-cache\_logs\2019-04-01T20_48_33_984Z-debug.log

Tengo mi clave ssh enlazada con Gitlab y tengo los permisos para ver el repositorio privado.

A: La solución que di a este problema fué ejecutando directamente el agente con el siguiente comando:
start-ssh-agent

Posteriormente instalé el repositorio:
npm i git+http://gitlab.com/[group]/[repo].git


text:
Q: Adobe reader - Javascript error when closing/saving a digitally signed pdf I am trying to save a digitally signed pdf. But when I close the document after clicking on save, I get this error in the javascript console.
NotAllowedError: Security settings prevent access to this property or method.
Doc.URL:2:XFA:FormSchV_Dtls[0]:docClose
Its like the macros are not getting saved. I have to upload this file on the MCA server as I have to file a return, but the server is rejecting it. PLease help me out !!

A: Does the document by chance have a willClose script?
From the error message, it seems that the document is not really a PDF, but an XFA file.
With "regular" PDFs, applying a digital signature (a real one), implies saving the document. You might check whether this happens. Then you will no longer need to save it specifically, but can close it immediately.


text:
Q: DynamoDB: Contains all filter I have a schema with a field called ids (list of numbers)
How can I create a QuerySpec to filter the items that contains all values of a specified list?
For example:
item 1: ids=[1,2,3]
item 2: ids=[1,3,5]

I need to retrieve only item 1 when I filter by [1,2]
I am using:
querySpec.withFilterExpression("contains(ids,:f1) and contains(ids,:f2)")
But I don't know if it is efficient or if there is a more convenient way to do it.

A: The value cannot be SET, MAP or LIST. You have to use AND operator to achieve the result as mentioned in the OP.

CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a"
  can be a list; however, "b" cannot be a set, a map, or a list.


text:
Q: How to perform feature selection (rfecv) in cross validation in sklearn I want to perform recursive feature elimination with cross validation (rfecv) in 10-fold cross validation (i.e. cross_val_predict or cross_validate) in sklearn.
Since rfecv itself has a cross validation part in its name, I am not clear how to do it. My current code is as follows.
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target

from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier(random_state = 0, class_weight="balanced")

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)

rfecv = RFECV(estimator=clf, step=1, cv=k_fold)

Please let me know how I can use the data X and y with rfecv in 10-fold cross validation.
I am happy to provide more details if needed.

A: To perform feature selection with RFE and then fit a rf with 10 fold cross validation, here's how you could do it:
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import confusion_matrix
from sklearn.feature_selection import RFE

rf = RandomForestClassifier(random_state = 0, class_weight="balanced")
rfe = RFE(estimator=rf, step=1)

Now transform the original X by fitting with the RFECV:
X_new = rfe.fit_transform(X, y)

Here are the ranked features (not much of a problem with only 4 of them):
rfe.ranking_
# array([2, 3, 1, 1])

Now split into train and test data and perform a cross validation in conjunction with a grid search using GridSearchCV (they usually go together):
X_train, X_test, y_train, y_test = train_test_split(X_new,y,train_size=0.7)

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)

param_grid = {
                 'n_estimators': [5, 10, 15, 20],
                 'max_depth': [2, 5, 7, 9]
             }

grid_clf = GridSearchCV(rf, param_grid, cv=k_fold.split(X_train, y_train))
grid_clf.fit(X_train, y_train)

y_pred = grid_clf.predict(X_test)

confusion_matrix(y_test, y_pred)

array([[17,  0,  0],
       [ 0, 11,  0],
       [ 0,  3, 14]], dtype=int64)

A: To use recursive feature elimination in conjunction with a pre-defined k_fold, you should use RFE and not RFECV:
from sklearn.feature_selection import RFE
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
clf = RandomForestClassifier(random_state = 0, class_weight="balanced")
selector = RFE(clf, 5, step=1)

cv_acc = []

for train_index, val_index in k_fold.split(X, y):
    selector.fit(X[train_index], y[train_index])
    pred = selector.predict(X[val_index])
    acc = accuracy_score(y[val_index], pred)
    cv_acc.append(acc)

cv_acc
# result:
[1.0,
 0.9333333333333333,
 0.9333333333333333,
 1.0,
 0.9333333333333333,
 0.9333333333333333,
 0.8666666666666667,
 1.0,
 0.8666666666666667,
 0.9333333333333333]


text:
Q: changing default value of ion-checkbox I have created a form which uses ion-checkboxes in angular, which when ticked submits "true" to the database, how do I submit the value of the box to the database, so for example in my list is Junior Groups, so I would like "Junior Groups" to appear in the database and not true. The form also sends an email so the recipient needs to know what the enquiry is interested in.
Code so far is:
html form:
<form [formGroup]="coachingform">
<ion-grid>
<ion-row>
<ion-col>
 <ion-item>
   <ion-label position="start">First Name</ion-label>
   <ion-input type="text" formControlName="firstname"></ion-input>
 </ion-item>
 <ion-item>
   <ion-label position="start">Last Name</ion-label>
   <ion-input type="text" formControlName="surname"></ion-input>
 </ion-item>
 <ion-item>
   <ion-label position="start">Email</ion-label>
   <ion-input type="email" formControlName="email"></ion-input>
 </ion-item>
 <ion-item>
  <ion-label position="start">Contact Number</ion-label>
  <ion-input type="tel" formControlName="telnumber"></ion-input>
</ion-item>
<ion-item>
  <ion-label position="start">What city are you based in?</ion-label>
<ion-input type="text" formControlName="location"></ion-input>
</ion-item>
<ion-list>
  <ion-label>What are you interested in?</ion-label>
  <ion-item *ngFor="let entry of form">
    <ion-label>{{entry.val}}</ion-label>
    <ion-checkbox slot="start" formControlName="interestedin"></ion-checkbox>
  </ion-item>
</ion-list>

then in the .ts file have the list as such:
export class CoachingenquiryPage implements OnInit {
coachingform: FormGroup
public form = [
{ val: 'Junior Groups', isChecked: true },
{ val: 'Adult Groups', isChecked: true },
{ val: 'Individual Lessons', isChecked: true },
{ val: 'Holiday Camps', isChecked: true },
];

any help would be hugely appreciated. many thanks
the updated .ts code is:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, FormGroup, Validators, FormArray }
from '@angular/forms'
import { HttpClient, } from '@angular/common/http';
import {  Router } from '@angular/router';

@Component({
selector: 'app-coachingenquiry',
templateUrl: './coachingenquiry.page.html',
styleUrls: ['./coachingenquiry.page.scss'],
})
export class CoachingenquiryPage implements OnInit {
coachingform: FormGroup
public options= [
{ val: 'Junior Groups', isChecked: true },
{ val: 'Adult Groups', isChecked: true },
{ val: 'Individual Lessons', isChecked: true },
{ val: 'Holiday Camps', isChecked: true },
];

constructor(private http: HttpClient, public fb: FormBuilder, private
router: Router) {
this.coachingform = this.fb.group({
  firstname: [''],
  surname: [''],
  email: [''],
  telnumber: [''],
  location: [''],
  interestedTopics: this.fb.array([]),

})
const control = this.coachingform.get("interestedTopics") as
FormArray;
this.options.forEach(f => {
  const group = this.fb.group({
    interestedin: [f.isChecked]
  });
  control.push(group);
});
}

ngOnInit() {
this.coachingform = new FormGroup({
  firstname: new FormControl(null, {
    updateOn: 'blur',
    validators: [Validators.required]
  }),
  surname: new FormControl(null, {
    updateOn: 'blur',
    validators: [Validators.required]
  }),
  email: new FormControl(null, {
    updateOn: 'blur',
    validators: [Validators.required, Validators.email]
  }),
  telnumber: new FormControl(null, {
    updateOn: 'blur',
    validators: [Validators.required, Validators.pattern('[- +()0-9]
 {11,}')]
  }),
  location: new FormControl(null, {
    updateOn: 'blur',
    validators: [Validators.required]
  }),
  interestedin: new FormControl(null, {
    updateOn: 'blur',
    validators: [Validators.required]
  }),
  })
}
onSubmitForm () {
var formData: any = new FormData();
formData.append("firstname",
this.coachingform.get('firstname').value);
formData.append("surname", this.coachingform.get('surname').value);
formData.append("email", this.coachingform.get('email').value);
formData.append("telnumber",
this.coachingform.get('telnumber').value);
formData.append("location", this.coachingform.get('location').value);
formData.append("interestedin",
this.coachingform.get('interestedin').value);
this.http.post('https://www.parktennis.org/app/services/app-
coachingenquiry.php', formData, {responseType: 'text'}).subscribe(()
=> {
this.coachingform.reset();
this.router.navigate(['/','landing']);
  });

}
}

A: <ion-checkbox slot="start" formControlName="interestedin"></ion-checkbox>

This won't work. Because I think interestedin is just a FormControl of your coachingform FormGroup.
You need to use FormArray for handling arrays.
First, Add an 'FormArray' in your coachingform FormGroup like:
this.coachingform = this.builder.group({
    firstname: [null],
    surname: [null],
    ...
    interestedTopics: this.builder.array([])
});

Then, add new controls into the array for all of your options.
const control = this.coachingform.get("interestedTopics") as FormArray;
control.clear();
this.options.forEach(f => {
    const group = this.builder.group({
    interestedin: [f.isChecked],
    value: [f.val]
});
control.push(group);

Note: For convenience, I've renamed your checkbox options from form to options.
And finally, your ion-list will be:
<ion-list formArrayName="interestedTopics">
    <ion-label>What are you interested in?</ion-label>
    <ion-item *ngFor="let entry of options; let i=index" [formGroupName]="i">
        <ion-label>{{entry.val}}</ion-label>
        <ion-checkbox slot="start" formControlName="interestedin"></ion-checkbox>
     </ion-item>
</ion-list>

Working demo at StackBlitz.
Result:

Edit:
Remove the form related code from your constructor.
Change your ngOnInit() hook as:
ngOnInit() {
    this.coachingform = new FormGroup({
      firstname: new FormControl(null, {
        updateOn: "blur",
        validators: [Validators.required]
      }),
      surname: new FormControl(null, {
        updateOn: "blur",
        validators: [Validators.required]
      }),
      email: new FormControl(null, {
        updateOn: "blur",
        validators: [Validators.required, Validators.email]
      }),
      telnumber: new FormControl(null, {
        updateOn: "blur",
        validators: [Validators.required, Validators.pattern("[- +()0-9]{11,}")]
      }),
      location: new FormControl(null, {
        updateOn: "blur",
        validators: [Validators.required]
      }),
      interestedTopics: this.builder.array([])
    });
    const control = this.coachingform.get("interestedTopics") as FormArray;
    control.clear();
    this.options.forEach(f => {
      const group = this.builder.group({
        interestedin: [f.isChecked]
      });
      control.push(group);
    });
  }

To get selection options:
const controlValue = this.coachingform.get("interestedTopics").value;
const selectedOptions = controlValue
    .filter(f => f.interestedin)
    .map(m => m.value);


text:
Q: How to redirect www to non-www https? I have installed https on my domain. And all this cases are available of my website:
http://example.com        // will be redirected to https://example.com
https://example.com
http://www.example.com    // will be redirected to https://www.example.com
https://www.example.com

See? everything will be using https protocol. All fine.

Now I need to redirect all www to non-www. So http://www.example.com and https://www.example.com should be redirected to https://example.com (in other word, all cases should be redirected to this).
Here is my current code in the /etc/apache2/sites-avalible/000-default.conf:
<VirtualHost *:80>
.
.
.
RewriteEngine on
RewriteCond %{SERVER_NAME} =lamtakam.com [OR]
RewriteCond %{SERVER_NAME} =www.lamtakam.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]               -- this
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]              -- and this are for www redirection
                                                        -- but doesn't work
</VirtualHost>

any idea?
also lamtakam is my exact domain I was talking about, if you need to check something.

Edit:
Currently I have this inside .htaccess file on the root of my project:
RewriteEngine on

Options -Indexes

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# this doesn't work on some version of xampp
# RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]

RewriteRule ^([\s\S]*)$ index.php?rt=$1 [L,B,QSA]

ErrorDocument 404 /error404.html

A: If you want rules in VirtualHost then it would be 2 set of rules. If you can keep rules in site root .htaccess then it would be a single rule. I am providing .htaccess rule here:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

Make sure you remove your existing rules shown in VirtualHost above and you test in a new browser to avoid old browser cache.


text:
Q: Store data as numbers in a file in Python I wrote a program that opens a file and read it line by line and store just the third element of each line. The problem is that, when I write those outputs into a file I need to change them as strings which is not suitable for me due to the fact that I want to do some mathematical operations on the written file later on. FYI, it also is not suitable to store it like this and use int() while reading it.
Can anybody help me with this issue?
with open("/home/test1_to_write", "w") as g:
    with open("/home/test1_to_read", 'r') as f:
        for line in f:
            a=line.split()
            number = int(a[3])
            g.write(str(number)+'\n')

g.close()

A: There's no way to tell a text file that 1 is the number one not the letter "1". If you need that, consider storing the whole thing as a list instead using some sort of serial format e.g. JSON:
import json

with open("/home/test1_to_write.json", 'w') as outfile:
    with open("/home/test1_to_read", 'r') as infile:
        data = [int(line.split()[3]) for line in infile]
        json.dump(data, outfile)

You can then load the data with:
with open("/home/test1_to_write.json", "r") as infile:
    read_data = json.load(infile)


text:
Q: Compare the colnames within two lists of data.frames? I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.
It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.
Input lists
> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7

Desired output
I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.
$A
  b
1 3
$B
  e
1 1
$C
  f
1 6

My attempts
I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?
## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]

A: You can just apply a function to subset a data.frame based on columns in another, and ensure it always return a data.frame using drop = F. And make sure to use SIMPLIFY = F in mapply so it always returns the list structure.
mapply(function(x,y) x[,-which(names(x) %in% names(y)), drop = F], list1, list2, SIMPLIFY = F)
#> $A
#>   b
#> 1 3
#>
#> $B
#>   e
#> 1 1
#>
#> $C
#>   f
#> 1 6

A: You can use lapply to extract the names and setdiff to get those not in the other list. No need that the list are sorted.
x <- lapply(list1, names)
y <- lapply(list2, names)
lapply(setNames(names(x), names(x)), function(i) list1[[i]][setdiff(x[[i]], y[[i]])])
#$A
#  b
#1 3
#
#$B
#  e
#1 1
#
#$C
#  f
#1 6

A: With purrr:
map2(.x = list1,
     .y = list2,
     ~ .x[setdiff(names(.x), names(.y))])

$A
  b
1 3

$B
  e
1 1

$C
  f
1 6


text:
Q: Computing $\lim (^{nk}C_n)^{\frac 1n}$ using series expansion I want to compute $\lim (^{nk}C_n)^{\frac 1n}$ using series expansion, where $k$ is a fixed integer greater than $1$.
This limit can be evaluated easily by recalling that if $x_n\gt 0$ for all $n\in \mathbb N$ then $(\frac{x_{n+1}}{x_n}\to b\in \mathbb R)\implies (|x_n|^{\frac 1n}\to b) $. But I have difficulty computing the limit using series expansion. Let $x_n= ^{nk}C_n$
$^{nk}C_n=\frac{nk (nk-1)(nk-2)...(nk-(n-1))}{n!}\implies x_n^{\frac 1n}=(\frac {n^n}{n!})^{\frac 1n}(\frac kn)^{\frac 1n} \Big((k-\frac1n)(k-\frac 2n)\cdots (k-\frac{n-1}n)\Big)^{\frac 1n}$
Here $(\frac {n^n}{n!})^{\frac 1n}(\frac kn)^{\frac 1n}\to e$.
Let $y_n=\Big((k-\frac1n)(k-\frac 2n)\cdots (k-\frac{n-1}n)\Big)^{\frac 1n}\\ \begin{align}\log y_n&=\frac{(n-1)\log k+\sum_{r=1}^{n-1}\log(1-\frac r{kn})}{n}\\&=
\frac{n-1}{n}\log k-\sum_{r=1}^{n-1}(\frac r{kn^2}+\frac 12\frac{r^2}{k^2n^3})+\sum_{r=1}^{n-1} o(\frac {1}{n^2})\\&\to\log k-(\frac 1{2k}+\frac 1{6k^2})\end{align}$
Therefore, $x_n^{\frac 1n}\to e.e^{\log k-(\frac 1{2k}+\frac 1{6k^2})}=k.e^{1-(\frac 1{2k}+\frac 1{6k^2})}$
But this is wrong. I'm not sure what went wrong above. I think that the step involving little o and steps after that are wrong. Please let me know what I am missing. Thanks.

A: When you expanded the logarithm you got the error term incorrectly. Each term in the expansion will have a non-zero limit as $n→+∞$. So you would need all terms. To get them in one go, you can use Riemann sums:
$$
\frac{1}{n}\sum\limits_{r = 1}^{n - 1} {\log \left( {1 - \frac{r}{{kn}}} \right)}  \to \int_0^1 {\log \left( {1 - \frac{x}{k}} \right)dx}  = (k - 1)\log \left( {1 - \frac{1}{k}} \right) - 1.
$$
This is consistent with Claude's answer.

A: $$A=\binom{k n}{n}^{\frac{1}{n}}=\Bigg[\frac{(k n)!}{n! (k n-n)!} \Bigg]^{\frac{1}{n}}$$
Take the logarithm
$$\log(A)={\frac{1}{n}}\log\Bigg[\frac{(k n)!}{n! (k n-n)!} \Bigg]$$ Use three times Stirling approximation
$$\log(p!)=p (\log (p)-1)+\frac{1}{2} \log (2 \pi  p)+\frac{1}{12 p}-\frac{1}{360
   p^3}+O\left(\frac{1}{p^5}\right)$$ and continue with Taylor expansions for large $n$. You should arrive at
$$n \,\log(A)=n (k \log (k)-(k-1) \log (k-1))+\frac{1}{2} \left(\log \left(\frac{k}{n}\right)-\log
   (2 \pi  (k-1))\right)+O\left(\frac{1}{n}\right)$$
$$\log(A)=k \log (k)-(k-1) \log (k-1)+O\left(\frac{1}{n}\right)$$ Now, use the fact that
$$A=e^{\log(A)}=\frac {k^k }{(k-1)^{k-1} }$$
Trying for $n=100$ and $k=4$, the exact value is
$9.19403$ while the final expression gives $\frac{256}{27}=9.48148$.


text:
Q: ListView entry has to be clicked twice for execution of code I have a ListView inside a navigation bar, and when i click on one of the entries, a WebView opens a specific page. However, the second time i click on some other entry, the code is not executed. I have to click the entry twice to execute the code that OnItemClick performs.
Java:
public class MainScreen extends Activity {
String[] cityArray = { "Agra ", "Ahmedabad ", "Alappuzha ", "Amritsar "};

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main_screen);
      final ListView list = (ListView) findViewById(R.id.ListView1);
      final WebView web = (WebView)findViewById(R.id.webView1);
      final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
      WebSettings webSettings = web.getSettings();
      webSettings.setJavaScriptEnabled(true);
      webSettings.setBuiltInZoomControls(false);
      ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, cityArray);
      list.setAdapter(adapter);

 web.setWebViewClient(new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }
    });
 web.loadData("", "text/html", "utf-8");
list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        if (position == -1)
        {
            web.loadData("", "text/html", "utf-8");
        }
        if (position == 0)
        {
            web.loadUrl("http://forecast.io/embed/#lat=27.18&lon=78.02&name=Agra&units=uk");
        }
        if (position == 1)
        {
            web.loadUrl("http://forecast.io/embed/#lat=23.03&lon=72.58&name=Ahmedabad&units=uk");
        }
    }

});
}
}

What am i doing wrong here?

A: Found the solution. The Url i'm asking the WebView to load is an embed url. It is not updated after tapping a separate ListView.
Solution was to add a web.reload(); or by just loading the Url twice. This purges the displayed data in Webview and it is displayed in one click.


text:
Q: Calculation of time and space complexity I am working on this Leetcode problem - "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Note that 1  does not map to any letters."

This is a recursive solution to the problem that I was able to understand, but I am not able to figure out the time and space complexity of the solution.
if not len(digits):
        return []

    res = []

    my_dict = {
        '2':'abc',
        '3':'def',
        '4':'ghi',
        '5':'jkl',
        '6':'mno',
        '7':'pqrs',
        '8':'tuv',
        '9':'wxyz'
    }

    if len(digits) == 1:
        return list(my_dict[digits[0]])

    my_list = my_dict[digits[0]] #string - abc

    for i in range(len(my_list)): # i = 0,1,2
        for item in self.letterCombinations(digits[1:]):
            print(item)
            res.append(my_list[i] + item)
    return res

Any help or explanation regarding calculating time and space complexity for this solution would be helpful. Thank you.

A: With certain combinatorial problems, the time and space complexity can become dominated by the size of the output. Looking at the loops and function calls, the work being done in the function is one string concatenation and one append for each element of the output. There's also up to 4 repeated recursive calls to self.letterCombinations(digits[1:]): assuming these aren't cached, we need to add in the extra repeated work being done there.
We can write a formula for the number of operations needed to solve the problem when len(digits) == n. If T(n) is the number of steps, and A(n) is the length of the answer array, we get T(n) = 4*T(n-1) + n*A(n) + O(1). We get an extra multiplicative factor of n on A(n) because string concatenation is linear time; an implementation with lists and str.join() would avoid that.
Since A(n) is upper-bounded by 4^n, and T(1) is a constant, this gives T(n) = O(n * (4^n)); the space complexity here is also O(n * (4^n)), given 4^n strings of length n.
One possibly confusing part of complexity analysis is that it's usually a worst-case analysis unless specified otherwise. That's why we use 4 instead of 3 here: if any input could give 4^n results, we use that figure, even though many digit inputs would give closer to 3^n results.