text:
Q: Problem of unbalanced data unbalanced data is an issue that can effect the performnce of classification model ,several remides can be done to balance the data two of them are upsampling and downsampling , my questions is :

*

*how do you know which method is the best for your model ?

*is it true that we need to compare f1-score rather than accuracy score ?

*do we also need to conduct a model for the unbalnced data and compare it to the upsampled/downsampled models

PS: doing cross validation to check al of them will take a lot of time especially with data that have large observations and complex models

A: You may try stratified k-fold cross-validation instead of the classic approach of k-fold cross-validation. In stratified k-fold cross-validation, the folds are selected so that the mean response value is approximately equal in all the folds.
Particularly, Stratification is the process of re-arranging the data as to ensure each fold is a good representative of the whole.
F1-score is the appropriate metric of performance instead of considering Accuracy.


text:
Q: Expressão regular de citações no R Gostaria de extrair todas as chaves de referência que uso em um documento markdown que começam com o caractere @.
Segue um exemplo das diferentes formas que posso citar um documento usando essa chave:
line <- 'According to @REF1, north American trees are lagging behind climate change [@REF2; @REF3]. However, some species have shown range limits expansion following warming temperature [*e.g.* white spruce @REF4; @REF5].'

A partir desse exemplo, gostaria de obter um vetor com as seguintes chaves:
citations
# [1] REF1
# [1] REF2
# [1] REF3
# [1] REF4
# [1] REF5

A: Depende do formato que essas citações podem ter. Uma opção seria:
str_extract_all(line, "(?<=@)\\w+")

Que retorna:
[1] "REF1" "REF2" "REF3" "REF4" "REF5"

Esta regex usa lookbehind - o trecho entre (?<= e ) - e serve para verificar se algo existe antes da posição atual. No caso, dentro do lookbehind só tem a @.
O detalhe é que a @, por estar em um lookbehind, não fará parte do match, então a regex só retornará o que está depois dela, que no caso é \\w+. O atalho \w significa "letras, números ou o caractere _", e o quantificador + significa "uma ou mais ocorrências".
Na outra resposta foi sugerido usar \\w*, mas o * significa "zero ou mais ocorrências", o que quer dizer que se tiver uma @ sozinha (sem nenhum caractere corresponde a \w depois), é retornado um match vazio. Veja a diferença:
line <- 'Teste @ abc @REF1'

str_extract_all(line, "(?<=@)\\w+")
str_extract_all(line, "(?<=@)\\w*")

O primeiro retorna:
[1] "REF1"

E o segundo retorna:
[1] ""     "REF1"

Se quiser, pode ser mais específico (mas aí vai depender do formato exato da citação). Por exemplo, se o formato sempre for "3 letras maiúsculas e um dígito", então você pode usar:
str_extract_all(line, "(?<=@)[A-Z]{3}[0-9]")

Como não foram dados mais detalhes quanto ao formato, deixo apenas esta sugestão, mas o ideal é que você seja o mais específico possível para evitar falsos positivos.
Por exemplo, como \w também considera o caractere _, então o trecho @___ é considerado válido (veja). Mas claro que se você "sabe" que esses casos não ocorrem com suas strings, não tem tanto problema usar \w. Tudo depende.

A: Com o modelo que você colocou consegui fazer assim.
library(tidyverse)

#usando o tidyverse
citations <- str_extract_all(line, "@\\w*") %>%
  as_vector() %>%
  str_remove("@")

citations
#> [1] "REF1" "REF2" "REF3" "REF4" "REF5"

#R base
gregexpr(pattern = "@\\w*", text = line) %>%
  regmatches(line, m = .) %>%
  unlist() %>%
  gsub("@","",.)
#> [1] "REF1" "REF2" "REF3" "REF4" "REF5"

Created on 2019-11-07 by the reprex package (v0.3.0)

A: Não há necessidade de usar o stringr nesse exercício. Podemos utilizar regmatches com gregexpr.
regmatches vai extrair as substrings que foram encontradas com gregexpr –essa última função encontra todas as sequências possíveis na string.
regmatches retornará uma list onde, nesse caso, o único objeto é um vetor com as substrings desejada. Então você fecha a expressão regmatches(...) em unlist para receber o resultado desejável.
Sobre a pattern que você deve usar, acredito que um modo mais fléxivel seja utilizando a POSIX class [[:alnum:]]. Esse tipo de classe corresponde a letras maiúsculas e minúsculas bem como números. Atente para o uso do parâmetro pearl=TRUE em gregexpr. Isso permite o uso de [[:alnum:]] como pattern. Também adicionamos quantificador + ao fim da pattern, que é um quantificador "greedy", ou seja, acha as substrings que tem letras e números em mais de uma vez sendo que o "match" é sempre para a maior substring possível. Por fim, usamos o lookaround tipo lookbehind (?<=...) para achar pedaços da string que comecem em @ como já foi explicado nas respostas acima.
Portanto a solução fica assim:
unlist(regmatches(line, gregexpr("(?<=@)[[:alnum:]]+", line, perl = TRUE)))

O que retorna:
[1] "REF1" "REF2" "REF3" "REF4" "REF5"

Veja que essa solução é aproximadamente 5x mais rápida que unlist(stringr::str_extract_all(...):
microbenchmark::microbenchmark(
  base= unlist(regmatches(line, gregexpr("(?<=@)[[:alnum:]]+", line, perl = TRUE))),
  stringr = unlist(str_extract_all(line, "(?<=@)[[:alnum:]]+"))
)

Resultado:
Unit: microseconds
    expr      min        lq      mean   median       uq      max neval cld
    base  323.824  335.3105  381.1747  366.854  388.370 1300.399   100  a
 stringr 1596.873 1632.4270 1772.1564 1666.888 1723.958 5634.818   100   b

redpajama_set_name: RedPajamaStackExchange


text:
Q: Incorrect syntax near the keyword 'where' when converting MySQL to MSSQL So I am trying to convert some stuff from MySql to MSSQL 2012 the problem is I dont know Sql that well to know what is wrong with this statement. I get a response when this is ran against the MySql DB with the same information as the MSSQL DB has.
I am getting the error :
Incorrect syntax near the keyword 'where'. Msg: 156, Level: 15, State: 1, Procedure: , Line: 11
select distinct
    coalesce(s.state_prov, ls.state_prov, 'State Unknown') as state_prov
from
    circuit_id_locations cid
join
    location_states ls
left join
    location_states s
on
cid.state_prov = s.abreviation
where
ls.idx = '99'
or
cid.id = '99'

A: You have a join statement without an 'on statement'
>>>MISSING JOIN TYPE (inner/left/right/cross)<<< join
    location_states ls
>>>MISSING ON<<<

left join
    location_states s

A: You have more JOINs than you do ON clauses, turn your normal join into a CROSS JOIN to make it work.
select distinct
    coalesce(s.state_prov, ls.state_prov, 'State Unknown') as state_prov
from
    circuit_id_locations cid
CROSS join
    location_states ls
left join
    location_states s
on
cid.state_prov = s.abreviation
where
ls.idx = '99'
or
cid.id = '99'


text:
Q: NumPy Array Indexing and Replacing I have a 3d numpy array as follows:
(3L, 5L, 5L)

If one element in 3d positions, for instance, [150, 160, 170] exists. How can I convert all of them into [0,0,0]?
import numpy as np
a = np.ones((3,5,5))
a[0,2:4,2:4] = 150
a[0,0:1,0:1] = 150 #important!
a[1,2:4,2:4] = 160
a[2,2:4,2:4] = 170
print a

The expected result should be:
[[[ 1.  1.  1.  1.  1.]
  [ 1.  1.  1.  1.  1.]
  [ 1.  1.  0.  0.  1.]
  [ 1.  1.  0.  0.  1.]
  [ 1.  1.  1.  1.  1.]]

 [[ 1.  1.  1.  1.  1.]
  [ 1.  1.  1.  1.  1.]
  [ 1.  1.  0.  0.  1.]
  [ 1.  1.  0.  0.  1.]
  [ 1.  1.  1.  1.  1.]]

 [[ 1.  1.  1.  1.  1.]
  [ 1.  1.  1.  1.  1.]
  [ 1.  1.  0.  0.  1.]
  [ 1.  1.  0.  0.  1.]
  [ 1.  1.  1.  1.  1.]]]

A: First I would convert into a stack of triples:
b = np.reshape(a.transpose(2, 1, 0), [25,3])

Then find the values you want:
idx = np.where((b == np.array([150, 160, 170])).all(axis=1))

And replace with whatever value you want:
b[idx] = 0

And finally convert back to the original shape:
c = np.reshape(b, [5, 5, 3]).transpose(2, 1, 0)

A: Construct your a:
In [48]: a=np.ones((3,5,5))
In [49]: a[0,2:4,2:4]=150
In [50]: a[1,2:4,2:4]=160
In [51]: a[2,2:4,2:4]=170

In [52]: a
Out[52]:
array([[[   1.,    1.,    1.,    1.,    1.],
        [   1.,    1.,    1.,    1.,    1.],
        [   1.,    1.,  150.,  150.,    1.],
        [   1.,    1.,  150.,  150.,    1.],
        [   1.,    1.,    1.,    1.,    1.]],

       [[   1.,    1.,    1.,    1.,    1.],
        [   1.,    1.,    1.,    1.,    1.],
        [   1.,    1.,  160.,  160.,    1.],
        [   1.,    1.,  160.,  160.,    1.],
        [   1.,    1.,    1.,    1.,    1.]],

       [[   1.,    1.,    1.,    1.,    1.],
        [   1.,    1.,    1.,    1.,    1.],
        [   1.,    1.,  170.,  170.,    1.],
        [   1.,    1.,  170.,  170.,    1.],
        [   1.,    1.,    1.,    1.,    1.]]])

Boolean of all places where the values, on the 1st dimension, are [150,160,170].  The key is to expand this to a 3d, shape (3,1,1) that can be broadcast to (3,5,5) and compared with a:
In [53]: I = a==np.array([150,160,170])[:,None,None]

In [54]: I
Out[54]:
array([[[False, False, False, False, False],
        [False, False, False, False, False],
        [False, False,  True,  True, False],
        [False, False,  True,  True, False],
        [False, False, False, False, False]],

       [[False, False, False, False, False],
        [False, False, False, False, False],
        [False, False,  True,  True, False],
        [False, False,  True,  True, False],
        [False, False, False, False, False]],

       [[False, False, False, False, False],
        [False, False, False, False, False],
        [False, False,  True,  True, False],
        [False, False,  True,  True, False],
        [False, False, False, False, False]]], dtype=bool)

Now it's trivial to change all those slots with value True to 0:
In [55]: a[I]=0

In [56]: a
Out[56]:
array([[[ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  0.,  0.,  1.],
        [ 1.,  1.,  0.,  0.,  1.],
        [ 1.,  1.,  1.,  1.,  1.]],

       [[ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  0.,  0.,  1.],
        [ 1.,  1.,  0.,  0.,  1.],
        [ 1.,  1.,  1.,  1.,  1.]],

       [[ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  0.,  0.,  1.],
        [ 1.,  1.,  0.,  0.,  1.],
        [ 1.,  1.,  1.,  1.,  1.]]])

Looking at the comments on a deleted answer I see you really want a case where all 3 values match.  That is, contrary to your example, there may be other slots a[0,...] is 150, etc. that you don't want to change.
You could still work with this I, by just taking an all on the 1st axis:
In [58]: a[:,I.all(axis=0)]=2

In [59]: a
Out[59]:
array([[[ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  2.,  2.,  1.],
        [ 1.,  1.,  2.,  2.,  1.],
        [ 1.,  1.,  1.,  1.,  1.]],

       [[ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  2.,  2.,  1.],
        [ 1.,  1.,  2.,  2.,  1.],
        [ 1.,  1.,  1.,  1.,  1.]],

       [[ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.,  1.],
        [ 1.,  1.,  2.,  2.,  1.],
        [ 1.,  1.,  2.,  2.,  1.],
        [ 1.,  1.,  1.,  1.,  1.]]])

Conceptually my answer is not that different from the accepted one.  That reshapes the array into a 2d, so the matching can be done with a 1d [150,160,170].  Actually it is automatically reshaped to (1,3) which can be broadcast agains (25,3) array.  Transposing and reshaping is a convenient way to standardize the format of problems like this, though it often isn't necessary.

It may help to split that last action up:
In [60]: J=I.all(axis=0)

In [61]: J
Out[61]:
array([[False, False, False, False, False],
       [False, False, False, False, False],
       [False, False,  True,  True, False],
       [False, False,  True,  True, False],
       [False, False, False, False, False]], dtype=bool)

In [62]: a[:, J] = 3

or use np.where to convert the boolean array to 2 list of indices:
In [73]: jj=np.where(J)
In [74]: jj
Out[74]: (array([2, 2, 3, 3], dtype=int32), array([2, 3, 2, 3], dtype=int32))

In [75]: a[:, jj[0], jj[1]] = 4

a[:,jj] doesn't work, but a[(slice(None),)+jj] does.  This last expression constructs a 3 element tuple, the equivalent to [75]'s.
I could also expand J to a size and shape that matches a:
In [90]: K=J[None,...].repeat(3,0)
In [91]: K
Out[91]:
array([[[False, False, False, False, False],
        [False, False, False, False, False],
        [False, False,  True,  True, False],
        [False, False,  True,  True, False],
        [False, False, False, False, False]],

       [[False, False, False, False, False],
        ....]], dtype=bool)

and use a[K].


text:
Q: how to make swift UIview child element shrink automaticaly when parent UIview's constraint is reduced? class ViewController{

    @IBOutlet weak var UiCalendarView: UIView!
    @IBOutlet weak var UiCalendarViewConstraint: NSLayoutConstraint!
    let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: 373, height:300))

    override func viewDidLoad() {
        super.viewDidLoad()
        UiCalendarView.addSubview(self.calendar)
        UiCalendarViewConstraint.constant = 23
    }
}

but UiCalendarViewConstraint.constant change doesn't do much since child component calendar has it's own height and it remains same.

A: You need to add constraints to the child and capture the reference when the size of the parent change you change the constraint of the child based on the height .
But if you pin the child with the parent from top and the bottom it's automatically change when the parent size is changed
let parentView = UIView()
let childView = UIView()
parentView.addSubView(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
parentView.translatesAutoresizingMaskIntoConstraints = false

childView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
childView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
childView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true

This snip of code will let the child the to fill the parentView when you will change the height or width of the parent automatically it's will be resize it.


text:
Q: How to make the drop down open at the position of selected value in angular? I made a drop-down in Angular using select. I want the selected value to be visible in the drop down the first time I click on it, so I don't have to scroll all the way down. For eg I made this dropdown showing years from 1950 to 2020. I want the drop down to open with the default selected year(2010 in my case) visible in it. How can I achieve it?
...
<select>
    <option *ngFor="let year of years" [selected]="year == 2010">{{year}}</option>
</select>

...

A: If you aren't opposed to using Angular Material, mat-select will open the select from the chosen value.
<mat-form-field>
 <mat-select value="2010">
  <mat-option *ngFor="let year of years" [value]="year">{{year}}</mat-option>
 </mat-select>
</mat-form-field>

https://material.angular.io/components/select/overview


text:
Q: Launch file from isolated storage in Windows Phone 8.1 My basic goal is like this:

*

*Get document from URI

*Save it to the isolated storage

*Launch with default app

I have done all code very well,".PDF,.txt" document is also opening, but its content is not appearing. It remains blank. In case of ".docx", I am getting this message:
"Document has been damaged and can't be opened".

See my code below:
String file = "abc.pdf";
Uri uri = new Uri("https://www.abc.com/abcd/getDocument");

WebClient wc = new WebClient();
wc.OpenReadAsync(uri);
wc.OpenReadCompleted += wc_OpenReadCompleted;

async void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
        byte[] buffer = new byte[e.Result.Length];
        await e.Result.ReadAsync(buffer, 0,(int)buffer.Length);

        using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream stream = storageFile.OpenFile(file, FileMode.Create))
            {
                await stream.WriteAsync(buffer, 0, buffer.Length);
                stream.Flush();
            }
        }

        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
        StorageFile pdffile = await local.GetFileAsync(file);

     // Launch the pdf file
     await Windows.System.Launcher.LaunchFileAsync(pdffile);

}

A: Your URI is not correct. Try to use correct URI. This is the only problem. You can verify by bowing the used URI in browser. It does not exist.
Use the same respective extensions for all the files like .pdf for PDF file, for docx file use .docx extension


text:
Q: Using Kendo Mobile, How to Make a View within the Drawer Full Screen? I building a Kendo Mobile App which is using the Kendo Mobile Drawer. I have a need to have a particular view hide and show the drawer navigation buttons / header / footer etc. similar to the Kindle reader app.  So that while the user interacts the view the view fills the full screen and continues until the user touches near the top or bottom of the screen. Then the app needs the navigation buttons etc to reappear.  Any suggestions on how to accomplish this task? Any help would be greatly appreciated.

A: A layout is essentially a view and can be rendered programmatically.  Something like this would work:

You should be able to load a different layout (one without header and footer) and display your content in it.


text:
Q: JavaScript API post and return using Google Sheets script? I need some help with this. I can't figure out how to print the return from an api post sent from Google Sheets (including any error codes). Posting seems to work fine as the data shows up on RequestBin when I run the function in Sheets (although there are no quotes "" around the nonce output, which I don't understand either).
I need to be able to print the return in Google Sheets (this function runs in the Script Editor) and the data needs to overflow into adjacent cells, whatever the post request returns.
This is the functional code that I have so far:
function testPost() {
  var nonce = new Date().getTime();

  var data = {
    'key':'QrHuXeXcbN',
    'signature':'c4cc0d98be8e0860391799c2ca719da5ea6514f1538c4ec69ec1c19',
    'nonce':nonce
  };

  var options = {
   'method' : 'post',
   'contentType': 'application/json',
   'payload' : JSON.stringify(data)
  };

  var response = UrlFetchApp.fetch('https://requestb.in/19bzt9a1', options);
}

I have tried a number of different ways to return the values but I can't figure it out.

A: Got it. Finally. Just needed this at the end... return response.getContentText()
function testPost() {
  var nonce = new Date().getTime();

  var data = {
    'key':'QrHuXeXcbN',
    'signature':'c4cc0d98be8e0860391799c2ca719da5ea6514f1538c4ec69ec1c19',
    'nonce':nonce
  };

  var options = {
   'method' : 'post',
   'contentType': 'application/json',
   'payload' : JSON.stringify(data)
  };

  var response = UrlFetchApp.fetch('https://requestb.in/19bzt9a1', options);
  return response.getContentText()
}


text:
Q: C# how to split a string on the basis of <> character I want to split my text by <> characters.
Example suppose I have a string
 string Name="this <link> is my <name>";

Now I want to split this so that I have a array of string like
ar[0]="this "
ar[1]="<link>"
ar[2]=" is my "
ar[3]="<name>"

I was trying with split function like
string[] ar=Name.Split('<');

I have also tried
 string[] nameArray = Regex.Split(name, "<[^<]+>");

But this is not giving me
 "<link>"
 and "<name>"

But it is not a good approach.
Can I use regular expression here.

A: This
Regex r = new Regex(@"(?<=.)(?=<)|(?<=>)(?=.)");
foreach (var s in r.Split("this_<link>_is_my_<name>"))
{
    Console.WriteLine(s);
}

gives
this_
<link>
_is_my_
<name>

(underscores used for clarity)
The regex splits on a zero-width point (so it doesn't remove anything) which is either:

*

*preceeded by something and followed by <

*preceeded by > and followed by something

The "something" checks are necessary to avoid empty strings at the start or end if your string starts or ends with something in brackets.
Note something like "<link<link>>" will give you { "<link", "<link>", ">" } so try to make your angle brackets balance.
If you want empty strings if the string starts with < or ends with > you can use (?=<)|(?<=>). If you want empty strings in the middle when you encounter ><, I think you need to first split on (?=<) and then split all the results on (?<=>) - I don't think you can do it in one go.


text:
Q: webrtc with python show realtime Temperature on a Web page my project based on a comparison between Websocket and Webrtc .until now its works very well using Websocket , It is a python script that runs a Websocket server  to send the realtime data temperature  to the client.What its next to do  is the same thing using Webrtc :I know that
The Webrtc is based on a triangular and peer-to-peer architecture in which a central server is used to connect two peers wishing to exchange  data streams(temperature)but I'm a beginner and i don't know what schould i change in my coding way.
i was checking out the project"webRTC without browser", but it doesn't describe what I'm looking for. . Is there a way to do it with the current setup or some examples like this project? i will be greatfull if i find someone cann help me to do it rignt .
servertemperature.py
import time
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
from tornado.ioloop import PeriodicCallback
import tornado.web

class WSHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self,origin):
        return True
    def open(self):
        self.callback = PeriodicCallback(self.send_temp, 120)
        self.callback.start()

    def send_hello(self):
        self.write_message('hello')

    def on_message(self, message):
        pass

    def on_close(self):
        self.callback.stop()
        print "Closed Connection"

    def send_temp(self):

        #Change this to the file of your temp probe!

        tfile = open("/sys/bus/w1/devices/28-03139779f433/w1_slave")
        text = tfile.read()
        tfile.close()
        temperaturedata = text.split("\n")[1].split(" ")[9]
        temperature = float(temperaturedata[2:])
        temperature = temperature / 1000 * 9 / 5 + 32
        self.write_message("Current Temperature: {0:.2f}F".format(temperature))
        print temperature
        time.sleep(1)

application = tornado.web.Application([(r'/', WSHandler),])

if _name_ == "_main_":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8080)
    print 'Server begin'
    tornado.ioloop.IOLoop.instance().start()

index.html
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no" />
        <title>BlenderWebController</title>

        <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

                    Warning

Temperature Log

                        <button class="btn btn-warning" type="button" id="close" style="display:inline;float:right;">Close</button>


text:
Q: "Missing method body" error import java.util.Scanner;

public class Rpn_calculator
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        double ans = 0;
        double n = 0;
        double r = 0;
        String j;

        System.out.println();
        System.out.println();
        System.out.print("Please enter a value for n  ");
        n = keyboard.nextDouble();
        System.out.print("Please enter a value for r  ");
        r = keyboard.nextDouble();
        System.out.println("Please choose one of these operands:+,-,*,nCr,/ to     continue, or q to quit ");
        j = keyboard.nextLine();
        while (j != "q")
        {
            if(j == "+")
                ans = n + r;
            if(j == "-")
                ans = n - r;
            if(j == "*")
                ans = n * r;
            if(j == "/")
                ans = n / r;
            if(j == "nCr")
                ans = factorial(n + r -1) / (factorial(r)*factorial(n - 1));
            System.out.print(ans);

            System.out.print("Please enter a value for n  ");
            n = keyboard.nextDouble();
            System.out.print("Please enter a value for r  ");
            r = keyboard.nextDouble();
            System.out.print("Please choose one of these operands:+,-,*,nCr,/ to continue or q to quit ");
            j = keyboard.nextLine();
        }
    }
    public static double factorial(double x);
    {
        double sum = 1;
        int i;
        for (i = 0; i<= x; i++);
        sum = sum * i;

        return sum;
    }
}

I am trying to create an RPN calculator for this assignment, I believe I have what I need to make it function, but I have syntax errors with my factorial function. It says "missing method body".
Also, I don't understand why, when I compile it, my string input request is ignored completely - locking the program in the while loop. I hope I'm not missing something really obvious.

A: There are a couple of semicolons where there shouldn't be:
public static double factorial(double x); // <-- This one
{
    double sum = 1;
    int i;
    for (i = 0; i<= x; i++); // <-- This one
    sum = sum * i;

    return sum;
}

When you put the semicolon right after the signature, you have no method body, hence the error. The for loop wouldn't be a compiler error, but it would be an empty loop.
Also, I think you need to use String.equals to compare strings in Java, as opposed to the == operator.


text:
Q: Disable MVC "must be a number" data type validation for a field I have a Telerik MVC ComboBox which contains a list of locations. The client wants the end user to be able to directly enter new locations into the list.
Upon submitting the form, it should accept a new value and insert into the locations table, and of course update the LocationID of the record being added to the ID of the newly inserted location.
Read below for code snippets
I've read that the ComboBox does allow you to enter in values that are not in the list, and used the demo (Here)
Code to save location, edit locationID is not a problem. My problem here is that my Combo box contains a list of integer/string value pairs, not string/string. And thus, the issue I have in my code is that if I try and submit a new location name, it tries to validate it and says its not a number.
I need a way to try and suppress this validation, just for the LocationID field, but still protect against null values.
BEGIN EDITS
EDIT: I did find this post, but as the OP there says, the javascript hack is not very extensible, so I really want to avoid it.
EDIT:
I ended up using the javascript hack, its all I've found which works. I plan to encapsulate this in a method or attribute, and post it as an answer.
I found that with this hack, it did not work in Firefox or Chrome if I place the code block inside the document ready event using Telerik().ScriptRegistrar().OnDocumentReady(), the properly window.mvcClientValidationmetadata is somehow cleared when it reaches this event, even though the metadata are properly pushed in originally.
To get around this, I had to manually put the code in its own script block just under the form closing tag (which is where the client-side validation array is rendered).
END EDITS
Additionally, right now I'm binding to my model directly like so:
        public JsonResult Create(MyEntity Model)

I'm not sure how that's going to work out when it comes time to do model binding, I'm guessing it may just return an error, and I won't even reach my action method code.
So I guess the idea here would be to use a FormCollection in the method signature, detect for a non-integer LocationID, insert update, and then run UpdateModel()? Of course, welcome to better suggestions.
Thanks!
Code Snippets
Model:
class IntegerValueList
{
    public Int16 ID { get; set; }
    public string Name { get; set; }
}

        var lists = new Dictionary<string, IEnumerable<object>>();

        lists["Locations"] = (from record in db.Locations
                              orderby record.Name
                              select new IntegerValueList
                              {
                                  ID = record.LocationID,
                                  Name = record.Name
                              }).ToList();

Controller:
        LocationList = new SelectList(lists["Locations"], "ID", "Name", LocationID);

View:

                        <%: Html.Telerik().ComboBoxFor(model => model.LocationID)
                                .BindTo(Model.LocationList)
                                .Filterable(c => c.FilterMode(AutoCompleteFilterMode.Contains))
                        %>

                        <%: Html.ValidationMessageFor(model => model.LocationID, "*") %>

A: When I've had to do this in the past, I have used a textbox for the field with a label like "Enter Location", and then a dropdown below it with a label like "Or select...", and then use the onChange event of the dropdown to populate the textbox.  Now you are not validating the dropdown.
You could even put a "Select" link next to the textbox and have the dropdown hidden until the link is clicked.  The drawbback is that we could end up with San Diego, SanDiego and Sandiego all entered in the location list...but then your customer's requirement doesn't let us explicitly prevent that.


text:
Q: Is it possible to use 'use as' for namespaces in a .phtml file? In a .phtml file, is it okay to do the following?
<?php use App\Library as Lib; ?>

<?php Lib::getTitle(); ?>
....
I have a .phtml file that uses a Utility class to make dropdowns and whatnot, didn't want to have to type out the whole namespace for everything.
Thanks in advance for the help.

A: If you've configured your server like so, using .phtml file should be strictly identical as using .php files.
See this question (if you're running Apache).


text:
Q: Обнаружение файлов в папке Допустим у меня есть программа проходящая по всему тексту. Текст подкрепплен к проекту файлом .txt, но мне надо что бы данная программа проходила не один текст а кучу различных. Можно ли создать допустим папку в которой будет куча различных текстов формата pdf или еще какого и что бы прога понимала что там появились новые тексты и их тоже считывала? Подскажите как такое реализовать и как лучше сделать.

A: Если вы хотите получать уведомления об изменении файлов в какой-то папке, то вы можете воспользоваться WatchService (туториал).
Если вы хотите дать возможность пользователю выбрать несколько файлов для обработки, то вы можете воспользоваться FileDialog или JFileChooser в режиме выбора нескольких файлов.
Для чтения PDF есть несколько библиотек, выбирайте на свой вкус. То же касается и остальных форматов файлов.


text:
Q: MailChimp API resubscribe confirmation mail not longer sending When a contact with status unsubscribed tries to subscribe with the same mail address again, I send a PUT request with status pending in order to trigger the opt-in process.
Suddenly the confirmation mail stopped from being sent. The contact switched from unsubscribed to pending, but has no chance to confirm its subscription.
This is a shortened version of the code:
<?php
$member_response = $MailChimp->get("lists/$list_id/members/$subscriber_hash"); // <-- Returns an array where status is `unsubscribed`

if($member_response['status'] == 'unsubscribed' || $member_response['status'] == 'pending') {
  // User exists but is not active. Do a PUT request with new values to trigger re-opt-in
  $update_response = $MailChimp->put("lists/$list_id/members/$subscriber_hash", $member_data); // <-- Returns an array where status is `pending`
}
?>

Shouldn´t the confirmation mail being sent when setting an existing subscriber to pending again?
Do I overlook something?

A: To follow up on my previous comment, here's a summary of the answers I got from MailChimp earlier this month.

*

*This (unannounced) change, unrelated to v3 API, was made in September 2016.

*When a user unsubscribes, they can't be resubscribed by you.  We already knew that, but the trick with changing 'status' back to 'pending' which used to trigger a new email every time you made an API request no longer works - emails are now throttled.  Originally MailChimp told me the exact rate was on a list by list basis, but when I followed up they later said it was 48 hours after the first attempt (and any subsequent attempts during that period would reset the timer.)

*MailChimp confirmed there is no logging of the confirmation request emails,  or a way in the API / admin UI to determine if they were sent (other than knowing that when a subscriber is set to pending the first time the email will automatically be sent.)

*It seems to me it is now possible to re-add users manually via admin.mailchimp.com, regardless of their previous status – I'm not sure this worked before. Curiously, this changes someone's status back to subscribed without requiring any confirmation by them. (if I can do that via the UI, why can't I do it via the API, etc.)

*I asked if addresses identical except for a the use of a plus sign, e.g. foo@example.com and foo+bar@example.com would be counted as two separate addresses given they produce different subscriber hashes, as used in the API endpoints. (During testing, I frequently use my one address and change the end of it to denote the date, use a counter etc.)  They actually told me they're not counted as uniques: the algorithm that controls signup limits resolves them to the same address, which I wasn't expecting.

*Finally, their API helpdesk (who send prompt and courteous responses - you don't need to have an account to write to them either) have the ability to manually check the status of an individual address for you on an ad-hoc basis.
Personal Opinion:
My impression is MailChimp would like to push people towards using their 3rd-party hosted / embeddable forms for handling signups, rather than using the API.
Reading between the lines, I wonder if they have been on the receiving end of a large number of spam complaints / blacklisting, given the free-tier and the number of customers they now have.
Although the v3 API is a big improvement in architecture over the previous version, updating code (including, in my case, a WordPress plugin) to use it was a fair bit of work, and there have been multiple unannounced and/or short notice disruptive changes with MailChimp products in recent year; the discontinuation of Mandrill, outdated security certificates on API servers, etc.
Actually, I'm struggling to think of another 3rd-party service which has repeatedly required this much development time just to keep a small group of API features operational (subscription, unsubscription and interest groups, in the case of my clients).  This is less a comment on the quality of the product and more the workload it generates for developers.
It's quite possible this will continue to be the case, so I'd encourage people to think carefully before selecting a bulk email service if you don't want to have to deal with situations where, for example, you can't detect if and when someone was sent an opt-in confirmation.


text:
Q: Search for several patterns at the same time in a list of text files I have a folder with text files, and want to search inside all the text files, if they have certain words at the same time, not necessarily in the same line. I've tried with grep but works line by line:
file-1.txt:
You shall find of the king a husband, madam; you,
sir, a father: he that so generally is at all times
good must of necessity hold his virtue to you; whose
worthiness would stir it up where it wanted rather
than lack it where there is such abundance.

file-2.txt:
He was excellent necessity, madam: the father very
lately spoke of him admiringly and mourningly: he
was skilful enough to have lived still, if knowledge
could be set up against mortality.
He hath abandoned his physicians, king; under whose
practises he hath persecuted time with hope, and
finds no other advantage in the process but only the
losing of hope by time.

I want to detect if king and father are present in the same file.
The code I've tried is:
for file in file-*.txt; do grep -E 'king.*father' "$file" && echo $file; done

But no luck. Any help?

A: You have two problems here:
A) grep -E still won't work across lines. Using -z will help, making all the file count as one line:
for file in file-*.txt; do grep -z  'king.*father' "$file" && echo $file; done

*

*This will match file-1.txt

B) Do I understand you'll need the words in different order too? For that you'll need egrep, and specifying both expressions inside a (), separated by a |:
for file in file-*.txt; do egrep -z  '(king.*father|father.*king)' "$file" && echo $file; done

A: Answering my own question, @Technologeeks answer is on point:
for file in file-*.txt; do egrep -z  '(king.*father|father.*king)' "$file" && echo $file; done

However, to search for lots of words at the same time:
for file in file-*.txt; do grep -q 'king' "$file" && grep -q 'father' "$file" && grep -q 'freedom' "$file" && grep -q 'matter' "$file" && echo $file; done

Can be done also with -z on each grep. Also add -q on last one:
for file in file-*.txt; do cat "$file" | grep -z father | grep -z king | grep -z -q time && echo "$file" ; done


text:
Q: Inverse z-Transformation and impulse response I have a question regarding a pole zero plot and I want to compute the impulse response with the inverse z-Transform.
From the pole zero plot I could extract:
$$H(z) = \frac{z+1}{(z-0.6i)(z+0.6i)}$$
How can I get $h[n]$?
If I use partial fraction expansion I get something complex for $A_1$ and $A_2$ and that doesn't make sense, at least to me.

A: Partial fractions will work and the end result will be real valued:
$$H(z)=\frac{Az}{z-0.6i}+\frac{A^*z}{z+0.6i}\tag{1}$$
where $A=0.5-i\cdot 5/6$, and $^*$ denotes complex conjugation. The inverse $\mathcal{Z}$-transform of $(1)$ is
$$\begin{align}h[n]&=\left[A(0.6i)^n+A^*(-0.6i)^n\right]u[n]\\&=\left[A(0.6)^ne^{in\pi/2}+A^*(0.6)^ne^{-in\pi/2}\right]u[n]\\&=2\,\text{Re}\left\{A(0.6)^ne^{in\pi/2}\right\}u[n]\\&=2(0.6)^n|A|\cos\left(\frac{n\pi}{2}+\arg(A)\right)\tag{2}\end{align}$$
which is real-valued, as it should be.


text:
Q: Laravel Passport Overriding Primary key is not working
*

*I am using user_sk as primary key in users table

*When authenticate with passport its not overriding primary key from model

*Already palced User model have protected $primaryKey = 'user_sk';

Its always shows error like this

"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `users` where `id` = 32 limit 1)"

A: It seems it is probably a relation that is breaking your code, based on the following question, this can not be marked as duplicate since the question has not accepted the answer.
Add the following to your User.php model and see if it helps.
public function clients() {
    return $this->hasMany(Passport::clientModel(), 'user_id', 'user_sk');
}


text:
Q: How to load dataset with pandas dataframes into Spacy? I currently have text data with pandas dataframe. I would like to do part of speech tags with Spacy library. But I don't know how to import load data from pandas into Spacy.
Does anybody know how to load data from pandas dataframe into Spacy? Thank you!
Here is my dataset:

df = pd.concat([jsons_data,label],axis=1)

text    title   authors label
0   On Saturday, September 17 at 8:30 pm EST, an e...   Another Terrorist Attack in NYC…Why Are we STI...   [View All Posts, Leonora Cravotta]  Real
1   Story highlights "This, though, is certain: to...   Hillary Clinton on police shootings: 'too many...   [Mj Lee, Cnn National Politics Reporter]    Real
2   Critical Counties is a CNN series exploring 11...   Critical counties: Wake County, NC, could put ...   [Joyce Tseng, Eli Watkins]  Real
3   McCain Criticized Trump for Arpaio's Pardon… S...   NFL Superstar Unleashes 4 Word Bombshell on Re...   []  Real
4   Story highlights Obams reaffirms US commitment...   Obama in NYC: 'We all have a role to play' in ...   [Kevin Liptak, Cnn White House Producer]    Real
5   Obama weighs in on the debate\n\nPresident Bar...   Obama weighs in on the debate   [Brianna Ehley, Jack Shafer]

This is my code to load data into Spacy:
import spacy
from dframcy import DframCy
nlp = spacy.load('en_core_web_sm')
dframcy = DframCy(nlp)
doc = dframcy.nlp(df)
annotation_dataframe = dframcy.to_dataframe(doc)

TypeError: Argument 'string' has incorrect type (expected str, got DataFrame)


text:
Q: Discord JS, Await Message, different inputs I am making a discord bot, choose your own adventure kind of style game. I'm using one command to start it, then Await messages to allow 3 more different responses. I'm using If statements with the response to determine what to do next, however if the message isn't equal to one of the responses then nothing happens.
const embed = new discord.RichEmbed()
            .setTitle("__**The Jungle!**__")
            .setColor("#49499c")
            .setDescription("a Pond\nExplore a Tree\nFollow a trail")
            //.attachFiles(["./pictures/Jungle.jpg"])
        const filter = response => {
            return response.author.id === message.author.id;
            }
        message.channel.send(embed).then(() => {
            message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] })
                .then(collected => {
                    if (collected.first()=="Explore a Pond")
                    {
                        Pond.execute(message, args, client);
                    }
                    else if (collected.first()=="Explore a Tree")
                    {
                        Tree.execute(message, args, client);
                    }
                    else if (collected.first()=="Follow a Trail")
                    {
                        Trail.execute(message, args, client);
                    }
                })
                .catch(collected => {
                    message.channel.send('Time up');
                });
        });

So I need some sort of catch, and let them try again. Preferably when they input wrong, it would let them put in another input until it's correct. So I imagine it would go up to before the await message again.
Any ideas or help would be great. Thanks.

A: You could make your code loop itself by calling a function :
const question = function (message) {
    message.channel.send(embed).then(() => {
    message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] })
    .then(collected => {
        if (collected.first()=="Explore a Pond") { Pond.execute(message, args, client); }
        else if (collected.first()=="Explore a Tree") { Tree.execute(message, args, client); }
        else if (collected.first()=="Follow a Trail") { Trail.execute(message, args, client); }
        else { message.channel.send("Could not find this answer"); return question(message); }
    })
     .catch(collected => { message.channel.send('Time up'); }); });
}

Please tell if me you encounter any kind of problems with this :)


text:
Q: Elegant way to code generated coffeescript in ruby? I have the following which converts a coffeescript when ...../coffee/xxxx.js is called. For example I am trying to load variables which compliments the script to be loaded. should I load it in a separate js file or any elegant way of injecting it as coffee script as well?
get "/coffee/*.js" do
    filename = params[:splat].first
    coffee "../public/coffee/#{filename}".to_sym
end


text:
Q: ICEFaces Security I have 2 security concerns that my client has come up with and I am stuck.
In order to avoid browsers caching sensitive information, the client's security guidlines require that POST requests do not return 200 response.  Initially I set up a phaseListener to deal with this but the only requests that came through were GETs.  I discovered that the POST request the client's security team were complaining about were ajax calls to the BlockingServlet.  How can I set up something similar for this?  I don't really understand how icefaces deals with the information stored on a form and how I can ensure that this info is not stored by the browser.  I have implemented the no-cache headers but that's not exactly solid security.
The phaseListener I used was basically http://balusc.blogspot.com/2007/03/post-redirect-get-pattern.html
The client is also concerned that input parameters are not properly validated providing a entry point for XSS. The example they gave was also going through the blockingServlet.  I suspect that ICEFaces has something built in to deal with this but I can't find any information about it.  Can anyone help?

A: XSS is an output problem,  you can't cram all input data though some magic function and expect your application to be 100% safe from xss.  This will never work for any application,  because XSS just doesn't work that way.   Make sure you test your application for vulnerability like XSS and SQL Injection,  there are free solutions like Sitewatch and the open source skipfish.
To prevent caching make sure this http header element is set:
Cache-Control: no-store
No other method should be used.


text:
Q: How to work with SOAP attachment? I need to work with SOAP attachment in .NET, if anyone know how to do that please let me know with an example.

A: You will have to be more clear about what you mean when you say "SOAP Attachment". If you are referring to "SOAP with Attachments", then you are referring to an obsolete technology which is not supported by .NET.


text:
Q: Connecting an arduino, accelerometer and a camera I am look at using accelerometer(s) as a wearable sensor to track the acceleration of someone's leg while they perform various motions. I would like to video/ take photos of the subject whilst the accelerometer(s) are collecting data. Is there someway to sync the camera with the data from the accelerometer? In order to draw the acceleration vectors on a frames/image from the camera. Therefore, the camera an accelerometer would have to be synchronised to be in real time. Could I use MATLAB?

A: I have actually done something similar in the past and it might give you a starting point.
I synchronized the video from a webcam and accelerometer data from an IMU connected to an arduino. I ended up programming most if it in Java but that's not really necessary you could probably do it in Matlab.
Assuming that you have already programmed the arduino to sample the accelerometer, you can send that data to a PC via a serial connection. Then you would connect the camera to the same PC, and use Matlab to start recording from both of them simultaneously.
It's far to complicated for me to explain all of the details in this post but I hope this gives you an idea of how to begin.
Goodluck!


text:
Q: Error: entitled_product_ids:expected Hash to be a Array (Shopify embedded app) I am sending the following request through cURL, all is going fine but there is an error with "entitled_product_id". It works fine in postman but not in cURL.
Thanks in advance.
cURL request code is
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pro_ids11));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Shopify-Access-Token: '.$shops_token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_error($ch)) {
    $error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
    echo $error_msg;
}

My json_encoded code is:
{
  "price_rule":
  {
    "title":"sad",
    "target_type":"line_item",
    "target_selection":"entitled",
    "allocation_method":"across",
    "value_type":"percentage",
    "value":"-3",
    "customer_selection":"all",
    "prerequisite_quantity_range":{"greater_than_or_equal_to":"2"},
    "entitled_product_ids":["2389482225165"],
    "starts_at":"2019-02-20T11:37:57.000Z"
  }
}

Response:
{
  "errors":
    {
      "entitled_product_ids":"expected Hash to be a Array"
    }
}


text:
Q: Программа почему-то выдает ошибки Условие задачи:
Написать статический метод int countCapitals(String s), который возвращает, сколько слов в строке s начинаются с заглавной буквы.
Заглавной буквой считается символ (Character) типа UPPERCASE_LETTER или типа TITLECASE_LETTER. Словом считается последовательность букв или цифр, разделённых одним или несколькими пробельными символами (whitespace), знаками (symbol) или знаками пунктуации (punctuation).
import java.util.Scanner;

public class P33 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        System.out.println(countCapitals(s));
    }
    static int countCapitals(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if ((Character.isUpperCase(s.charAt(i)) || Character.isTitleCase(s.charAt(i))) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)) || checkSymbol(s.charAt(i - 1)))) {
                count++;
            }
        }
        return count;
    }
    private static boolean checkSymbol(char c) {
        char[] symbols = {'.', ',', '-', ':', ';', '?', '!'};
        for(int i = 0; i < symbols.length; i++){
            if(symbols[i] == c){
                return true;
            }
        }
        return false;
    }
}


text:
Q: Python hex digest to integer Many online gambling games use a function that converts a hash into a decimal from 0-(usually 2^52).
Here's some code I grabbed that works fine, but I don't understand why it works:
def get_result(hash):
    hm = hmac.new(str.encode(hash),b'', hashlib.sha256) #hashing object

    h = hm.hexdigest() #hex digest, 32 bytes 256 bit
    print(h) #Something like 848ab848c6486d4f64
    c = int(h,16)
    print(c) #numbers only, 77 numbers long...?
    if (c % 33 == 0):
        return 1
    h = int(h[:13],16)
    return (((100 * E - h) / (E - h)) // 1) / 100.0

The part of the code that I don't understand is the conversion from h to c. h is a hex digest, so it is base-16. The python documentation says that the int(a,b) function converts the string a into a base-b integer. Here's my question:

*

*How can an integer number be base-16? Isn't the definition of decimal base-10 (0-9)? Where do the extra 6 come from?

*As far as I'm aware, a single hex digit can be stored by 4 bits, or 1/2 a byte. So a hex string of 64 length will occupy 32 bytes. Does this mean that any base of this data will also be 32 bytes? (converting the hex string to base-n, n being anything)

*What does the fact that the c variable is always 77 digits long mean?

A:
How can an integer number be base-16? Where do the extra 6 come from?

This is known as the hexadecimal system.

Isn't the definition of decimal base-10 (0-9)?

Integer and decimal are not synonyms. You can have a integer in base 2 instead of base 10.

As far as I'm aware, a single hex digit can be stored by 4 bits, or 1/2 a byte. So a hex string of 64 length will occupy 32 bytes.

There are two different concepts: a hex string and a hex integer.
When you type in Python, for example, "8ff", you're creating a hex string of length 3. A string is an array of characters. A character is (under the hood) a 1-byte integer. Therefore, you're storing 3 bytes¹ (about your second statement, a hex string of length 64 will actually occupy 64 bytes).
Now, when you type in Python 0x8ff, you're creating a hex integer of 3 digits. If you print it, it'll show 2303, because of the conversion from base-16 (8ff, hex) to base-10 (2303, dec). A single integer stores 4 bytes², so you're storing 4 bytes.

Does this mean that any base of this data will also be 32 bytes? (converting the hex string to base-n, n being anything)

It depends, what type of data?

*

*A string of length 3 will always occupy 3 bytes (let's ignore Unicode), it doesn't matter if its "8ff" or "123".

*A string of length 10 will always occupy 10 bytes, it doesn't matter if its "85d8afff" or "ef08c0e38e".

*An integer will always occupy 4 bytes³, it doesn't matter if its 10 or 1000000.

What does the fact that the c variable is always 77 digits long mean?

As @flakes noted, that's because 2^256 ~= 1.16e+77 in decimal.

¹ Actually a string of length 3 stores 4 bytes: three for its characters and one for the null terminator.
¹ Let's ignore that integers in Python are unbounded.
² If it's lesser than 2,147,483,647 (signed) or 4,294,967,295 (unsigned).


text:
Q: Y offset position and active class state I'm trying to get the Y offset positions of the sections in viewport and adding an active state to the equivalent menu item, but it does not work, any help please?
// Get the Y offset position of the sections in viewport
const allSections = document.querySelectorAll("allSections");

allSections.forEach( (section) => {
     allSections.scrollingElement.scrollTop = section.offsetTop;
     section.innerText = "Y offset after scrolling: " +
                 allSections.contentWindow.pageYOffset + " pixels";

     allSections.classList.add('active');

} )

HTML

Section 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

CSS
.navbar__menu li:hover {
    display: inline-block;
    background-color: #ff6666;
}

.navbar__menu li:active active {
    display: inline-block;
    background-color: #808080;
}


text:
Q: .net 4.0 Code Contracts. When to use? When are they a waste of time? I have been studying .NET 4.0 Code Contracts and looking on stackoverflow as well at question regarding this.
I still have never come across any sample code that uses code contracts so that gets me wondering.. is this really useful ?  Or maybe its only useful one your code reaches a certain complexity? Anyone out there using Code Contracts and really glad they did?
Seems to me that all Code Contracts are is a Assertion on what goes in and what goes out of a method with the addition of being able to try to figure out the values going in and out at compile time... But then this is going to require more code on all your methods.. is it worth it ?
A benefit I noticed is it seems to me you can use code contracts kind of as a first line of unit testing... then when you write unit test to can avoid writing some of the more basic tests because the Code Contracts cover it already.. is that true ?
Will contracts work with WCF calls? I am guessing not since a proxy is created with you automatically that you cant change.

A: I use them anytime i need to validate that an input parameter needs to have a specific value (number is positive, object is not null).
For outputs, I use them anytime I am certain that a return value should be in a certain state (not null for example).
Having contracts in the code ensures that an exception will be thrown the moment that an unexpected value crops up, and not further down in the code where objects may accidentally be left in a corrupted state because of an accidental assumption.
Personally, I think it makes the code a lot cleaner.  The notation makes it a lot less to write (instead of using if(....== null)....).  This way too Contract.Requires is very up front in what it is trying to accomplish.  When I see that I know that the code is evaluating that a parameter is in a certain state.

A: there is field of study on contracts: http://en.wikipedia.org/wiki/Design_by_contract it was long before they were introduced in .net.
Code contracts are useful to give answers to following questions:

*

*What does method expect?

*What does method guarantee?

*What does method maintain?

If you can write small and readable contract for those questions then use it.

A: One of the primary reasons to use CodeContracts is to enable Static Analysis to detect violations of the CodeContracts so they're caught early rather than resulting in bugs or unknown behavior at runtime.
You can disable runtime enforcement of CodeContracts if you want to.
Another good reason to use them is to add Contract definitions to XML Code Comments to enhance API documentation. This also works with Sandcastle though there are some tweaks necessary to integrate them fully.  Refer to section 8.3 in the Code Contracts User Manual dated 2/4/2011 (or later) available at http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf


text:
Q: Using bold or italics within a word in a comment does not work I just tried to comment multiple times on "November 2011 Moderator Election: Town Hall Chat (scheduled)".
The intended comment was to be rendered as:

not "maderator nominations"

But instead, it was rendered as:
not "m**a**derator nominations"

I also tried the following variants, with no effect (rendered as you see here):
not "m*a*derator nominations"
not 'm**a**derator nominations'
not 'm*a*derator nominations'

Note there were other posts about similar behavior, but they were either marked as status-completed or were specific to placement of the bold/italics in relation to the quotes (usually right before/after them).

A: This has nothing to do with the quote signs. Nor with comments, for that matter; as you observed when posting your question, it's not working in regular post Markdown either -- just that here, you have the HTML tag workaround.
As for the reasons that this isn't working (which is indeed intentional), I refer you to Three Markdown Gotchas (in particular, point 1) and its follow-up Markdown, One Year Later.


text:
Q: Python - start writing into the second row of a text file I want to start writing into the second row of my text file.
Here is what I currently have (but this starts at the bottom of the file):
predicted_inp = input("What did you expect answer should be?")
actions[a] = predicted_inp
f = open("training.txt", "a")
f.write(""+predicted_inp+"" + ':' + ""+a+""+",", file=f)[1]
f.close()

Dismiss the input filed and the second line.

A: a is for appending to the end of a file.
Read the whole file into a list, replace the second element of the list, then write it all back out.
with open("training.txt", "r") as f:
    lines = f.readlines()
    lines[1] = f"{predicted_inp}:{a}\n"
with open("training.txt", "w") as f:
    f.writelines(lines)


text:
Q: How to declare a IntPtr? I have a Window handle Picker and it says my handle is 0094167C.
When I declare the variable in c# the letter in this code gives an error.
How to declare?
public const IntPtr WinHandle = 0094167C;

A: You know that the handle will typically change with each application and/or system start? This means your constant is subject to failure anyway.
If, however, you really want to assign a constant other than zero to an IntPtr (which would be IntPtr.Zero), the documentation states that there are constructors that take Int32, Int64 or Void* as parameter.

A: As OregonGhost points out you probably don't want to do that for a windows handle. However, for a IntPtr in general, what you can do is this static readonly fields:
static readonly IntPtr TenK = new IntPtr(1024 * 10000);

A: I'd like to add to AgnosticOracle's answer.
In addition to constant-like static-readonly IntPtr/UIntPtr variables, you can use nint and nuint which are backed by IntPtr and UIntPtr, respectively.
These types can have integer and unsigned integer values assigned to them and can also be defined as constants.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types#native-sized-integers


text:
Q: Issue parsing both values in JSON array | PHP I have the following JSON array, unfortunately the objects are not being nested in a larger parent so I am unsure how to parse the object.
JSON Array:
[{"name":"Jacob","id":4},{"name":"Mandy","id":3}]

Currently I have done the following, which is just echoing 0 and 1:
$json = '[{"name":"Jacob","id":4},{"name":"Mandy","id":3}]';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo $key;
}

But I would like to access the values of name and id on every foreach, how can the be done?

A: echo $value["id"]." ".$value["name"];

should do it (within your loop), just like any associative array values.

A: This works for me:
$json = '[{"name":"Jacob","id":4},{"name":"Mandy","id":3}]';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    $name = $value['name'];
    $id = $value['id'];

    // do whatever you want with $name and $id
}


text:
Q: How to create whole solution from published files of an asp.net core 3.1 project? I lost one week of development because of not committing my code. I work on a personal project and I lost my code I only have the published version of my asp.net core 3.1 project. and my code is not obfuscated.
I use DotPeek to open my main dll and I get controllers but there are no views in there ? I wonder to know, is there any way for me to create a solution like I had without creating views by my hand?
Is it possible to completely regenerate Visual Studio solution folder for this project from Published files?


text:
Q: play an avi video file in java swing I need to play an avi video file and add it to a jpanel.  All I need to be able to do is to play from beginning to end of the video and then proceed with my program.  I don't need any seek functions or anything like that.  What is the simplest way of doing this? preferbly without using xuggler if possible

A: It easy to embed the VLC player inside a swing application using VLCJ. Here is a working example:
 public class PlayerPanel extends JPanel {

     private File vlcInstallPath = new File("D:/vlc");
     private EmbeddedMediaPlayer player;

     public PlayerPanel() {
         NativeLibrary.addSearchPath("libvlc", vlcInstallPath.getAbsolutePath());
         EmbeddedMediaPlayerComponent videoCanvas = new EmbeddedMediaPlayerComponent();
         this.setLayout(new BorderLayout());
         this.add(videoCanvas, BorderLayout.CENTER);
         this.player = videoCanvas.getMediaPlayer();
     }

     public void play(String media) {
         player.prepareMedia(media);
         player.parseMedia();
         player.play();
     }
 }

 class VideoPlayer extends JFrame {

     public VideoPlayer() {
          PlayerPanel player = new PlayerPanel();
          this.setTitle("Swing Video Player");
          this.setDefaultCloseOperation(EXIT_ON_CLOSE);
          this.setLayout(new BorderLayout());
          this.setSize(640, 480);
          this.setLocationRelativeTo(null);
          this.add(player, BorderLayout.CENTER);
          this.validate();
          this.setVisible(true);

          player.play("http://174.132.240.162:8000/;stream.nsv");
     }

      public static void main(String[] args) {
          new VideoPlayer();
      }
 }


text:
Q: Identify a story in which Superman marries a witch I vaguely recall the following:

*

*The comic was from the 1970's (could even be the 1960's) silver age type

*It was a 'what if/untold story' type scenario

*Superman falls in love with a girl get married

*The girl reveals herself to be a witch by casting a spell and transforming herself

*She dies during childbirth?

*But a son is born to Superman

*Superman is crying and holding his baby son wrapped in cloth

Can this DC comic be identified?

A: This is probably "The Satanic Son of Superman", printed in Action Comics #410 in 1972. The portion you're remembering is actually a very small segment of the issue, serving as a backstory for the issue's villain (Superman's son's evil twin, and no I'm not making that up).

*

*Superman falls in love and gets married

Relevant transcript:

But as you suspend your monumental burden in space, Superman, your troubled mind wanders once again...through the misty realms of cherished memories to a happier time, years ago...
When you and your young wife were discussing the future of your soon-to-be-born child...
Krysalla: Darling, there's something about myself I must tell you...something I'm afraid might...affect our baby!

Neither actually shown, but check

*His wife turns out to be a witch

Relevant transcript:

At first you wouldn't believe your eyes as she backed away from you...
Krysalla: I...I am a witch. See?

*She dies in childbirth, gives Superman a son, Superman is holding the baby crying

Relevant transcript:

Doctor: I'm sorry, Superman! We tried everything possible to save her! But your newborn son is alive and healthy!

*It was a what-if

Relevant transcript:

The end of an imaginary story that hasn't happened yet -- but who can tell? Someday it might!


text:
Q: Create new instance of Child class from Base class in Typescript I want to create new instance of Child class from Base class method.
It's a little bit complicated, but i will try to explain.
Here's an example:
class Base(){
    constructor(){}

    clone(){
        //Here i want to create new instance
    }
}

class Child extends Base(){}

var bar = new Child();
var cloned = bar.clone();

clone instanceof Child //should be true!

So. From this example i want to clone my bar instance, that should be instance of Child
Well. I'm trying following in Bar.clone method:
clone(){
    return new this.constructor()
}

...And this works in compiled code, but i have typescript error:
error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
Any ideas how i can handle this?
Thank you. Hope this helps some1 :)

A: You need to cast to a generic object when cloning an unknown object.
The best way to do this is to use the <any> statement.
class Base {
    constructor() {

    }

    public clone() {
        return new (<any>this.constructor);
    }
}

class Child extends Base {

    test:string;

    constructor() {
        this.test = 'test string';
        super();
    }
}

var bar = new Child();
var cloned = bar.clone();

console.log(cloned instanceof Child); // returns 'true'
console.log(cloned.test); // returns 'test string'


text:
Q: How can I get better names for function parameters I am new to android programming and I see in tutorials people have better parameters names for example in ExpandableListView in getView function parameters are like groupPosition, parent and so but in my Android Studio they are i, i1 which is really non intuitive.

A: If you press Alt+Insert on Windows or CMD+n on OSX you can can generate some methods: getters, setters, constructors.... and Override methods. If you you click on it and choose the method you want you will have the right names.
You even have a shortcut on Windows: Ctrl+O. On OSX it is ^+O


text:
Q: Ajax image page transition I just saw a really cool page transition on Behance where you click a image and it just expands to a new div (I think) with a with of 50%. Can someone explain to me how to make this work or have an example? Transition here:
https://vimeo.com/162486588

A: You can use css transitions if you like. Check the example that I wrote for you.
.normal {
    float: left;
    margin-right: 10px;
    width: 10%;
    height: auto;
    transition: width 2s, height 2s;
}

.transition {
    width: 50%;
    height: auto;
}

Basically they work by defining 'start' values (in our case width & height inside .normal) and also a definition of how to make the transition and what properties to apply it to (in our case width and height with 2s duration each).
If you now add a class to the element that has the properties with different values (in our case .transition), they'll be animated to the new value.
To complete the example, I also added some text that is faded in after the transition has been completed.
The javascript part is fairly simple: When clicking the image, add the .transition class, then wait for 2 seconds (the transition duration) and finally fade in the text.
$('img').click(function() {
    $(this).addClass('transition');
    setTimeout(function() {
            $('.text').fadeIn();
    }, 2000);
});


text:
Q: IIS 8.5 re-directing to wrong site when using https I've got a weird problem with a server running IIS.
The server is running a number of websites (on different IP addresses), some of these use SSL and some don't.  The problem comes when you try to access a website using https when that site doesn't have any bindings for https.  The server automatically re-directs to another site on the server  that does have https (always the same site on it's own IP address).  There are no URL re-write rules and no special config that I can see anywhere.  I've tried to put in a re-write rule as a test for one of the sites, but it just gets ignored.  I'm unable to see how it's managing to do this.  Does anyone have any ideas?
Thanks,
Stuart

A: Make sure the bindings on the websites are all set to not have an asterisk on the IP Address. This is the default behavior for the Default Web Site in IIS.


text:
Q: Exception while getting the source code of a webpage I have tried both of the following methods to get the source code of a webpage and neither were able to open the webpage. Both methods through the exception remote sever 403 forbidden
string htmlstring = String.Empty;
WebClient wc = new WebClient();
htmlstring = wc.DownloadString(website);

and
string htmlstring = String.Empty;
WebRequest request = WebRequest.Create(website);
WebResponse response = request.GetResponse();
Stream dt = response.GetResponseStream();
StreamReader sr = new StreamReader(dt);
htmlstring = sr.ReadToEnd();


text:
Q: fail2ban running on CentOS 7 & getting "ssh connection refused" Is anyone successfully running fail2ban on CentOS 7 and can tell me how to do it?
I tried to install fail2ban with yum install fail2ban and run it (there are no extra rules in iptables -L which seems odd according to what I found on the net).
As soon as I reboot the server I can't login as root or other user via ssh. The ports are not visible when scanning and of course I get this error when I try to connect:
ssh: connect to host XXX.XXX.XXX.XXX port 12321: Connection refused

I changed the ssh port, but I also tried it with port 22 without luck.
I wonder if someone knows a solutions to this problem?
It has to be a problem with fail2ban because I didn't install anything else.

UPDATE
I can log in via ssh after reboot. But no html page is served. Output of iptables -L:

Chain INPUT (policy ACCEPT) target     prot opt source
  destination          f2b-sshd   tcp  --  anywhere             anywhere
  multiport dports ssh ACCEPT     all  --  anywhere             anywhere
  ctstate RELATED,ESTABLISHED ACCEPT     all  --  anywhere
  anywhere             INPUT_direct  all  --  anywhere
  anywhere             INPUT_ZONES_SOURCE  all  --  anywhere
  anywhere             INPUT_ZONES  all  --  anywhere
  anywhere             ACCEPT     icmp --  anywhere             anywhere
  REJECT     all  --  anywhere             anywhere
  reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT) target     prot opt source
  destination          ACCEPT     all  --  anywhere             anywhere
  ctstate RELATED,ESTABLISHED ACCEPT     all  --  anywhere
  anywhere             FORWARD_direct  all  --  anywhere
  anywhere             FORWARD_IN_ZONES_SOURCE  all  --  anywhere
  anywhere             FORWARD_IN_ZONES  all  --  anywhere
  anywhere             FORWARD_OUT_ZONES_SOURCE  all  --  anywhere
  anywhere             FORWARD_OUT_ZONES  all  --  anywhere
  anywhere             ACCEPT     icmp --  anywhere             anywhere
  REJECT     all  --  anywhere             anywhere
  reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT) target     prot opt source
  destination          OUTPUT_direct  all  --  anywhere
  anywhere
Chain FORWARD_IN_ZONES (1 references) target     prot opt source
  destination          FWDI_public  all  --  anywhere
  anywhere            [goto]  FWDI_public  all  --  anywhere
  anywhere            [goto]
Chain FORWARD_IN_ZONES_SOURCE (1 references) target     prot opt
  source               destination
Chain FORWARD_OUT_ZONES (1 references) target     prot opt source
  destination          FWDO_public  all  --  anywhere
  anywhere            [goto]  FWDO_public  all  --  anywhere
  anywhere            [goto]
Chain FORWARD_OUT_ZONES_SOURCE (1 references) target     prot opt
  source               destination
Chain FORWARD_direct (1 references) target     prot opt source
  destination
Chain FWDI_public (2 references) target     prot opt source
  destination          FWDI_public_log  all  --  anywhere
  anywhere             FWDI_public_deny  all  --  anywhere
  anywhere             FWDI_public_allow  all  --  anywhere
  anywhere
Chain FWDI_public_allow (1 references) target     prot opt source
  destination
Chain FWDI_public_deny (1 references) target     prot opt source
  destination
Chain FWDI_public_log (1 references) target     prot opt source
  destination
Chain FWDO_public (2 references) target     prot opt source
  destination          FWDO_public_log  all  --  anywhere
  anywhere             FWDO_public_deny  all  --  anywhere
  anywhere             FWDO_public_allow  all  --  anywhere
  anywhere
Chain FWDO_public_allow (1 references) target     prot opt source
  destination
Chain FWDO_public_deny (1 references) target     prot opt source
  destination
Chain FWDO_public_log (1 references) target     prot opt source
  destination
Chain INPUT_ZONES (1 references) target     prot opt source
  destination          IN_public  all  --  anywhere             anywhere
  [goto]  IN_public  all  --  anywhere             anywhere
  [goto]
Chain INPUT_ZONES_SOURCE (1 references) target     prot opt source
  destination
Chain INPUT_direct (1 references) target     prot opt source
  destination
Chain IN_public (2 references) target     prot opt source
  destination          IN_public_log  all  --  anywhere
  anywhere             IN_public_deny  all  --  anywhere
  anywhere             IN_public_allow  all  --  anywhere
  anywhere
Chain IN_public_allow (1 references) target     prot opt source
  destination          ACCEPT     tcp  --  anywhere             anywhere
  tcp dpt:ssh ctstate NEW
Chain IN_public_deny (1 references) target     prot opt source
  destination
Chain IN_public_log (1 references) target     prot opt source
  destination
Chain OUTPUT_direct (1 references) target     prot opt source
  destination
Chain f2b-sshd (1 references) target     prot opt source
  destination          RETURN     all  --  anywhere             anywhere

A: I installed ~20 CentOS 7 servers with fail2ban out of the box and the default configuration is very open so a "connection refused" comes only after 5 failed login tries.
CentOS 7 now uses firewalld, but a rule for ssh(22) is set up per default.
If you change the ssh port in sshd_config, you also have to adjust the firewalld-rule, i.e.:
 firewall-cmd --zone=public --add-port=12321/tcp --permanent

Remember to run firewall-cmd --reload after changing configuration.
Better you just test with a fresh reinstall of CentOS, install fail2ban, restart and I can't see any reason why you shouldn't be able to login if it worked before (make sure that eth0 is up and has an IP address! I tend to forget "autoconnect" at installation time)

A: ISP's like amazon have their own firewall.  if your ISP has this service you have to open up your IP in there in order to get through.


text:
Q: Is there any SMPS controllers with CPU core inside? I heard that there is an SMPS controllers combined with CPU core. Or (which is the same in another words) a CPU controller with a wide peripheral to control an SMPS.
Tried to search in Google like "programmable SMPS controller", "SMPS controller with CPU core" and some others but didn't find anything combined in one chip: all I found was a special purpose PWM controllers without any programmable core or a general purpose controllers.
I think that Microchip has something like that.
Can you give me a clue which direction to look?

A: The term you're looking for is "Digital SMPS" or "Digital DC-DC", try to google variations of that.
An example:
http://www.ti.com/download/trng/docs/seminar/Topic_7_Hagen.pdf

A: One commercial-grade example that comes to mind is AXP209. Though the IC doesn't include the CPU, instead, it provides interfaces for an external CPU to alter the PMU settings.
Amateur implementations of "Smart SMPS" I have seen are often based on a small MCU like ATTiny which features a fast PWM pin (example).

A: Many power supplies using digital control have at their heart a DSC, or "digital signal controller" which essentially is a term for a microcontroller with some DSP enhancements. Examples include Microchip's dsPIC and TI's TMS320/C2000 parts.
These parts don't have a power supply controller on board per se, but have sufficient computation power to allow one to control a power supply through software - using difference equations to compute the control law and drive the power devices in a discrete-time way.
The controller is often also used for power management and external communication functions - it is advantageous to be able to use a single part for both control and power management, for cost and system complexity reasons.
Bear in mind that even though these are relatively complex devices, we're still talking about 16-bit parts operating at 50-100 MIPS - a small fraction of the computing power of a full PC, for example, but enough to do what needs to be done in the context of the power supply.


text:
Q: Managing Queued jobs / Database connections / performance on Laravel Vapor We are running our website on the AWS serverless infrastructure through Laravel vapor now. It runs on a serverless Aurora database and uses Amazon SQS as the queue driver.  Basically the defaults for a Laravel Vapor deploy.
We are currently running into a performance issue that while we are trying to resolve it, has us smash our head into other walls we meet on our journey.  So here we go.
What we want to do
Our customers can have various types of subscriptions that need to be renewed. These subscriptions come in all kinds of flavours, can have different billing intervals, different currencies and different prices.
On our customer dashboard we want to present them with a nice card informing the customer about their upcoming renewals, with a good estimate of what the cost will be, so they can make sure they have enough credits:

As our subscriptions come with different flavours, we have one table that holds the basic subscription details, such as net_renewal_date.  It also references a subscriptionable_id of subscriptionable_type which is a morph relation ship to the different types of models that a user can have a subscription for.
Our first attempt
In our first attempt, we basically added a REST endpoint which fetched the upcoming renewal forecast.
It basically took all Subscriptions that were up for renewal the coming 30 days.  For each of those items, we would calculate the current price in its currency, and add tax caculations.
That was then returned into a collection that we further used to:
1/ calculated the total per currency
2/ filter that collection for items within the next 14 days, and calculate the same total per currency.
We would then basically just convert the different amounts to our base currency (EUR) and return the sum thereof.
This worked great for the vast majority of our clients.  Even customers with 100 subscriptions were no issue at all.
But then we migrated one of our larger customers to the new platform.  He basically had 1500+ subcsriptions renewing in the upcoming 30 days, so that didn't go well...
Our second attempt
Because going through the above code simply doens't work in an acceptable amount of time, we decided we had to move the simulation calculation into a seperate job.
We added an attribute to the subscriptions table and called it 'simulated_renewal_amount'
This job would need to run every time when:
- a price changes
- the customer's discount would change (based on his loyalty, we provide seperate prices
- the exchanges rates change.
So the idea was to listen for any of these changes, and then dispatch a job to recalculate the simulated amount to any of the involved subscriptions.  This however means that a change in an exchange rate for instance can easily trigger 10,000 jobs to be processed.
And this is where it becomes tricky.
Even though running just one job only takes less than 1200ms in most cases, it seems that dispatching a lot of jobs that need to do the same calculations for a set of subscriptions is causing jobs running 60+ seconds when they are being aborted.
What is the best practice to setup such a queued job?  Should I just created one job in stead and process them sequentially?
Any insights on how we can best set this up to start with, would be very welcome.  We've played a lot with it, and it always seems to be ending up with the same kind of issues.
FYI - we host the site on laravel vapor, so serverless on AWS infrastructure with an Aurora database.

A: We have got the same issue. Vapor supports multiple queues but it does not allow you to set job concurrency on a per queue basis, so its not very configurable for drip feeding lots of jobs. We have solved this by making a seeder job that pulls out serialized jobs from an "instant jobs" table. We added a sleep loop also to allow granular processing throughout the whole minute (a new seeder job is scheduled each minute).
public function handle()
{
    $killAt = Carbon::now()->addSeconds(50);

    do{
        InstantJob::orderBy('id')->cursor()->each(function(InstantJob $job){
            if($job->isThrottled()){
                return true;
            }

            $job->dispatch();
        });

        sleep(5);
    } while (Carbon::now()->lessThan($killAt));
}

The throttle, if you are interested works off a throttle key (job group/name etc.) and looks like:
public function isThrottled(): bool
{
    Redis::connection('cache')
        ->throttle($this->throttle_key)
        ->block(0)
        ->allow(10) //jobs
        ->every(5) // seconds
        ->then(function () use(&$throttled) {
            $throttled = false;
        }, function () use(&$throttled){
            $throttled = true;
        });

    return $throttled;
}

This actually solves our problem of drip feeding jobs onto the queue without actually starting them.
One question for you... We are currently using a small RDS instance and we get a lot of issues with too many concurrent connections. Do you see this issue with serverless db's? Do they scale fast enough to ensure no drop outs?


text:
Q: Make Files Uploaded by SMTP to S3 Public I'm using cloudmailin.com to upload attachments from emails to an S3 bucket. The bucket itself has public settings, but I am unable to access the uploaded data from the data's link as S3 apparently doesn't make files uploaded by other users public.
Currently, I'm using the bucket policy below, which is supposed to make the bucket's contents public:
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::mjkaufer_cloudmailin/*"
        }
    ]
}

This only works if I manually upload something to S3. If I manually upload something, I can view the link and it can open in a new window. But if it's uploaded from cloudmailin, I'm unable to view the file.
Does anybody know a workaround? I just need to make it such that files uploaded to a bucket by a 3rd party (cloudmailin) are visible.
Thanks.

A: The problem is that as CloudMailin uploads your attachments to AWS S3 it needs to set the ACL permissions on them. AWS offers a couple of 'canned permissions' for this. The only two that are really of interest to CloudMailin are the following:

*

*bucket-owner-full-control - this is what you're currently set to, it grants the bucket owner full control over the uploaded attachment.

*public-read - this will grant you full control as the bucket owner but will also set read only privileges for everyone.

If you log into CloudMailin head to your address list and click 'manage' on the address you need to edit. Then head to 'Edit Attachment Store' and select 'Public Read' then CloudMailin will set this canned policy as the email attachments are uploaded to S3.


text:
Q: How to stretch and center image in IE (CSS)? Here's my code: http://jsfiddle.net/kHT8z/8/
It's written that way cause IE don't support css's background-size.
I want to stretch the images center the thumbnail image proportionally with width 100% and to center it. How to do that (I want it to work in IE6)

A: Via Chris Coyier: http://css-tricks.com/3458-perfect-full-page-background-image/
This code will let ie do background-size:cover. Just avoiding using it on the body or html tags and it should work fine. (Don't forget to change '.mybackground.jpg' to your image)
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";


text:
Q: vb.net Imports needed for WPF Window class? I have a class library with extension methods and I'm trying to write an extension method that works with a Window class, from a WPF app.
When I try writing the extension to accept a parameter of type Window, I get an error that this type can't be found;
I can't seem to find an assembly to import that will resolve this error, so I thought I'd post it here to see if I'm doing something wrong.
As an example, here's a simple extension I'd like to be able to use:
    <Extension>
    Public Sub helloworld(window As System.Windows.Window) 'Error- type system.windows.window is not defined

        ...

    End Sub

But I'm getting the error that the type system.windows.window is not defined.
I've even tried adding a reference to this class library to the System.Windows assembly, and adding an imports at the top of the screen, but it doesn't help.

A: I ended up taking a look at the references used on a normal WPF app project, and realized that there's a reference to PresentationFramework.... which is verbiage similar to...Windows Presentation Framework (WPF) ;)
I added this reference to my class library, and suddenly everything just worked.


text:
Q: C Preprocessor adds comments of its own
*

*If any, what are the (obviously ignored by GCC) comments below called?

*How do I get rid of them?

Here:
eisbaw@leno:~/GCC$ cpp < /dev/null
# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "<stdin>"
eisbaw@leno:~/GCC$

A: They are called linemarkers and you can use -P to have cpp or gcc omit them.
They are described in the Preprocessor Output section of the cpp manual.
And I agree with user30997 that you probably don't want to get rid of them.  They are ignored by gcc in the sense that they do not affect the compilation process, but they do provide useful diagnostic information when your code does not compile correctly.

A: You probably don't want to get rid of them.  They are inserted by the precprocessor so that any compiler that reads this compilation unit can determine the source file and line number that spawned any line it examines.  Without it, you can't get meaningful errors like "syntax error on line 7 of main.cpp:  semicolon expected."  Or whatever.
If you REALLY want to ditch them, you can always just write something quick that will kill anything beginning with "# ".


text:
Q: JAX-RS client API: Why is the MessageBodyReader allowed to throw a WebApplicationException According to the Javadoc, the readFrom method of a MessageBodyReader may throw a WebApplicationException, which seems strange as this seems only to make sense on the server side when parsing request messages.
But the same classes are also used on client side to parse response messages, which happens after the webservice has been called (which might be successful or not) and thus the readFrom method should not affect the HTTP status code in this case.
So why is the MessageBodyReader allowed to throw a WebApplicationException and how should it be handled by a client?
Eg. jersey-media-jaxb is an example which throws a WebApplicationException:
https://jersey.java.net/project-info/2.22.1/jersey/project/jersey-media-jaxb/xref/org/glassfish/jersey/jaxb/internal/AbstractRootElementJaxbProvider.html
The question arises since the client implementation provided by Jersey seems to have bug. I filed a related issue here: https://java.net/jira/browse/JERSEY-3005


text:
Q: Get string in between two words | last occurance So, I have been searching around and could find many answers but, they don't answer my questions. This is the code I use to get the strings between "duration": and , it works fine but, it gets every occurrence, I want to get only the last occurrence.  Regex101 Demo
(?<=\"duration":)(.*?)(?=\,)

gets:

{"duration": 5.016, "duration": 5.016, "duration": 5.016,
  "duration": 125,}

and I would like to get.

{"duration": 5.016, "duration": 5.016, "duration": 5.016, "duration":
  125,}

This is not just for JSON

A: You can use lookahead regex like this:
(?<="duration": )[^,]+(?!.*"duration")

Updated RegEx Demo

*

*[^,]+ matches 1 or more of any character that is not comma,

*(?!.*"duration") is a negative lookahead that asserts we have no occurrence of "duration" ahead of the current position.


text:
Q: General solution of a nonlinear differential equation Nonlinear differential equation gone beyond my field of expertise but I'd like to know the details of a problem and to do that I should know the general solution of the following nonlinear differential equation:
$$y'(x) = \alpha\beta e^{-\frac{x}{\gamma}} - \delta \sqrt{y(x)}$$
with $\alpha, \gamma, \delta > 0$ and $0 \leq \beta \leq 1$. Since $x$ represents the time is it also possible to assume $x \geq 0$.
I tried to solve it with Wolfram Alpha and Wolfram Mathematica but I didn't get any result due to computational time excedeed.
Is it possible to find an analytical form of $y(x)$?

A: I do not have a solution. But I wonder if you can gain some information about the behaviors of the equation in the extremes.
Let $y=\frac{z^2}{2}$,
$$y'=zz'=\alpha\beta e^{-\frac{x}{\gamma}}-\sqrt{2}\delta z=ce^{-\frac{x}{\gamma}}-kz$$
$$zz'+kz=f(x)=ce^{-\frac{x}{\gamma}}$$
Let $w=-kx$,
$$zz_w-z=-\frac{c}{k}e^{\frac{w}{\gamma k}}$$
This form is a type of Abel's equation. Unfortunately, I don't think there is a known analytic solution to this specific form. We can examine the solutions in the limits, however.
For $x\ll\gamma$, $e^{\frac{w}{\gamma k}}\approx1+\frac{w}{\gamma k}$, the text, Polyanin and Zaitsev, gives a parametric solution to
$$zz_w-z=-\frac{c}{k}(1+\frac{w}{\gamma k})$$
$$\frac{z}{t}=w+\gamma k=c_0exp(-\int\frac{t dt}{t^2-t+\frac{c}{\gamma k^2}})$$
Or
$$\frac{z}{t}=-kx+\gamma k=c_0exp(-\int\frac{t dt}{t^2-t+\frac{c}{\gamma k^2}})$$
For $x\gg\gamma$, $y'=-\delta\sqrt{y}$ and
$$2\sqrt{y}=-\delta x+c_1$$
There is a problem with this last equation. $\sqrt{y}>0$, but $-\delta x < 0$. If you change the requirements so that $\delta < 0$ then the solutions above hold.


text:
Q: Force Gravatar Refresh When a gravatar is changed, other users will only notice it if they clear their cache.
Therefore, Gravatar changes can go unnoticed for a very long time because people don't usually clear their cache.
It would be very easy to add a version field to the users table and append it to the Gravatar query string, like this:

http://www.gravatar.com/avatar/hash?s=32&X-StackOverflow-Version=3.

Gravatar will ignore the extra field  (I checked)
Then, whenever someone changes their gravatar, they could update this version field in their profile page, and force everyone to see the change.

A: If you want to force Gravatar to immediately start to show a different gravatar for you, change your email address in your M?S[OFU] profile. Email addresses are free.

A: Part of the problem is that Gravatar is sending a bad Last-Modified header. It seems to be when you signed up for Gravatar, not when you last changed your gravatar image. This makes Chrome, in particular, think that the image has not changed, even on a Ctrl+F5 refresh. Even though Gravatar sends a max-age of 300 seconds (5 minutes), the browser sees that Last-Modified hasn't changed and figures it doesn't need to re-download the file. The only way I've gotten Chrome to update Gravatars is by clearing my cache.
This could be resolved if Gravatar would send a proper Last-Modified header. Tell them about it here. (Note: that page is technically for reporting abuse, but it is the only way I could find to send a message to an actual person. If there is a page to report problems please let me know.)
Update: Looks like Gravatar has fixed this problem and sends a proper Last-Modified header.
The issue would also be partly resolved in Chrome if Ctrl+F5 refresh actually ignored cache like it is supposed to. (I opened a Chrome bug report about this, which was closed as a dup of this bug report.)
Update: Looks like Chrome has fixed this bug now! Not sure what release will first include the fix though.

A:
Gravatar will ignore the extra field (I checked)

Please reference their API that indicates this usage is supported and will always be true in future revisions of their interface.  Otherwise it would be unwise to implement it.

A: The gravatar.com server tells a browser to cache for only 5 minutes, though they are doing some caching themselves as well. I doubt that their own caching can be fooled by additional parameters.
Date: Tue, 02 Feb 2010 19:36:17 GMT
Last-Modified: Tue, 25 Aug 2009 20:32:54 GMT
Expires: Tue, 02 Feb 2010 19:41:17 GMT
Cache-Control: max-age=300

A: I am not sure we want to encourage people to change their gravatar images frequently.
It doesn't take that long for gravatars to refresh, anyway.


text:
Q: The identifying properties of "it/that" against the question of "who" When I ask the question "who broke the bike?" and I respond with "it was Jane", is the word 'it' a pronoun identifying Jane?
My understanding is that 'it' is referring to "the person who broke the bike" without identifying who broke the bike.
It seems that when I list the noun 'Jane', that's identifying who broke the bike and the pronoun 'it' is connecting Jane to the person who broke the bike, but is not identifying her as the one who broke the bike.
As a bonus: the context for this question is supposing that we do not refer to grown humans as 'it' because it's dehumanizing as we reserve 'it' for unspecified people, objects, and animals. Any input on this is welcome.


text:
Q: USB 2 Hub for running USB External Drives I am experiencing an odd problem with using 2 different USB 2.0 Hubs to run a Seagate FreeAgent USB harddrive on.
I'm getting an 'unknown inpage error' (or similar). When i plug in directly to the computer it has no problem. Any ideas what this error is about and how I can get around it? I need to run it on a HUB as im short on USB. Hardware recommendations welcomed!
USB Drive only runs a USB cable. (Does that make it a unpowered drive?)
USB Hub only runs a USB cable. (Does that make it unpowered?)

A: Is this a 2.5" drive?  It possibly needs a powered USB hub.  Is the hub powered?

A: First, I would ask: Are you using a powered HUB or not? It could simply be a power problem.
Don't ask me why this might work considering it works when plugged in directly, but others have solved this by doing a couple of things: Running chkdsk /f and/or changing the drive letter in the disk management mmc (Of course, you can probably change it back. It won't hurt to try both since they are quick.