text:
Q: Prove that the union of these measurable sets is less than $\epsilon$ for some large $N$ Suppose $E_k \subset \mathbb{R}$ is measurable for each $k = 1,2,\dots$ and $$m(E_k) < \frac{1}{2^k}$$ Prove that for every $\epsilon > 0$ there exists an $N$ such that $$m(\bigcup_{k = N}^{\infty} E_k) < \epsilon$$
This one I've had a bit of trouble figuring out how to start. Nothing seems to be jumping out to me directly. Any thoughts? Thanks!

A: HINT
$$m\left(\bigcup_{k=N}^\infty E_k\right)\leq \sum_{k=N}^\infty m(E_k)$$

A: Hint: $$\sum_{k=N}^{\infty}\frac1{2^{k}}=\frac1{2^{N-1}}$$

A: The other two comments mention proofs specific to this case, but you can actually prove a much, much more general statement. If $A_n \subseteq \mathbb{R}$ for each $n \in \mathbb{N}$, and $m(A_n) < a_n$ where $a_n \in \mathbb{R}$ and $\left|\sum_{n = 1}^{\infty}a_n\right| < \infty$, then for all $\varepsilon > 0$ you can find an $N$ so that $m\left(\bigcup_{n = N}^{\infty}A_n\right) < \varepsilon$. To prove this, we need a lemma that if $\sum_{n = 1}^{\infty}a_n < \infty$ then there is an $N$ so that $\sum_{n = N}^{\infty}a_n < \varepsilon$. This follows since the sequence of partial sums converges, so it is cauchy; in particular, we can find an $N$ so that if $m \geq N$, then $\sum_{n = N}^{m}a_n < \frac{\varepsilon}{2}$, so then $\sum_{n = N}^{\infty} \leq \frac{\varepsilon}{2} < \varepsilon$
Let $\varepsilon > 0$ be given, and choose $N$ so that $\sum_{n = N}^{\infty}a_n < \varepsilon$. Then, we can use subadditivity; $m\left(\bigcup_{n \geq N}A_n\right) \leq \sum_{n = N}^{\infty}m(A_n) = \sum_{n = N}^{\infty}a_n < \varepsilon$ as desired. Applying this result to this case gives the proof you want (since $\sum_{n = 1}^{\infty}2^{-n} = 1 < \infty$), but also gives you a more general result which is often helpful.


text:
Q: concurrent.futures does not work on ubuntu 18.04 and centosos 7 I created a command line interface to run a simulation written in python (3.8). I added an option to launch several simulations at once using concurrent.futures and specifically ProcessPoolExecutor.This is my first experience with this package and I'm having problems. The code I created works perfectly in windows 10 and ubuntu 20.04 (on wsl2). But fail when I launch it in ssh server (CentosOS 7) and on ubuntu 18.04.
The exception I get is: BrokenProcessPool.
I also noticed one thing, when I launch my code asking for a less heavy workload and therefore taking less time, it goes perfectly. The code fails exclusively with heavy workloads, (e.g. simulations with numerous parameters). This suggests that there is some sort of timeout time. I have already tried using different methods of creating processes: ("fork", "spawn" and "forkserver"), always the same error. The exception is not related to the simulation code, I've already done numerous tests to make sure that's not the case.
Below is a minimal example of my code (I can't paste an entire simulation consisting of 6 different modules so for simplicity the simulation is "do something").
modes.py
from concurrent.futures import ProcessPoolExecutor as Executor
from concurrent.futures import as_completed
import pickle
from model import Simulation

class Mode:
    def __init__(self, num_workers):
        self.num_workers = num_workers
        self.args = [{"key": "arg"} ,
                     {"key1": "arg"}]

    def simulate(self):
        result = Simulation() #do something
        with open("location", "wb") as file:
            pickle.dump(result, file)
        return "Saved"

    def run_p(self):
        with Executor(max_workers=self.num_workers) as executor:
            for out in as_completed([executor.submit(self.simulate, args) for args in self.args]):
                print(out.result())

main.py
from .modes import Mode

def go():
    mode = Mode(num_workers=5)
    mode.run_p()

if __name__ == '__main__':
    go()

My question in a nutshell is: what I need to do for my code to work in both centosOS 7 and windows, using ProcessPoolExecutor? Any suggestions are appreciated! Thank you all for your help.
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

A: The processes are most likely killed by OOM due to low memory on the server:
BrokenProcessPool:

Derived from BrokenExecutor (formerly RuntimeError), this exception
class is raised when one of the workers of a ProcessPoolExecutor has
terminated in a non-clean fashion (for example, if it was killed
from the outside).

You can confirm this by checking the logs and dmesg output.
I would also don't recommend changing the max_workers manually. The default value (os.cpu_count()) is usually good enough and there is no point to set this to a number greater than available CPUs for a CPU bound workload as it will actually slow down the performance due to context switching etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: if with multiple conditions not able to figure it out I am trying to achieve the following using python pandas but not able to figure out why it's not working. I have searched extensively in the web but desired outcome unable to find.
Data is as follows
Data    ADJ_LOW_1   ADJ_LOW_2       MIN     ADJ_HIGH_1     ADJ_HIGH_1   MAX
Data1   34.155      33.81       33.3    36.865     36.865   36.9
Data2   15.444      15.288      15.9    15.756     15.756   17.25
Data3   2.3265      2.303       2.35    2.4745     2.4745   2.6
Data4   21938.4     21716.8     21242   22624      22624    22600
Data5   6.5835      6.517       6.25    6.8175     6.8175   7.45
Data6   196.02      194.04      192.15  218.16     218.16   214.4
Data7   109.395     108.29      107.95  126.654    126.654  113.6
Data8   7.7715      7.693       7.5         8.383      8.383    8.25
Data9   604.89      598.78      572         640.3905   640.3905 648.9
Data10  843.5295    835.009     829         871.327    871.327  924.25

data type is
ADJ_LOW_1     float64
ADJ_LOW_2     float64
MIN           float64
ADJ_HIGH_1    float64
ADJ_HIGH_1    float64
MAX           float64

dtype: object
my objective is to achieve the following outcome:
if ADJ_LOW_1 <= MIN & ADJ_HIGH_1 >= MAX then insert column 'Result' and put value "P1"

elif

if ADJ_LOW_2<= MIN & ADJ_HIGH_1 >= MAX then insert column 'Result' and put value "P2"

elif

if ADJ_LOW_1<= MIN & ADJ_HIGH_2 >= MAX then insert column 'Result' and put value "P3"

esle

  "Blank"
``
x is the data reference
`x.ADJ_LOW_1<=x.MIN & x.ADJ_HIGH_1>=x.MAX: x['R']="P1" elif x.ADJ_LOW_2<=x.MIN & x.ADJ_HIGH_1>=x.MAX: x['R']="P2" elif x.ADJ_LOW_1<=x.MIN & x.ADJ_HIGH_2>=x.MAX: x['R']="P3" else: x['R']=" "`

A: You can use np.select for handling multiple conditions:
conditions = [
    (df['ADJ_LOW_1'] <= df["MIN"]) & (df['ADJ_HIGH_1'] >= df['MAX']),
    (df['ADJ_LOW_2'] <= df["MIN"]) & (df['ADJ_HIGH_1'] >= df['MAX']),
    (df['ADJ_LOW_1'] <= df["MIN"]) & (df['ADJ_HIGH_2'] >= df['MAX'])]

choices = ['P1', 'P2', 'P3']

df['Result'] = np.select(conditions, choices, default='Blank')


text:
Q: Let f(z) be a holomorphic function which takes only pure imaginary values. Show that f is constant. Let f(z) be a holomorphic function which takes only pure imaginary values.
Show that f is constant.
I am a little stuck with this as I have noted that $z=u+iv$ where $u=0$ hence $du/dx=du/dy=0$ so by the Cauchy riemann equations $dv/dx=dv/dy=0$ and hence integration we have v is a constant but I'm lost on how to show that f is constant?
where do we take the function in this?


text:
Q: Simple way to find all paths from top row of a matrix to bottom row Given a matrix A how will you find the number of all possible paths from row 1 to last row provided each '1' can connect with 3 elements adjacent to it in the row below (except for the edge 1's if any, they connect with 2 obviously).
I am looking for ways to implement this without using complex language-specific libraries or functions.
I'm using fortran95 and have tried for hours but still couldn't get all the paths.
A =
 0 1 0 1
 1 1 1 0
 1 0 1 0
 0 1 0 1

A: You can use a slight modification of the floodfill algorithm to solve this problem. Essentially, we are treating the two-dimensional grid as an implicit graph in which each unit square is a vertex, and two vertices are connected provided that one of the vertices is directly above or diagonally above the other vertex. Unfortunately, I am not familiar with Fortran, but here is some C++ code mixed in with some pseudocode that might help you. I will leave the specific implementation details to you.
int count_paths(vector<vector<int>> grid) {
   int sum = 0;
   for (int i = 0; i < number of columns; i++) {
      sum += floodfill(0, i);
   }
   return sum;
}

int floodfill(int row, int column) {
   if (row, column) is out of bounds, return 0.
   if the value in the grid at (row, column) is 0, return 0.
   if we are in the last row, return 1.

   return  floodfill(row + 1, column) + floodfill(row + 1, column + 1) +
           floodfill(row + 1, column - 1)
}

A: The problem with the depth-first search for this problem is that it is O(3ⁿm) in the worst case because it traverses all possible paths. breadth-first search can be more efficient because it always uses roughly 3mn steps to generate all possible arcs of the graph only once, unless the array A is very sparse. Example of both, building on @Ekesh Kumar's pseudocode for the depth-first search:
module functions
   implicit none
   contains
      recursive function depth_first(A,i,j) result(r)
         logical, intent(in) :: A(:,:) ! The map
         integer, intent(in) :: i      ! Row
         integer, intent(in) :: j      ! Column
         integer r                     ! Result variable
         if(j < 1 .OR. j > size(A,2)) then
            r = 0
         else if(.NOT. A(i,j)) then
            r = 0
         else if(i == size(A,1)) then
            r = 1
         else
            r = depth_first(A,i+1,j-1)+depth_first(A,i+1,j)+depth_first(A,i+1,j+1)
         end if
      end function depth_first

      function breadth_first(A)
         logical, intent(in) :: A(:,:) ! The map
         integer breadth_first         ! Result variable
         integer row(size(A,2))        ! Number of path to elements of current row
         integer i                     ! Current row
         row = merge(1,0,A(1,:))
         do i = 2, size(A,1)
            row = merge(eoshift(row,-1)+row+eoshift(row,1),0,A(i,:))
         end do
         breadth_first = sum(row)
      end function breadth_first
end module functions

program paths
   use functions
   implicit none
   integer, parameter :: m = 4 ! Number of rows
   integer, parameter :: n = 4 ! Number of columns
   ! Using a LOGICAL array is more 'Fortranny' :)
   logical :: A(m,n) = reshape([ &
      0, 1, 0, 1, &
      1, 1, 1, 0, &
      1, 0, 1, 0, &
      0, 1, 0, 1], &
      [m,n], order = [2,1]) == 1
   integer j                  ! Current column in first row
   write(*,'(*(g0))') 'Results of depth-first search: paths = ',sum([(depth_first(A,1,j),j=1,n)])
   write(*,'(*(g0))') 'Results of breadth-first search: paths = ',breadth_first(A)
end program paths


text:
Q: Node.js require is not defined I work on a node.js web application and I use javascript server side. I have an error that blocks me every time i use "require" :
var documentClient = require ("documentdb"). DocumentClient;

the error is: require is not defined.


text:
Q: How do I know when a GLSurfaceView is fully initialized from the Activity? I have an Activity that contains several views.  One of which is a GLSurfaceView.  This GLSurfaceView displays pretty 3D effects based on what is selected in my Activity's other views (ListViews, EditTexts, etc).  The issue I am having is that I don't know when my GLSurfaceView has been fully initialized from the Activity.
I began by simply attempting to pass my graphics data to my GLSurfaceView in my Activity's onCreate() method shortly after the setContentView() method.  This worked fine on the emulator but on several devices this fails with null pointer exceptions from attempting to access objects that had not even been constructed yet.  I assumed it was because my view had not been inflated yet and perhaps inflating views just takes longer on my devices.
I scattered some logging just to see the order of things and I found that my GLSurfaceView's onSurfaceCreated method is called well after the GLSurfaceView's onFinishInflate method.
So now I am looking for a good way to determine in my Activity when my GLSurfaceView's onSurfaceCreated method has been called so that I can safely tell my GLSurfaceView what to draw.

A: Subclass GLSurfaceView ("To handle an event you will typically subclass GLSurfaceView and override the appropriate method, just as you would with any other View"). You might also register a SurfaceHolder.Callback with the Surfenter code hereaceHolder -- that works with regular SurfaceViews to know when their surfaces have been created.


text:
Q: Get data from another table in mysql with a variable and display it What I am trying to achieve is where "alarmtype" is, display text that I can retrieve from another table in my database. Currently, it is displaying a variable. Here is my code
<?php
    foreach($db->getEvents() as $event)
    {

        echo "
";
        echo "
";
        echo "
Alarm Number: " . $event->alarmnumber . " Date: " . $event->newdate . "
";
        echo "
" . $event->alarmtype . "
";
        echo "
Location: " . $event->location . "
";
        echo "Modify Alarm";
        echo "
";
        echo "
";
    }
?>

I need to take the alarmtype variable and call another sql where it will pull the text I have store in the database to replace the variable. I hope I explained that well enough.
EDIT
public function getEventByID()
{
    $sql = sprintf("SELECT * FROM alarms T1 INNER JOIN calltype T2 ON T1.alarmtype = T2.id");
    return $this->query($sql)->fetchObject();
}

I added this code to my SQL, it loads fine however does not display the text. I also updated
echo "
" . $event->alarmtype . "
";

to
echo "
" . $event->type . "
";
No luck yet. I ran the sql command and it links both databases together.


text:
Q: Why do my searchkick has_many and HABTM association not work? I recently setup searchkick and it works wonderfully for attributes on the model I have indexed.
However, when it comes to associations, it fails badly.
This is my model with associations & search_data method:
class Profile < ActiveRecord::Base
  searchkick

  has_and_belongs_to_many :positions
  belongs_to :school

  def search_data
    {
      name: name,
      bib_color: bib_color,
      height: height,
      weight: weight,
      player_type: player_type,
      school_name: school.name,
      age: age,
      position_name: positions.map(&:name)
    }
  end
end

I made sure to run Profile.reindex, but when I run a query for Center Back, which is the name of a position, it returns an empty query set when I know there are results.
> Profile.search("center back").to_a
  Profile Search (27.5ms)  curl http://localhost:9200/profiles_development/_search?pretty -d '{"query":{"dis_max":{"queries":[{"match":{"_all":{"query":"center back","boost":10,"operator":"and","analyzer":"searchkick_search"}}},{"match":{"_all":{"query":"center back","boost":10,"operator":"and","analyzer":"searchkick_search2"}}},{"match":{"_all":{"query":"center back","boost":1,"operator":"and","analyzer":"searchkick_search","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}},{"match":{"_all":{"query":"center back","boost":1,"operator":"and","analyzer":"searchkick_search2","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}'
=> []

Yet here are the results otherwise:
> p
=> #<Position:0x007fa881566310 id: 1, created_at: Sun, 04 Sep 2016 06:49:45 UTC +00:00, updated_at: Wed, 14 Sep 2016 06:17:02 UTC +00:00, name: "Center Back">
> p.profiles.count
   (4.1ms)  SELECT COUNT(*) FROM "profiles" INNER JOIN "positions_profiles" ON "profiles"."id" = "positions_profiles"."profile_id" WHERE "positions_profiles"."position_id" = $1  [["position_id", 1]]
=> 5

There should be at least 5 profiles, yet the results return as empty.
I have even tried formatting my search_data like so:
  def search_data
    attrs = attributes.dup
    relational = {
       school_name: school.name,
       grade_name: grades.map(&:subject),
       position_names: positions.map(&:name)
    }
    attrs.merge! relational
  end

The same thing happens if I try a regular has_many association and declare it accordingly.
What could be causing this and how do I fix it?

A: So it turns out that the search_data is actually correct, but I didn't realize I had to run the rails searchkick:reindex:all command, as opposed to just doing Profile.reindex in my rails console that was running.
Once I ran that command, I noticed that it reindexed everything including all the associations and now it works like a charm!


text:
Q: How to handle multiple files in a post petition to recover them and show them in a view? I am trying to upload multiple image files with a form in html in django, but when trigger the button only one file is uploaded, how can I recover several files and show them in my view?
<form enctype="multipart/form-data" method="post">
    {% csrf_token %}

Búsqueda general

        <input type="file" name="document" accept="image/*" multiple="multiple">

        <button type="submit" id="subir">Subir imagenes</button>

 </form>

        {% if uploaded_file_url %}

File uploaded at: {{ uploaded_file_url }}

        {% endif %}

views.py
def cuad(request):
    if request.method == 'POST' and request.FILES.getlist('document', False):
        myfile = request.FILES['document']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        print(request.FILES)
        return render(request, "visores/cuadrantes.html", {
            'uploaded_file_url': uploaded_file_url,
            'filename': filename
        })
    return render(request, "visores/cuadrantes.html")

I get this on console when I print request:
<MultiValueDict: {'document': [<TemporaryUploadedFile: P5140037.JPG
(image/jpeg)>, <TemporaryUploadedFile: P5140038.JPG (image/jpeg)>,
<TemporaryUploadedFile: P5140039.JPG (image/jpeg)>,
<TemporaryUploadedFile: P5140043.JPG (image/jpeg)>]}>

A: You can try something like:
def cuad(request):
    if request.method == 'POST' and request.FILES.getlist('document', False):
        myfiles = request.FILES['document']
        uploaded_documents = {}
        for document in myfiles:
            fs = FileSystemStorage()
            filename = fs.save(document.name, document)
            uploaded_file_url = (fs.url(filename))
            uploaded_documents[filename] = uploaded_file_url

        return render(request, "visores/cuadrantes.html", {
            'uploaded_documents': uploaded_documents,
        })
    return render(request, "visores/cuadrantes.html")

in the template:
{% for document in uploaded_documents %}
    {% for filename, file_url in document.items %}

File uploaded at: {{ file_url }}

    {% endfor %}
{% endfor %}

A: cuadrantes.html
<form enctype="multipart/form-data" method="post">
    {% csrf_token %}

Búsqueda general

        <input type="file" name="document" accept="image/*" multiple="multiple">

        <button type="submit" id="subir">Subir imagenes</button>

</form>
{% for filename, uploaded_file_url in uploaded_documents.items %}

{% endfor %}

views.py
@login_required
def cuad(request):
    uploaded_documents = {}
    if request.method == 'POST' and request.FILES.getlist('document', False):
        myfiles = request.FILES.getlist('document')
        for document in myfiles:
            fs = FileSystemStorage()
            filename = fs.save(document.name, document)
            uploaded_file_url = fs.url(filename)
            uploaded_documents[filename] = uploaded_file_url
    return render(request, "visores/cuadrantes.html", {
        'uploaded_documents': uploaded_documents,
    })


text:
Q: Multilevel modelling in JAGS: Unable to resolve node I am building a multilevel model in JAGS (JAGS version 3.4.0). I want to build varying slope-varying intercept model. I keep receiving an error message and I have no idea what is the problem and how to deal with it. I would very appreciate any help!
You can find the data for the code here: https://www.dropbox.com/s/ibk3nqwc1pm0kpo/Replication_Democratization%20copy.dta?dl=0
Here is the code:
    library(rjags)
    load.module("glm")
    load.module("lecuyer")
    attach(soestData)

    yearDummies = model.matrix(~factor(year))
    X0  <- data.frame(1, "Population" = lag(logpwt_pop2,2), "log GDP" = lag(logGdp,2), "logTrade" = lag(logTrade,2),
              "Civil War" = lag(civilwar,2), "FDI" = lag(wdi_fdi,2), "West Trade" = lag(westTrade,2),
              "Protest" = lag(protest,2), "Oil" = lag(oilmil,2), yearDummies)

    cat('model {
    for (i in 1:n){
       y[i] ~ dnorm (y.hat[i], tau.y)
       y.hat[i] <- inprod(b.0,X.0[i,]) + a[country[i]] + b[country[i]]*x[i]
     }

     tau.y <- pow(sigma.y, -2)
     sigma.y ~ dunif (0, 100)
     for (k in 1:K.0){
       b.0[k] ~ dnorm (0, .0001)
     }
     for (j in 1:J){
       a[j] <- xi.a*B.raw[j,1]
       b[j] <- xi.b*B.raw[j,2]
       B.raw[j,1:2] ~ dmnorm (B.raw.hat[j,], Tau.B.raw[,])
       B.raw.hat[j,1] <- mu.a.raw
       B.raw.hat[j,2] <- mu.b.raw
     }
     mu.a <- xi.a*mu.a.raw
     mu.b <- xi.b*mu.b.raw
     mu.a.raw ~ dnorm (0, .0001)
     mu.b.raw ~ dnorm (0, .0001)
     xi.a ~ dunif (0, 100)
     xi.b ~ dunif (0, 100)
     Tau.B.raw[1:2,1:2] ~ dwish (W[,], df)
     df <- 3
     Sigma.B.raw[1:2,1:2] <- inverse(Tau.B.raw[,])
     sigma.a <- xi.a*sqrt(Sigma.B.raw[1,1])
     sigma.b <- xi.b*sqrt(Sigma.B.raw[2,2])
     rho <- Sigma.B.raw[1,2]/sqrt(Sigma.B.raw[1,1]*Sigma.B.raw[2,2]) }
       ',file={t <- tempfile()})

   W <- diag (2)
   data <- list("y"=delta2ifhpol,
         "x"=lag(dm_sancgoal,2),
         "X.0" = X0,
         "country"=cname,
         "n"=nrow(soestData),
         "J"=length(unique(cname)),
         "K.0" = ncol(X0),
         "W" = W )

        # inits
       random.no <- round(runif(3,0,1000),0)
       inits <- list(
       list(".RNG.name"="lecuyer::RngStream", ".RNG.seed"=random.no[1]),
       list(".RNG.name"="lecuyer::RngStream", ".RNG.seed"=random.no[2]),
       list(".RNG.name"="lecuyer::RngStream", ".RNG.seed"=random.no[3]) )

      parameters.to.save <-c ("b.0", "a", "b", "mu.a", "mu.b", "sigma.y", "sigma.a","sigma.b", "rho")
      jags <- jags.model(t.easy, # temporary file
               data=data.easy,
               inits=inits,
               n.chain=3 )

After I run this code I keep getting this error message
       Error in jags.model(t, data = data, inits = inits, n.chain = 3) :
       RUNTIME ERROR:
       Compilation error on line 3.
       Unable to resolve node y.hat[1]
       This may be due to an undefined ancestor node or a directed cycle in the graph
       In addition: Warning message:
       In jags.model(t, data = data, inits = inits, n.chain = 3) :
         NAs introduced by coercion

I have no idea what it the problem. I specified every parameter and every prior and it didn't work. I deleted all NA's and it didn't work... I have no idea what's wrong.
Any thoughts?


text:
Q: How to relate Cosh and $e$ in some expression? I have the following expression
$$\sqrt\frac{\left(1+e^{k(c_2-c_1)}\right)^2}{e^{k(c_2-c_1)}}$$
Why is it that the expression equals the following:
$$\cosh\left(\frac{k}{2}(c_2-c_1)\right)$$

I know that $\cosh(x)= \cosh(-x)=(e^x+e^{-x})/2$, but I cannot relate this the the first expression.
The first expression, think equals $$e^{-k/2(c_2-c_1)}+e^{k/2(c_2-c_1)}$$

A: The formula's not right as is. But I can still explain the "trick" here.
Given a formula of the form
$$ x + \frac{1}{x} $$
one might instead prefer to collect the terms and write it as
$$ \frac{x^2 + 1}{x} $$
That's basically what's going on here; the formula for the hyperbolic cosine can be rearranged to
$$ \cosh(x) = \frac{e^{2x} + 1}{2 e^x} $$

A: The hyperbolic functions can also be written as
$$ \cosh x=\frac{\mathrm e^{2x}+1}{2\mathrm e^x},\quad\sinh x=\frac{\mathrm e^{2x}-1}{2\mathrm e^x},\quad\tanh x=\frac{\mathrm e^{2x}-1}{\mathrm e^{2x}+1}.$$

A: Let $x = c_2-c_1$ , then:$$ \cosh\left(\frac{k}{2}x\right)=\frac{e^{\frac{k}{2}x}+e^{-\frac{k}{2}x}}{2}=\frac{e^{-\frac{k}{2}x}\left(1+e^{kx}\right)}{2}=\frac{1+e^{kx}}{2e^{\frac{k}{2}x}}=\frac{1}{2}\sqrt\frac{\left(1+e^{kx}\right)^2}{e^{kx}}$$

A: Divide the denominator into each term of the numerator, noting the square.
$$\sqrt\frac{\left(1+e^{k(c_2-c_1)}\right)^2}{e^{k(c_2-c_1)}}=\sqrt{\left(e^{-\frac k2(c_2-c_1)}+e^{\frac k2(c_2-c_1)}\right)^2}\\=e^{-\frac k2(c_2-c_1)}+e^{\frac k2(c_2-c_1)} \\=2\cosh\left(\frac k2(c_2-c_1)\right)$$
The equality is off by the factor $2$

A: set $a=k(c_2-c_1)$ then I obtain as follow


text:
Q: Div Preencher espaço em branco Olá,estou precisando de um help para alinhar div.
Como podem ver na imagem:

A div não ocupa este espaço em branco,porém queria que ela ocupasse este espaço,que nem a div de cima fica do lado de outra.
As tabelas estão destribuidas desta forma:

Agradeço desde já !

A: MANSORY LAYOUT
O que você está querendo criar é um mosaico, conhecido em inglês como Mansory Layout, você pode até se preferir usar a biblioteca Mansory.js.
Considerando o uso de frameworks eu sugeriria o uso do BOOTSTRAP4 ou BULMA, ambos possuem suas grid baseadas em flexbox, inclusive o Bulma possui classes desenvolvidas justamente pra criação de Mansory Layouts... caso seja muito prejudicial a seu projeto modificar tanto a estrutura e tudo mais, você mesmo pode criar seu mansory usando FLEXBOX.
Fiz um JSFIDDLE com um exemplo da solução usando flexbox css.
BOOTSTRAP
Se ainda assim você preferir usar o Bootstrap 3, aconselho fortemente o agrupamento de cada linha de tabelas dentro de uma tag

, é a maneira mais simples de solucionar seu problema, apesar de não ser a solução perfeita.


text:
Q: Celery + gevent using only one CPU core I've issues with performance load running Celery with gevent, everything is running on the same core on my VPS.
Here's a screenshot of 4 Celery instance with 20 gevent concurrency each
How to fix this ? What am I doing wrong ?
Here's my first task :
def update_sender():
    items = models.Item.objects.filter(active=True).all()
    count = items.count()
    items = [i.id for i in items]
    step = count / settings.WORKERS
    for job in list(chunks(items, step)):
        update_item.apply_async(args=[job])

Calling the following sub task:
def update_item(items):
    for item in items:
        try:
            i = models.Item.objects.get(id=item)
            url = "someurl"
            rep = requests.get(url)
            jrep = rep.json()
            tracker = ItemTracker(i, jrep)
            if tracker.skip():
                continue
            if tracker.method1():
                if not tracker.method2():
                    tracker.method3()
                tracker.save()

It's all about doing a lot of HTTP requests and updating database concurrently.

A: Celery with gevent still only uses a single process, its just starting multiple greenlets inside of the process, but it is still only executing one greenlet at a time.  To allow using more than 1 core, you need to start multiple celery processes using something like celery-multi


text:
Q: Is it possible to use GKSU from the Dash (Use administrative level from Dash) I know I can press ALT+F2 and type for example gksu nautilus but I want to be able to use it from Dash. How can I do this?

A: Press Alt + F2 and type alacarte and run.  This is the menu editor and will allow you to make a launcher that not only shows up in the Classic Menu but the Dash as well.  Click on add new item and type in gksu nautilus for the command,select an icon and give it a name like Super Nautilus and click ok.  Now when you click on Dash and start to type nautilus it will show up as one of the Applications

A: Well I don't think that the Dash allows to pass parameters to an app.
The only thing I can think of is to add gksu to the main menu (in dash type 'main menu')  but it will not accept any option so you will have to enter the name of the app when gksu opens.
At least, that is the default Dash behavior.


text:
Q: JAWs screen reader reading older version of button text with changing Angular string interpolation I have a button with text that changes occasionally through Angular's string interpolation. It renders to the screen fine, but when I tab over it with JAWs it often reads out the older version of the text (whatever it said before it changed last)
eg. <button (click)="addUser()" mat-flat-button color="primary"> Add {{ this.users.length }} {{ this.type === 'test' ? 'first type' : 'second type' }}</button>
Has anyone else experienced this?

A: I may have figured it out, though it is not the answer I want.
I added an [attr.aria-label] to the button with the exact same text I wanted in the button, and it seemed to work. So I have a fix, but I still have no idea why that was happening.
eg <button [attr.aria-label]="myText">{{ myText }}


text:
Q: libvirt / kvm guests take very long time to start after host reboot Host system is CentOS 6.5 x86_64.  I have setup an Ubuntu guest by following this wiki.  The guest works, but: if I reboot the host, it takes a very long time (about 30 minutes on the last reboot) before the guests actually start.  If, during this time, I start virsh and do a "list", it just hangs.
Here's a snippet from /var/log/libvirt/libvirt.log:
2014-10-14 16:47:11.509+0000: 4668: info : virDomainLoadAllConfigs:14696 : Scanning for configs in /var/run/libvirt/qemu
2014-10-14 16:47:11.527+0000: 4668: info : virDomainLoadAllConfigs:14696 : Scanning for configs in /etc/libvirt/qemu
2014-10-14 16:47:11.527+0000: 4668: info : virDomainLoadAllConfigs:14718 : Loading config file 'mythbuntu.xml'
2014-10-14 16:47:11.529+0000: 4668: info : qemuDomainSnapshotLoad:484 : Scanning for snapshots for domain mythbuntu in /var/lib/libvirt/qemu/snapshot/mythbuntu
2014-10-14 17:14:41.751+0000: 4668: info : virNetDevProbeVnetHdr:94 : Enabling IFF_VNET_HDR
2014-10-14 17:14:41.805+0000: 4668: info : virSecurityDACSetOwnership:296 : Setting DAC user and group on '/home/kvm/mythbuntu.img' to '107:107'
2014-10-14 17:14:41.806+0000: 4668: info : virSecurityDACSetOwnership:296 : Setting DAC user and group on '/mnt/mythtv1/mythbackend_recordings' to '107:107'
2014-10-14 17:14:42.084+0000: 4668: info : lxcSecurityInit:1380 : lxcSecurityInit (null)

Notice that huge jump in time, from 16:47:11 to 17:14:41?  The latter time is when the guest actually started, and at this point, "virsh list" was once again usable.
It seems like libvirt/kvm/qemu is getting hung up on something, but eventually is able to proceed.  Anyone have any idea what it might be hung up on?
Edit: I am not using snapshots.  And in fact:
# ls /var/lib/libvirt/qemu/snapshot/mythbuntu
ls: cannot access /var/lib/libvirt/qemu/snapshot/mythbuntu: No such file or directory

The parent looks like this:
# ls -R /var/lib/libvirt/qemu/
/var/lib/libvirt/qemu/:
dump  mythbuntu.monitor  save  snapshot

/var/lib/libvirt/qemu/dump:

/var/lib/libvirt/qemu/save:

/var/lib/libvirt/qemu/snapshot:


text:
Q: MongoDB CL: How can I escape "(" in regex literals? Problem
Using the mongo command-line tool, I want to fetch documents containing " (" in a string field using a regex literal, like this:
{writers: / \(/}

However this fails in the mongo command line tool (v4.4.0), presumably because it's looking for a closing parentheses ) despite ( being escaped:

What I've tried
Double escaping / \\(/ also does not work:

Workarounds

*

*The expression works fine in Compass:

*I can express ( using its octal escape sequence {writers: / \50/}:

*I can use {regex...} with a string literal:

Version
I'm using mongo 4.2.9 and 4.4.0:

Is there a way to match "(" characters in regex literals without resorting such workarounds?
/.../ is a much cleaner syntax.

A: In the mongo shell, unfortunately I don't think there's a cleaner way other than doing \\(. This is the limitation of the mongo shell itself.
However, it is possible to use the new mongosh (currently beta) to do what you want:
❯ mongosh
Current sessionID:  71d48f548f666555d896a975
Connecting to:      mongodb://127.0.0.1:27017
Using MongoDB: 4.4.0
Using Mongosh Beta: 0.0.5

For more information about mongosh, please see the wiki: github.com/mongodb-js/mongosh/wiki

> db.test.find({val: /\(/})
[ { _id: 5f5886ab588163bae7b4e1b5, val: '()' } ]

Note that the backslash escape is still required, since the bracket is part of PCRE syntax.


text:
Q: How to run an SP having custom-type variables on definiton via SSIS using Execute SQL Task I have a Stored Procedure in SQL Server starting like below:
CREATE PROCEDURE [dbo].[spReporting]
   @DateCreated_Start datetime,
   @DateCreated_Finish datetime,
   @DeadlineDate datetime = NULL,
   @Duration [NumericTableType] READONLY,
   @ValueCheck [StringTableType] READONLY
AS
BEGIN
....
END

As to be seen, there are two custom types a variable can have, NumericTableType and StringTableType.
What I want to do is to execute the stored procedure in SSIS using an "Execute SQL Task" in Control Flow. The execute command (SQL Statement) I use is: exec spReporting ?,?,?,?,? However, I don't know how I should give the parameters since the custom parameters are not defined in "Parameter Mapping" section.
I tried changing the SQL Statement like: exec [dbo].[spReporting_AP] ?,?,null,null,null, but didn't help. I don't want to use a script task for this, unless I have to. Any advice/help would be appreciated.Thanks.

A: Are the two custom types both table types?  If so, you can use a global temp table that's loaded in a preceding task in the package to populate a variable of the same type, and then execute the stored procedure with this variable.  In order to have the global temp table accessible to other components in the package, the TransactionOption must be set to Required on the package, and either Supported or Required on the objects involved.  If you want to isolate this work to a particular part of the package, place all the components involved in the same Sequence Container and apply the same TransactionOption settings there.  You won't need to use parameters to do this, and the following example illustrates executing the stored procure after populating a variable of the same type.
DECLARE @TableParameter AS YourTableType

INSERT INTO @TableParameter (Column1, Column2)
SELECT Column1, Column1 FROM ##TempTable

EXEC dbo.testsp @TableParameter

A: Some approaches to implement:

*

*Initialize Custom type variables inside SQL statement. This is done by storing data for custom type variables in some SQL tables before executing SP. Then create an Execute SQL task which:

*

*Create variables of Custom type

*Fill in the variables with SELECT INTO statements

*Executes the SP

Passing parameters like DateCreated_Start could be done with technique of String Variable dynamic evaluation with expression.

*Script Task calling SP with all parameters etc.


text:
Q: Cannot read property 'emailAddressValidation' of undefined I'm just learning node with MVC pattern.I made one Validation class to validate user data.
class UserValidation {
  constructor() {}

  emailAddressValidation(email) {
    console.log(email);
    const regularExpression =
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return regularExpression.test(email.toLowerCase());
  }

  passwordValidation(password) {
    const regularExpression =
      /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
  }

  loginValidation(req, res, next) {
    const { email, password } = req.body;
    console.log(email);
    this.emailAddressValidation('addad');
    // try {
    //   if (
    //     this.emailAddressValidation(email) &&
    //     this.passwordValidation(password)
    //   ) {
    //     next();
    //   } else {
    //     throw new Error(
    //       'All fields are Required.email,password.Password should be alpha numeric.'
    //     );
    //   }
    // } catch (error) {
    //   res.status(400).json({ err: 1, message: error.message });
    // }
  }

  NewUserValidation(req, res, next) {
    const { name, email, password, address, skills } = req.body;

    try {
      if (
        name &&
        this.emailAddressValidation(email) &&
        this.passwordValidation(password) &&
        address.length > 0 &&
        skills.length > 0
      ) {
        next();
      } else {
        throw new Error(
          'All fields are required.Name,email,password,Address,Skills.Password should be alphanumeric.'
        );
      }
    } catch (error) {
      res.status(400).json({ err: 1, message: error.message });
    }
  }
}

export default new UserValidation();

Something like this and using it in my route like this
router.post('/login', UserValidation.loginValidation);

But I don't know why I got this error

TypeError: Cannot read property 'emailAddressValidation' of undefined

A: this will refer to an instance of that class. You will have to initialize an object of UserValidation and call loginValidation on that object. Something like this:
const validator = UserValidation()
router.post('/login', validator.loginValidation);


text:
Q: How can I tell if Comcast is blocking access to an IP? I have a site hosted on CentOS 7, part of an A2 Hosting environment.  Although I can access my site (http://68.66.205.103/) on my phone and an AT&T ISP, I can't access it from a Comcast ISP or my RCN ISP (which uses Comcast's network).  Here's my traceroute
localhost:tmp davea$ traceroute 68.66.205.103
traceroute to 68.66.205.103 (68.66.205.103), 64 hops max, 52 byte packets
 1  192.168.1.1 (192.168.1.1)  15.293 ms  6.332 ms  1.234 ms
 2  bdl1.lem-cbr2.chi-lem.il.cable.rcn.net (10.48.40.1)  9.922 ms  17.757 ms  12.261 ms
 3  216.80.78.71 (216.80.78.71)  10.832 ms  10.550 ms  11.397 ms
 4  bdle2.border1.eqnx.il.rcn.net (207.172.15.196)  13.622 ms  23.229 ms
    bdle3.border1.eqnx.il.rcn.net (207.172.15.212)  11.654 ms
 5  * * *
 6  * * *
 7  * * *
 8  * * *
 9  * * *
10  * * *
11  * * *

What's interesting though, is that on my same machine on a Comcast ISP, I can access the site on a TOR Browser, so I don't know if that means the ISP is blocking the remote IP address or there is something else going on.  Any advice is appreciated, -

A: Is really Comcast blocking your IP of their own accord? Well, the answer is....complicated.
It is not exactly a decision of Comcast per se.
The IP address of the server you have now has been reported as being part of a BOTNET.
Many organisations all over the world, and even organisations using firewall vendors (namely recent CheckPoint technology) might be blocking full access or certain types of access as a server to that IP address while the server is in malware blacklists (i.e. clients on that networks won't open it).
Comcast is also (in)famous for intercepting at least HTTP requests with  (transparent) proxies.
What we can know for sure Comcast is consuming/using one or more blacklists  applied to some technology they use to filter out accesses to certain services. They won't probably be the only organisation doing that.
As an example of statics/reports of your IP address in a backlist see (while it is active) http://vxcube.com/tools/ip/68.66.205.103/threat
and also the malware they report they saw activity from your IP address:
MMD-0052-2016 - Overview of "SkidDDoS" ELF++ IRC Botnet
Also in http://vxcube.com/tools/ip/68.66.205.103/graph , selecting the option to see URLs scanned/accessed by your host:
http://68.66.205.103/bins.sh
http://80.211.225.35/'
http://80.211.225.35/apache2
http://80.211.225.35/banana124.sh
http://80.211.225.35/bash
http://80.211.225.35/cron
http://80.211.225.35/ftp
http://80.211.225.35/ntpd
http://80.211.225.35/openssh
http://80.211.225.35/pftp

Also inserting your IP address in Shodan, it alerted me you are exposing to the Internet dangerous services.
You should not have at least rpcbind exposed to the Internet; it should be firewalled.
$ nmap -sT 68.66.205.103

Starting Nmap 7.60 ( https://nmap.org ) at 2018-02-25 18:14 WET
Nmap scan report for 68.66.205.103.static.a2webhosting.com (68.66.205.103)
Host is up (0.14s latency).
Not shown: 998 closed ports
PORT    STATE SERVICE
80/tcp  open  http
111/tcp open  rpcbind

(Unfortunately, my own ISP prevents me from doing a reliable UDP port scanning operation)
It goes without saying that server should be reinstalled, and the security policy should be reevaluated.
P.S. I changed the question tag for malware.

A: Running a traceroute won't give you a deterministic answer. To check whether a port is blocked you need to connect to it directly. You can use tcptraceroute or hping to attempt to reach your :.
# tcptraceroute www.google.com 443
Running:
    traceroute -T -O info -p 443 www.google.com
traceroute to www.google.com (216.58.198.164), 30 hops max, 60 byte packets
...
9  108.170.232.97 (108.170.232.97)  10.305 ms  10.775 ms 108.170.232.99 (108.170.232.99)  10.724 ms
10  lhr25s10-in-f164.1e100.net (216.58.198.164) <syn,ack>  9.316 ms  9.444 ms  11.003 ms

Or using HPING3:
# hping3 -V -S -p 443 www.google.co.uk
using wlp3s0, addr: <ipaddr>, MTU: 1500
HPING www.google.co.uk (wlp3s0 172.217.23.3): S set, 40 headers + 0 data bytes
len=46 ip=172.217.23.3 ttl=57 id=54832 sport=443 flags=SA seq=0 win=42780 rtt=31.8 ms
...

The fact that you can access your service over one other ISP and TOR does make it possible that Comcast is indeed blocking access to port 80. A simple test to validate malware based filtering is changing the port into a non-standard value (like 5580 or 9980) and trying again.


text:
Q: Nesting stack navigation inside a drawer navigation I am trying to nest a stack navigation inside a drawer navigation on snack expo. I asked this question before and was told to do it all over again. I did and I still get different errors. I would really appreciated if someone could explain what am I doing wrong? I can also post the link to my project if this helps https://snack.expo.io/@andreeam/it-in-the-valley
Thank you
Errors below:
Device: (3:9741) (0,l.useLinkBuilder) is not a function. (In '(0,l.useLinkBuilder)()', '(0,l.useLinkBuilder)' is undefined)

And I also get
Device: (104:51757) r.render is not a function. (In 'r.render()', 'r.render' is undefined)

Cannot assign to read only property 'exports' of object '#<Object>'
  Evaluating module://react-native-screens.js
  Evaluating module://@react-navigation/drawer.js
  Evaluating module://App.js.js
  Loading module://App.js

Here is my app.js
import * as React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';

import SignIn from './components/SignIn';
import ForgotPassword from './components/ForgotPassword';
import Dashboard from './components/Dashboard';
import Advertisers from './components/Advertisers';
import Adverts from './components/Adverts';
import Stats from './components/Stats';
import Plans from './components/Plans';
import ManageAdverts from './components/manageadvert';

const Stack = createStackNavigator();

class MyStack extends React.Component {
  render() {
    return (
    <Stack.Navigator
      initialRouteName="SignIn"
      screenOptions={{
        headerTitleAlign: 'center',
        headerStyle: { backgroundColor: '#2d3436'},
        headerTintColor: '#fff',
        headerTitleStyle: { fontWeight: 'bold'}
      }}>

      <Stack.Screen
        name="Reset your password"
        component={ForgotPassword}
        options={
          {title: 'Reset your password'},
          {headerLeft: null}
        }
        />

      <Stack.Screen
        name="SignIn"
        component={SignIn}
        options = {
          {headerShown: false,
          title: 'SignOut'}
        }
      />
      <Stack.Screen
       name="Dashboard"
       component={Dashboard}
      />

      <Stack.Screen
        name="Advertisers"
        component={Advertisers}
        options={
          {title: 'Advertisers'}
        }
      />

      <Stack.Screen
        name="Adverts"
        component={Adverts}
        options={
          {title: 'Adverts'}
        }
      />
      <Stack.Screen
        name="Stats"
        component={Stats}
        options={
          {title: 'Stats'}
        }
      />
      <Stack.Screen
        name="Plans"
        component={Plans}
        options={
          {title: 'Plans'}
        }
      />

      <Stack.Screen
        name="Manage Adverts"
        component={ManageAdverts}
        options={
          {title: 'Manage Adverts'}
        }
      />
    </Stack.Navigator>
  );
}}

export default class App extends React.Component {
  render() {
  return (
    <NavigationContainer>
      <MyStack />
    </NavigationContainer>
);
}
}

A: I got this error when I upgraded expo to version 37. I was able to resolve this issue by updating the relevant reactmodules to the latest version.


text:
Q: Is it possible to create "parameter decorators" (like TypeScript) in Python? TypeScript has a feature known as parameter decorators — literally a decorator that you can apply to a parameter of a function or method:
class BugReport {
  // ...
  print(@required verbose: boolean) {
    // ...
  }
}

Another example from NestJS:
class SomeController {
  // ...
  async findOne(@User() user: UserEntity) {
    // ...
  }
}

Note in the above examples that the decorators are decorating parameters of each method, not the methods themselves.
I don't think that parameter decorators like this exist in Python (at least as of v3.11, nor could I find any open PEPs that cover it); however, I'm curious to know if there is a way to implement something like this in Python?
It doesn't have to have the exact same syntax, of course; just the same effect.
I'm not super familiar with how parameter decorators work under-the-hood, but my best understanding is that they attach metadata to the corresponding function or method at compile time (so they would likely need to work in tandem with a function/method decorator, metaclass, etc.).

A: Python doesn't have parameter decorators – only function decorators – but it does provide runtime access to type annotations, as well as typing.Annotated.
from typing import Annotated

class BugReport:

    @validate_required
    def print(self, verbose: Annotated[bool, Required]) -> None:
        ...

import functools
import inspect
import typing

class Required:
    pass

Required = Required()

def validate_required(fn):
    required = {
        name
        for name, t in inspect.get_annotations(fn).items()
        if typing.get_origin(t) is typing.Annotated
        and Required in typing.get_args(t)[1:]
    }
    signature = inspect.signature(fn)

    @functools.wraps(fn)
    def validated(*args, **kwargs):
        bound_args = signature.bind(*args, **kwargs)

        for required_arg in required:
            if bound_args.arguments[required_arg] is None:
                raise ValueError(f"required argument is None: {required_arg!r}")

        return fn(*args, **kwargs)

    return validated

To do this particular kind of thing in practice, you might want to extend Typeguard instead, although I honestly wouldn't recommend it; it's too fragile and slow.

A: The closest approach I can think of would be to use a function/method decorator that takes the parameter name as one of its parameters.
A trivial example might look like this:
Note: this is technically not the same as TypeScript parameter decorators because it changes the runtime behaviour of the method rather than just attaching metadata; I will revisit this when I have more time to see if I can come up with a better implementation
class UserEntity:
    pass

def UserParam(name: str):
    def decorator(fn):
        def decorated(*args, **kwargs):
            # Inject the UserEntity into the function params.
            return fn(*args, **kwargs, **{name: UserEntity()})
        return decorated
    return decorator

class SomeController:
    @UserParam('user')
    def findOne(self, user: UserEntity):
        print(repr(user))

SomeController().findOne()

A more realistic example would likely need to work in tandem with another decorator or metaclass, however.


text:
Q: Three-way Referential Integrity - SQL Server 2008 I am building a database using SQL Server 2008 to store prices of securities that are traded on multiple markets.
For a given market, all the securities have the same holiday calendar. However, the holiday calendars are different from market to market.
I want the following four tables: Market, GoodBusinessDay, Security, and SecurityPriceHistory, and I want to enforce that SecurityPriceHistory does not have rows for business days when the market on which a security was traded was closed.
The fields in the tables are as follows:

Market: MarketID (PK), MarketName
GoodBusinessDay: MarketID (FK),
  SettlementDate (the pair is the PK)
Security: SecurityID (PK), MarketID
  (FK), SecurityName
SecurityPriceHistory: This is the
  question - my preference is
  SecurityID, SettlementDate,
  SecurityPrice

How can I define the tables this way and guarantee that for every row in SecurityPriceHistory, there is a corresponding row in GoodBusinessDay?
If I added a column for MarketID to SecurityPriceHistory. I could see how I could do this with two foreign keys (one pointing back to Security and one pointing to GoodBusinessDay), but that doesn't seem like the right way to do it.

A: This model should do. The relationship between Market and BusinessDay is identifying, that is, a businessday does not exist outside the context of the market to which it belongs.
Similarly, the relationship between BusinessDay and SecurityPriceHistory is identifying, as it the relationship between Security and SecurityPriceHistory.
This means that the primary key of SecurityPriceHistory is composite: security_id,market_id and settlement_date.

This will enforce the constraint that each security may be have no more than one row in SecurityPriceHistory for a given market/business day. It does, however, allow for the same security to trade in multiple markets, despite the security's relationship to a particular market: to restrict that, the relationship between Market and Security needs to be identifying, thus:

A: SecurityPriceHistory could have a FK to GoodBusinessDay and NO FK to Market. You could figure out the market by joining to the GoodBusinessDay table. I don't really like this option, but it's a possibility.
You could also use a trigger to check and make sure that there's a proper GoodBusinessDay record on insert/update, otherwise reject the transaction.

A: I think you're going to need the marketID field in your securityPriceHistory table, assuming the same securityID could be sold in different markets on the same goodBusinessDay.
Setting it up the way you're thinking is fine.  You have a parent, two related children, then a grandchild that has relationships with both children.

Even if a security can only be sold on one market, I'd still include the marketID in the securityPriceHistory table, with two compound FKs, MarketDay and MarketSecurity.  Clearer that way, IMO.


text:
Q: Sencha Touch/Modern Hide Address Bar and/or Bottom Bar In Sencha Touch/ExtJs 6 Modern is there a way to hide the address bar and bottom bar on mobile devices. I have tried this which was suggested and it doesn't work.
Ext.application({

    viewport: {
      autoMaximize: true
    },

    ...
});


text:
Q: Match document if it contains multiple nested documents in elasticsearch I have a document that contains arrays of nested documents. I have a requirement to return matches if the document contains all of the specified nested documents.
here is the relevant part of the mapping:
"element": {
  "dynamic": "false",
  "properties": {
    "tenantId": {
      "type": "string",
      "index": "not_analyzed"
    },
    "fqn": {
      "type": "string",
      "index": "not_analyzed"
    },
    "id": {
      "type": "string",
      "index": "not_analyzed"
    },
    "name": {
      "type": "string",
      "index": "not_analyzed"
    },
    "type": {
      "type": "string",
      "index": "not_analyzed"
    },
    "location": {
      "type": "string",
      "index": "not_analyzed"
    },
    "tags": {
      "type": "nested",
      "properties": {
        "id": {
          "type": "string",
          "index": "not_analyzed"
        },
        "dataSourceId": {
          "type": "long",
          "index": "not_analyzed"
        },
        "name": {
          "type": "string",
          "index": "not_analyzed"
        },
        "value": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}

The goal is to be able to return elements that contain all of a list of tags (although the element is permitted to contain additional tags beyond the search requirement).
Here is what I have so far:
{
   "query": {
     "bool": {
       "filter": {
          "nested": {
             "path": "tags",
             "query": {
                "bool": {
                   "must": [
                      {
                        "bool": {
                          "must":{
                             "term": { "tags.name": "name1" },
                             "term": { "tags.value": "value1" }
                          }
                        }
                      },
                      {
                        "bool": {
                          "must":{
                             "term": { "tags.name": "name2" },
                             "term": { "tags.value": "value2" }
                          }
                        }
                      }
                   ]
                }
             }
          }
       }
    }
  }
}

The problem with this approach is that it returns 0 hits with multiple tag values (it works fine for a single value). I believe that this is because the query is requiring that a tag have multiple names and values in order to match, which obviously can't happen. Does anyone know how to query for elements that contain all of a list of tags?
edit: this is using elasticsearch 5.0

A: We figured it out. The answer was to create two nested queries, instead of having two clauses to the same nested query.
{
 "query":{
   "bool":{
     "must":[{
        "nested":{
           "path":"tags",
           "query":{
              "bool":{
                 "must":[
                    {"term":{"tags.name":"name1"}},
                    {"term":{"tags.value":"value1"}}
                 ]
              }
           }
        }
     },
     {
        "nested":{
           "path":"tags",
           "query":{
              "bool":{
                 "must":[
                    {"term":{"tags.name":"name2"}},
                    {"term":{"tags.value":"value2"}}
                 ]
              }
           }
        }
     }]
   }
 }
}


text:
Q: Prevent blank screen (locking) in gnome-shell while watching videos When my computer (running ubuntu 17.10) is idle for 5 minutes it goes blank and lock the screen. This is perfect, but while watching a video with flash, mpv, ... I would expect the power saving feature to turn off, or better, the video player to tell gnome-shell that there's activity. It's better cause this way it the video player crash, the screen blanking/locking did not change.
In MPV there's an heartbeet-cmd to tell the computer it's active, this seams perfect, but is there a command to tell gnome-shell that there is activity, preventing it from power saving?


text:
Q: prove $\sin{x}+\sin{2x}+\sin{3x}=3$ does not hold for any real $x$? How do we prove that the equality
$$
\sin{x}+\sin{2x}+\sin{3x}=3
$$
does not hold for any real value of $x$ only using trigonometry ?

A: That would only be possible if all of $\sin x$, $\sin 2x$ and $\sin 3x$
equalled $1$. But $\sin x=1$ implies $\sin 2x=0$.
A good follow-up: find the maximum of $\sin x+\sin 2x+\sin3x$
for real $x$.

A: $\sin(x)=1$ implies that $x=\pi/2+2\pi k$, this implies that $\sin(2x)=0$, so it is not true. Since you must have $\sin(x)=\sin(2x)=\sin(3x)=1$ since $\sin(x)\in [-1,1]$.


text:
Q: Как определить тип переменной переданной в аргумент функции У меня есть шаблонная функция которая считает длинну строки. Но проблема в том что иногда я передаю в неё например строку типа char а иногда wchar_t и в этом проблема. Можно-ли прописать какое-то условие что-бы определять какого типа была передана переменная str и в зависимости от условия выполнять код. Что-то вроде
template<typename Type>
func(const Type* str)
{
    if(const Type* == wchar_t) {
        return lstrlen(str);
    }
    else if(const Type* == char){
        return lstrlenA(str);
    }

}


text:
Q: Resume App from BroadcastReceiver Is there a way to Resume an app from a BroadcastReceiver? (in the way that the Launcher Resumes or Starts an app)
I want to do this when the device is plugged in (don't worry, this isn't going in the Play store)
It seems like you must use FLAG_ACTIVITY_NEW_TASK or else you receive a RuntimeException for "Calling startActivity() from outside of an Activity context"

public class PowerReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("android.intent.action.ACTION_POWER_CONNECTED")) {

            final Intent newIntent = new Intent(context, FooActivity.class);
            //newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(newIntent);
        }
    }
}


text:
Q: Move row to different sheets based on value in 1 cell, but can't get it to take new row each time I have been trying out something, by looking at other code ecample and stuff like that.
But I have some problems.
In my data input sheet, i have a dropdown menu with possible Names. But from what I have made now in the code, it just delete that. It does not copy the data over in other sheet and then just blank it out in data sheet, so every time I would have to make the dropdown list again.
Also when it move it over, it first move it to row 2, then to row 4. So jump over row 3, but then after that it just go to row 4 again and overwrite what is in row 4.
I think I need some kind of variables here for each sheet, but Im not strong in VBA, so not sure how to do it.
Here is the code that I have.
Sub CommandButton1_Click()
Dim TargetCounters(3) As Integer
Dim TargetNames(3) As String
TargetNames(0) = "Co"
TargetNames(1) = "Od"
TargetNames(2) = "Th"
TargetNames(3) = "Ca"

Dim i As Integer
Dim shSource As Worksheet

Dim shTargets(3) As Worksheet

Set shSource = ThisWorkbook.Sheets("Data input")

For i = 0 To 3
Set shTargets(i) = ThisWorkbook.Sheets(TargetNames(i))
If shTargets(i).Cells(2, 1).Value = "" Then
    TargetCounters(i) = 2
Else
    TargetCounters(i) = shTargets(i).Cells(2, 1).CurrentRegion.Rows.Count + 2
End If
Next i

i = 2
Dim MatchIndex As Integer

Do Until shSource.Cells(i, 1).Value = ""

        Select Case shSource.Cells(i, 1).Value
        Case "Co":
            MatchIndex = 0
        Case "Od":
            MatchIndex = 1
        Case "Th":
            MatchIndex = 2
        Case "Ca":
            MatchIndex = 3
        Case Else
            MatchIndex = -1
        End Select
        If (MatchIndex = -1) Then
            i = i + 1
        Else
            shSource.Rows(i).Copy
            shTargets(MatchIndex).Cells(TargetCounters(MatchIndex), 1).PasteSpecial Paste:=xlPasteValues
            shSource.Rows(i).Delete
            TargetCounters(MatchIndex) = TargetCounters(MatchIndex) + 1
        End If
    Loop
End Sub

Here is a link to the excel I made. Right now I only made it to move to 4 sheets, but when working I will be able to add the rest.
https://www.dropbox.com/s/vvjt8z82xiuw9y1/Movedata.xlsm?dl=0
In short my problems is
It delete my dropdown list and it does not insert in a new free row everytime.
EDIT:
Have found out about the delete part now. Found there was function ClearContents instead of Delete.


text:
Q: Ajax div can't access address bar variable Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge

Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;

But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
    var everyone = document.getElementById('everyone'),
        searching = document.getElementById('searching'),
        searchingSubmit = document.getElementById('searchingSubmit');

    everyone.onclick = function() {
        loadXMLDoc('indexEveryone');
        everyone.className = 'filterOptionActive';
        searching.className = 'filterOption';
    }

    searching.onclick = function() {
        loadXMLDoc('indexSearching');
        searching.className = 'filterOptionActive';
        everyone.className = 'filterOption';
    }

     searchingSubmit.onclick = function() {
        loadXMLDoc('indexSearchingSubmit');
    }

    function loadXMLDoc(pageName)
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
            }
          }

        function get_query(){
          var url = location.href;
          var qs = url.substring(url.indexOf('?') + 1).split('&');
          for(var i = 0, result = {}; i < qs.length; i++){
            qs[i] = qs[i].split('=');
            result[qs[i][0]] = decodeURIComponent(qs[i][1]);
          }
          return result;
        }

        xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
        xmlhttp.send();
        }
}
</script>
<!-- ends ajax script -->

A: If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.


text:
Q: How to tokenize this? I am trying to hand code a tokenizer. I keep on reading the characters which can be part of a token. For example an integer can only contain digits. So in the below text I keep on reading the characters until I find a non-digit character. So I get 123 as the token. Next I get ( as the token, and then abc as identifier. This is fine as ( is a delimiter.
123(abc

However, in the below text I get 123 as integer and then abc as identifier. But actually this in not valid since there is no delimiter between them.
123abc(

Should the tokenizer check for delimiters and report an error? If yes what tokens should be returned and where should the tokenizer continue reading from after an invalid token is found?
Or should the tokenizer simply return 123 as integer and abc as identifier and let the parser detect the errors?

A: Usually, the tokenizer (or lexer) performs no checking of valid syntax.
The role of a lexer is to split the input into tokens, which can then be transformed into a syntax tree by the parser. Therefore, it'd usually be the job of the parser to perform such a check.

A: You might consider generating your tokenizer or lexer. Tools like Flex or ANTLR should help. And you might also generate your parser with ANTLR or Bison
If you insist on hand-coding your lexer (and your parser), having some look-ahead is extremely helpful in practice. For instance, you could read your input line by line and tokenize inside the current line (with the ability to inspect the next few characters).

A: This is somewhat of a gray area, but most hand-coded lexers just do the tokenizing, and let the parser decide whether the stream of tokens make sense.

A: If "123abc" is an invalid token then you should handle it as soon as you spot it since it's directly related to the way tokens are defined, not how they interact with each other (which would be the lexer's job). It's an orthographic error rather than a grammar-related one.
There are multiple ways to go about it:

*

*You could abort the parsing and just throw some exception, leaving the caller with no tokens or just the tokens you had successfully parsed until then. This will save you any "recovery" logic and might be enough for your use case. Although, if you're parsing stuff for syntax highlighting for instance, this would probably not be sufficient as you don't want all of the remaining code to look unparsed.
Example: A conforming XML parser could use this for fatal errors if there's no need to handle malformed markup, just spit out a basic error and quit.

*Alternatively, you could insert an "error" token with proper metadata about the nature of the error and skip ahead to the next valid token.
You might need to have heuristics in your lexer to handle the error token gracefully and find how to interpret further tokens when an error token is found inside an nested expression (like, should you consider the expression has ended? look for a closing token? etc.).
Anyway, this approach will allow for error tokens to be used to display precise info about the location and nature of errors encountered (think inline error reporting in a GUI).


text:
Q: Pramp - Award Budget Cuts Solution I have a hard time wrapping my head around the solution given by Pramp for the problem:
Award Budget Cuts
https://www.pramp.com/challenge/r1Kw0vwG6OhK9AEGAyWV
I do not seem to be able to find some other explanations of what they are doing in their solution.
I kinda understand the other ways of solving it, suggested by other users here:
https://codereview.stackexchange.com/questions/194272/award-budget-cuts-implementation-in-java
But I am trying to understand the reasoning behind the:
surplus1 = surplus0 - 1*(grantsArray[0]-grantsArray[1])
surplus2 = surplus1 - 2*(grantsArray[1]-grantsArray[2])
surplus3 = surplus2 - 3*(grantsArray[2]-grantsArray[3])

Really don't understand that part...


text:
Q: Entering data in multiple tables using foreign key constraints I have following data:
Array
(
    [teacher_street] => Okhla
    [teacher_city] => Delhi
    [teacher_state] => National Capital Territory of Delhi
    [teacher_pin] => 110025
)

I need to insert the above data into a table called address:
CREATE TABLE `address` (
  `address_id` int(11) NOT NULL,
  `address_street` varchar(255) NOT NULL,
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `address_pin` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, I need to insert city and state in city table and state table first, if they don't exist. If they exist, I need to get primary keys corresponding to them:
CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `city_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `state_name` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After that I need to get the corresponding primary keys and need to put in first table. How can I achieve the same in one go?

A: Your city and state tables appear to have no AUTO_INCREMENT primary keys. You would have to specify the value as you insert into these tables.
If so, then your application code has the value it just inserted, and you can use it as you insert to the address table.
If you do in fact use AUTO_INCREMENT primary keys, you'll have to query LAST_INSERT_ID() to fetch the id after you insert to the city and state tables, and use these as you insert to the address table. Or else if you don't want to do that, query the id by searching for city name or state name before you insert to address.


text:
Q: Computing gradients in extracted Tensorflow subgraph which contains a 'while_loop' In some deep learning workflows, it is useful to train a model, extract it out of its graph using tf.graph_util.convert_variables_to_constants or tf.graph_util.extract_sub_graph so training-related tensors are left out, and then connect the extracted subgraph to other model(s) via tf.import_graph_def. In this way, the trained model can serve as a building block in a larger setup.
Often, we'd like to backpropagate through the new, composite model, in order to fine-tune it, optimize the inputs and so on.
However, it appears that one cannot define a gradient through a while_loop tensorflow operation in an imported graph, since it relies on 'outer context', an object added into the metagraph's collections (see TF issue #7404). Slightly adapting the example in this Github issue, here's an example of what I am trying to do:
import tensorflow as tf
g1=tf.Graph()
sess1=tf.Session(graph=g1)
with g1.as_default():
    with sess1.as_default():
        i=tf.constant(0, name="input")
        out=tf.while_loop(lambda i: tf.less(i,5), lambda i: [tf.add(i,1)], [i], name="output")
        loss=tf.square(out,name='loss')
        graph_def = tf.graph_util.convert_variables_to_constants(sess1,g1.as_graph_def(),['output/Exit'])

g2 = tf.Graph()
with g2.as_default():
    tf.import_graph_def(graph_def,name='')
    i_imported = g2.get_tensor_by_name("input:0")
    out_imported = g2.get_tensor_by_name("output/Exit:0")
    tf.gradients(out_imported, i_imported)

The last line raises an AttributeError: 'NoneType' object has no attribute 'outer_context' error.
Tensorflow's solution to this issue is to use tf.train.export_meta_graph and tf.train.import_meta_graph so the outer  context is copied, but this copies the entire graph, without editting. In this minimal case, the 'loss' tensor won't be removed.
I tried copying the missing context to the new graph:
g2.add_to_collection('while_context',g1.get_collection('while_context'))

But it doesn't solve the issue.
Is there a way to overcome this limitation or is it an irreparable Tensorflow design flaw?


text:
Q: changing the appearance of output using lapply function I used lapply function in the following code.
library(bio3d)
files <- list.files('/home/sanvi/Desktop/folder', '.*\\.pdb$', full.names=TRUE)
rgs <- lapply(files, function(x) {
    data <- read.pdb(x)
    mass <- rep(12, length(data$xyz)/3)
    rgyr(data, mass)
})
rgs

[[1]]
[1] 32.56132

[[2]]
[1] 11.83162

I would like to get the output as shown below.
filename1.pdb    32.56132
filename2.pdb    11.83162

Are there any way to get the output as shown above?

A: We can use stack after naming the list ('rgs') with the basename of 'files'.  This will output a two column 'data.frame'
stack(setNames(rgs, basename(files)))
#            ind   values
#1 filename1.pdb 32.56132
#2 filename2.pdb 11.83162

data
rgs <- list(32.56132, 11.83162)
files <- paste("/home/sanvi/Desktop/folder",
     c("filename1.pdb", "filename2.pdb"), sep="/")


text:
Q: laravel sync() equivalent for OneToMany relation i want to know what is the best practice to update a relationship, like the sync() methode for many to many relations.
i have a one to many relation like that :
One question can have multiple responses, and one response can be only for one question
The user is able to change responses for each question, add more responses, or delete some, (by using javascript) or modify it in the Edit page input.
In the QuestionsController@update i get responses like that :
array:7 [▼
  0 => "first response"
  1 => "second"
  2 => "third"
]

(depending on the number of questions that the user sent, it can be more or less)
I thought I could do :
$question = Question::findOrFail($id);
$responses = $request->get('responses');
$question->responses()->sync($responses);

but it only works for many to many relations...
so i do that :
$question = Question::findOrFail($id);
foreach($request->get('responses') as $response){
    $responses[] = new Response(['content' => $response]);
}
$question->responses()->delete();
$question->responses()->saveMany($reponses);

what do you think about that ? it works but i have a doubt that this is the best thing to do
thanks


text:
Q: Enhanced For-Loop raises a compilation error with Custom Collection implementing Iterable interface I'm trying to make a recursive list data structure in Java, similar to lists in functional languages.
I want it to implement Iterable so that it can be used in for-each loops.
So I'me implemented the iterator() method which creates an Iterator, and this loop works fine (list is of type RecursiveList<Integer>):
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
    Integer i = it.next();
    System.out.println(i);
}

Now I was under the impression that for (int i : list) is basically just a syntactic sugar over the for-loop above, but when I try to use the for-each, I'm getting a compilation error:
incompatible types: Object cannot be converted to int

I can't for the life of me figure out why it isn't working. Here's the relevant code:
import java.util.*;

class RecursiveList<T> implements Iterable {

  private T head;
  private RecursiveList<T> tail;
  // head and tail are null if and only if the list is empty
  // [] = { head = null; tail = null}
  // [1,2] = { head = 1; tail = { head = 2; tail = { head = null; tail = null } } }

  public RecursiveList() {
    this.head = null;
    this.tail = null;
  }

  private RecursiveList(T head, RecursiveList<T> tail) {
    this.head = head;
    this.tail = tail;
  }

  public boolean add(T newHead) {
    RecursiveList<T> tail = new RecursiveList<T>(this.head, this.tail);
    this.head = newHead;
    this.tail = tail;
    return true;
  }

  public Iterator<T> iterator() {
    RecursiveList<T> init = this;

    return new Iterator<T>() {
      private RecursiveList<T> list = init;

      public boolean hasNext() {
          return list.head != null;
      }

      public T next() {
          T ret = list.head;
          if (ret == null) throw new NoSuchElementException();
          list = list.tail;
          return ret;
      }
    }
  }
}

class Main {
  public static void main(String[] args) {
    RecursiveList<Integer> list = new RecursiveList<Integer>();

    list.add(1);
    list.add(2);
    list.add(3);

    // works:
    for(Iterator<Integer> it = list.iterator(); it.hasNext();) {
      Integer i = it.next();
      System.out.println(i);
    }
    // output:
    // 3
    // 2
    // 1

    // doesn't work:
    // for (int i : list) System.out.println(i);
  }
}

What's making me feel real stupid is my IDE is catching the problem too and underlining list giving the same error message, so there must be something obviously wrong with how I've written the types that I'm missing, I just can't figure what's happening since iterator() seems to be successfully creating an Iterator instance with the right type based on the more verbose loop working.

A: Interface Iterable is generic, but your custom Collection implements iterable of row type, which is effectively Iterable<Object>. For that reason, elements retrieved from your collection inside the enhanced for-loop are treated as being of type Object.
You need to change the declaration of your Collection to:
class RecursiveList<T> implements Iterable<T>


text:
Q: Change "clean css" options in grunt min css Is there some kind of special syntax I need to use to override Clean CSS defaults when using Grunt CSS min?
Looking at the docs I can successfully get the "roundingPrecision" example working but trying to override other Clean CSS rules does not work for me.
I've given a config example below where I'm trying to prevent duplicate rules being removed (in this case I need a non-css variable fallback for browsers that do not support CSS variables). This is not working for me though.
Here is the CSS Min part of my Grunt config:
    cssmin: {
        options: {
            removeDuplicateRules: false,
            roundingPrecision: -1
        },
        prod: {
            files: [{
                expand: true,
                ext: '.min.css',
                src: ['<%= cssPath %>style.css'],
            }]
        },
    },

With the above config, this is what happens:
    .test {
       background: red;
       background: var(--colour-blue);
    }

Becomes
    .test{background:var(--colour-blue);}

However, the second background rule should not be removed.
I've noticed in a another StackOverflow question it seems like I may need to target some specific area of Clean CSS—Use clean-css compatibility options in grunt-contrib-cssmin—but I'm not sure how to do that for other properties like "removeDuplicateRules: false".
I'm guessing that I'm doing something fundamentally wrong. Any pointers would be helpful—thanks.
Update #2
As suggested I've tried to use the attempted "level" options as follows, without any success:
cssmin: {
  options: {
    level: {
      1: {
        all: false
      },
      2: {
        all: false
      }
    }
  },
  prod: {
    files: [{
      expand: true,
      ext: '.min.css',
      src: ['<%= cssPath %>style.css'],
    }]
  },
},


text:
Q: What is the bug in this code? Based on a this logic given as an answer on SO to a different(similar) question, to remove repeated numbers in a array in O(N) time complexity, I implemented that logic in C, as shown below. But the result of my code does not return unique numbers. I tried debugging but could not get the logic behind it to fix this.
int remove_repeat(int *a, int n)
{
    int i, k;

    k = 0;
    for (i = 1; i < n; i++)
    {
        if (a[k] != a[i])
        {
            a[k+1] = a[i];
            k++;
        }
    }
    return (k+1);
}

main()
{
    int a[] = {1, 4, 1, 2, 3, 3, 3, 1, 5};
    int n;
    int i;

    n = remove_repeat(a, 9);

    for (i = 0; i < n; i++)
            printf("a[%d] = %d\n", i, a[i]);

}

1] What is incorrect in above code to remove duplicates.
2] Any other O(N) or O(NlogN) solution for this problem. Its logic?

A: *

*Heap sort in O(n log n) time.

*Iterate through in O(n) time replacing repeating elements with a sentinel value (such as INT_MAX).

*Heap sort again in O(n log n) to distil out the repeating elements.

Still bounded by O(n log n).

A: You are going to need two loops, one to go through the source and one to check each item in the destination array.
You are not going to get O(N).
[EDIT]
The article you linked to suggests a sorted  output array which means the search for duplicates in the output array can be a binary search...which is O(LogN).

A: Your code would appear to require that the input is sorted. With unsorted inputs as you are testing with, your code will not remove all duplicates (only adjacent ones).

A: You are able to get O(N) solution if the number of integers is known up front and smaller than the amount of memory you have :).  Make one pass to determine the unique integers you have using auxillary storage, then another to output the unique values.
Code below is in Java, but hopefully you get the idea.
int[] removeRepeats(int[] a) {
    // Assume these are the integers between 0 and 1000
    Boolean[] v = new Boolean[1000]; // A lazy way of getting a tri-state var (false, true, null)

    for (int i=0;i<a.length;++i) {
       v[a[i]] = Boolean.TRUE;
    }

    // v[i] = null => number not seen
    // v[i] = true => number seen

    int[] out = new int[a.length];
    int ptr = 0;
    for (int i=0;i<a.length;++i) {
        if (v[a[i]] != null && v[a[i]].equals(Boolean.TRUE)) {
            out[ptr++] = a[i];
            v[a[i]] = Boolean.FALSE;
        }
    }

    // Out now doesn't contain duplicates, order is preserved and ptr represents how
    // many elements are set.
    return out;
}

A: Your code only checks whether an item in the array is the same as its immediate predecessor.
If your array starts out sorted, that will work, because all instances of a particular number will be contiguous.
If your array isn't sorted to start with, that won't work because instances of a particular number may not be contiguous, so you have to look through all the preceding numbers to determine whether one has been seen yet.
To do the job in O(N log N) time, you can sort the array, then use the logic you already have to remove duplicates from the sorted array. Obviously enough, this is only useful if you're all right with rearranging the numbers.
If you want to retain the original order, you can use something like a hash table or bit set to track whether a number has been seen yet or not, and only copy each number to the output when/if it has not yet been seen. To do this, we change your current:
if (a[k] != a[i])
    a[k+1] = a[i];

to something like:
if (!hash_find(hash_table, a[i])) {
    hash_insert(hash_table, a[i]);
    a[k+1] = a[i];
}

If your numbers all fall within fairly narrow bounds or you expect the values to be dense (i.e., most values are present) you might want to use a bit-set instead of a hash table. This would be just an array of bits, set to zero or one to indicate whether a particular number has been seen yet.
On the other hand, if you're more concerned with the upper bound on complexity than the average case, you could use a balanced tree-based collection instead of a hash table. This will typically use more memory and run more slowly, but its expected complexity and worst case complexity are essentially identical (O(N log N)). A typical hash table degenerates from constant complexity to linear complexity in the worst case, which will change your overall complexity from O(N) to O(N2).

A: Your logic just wrong, so the code is wrong too. Do your logic by yourself before coding it.
I suggest a O(NlnN) way with a modification of heapsort.
With heapsort, we join from a[i] to a[n], find the minimum and replace it with a[i], right?
So now is the modification, if the minimum is the same with a[i-1] then swap minimum and a[n], reduce your array item's number by 1.
It should do the trick in O(NlnN) way.

A: Your code will work only on particular cases. Clearly, you're checking adjacent values but duplicate values can occur any where in array. Hence, it's totally wrong.


text:
Q: C++: ios::app doesnt need ios::out in fstream i was testing with flags in file stream objects the other day
And i did this.
fstream binf("h.txt", ios::app);
binf << "hey";

With fstream since i didnt use ios::out, the output operation shouldnt have worked , but it does work
I noticed that the the output operation works with ios::app only but if i use any other flag without ios::out it doesnt work
Can anyone tell me why I was able to output to the file while using only ios::app without ios::out

A: Well, appending implies writing, that's about the longest explanation I can come up with.

A: Using app implies out.
The standard specifies that app and out|app have the same result, equivalent to C fopen in mode "a".

A: This answer is more compiler specific,but they are amazing to be noticed:-

VS 2010 fstream :- ios_base::out flag is already set

explicit basic_ofstream(const char *_Filename,
        ios_base::openmode _Mode = ios_base::out,
        int _Prot = (int)ios_base::_Openprot)
        : _Mybase(&_Filebuffer)
        {
        if (_Filebuffer.open(_Filename, _Mode | ios_base::out, _Prot) == 0)
            _Myios::setstate(ios_base::failbit);
        }

GCC 4.5 fstream:-  Again ios_base::out flag is already set

explicit
      basic_ofstream(const char* __s,
             ios_base::openmode __mode = ios_base::out|ios_base::trunc)
      : __ostream_type(), _M_filebuf()
      {
    this->init(&_M_filebuf);
    this->open(__s, __mode);
      }

void
      open(const char* __s,
       ios_base::openmode __mode = ios_base::out | ios_base::trunc)
      {
    if (!_M_filebuf.open(__s, __mode | ios_base::out))
      this->setstate(ios_base::failbit);
    else
      this->clear();
      }

And even more interesting thing is, only in ios_base::in the last bit is a 1.Which signifies ios_base::in is able to retain its identity even raised with flag ios_base::out.


text:
Q: Выборочная загрузка тайлов OSM Существует ли возможность загружать тайлы OSM без POI, используя штатное API?

A: У OSM нет API для получения тайлов. Вы просто подключаете картинки с определённого адреса. Поскольку это картинки — растровые изображения — то на части их разделить не получится. Так что нет.
Однако адрес картинок легко подменить, и у OpenStreetMap есть множество слоёв без POI. Например, от MapQuest. Кроме того, вы можете настроить собственный рендеринг, где, например, взять тот же стандартный стиль и убрать из него значки и подписи POI.


text:
Q: How to find out the min value of the third field according to the first two fields using awk The ontent of file named test.file is as follows:
333379266       834640619       88
333379280       834640621       99
333379280       834640621       66
333376672       857526666       99
333376672       857526666       78
333376672       857526666       62

The first two columns may be duplicate, and I want to output the first two columns and the corresponding min value of the third column.In this case,The result file should be as follows:
333379280 834640621 66
333379266 834640619 88
333376672 857526666 62

My attemp is:
awk '{a[$1" "$2]=99999;a[$1" "$2]=a[$1" "$2]<$3?a[$1" "$2]:$3}END{for(i in a) print i,a[i]}' test.file
My question is:
Is there any other way to achieve this requirement.

A: Could you please try following to look for minimum values for 1st and 2nd field keys in whole Input_file.
awk '
{
  ind=$1 OFS $2
  array[ind]=(array[ind]<$3?(array[ind]?array[ind]:$3):$3)
}
END{
  for(i in array){
     print i,array[i]
  }
}'  Input_file

OR as per @kent's comments adding following solution with an additional condition to check for null value in 3rd field as follows.
awk '
{
  ind=$1 OFS $2
  array[ind]=(array[ind]<$3||array[ind]==""?(array[ind]?array[ind]:$3):$3)
}
END{
  for(i in array){
     print i,array[i]
  }
}' Input_file

Explanation: Adding detailed explanation for above code.
awk '                                                                ##Starting awk program from here.
{
  ind=$1 OFS $2                                                      ##Creating variable ind whose value is 1st and 2nd field.
  array[ind]=(array[ind]<$3?(array[ind]?array[ind]:$3):$3)           ##Creating array with index of variable ind and checking if its value is lesser than $3 then keep it same else assign $3 to it.
}
END{                                                                 ##Starting END block for this awk program here.
  for(i in array){                                                   ##Traversing through all elements of array here.
     print i,array[i]                                                ##Printing key of array and value of array here.
  }
}'  Input_file                                                       ##Mentioning Input_file name here.


text:
Q: 403 Error in Gitlab connection with Jenkins I tried connecting Jenkins with Gitlab, while using System hooks in the Gitlab repository.
It is throwing me the following error :
Hook executed successfully but returned HTTP 403 window.location.replace('/login?from=%2Fjenkins%2Fproject%2FContinious_Integration');

Authentication required Hook executed successfully but returned HTTP 403 window.location.replace('/login?from=%2Fjenkins%2Fproject%2FContinious_Integration'); Authentication required

A: Open Jenkins global configuration -> require authorization for /project endpoint

*

*Copy userid and API key for a Jenkins user who has authorization to
run the job

*Create a webhook on GitLab to trigger the job,

*Use HTTP basic auth (Below format)

user:apikey@gitlab/project/jobname

This worked for me..!


text:
Q: NelderMeadMinimize for 2D Gaussian fitting I would like to fit a large number (10^5-10^6) of small images to 2D gaussians by taking advantage of the NelderMeadMinimize package from Oleksandr: Shaving the last 50 ms off NMinimize. The application is for analyzing localization microscopy data (fitting lots of single molecule fluorescent emitters in large movies.) There is plenty of good/free software out there for doing this (ImageJ/FIJI plugins), but having an all Mathematica solution with the NedlerMead package would be nice (and bring calculation time to a reasonable amount.)
Using the compiled NelderMead Package for 2D gaussian fitting has been posed previously by blochwave with some suggestions in the comments, but with no resolution. I have been hesitant to re-ask this question since it is certainly a duplicate, but I believe there has been some interest in the past for fast fitting for image analysis (in the comments!) so it would nice to see a working example if possible! (My simpleton attempts are adapted from blochwaves' original question.)
Needs["NelderMeadMinimize`"]

Simple 1D gaussian test with a little noise:
data = Table[a Exp[-(x - b)^2/(2 c^2)] + RandomReal[], {x, 1, 9}] /. {a -> 10, b -> 5, c -> 1};
fitter = With[{x = Range[Length[#]]}, NelderMeadMinimize[Norm[#[[x]] - a Exp[-(x - b)^2/(2 c^2)]], {a, b, c}]] &;
fitter[data]

(*{0.623781, {a -> 10.8638, b -> 4.96825, c -> 1.01535}}*)

Using CompiledNelderMead:
With[{epsilon = $MachineEpsilon,
   minimizer =
    NelderMeadMinimize`Dump`CompiledNelderMead[
     Function[{a, b, c},
      Block[{x = Range@Length[data]},
       Norm[data[[x]] - a Exp[-(x - b)^2/(2 c^2)]]]], {a, b, c},
     "ReturnValues" -> "OptimizedParameters"]},
  serialFitter =
    Compile[{{data, _Real, 1}},
     minimizer[RandomReal[{0, 1}, {3 + 1, 3}], epsilon, -1],
     CompilationOptions -> {"InlineCompiledFunctions" -> True},
     RuntimeOptions -> {"Speed", "EvaluateSymbolically" -> False},
     CompilationTarget -> "C"];];
serialFitter[data]
(*{10.5594, 5.02918, 1.06511}*)

Ok great, compiled 1D gaussian fit works. Make some 2D test data. The previous suggestions were to make sure that all the lists that are fed into NelderMeadMinimize are 1D lists, hence the Flattens.
xyz = Table[{x, y,
     a Exp[(-(x - b)^2 - (y - c)^2)/(2 d^2)] + RandomReal[]}, {x, 1,
     9}, {y, 1, 9}] /. {a -> 10, b -> 5, c -> 5, d -> 1};
xvals = Flatten@xyz[[All, All, 1]];
yvals = Flatten@xyz[[All, All, 2]];
zvals = Flatten@xyz[[All, All, 3]];
ArrayPlot[xyz[[All, All, 3]]];

Test 2D gaussian fitting with NelderMeadMinimize:
fitter = Block[{data = #},
    NelderMeadMinimize[
     Block[{x = xvals, y = yvals},
      Norm[data - a Exp[(-(x - b)^2 - (y - c)^2)/(2 d^2)]]], {a, b, c,
       d}]] &;
fitter[zvals]
(*{4.83445, {a -> 10.0792, b -> 5.03425, c -> 5.00488, d -> 1.11341}}*)

Good, now try compiled 2D gaussian with CompiledNelderMead:
fitter = Compile[{{xvals, _Real, 1}, {yvals, _Real, 1}, {data, _Real,
     1}}, NelderMeadMinimize`Dump`CompiledNelderMead[
     Function[{a, b, c, d},
      Block[{x = xvals, y = yvals},
       Norm[Flatten[data] -
         a Exp[(-(x - b)^2 - (y - c)^2)/(2 d^2)]]]], {a, b, c, d},
     "ReturnValues" -> "OptimizedParameters"][
    RandomReal[{0, 1}, {4 + 1, 4}], $MachineEpsilon, -1],
   CompilationOptions -> {"InlineCompiledFunctions" -> True},
   RuntimeOptions -> {"Speed", "EvaluateSymbolically" -> False},
   CompilationTarget -> "C"];
fitter[xvals, yvals, zvals]

Correct result, but uncompiled evaluation and the same error about rank 2 tensor that was observed previously:

Perhaps I didn't understand something in the previous suggestion, but I am at a lost for what else to try (and apologies for the duplicated question!).


text:
Q: How to rename an image I have an image, person1.png, and four other images, person2.png, person3.png, person5.png, and person4.png. I want to rename these images in C# code. How would I do this?

A: Since the PNG files are in your XAP, you can save them into your IsolatedStorage like this:
//make sure PNG_IMAGE is set as 'Content' build type
var pngStream= Application.GetResourceStream(new Uri(PNG_IMAGE, UriKind.Relative)).Stream;

int counter;
byte[] buffer = new byte[1024];
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
   using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(IMAGE_NAME, FileMode.Create, isf))
   {
      counter = 0;
      while (0 < (counter = pngStream.Read(buffer, 0, buffer.Length)))
      {
             isfs.Write(buffer, 0, counter);
      }

      pngStream.Close();

    }
 }

Here you can save it to whatever file name you want by changing IMAGE_NAME.
To read it out again, you can do this:
byte[] streamData;

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
     using (IsolatedStorageFileStream isfs = isf.OpenFile("image.png", FileMode.Open, FileAccess.Read))
     {
          streamData = new byte[isfs.Length];
          isfs.Read(streamData, 0, streamData.Length);
     }
}

MemoryStream ms = new MemoryStream(streamData);
BitmapImage bmpImage= new BitmapImage();
bmpImage.SetSource(ms);
image1.Source = bmpImage; //image1 being your Image control

A: Use the FileInfo.MoveTo method documented here. Moving a file to the same path but with a different name is how you rename files.

FileInfo fInfo = new FileInfo ("path\to\person1.png");
fInfo.MoveTo("path\to\newname.png")

If you need to manipulate paths, use the Path.Combine method documented here

A: On Windows Phone 7 the API methods to copy or move (rename) a file don't exist. (See http://msdn.microsoft.com/en-us/library/57z06scs(v=VS.95).aspx) You therefore have to do this yourself.
Something like:
var oldName = "file.old"; var newName = "file.new";

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var readStream = new IsolatedStorageFileStream(oldName, FileMode.Open, store))
    using (var writeStream = new IsolatedStorageFileStream(newName, FileMode.Create, store))
    using (var reader = new StreamReader(readStream))
    using (var writer = new StreamWriter(writeStream))
    {
        writer.Write(reader.ReadToEnd());
    }

    store.DeleteFile(oldName);
}

A: When you upload image this function auto change the image name to Full date and return the full path where the image saved and with it new name.
 string path = upload_Image(FileUpload1, "~/images/");
 if (!path.Equals(""))
    {
        //use the path var..
    }

and this is the function
    string upload_Image(FileUpload fileupload, string ImageSavedPath)
{
    FileUpload fu = fileupload;
    string imagepath = "";
    if (fileupload.HasFile)
    {
        string filepath = Server.MapPath(ImageSavedPath);
        String fileExtension = System.IO.Path.GetExtension(fu.FileName).ToLower();
        String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
        for (int i = 0; i < allowedExtensions.Length; i++)
        {
            if (fileExtension == allowedExtensions[i])
            {
                try
                {
                    string s_newfilename = DateTime.Now.Year.ToString() +
                        DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
                        DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + fileExtension;
                    fu.PostedFile.SaveAs(filepath + s_newfilename);

                    imagepath = ImageSavedPath + s_newfilename;
                }
                catch (Exception ex)
                {
                    return "";
                }

            }

        }

    }
    return imagepath;

}

if you need more help i'll try  :)


text:
Q: Is there an equivalent for :HEX and :OCT in current Pascal? I am trying to transpose an old Pascal programm into one that compiles (and work) with Free Pascal.
One mechanism that I have encountered is a sort of conversion done at the reading of the value:
readln (file,ValueHex:HEX);

or
readln (file,ValueOct:OCT);

In the later case, when the value read in the file was "12" (value in octal), the value stored in "MyValue" was "10" (value in decimal).
For writting these values the code was:
writeln (hex(ValueHex,4), oct(ValueOct,3));

and now is:
writeln (HEXSTR(ValueHex,4), OCTSTR(ValueOct,4));

The writting part works as intended but in all the Free Pascal documentation I could not find the equivalent of :HEX and :OCT, does it even exist or do I have to write dedicated functions converting hexadecimal and octal values to decimal ones?

A: No. You will need to read as string and do the conversion yourself. I haven't even heard of these extension before, so it is probably not a common one. Which dialect is it?
Note that FreePascal also supports & as octal and % as binary prefix.
uses sysutils;
begin
  Writeln (StrToInt('$1234'));
  Writeln (StrToInt('&1000'));
  Writeln (StrToInt('%1010101'));
end.

For hex there is also an option without prefix:
https://www.freepascal.org/docs-html/rtl/strutils/hex2dec.html


text:
Q: Using WCF Client without installing .NET Framework 3.5? I have a WCF Service built with .NET Framework 3.5. I have a task to develop a WCF Client which only uses .NET Framework 2.0. The WCF Client will receive messages which is broadcasted from WCF Service. Can I do this?
The WCF Client runs well on a computer has .NET Framework 3.5. However on a computer which only has .NET Framework 2.0, and including WCF's DLLs in application's folder, WCF Client only send message to service ok but can't receive message from WCF Service.

WCF Client  ---> WCF Service : OK
WCF Client  <--- WCF Service : Not OK

Please help me. Thanks.

A: If your service exposes a basicHttpBinding endpoint, then you should be able to consume it in a .NET 2.0 application by using "Add Web Reference".