text:
Q: checkboxGroupInput updates before observeEvent I am trying to get the values selected in the checkboxGroupInput to show in the main panel of multiple tabs after the "submit" button is clicked.  Using observeEvent, the first time choices are selected, they don't show in the main panel until the submit button is clicked, but after that, the values show in the main panel when selected without submitting them.  How can I make it so submit has to be clicked before the main panel updates?
library(shiny)

ui <- fluidPage(

titlePanel(
  "Example"),
sidebarLayout(
  sidebarPanel(
    checkboxGroupInput("choice", label = "Choose Letter",
                       choices = list("A", "B", "C", "D")),
    actionButton("submit", "Submit"),
    width=3
  ),

  mainPanel(
    tabsetPanel(
      navbarMenu("Pages",
                 tabPanel("Page 1", h3(htmlOutput("choice1"))),
                 tabPanel("Page 2", h3(textOutput("choice2")))
    )
   )
  )
 )
)

server <- function(input, output) {
  observeEvent(input$submit,{
    lapply(1:2, function(nr){
    output[[paste0("choice",nr)]]<-renderText({choose<-paste(input$choice, collapse=", ")
    paste(choose)})
   })
  })
}

shinyApp(ui = ui, server = server)

I also tried eventReactive, which I've never used before, so I'm not sure I understand it.  Using the following code in the server, I get the error "Error in as.vector: cannot coerce type 'closure' to vector of type 'character' "
 a<-eventReactive(input$submit,{
 paste(input$choice, collapse=", ")
 })

 lapply(1:2, function(nr){
 output[[paste0("choice",nr)]]<-renderText(paste(a))
 })

A: I will post the solution but with minimal explanation with a hope that someone can come along and explain more or correct mine.
First: renderText interact with "or depends on" input$choice directly hence any update or change in input$choice will reflect on renderText. To solve this dependency issue you need a placeholder that depends on OR triggered using  observeEvent which is reactiveValues
server <- function(input, output) {
           data <- reactiveValues()
           observeEvent(input$submit,{
                        data$nr <- input$choice
                        lapply(1:2, function(nr){
           utput[[paste0("choice",nr)]]<-renderText({choose<-paste(data$nr, collapse=", ")
           paste(choose)})
      })
   })
}

Second: Any object created with eventReactive is the same as those created with reactive, they were functions and in the time of invoking they should be called using (), e.g. in your case a should be called as follows a()
a<-eventReactive(input$submit,{
paste(input$choice, collapse=", ")
})

 lapply(1:2, function(nr){
        output[[paste0("choice",nr)]]<-renderText(paste(a()))
})

For more information on reactivity and dependency in shiny, you can check here


text:
Q: I want to drop rows In my data frame base on column 1 Column1.          Column2

Start1                   633

End.                       855

Start2.                     767

Start3.                      231

End.                           545

Start4.                      111

Start5                       243

End.                           333

Output
Column1.          Column2

Start1                   633

End.                       855

Start3.                      231

End.                           545

Start5                       243

End.                           333

In column1 Start2 row drop because it's not end same as start4

A: You can use cumsum and groupby like this:
df = pd.DataFrame({'Column1':['Start1','End.','Start2','Start3','End.','Start4','Start5','End.'],
                   'Column2':[633,855,767,231,545,111,243,333]})

Input dataframe:
  Column1  Column2
0  Start1      633
1    End.      855
2  Start2      767
3  Start3      231
4    End.      545
5  Start4      111
6  Start5      243
7    End.      333

Use  cumsum and groupby:
df[df.groupby((df['Column1'] != 'End.').cumsum())['Column1'].transform('count') == 2]

Output:
  Column1  Column2
0  Start1      633
1    End.      855
3  Start3      231
4    End.      545
6  Start5      243
7    End.      333

A: It is longer than the previous answer but I Believe it is more understandable:
In [1]:
import pandas as pd
## Create the Dataframe
cols = ['Column1', 'Column2']
data = [['Start1', 633],['End', 855],['Start2', 767],['Start3', 231],
        ['End', 545],['Start4', 111],['Start5', 243],['End', 333]]
df = pd.DataFrame(data=data, columns=cols)
df

Out [1]:
    Column1 Column2
0   Start1  633
1   End     855
2   Start2  767
3   Start3  231
4   End     545
5   Start4  111
6   Start5  243
7   End     333

Here I loop on the rows and if the rows after contains as well Start I delete the row.
In [2]:
idx = df.index.tolist()
droped_idx = []
for i in idx[:-1]:
    row = df.iloc[i, 0]
    next_row = df.iloc[i+1, 0]
    if (('Start' in row) & ('Start' in next_row)):
        droped_idx.append(i)

df.drop(index=droped_idx, inplace=True)
df

Out [2]:
    Column1 Column2
0   Start1  633
1   End     855
3   Start3  231
4   End     545
6   Start5  243
7   End     333

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extract texts from multiple textnodes within an element using Selenium and BeautifulSoup I have an element found through BeautifulSoup that (HTML) looks like this:

    Vendita Residenziale

    New York

    Appartamento

    Prezzo:
    € 100.000/200.000
    - Metri quadri:
    130/170

And I need to get in one variable Vendita Residenziale, in another New York,in another Appartamento , in another 100.000/200.000 (not the strong tag) and in the last one 130/170.
I can extract the span tag text doing:
x = ele.find('span', attrs = {'class': 'contract'}).get_text()

but I'm struggling to get the other information, I tried to:
y = ele.find('div', attrs = {'class':'ListingData'}).get_text().replace("\n","").strip()

but this gives me all the div content and that's okay but I need to get the individual lines of information like a "result[1]" for New York, "result[2]" for Appartamento and so on. Is there a method?

A: I used a mix of BeautifulSoup4 and Regular Expression, you can toy with the  regex.
a=bs4.BeautifulSoup(txt,'html.parser')
a.findAll(id="l_Contract")[0].text # Vendita Residenziale
p=re.compile("
").split(txt)
p[1] # "New York"
p[2] # "Appartamento"
re.compile("€\s+([0-9.]+\/[0-9.]+)\s+-\s+").search(txt).group(1) #100.000/200.000

Another way would be simply doing this
a.findAll(class_="ListingData")[0].text
#Output
'\nVendita Residenziale\n    New York\n    Appartamento\nPrezzo:\n    € 100.000/200.000\n    - Metri quadri:\n    130/170\n    '

Wich is easier to parse.

A: Since all text you want is in the
 tag, seems the easiest way would be to get the
 text, and split the text on newlines '\n' into a result list:
result = [e.strip() for e in ele.div.text.strip().split('\n')]

>>> result
[u'Vendita Residenziale', u'New York', u'Appartamento', u'Prezzo:', u'\u20ac 100.000/200.000', u'- Metri quadri:', u'130/170']

which can then be indexed as desired:
for n, res in enumerate(result):
    print(f'result[{n}] = {res}')

result[0] = Vendita Residenziale
result[1] = New York
result[2] = Appartamento
result[3] = Prezzo:
result[4] = € 100.000/200.000
result[5] = - Metri quadri:
result[6] = 130/170

A: You could use navigable string and .contents
from bs4 import BeautifulSoup, NavigableString

html = '''

    Vendita Residenziale

    New York

    Appartamento

    Prezzo:
    € 100.000/200.000
    - Metri quadri:
    130/170

'''

soup = bs(html, 'lxml')
item1 = soup.select_one('#l_Contract').text
items = soup.select_one('.ListingData').contents
results = []
for item in items:
    if isinstance(item, NavigableString) and item.strip():
        results.append(item.strip())

item2 = results[0]
item3 = results[1]
item4 = results[2]

print(item1, ',', item2, ',', item3, ',', item4)

A: not really a bs4 issue here, the other data you want isn't inside of span tags, extract your data based on string observations
sp=sp.find('div',id='onesiwant')
for div in sp:
    all=div.text.strip()
    #now you can split('\n')
     html=str(div)
     get the stuff out of span
        now split by '
' tags

your asking how to use bs4 to get data out of text in between tags or seperated by \n, so bs4 here is not necessary, just string manipulation

A: Selenium alone can extract all the required texts and you can use the following solution:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "div[@class='ListingData']")))
text_Vendita_Residenziale = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "div[@class='ListingData']/span[@class='contract' and contains(@id='Contract')]")))
text_NewYork = driver.execute_script('return arguments[0].childNodes[3].textContent;', element).strip()
text_Appartamento = driver.execute_script('return arguments[0].childNodes[5].textContent;', element).strip()
text_100_200 = driver.execute_script('return arguments[0].childNodes[8].textContent;', element).strip()
text_130_170 = driver.execute_script('return arguments[0].lastChild.textContent;', element).strip()


text:
Q: Trying to test function with mocha + nyc I'm trying to test my function with mocha + nyc for cheching coverage.
This is function to test:
function TypeCompare(Obj){

Obj.forEach(function (el){
  el.Age = StringToNumber(el.Age);
  el.Name = isValidString(el.Name);
  el.Surname = isValidString(el.Surname);
  el.Mail = isEmail(el.Mail);
  el.DateofReg = StringToDate(el.DateofReg);
  el.Phone = isPhone(el.Phone);
  el.Time = StringToTime(el.Time);
  if(el.Age == "Age error" || el.Name == "Name/Sname error" || el.Surname == "Name/Sname error" || el.DateofReg == "Date error" || el.Time == "Time error" ||el.Mail == "Email error" || el.Phone == "Phone error"){
  invalid_types.push(el);
} else {
  valid_types.push(el);
}
});
RecordToDB(valid_types);
RecordToCSV(invalid_types);
}

The function getting array of objects check objects with other function for valid and push valid objects to valid_types and invalid to invalid_types.
This is my testing function:
describe('Testing function TypeCompare which getting arr[objects] on input
check arr for valid and invalid objects', function () {
  it('should return [valid_obj] and [] if all objects is valid', function ()
{
var arr = [{Age: '20', Name: 'Kiryl', Surname: 'Kazushchyk', Mail: 'kastys1@yandex.ru', DateofReg: '10-20-2015',
  Phone: '+375257794915', Time: '10:44'},
  {Age: 'fgh', Name: 'Kiryl', Surname: 'Kazushchyk', Mail: 'kastys1@yandex.ru', DateofReg: '10-20-2015',
    Phone: '+375257794915', Time: '10:44'}];
app.TypeCompare(arr);
// console.log(TypeCompare.valid_types);
// console.log(TypeCompare.invalid_types);
var expected_valid = [{Age: '20', Name: 'Kiryl', Surname: 'Kazushchyk', Mail: 'kastys1@yandex.ru', DateofReg: '2015-10-20',
  Phone: '+375257794915', Time: '10:44:00'}];
var expected_invalid = [{Age: 'Age error', Name: 'Kiryl', Surname: 'Kazushchyk', Mail: 'kastys1@yandex.ru', DateofReg: '2015-10-20',
  Phone: '+375257794915', Time: '10:44:00'}];

assert(app.invalid_types[0].Age === expected_invalid[0].Age);
assert(app.valid_types[0].Age === expected_valid[0].Age);
  });
});

I'm export this:
module.exports.TypeCompare =TypeCompare;
module.exports.valid_types = valid_types;
module.exports.invalid_types = invalid_types;

The test is passed ok, but i don't recive any information about summary:
test result without coverage
If i test my other functions everything is okay:test result other functions
Can someone tell me what is the problem?

A: Solved. The problem was in functions which called with TypeCompare


text:
Q: How to get a specific info on an Html page, using Cheerio on GAS? I haven't been able to identify any class, id, etc where the code is supposed to get the information from.
Here's the html page and the piece of information I should get everyday:

...and here's the piece of code I'm trying to use:
    var content = UrlFetchApp.fetch("https://ovoonline.com.br/", options).getContentText();
    const $ = Cheerio.load(content);
    Logger.log($('td[colspan="2"]').text());

This is its selector, but it doesn't output the correct result:
body > table > tbody > tr > td > table > tbody > tr > td:nth-child(2) > table:nth-child(2) > tbody > tr:nth-child(6) > td > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(1) > td:nth-child(1) > table > tbody > tr:nth-child(18) > td > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr > td:nth-child(1)

Thank you!

A: This worked for me:
    var content = UrlFetchApp.fetch("https://ovoonline.com.br/",options)
                  .getContentText();

   const $ = Cheerio.load(content);
   Logger.log($('td[width="45"]').eq(1).text());

Result Log:


text:
Q: Are there exotic group laws on affine space in characteristic zero? Let $k$ be a field of characteristic zero, and let $X = \mathbb{A}^n_k$ be affine $n$-space. Up to $k$-rational translation, we may assume that a map $e : \operatorname{Spec} k \to X$ is the inclusion of the origin.
Are there any possible algebraic group laws on $X$ whose identity is the origin besides the natural one? Equivalently, are there any possible Hopf algebra structures on $k[x_1,\ldots, x_n]$ besides the following?
$$
    \mu : x_i \mapsto 1 \otimes x_i + x_i \otimes 1
$$
$$
     i : x_i \mapsto -x_i
$$
Even in one dimension, the algebra required to prove this is somewhat involved: using characteristic not 2, one can see that $i$ must be negation. Then writing the comultiplication as $x \mapsto p(x_1, x_2) \in k[x_1, x_2]$, it is easy to see that $p(x_1, x_2) \in x_1 + x_2 + (x_1 x_2)$, but a complicated induction with associativity seems to be necessary to handle the higher order terms (and indeed, the nonvanishing of all binomial coefficients is the only way I can imagine that characteristic zero can enter the proof).
Is there a way to use some algebraic geometry to sidestep the algebra, or a better way to organize the algebraic argument?
I'm also happy to use transcendental methods as long as the argument applies to all characteristic zero fields. Note that by Galois descent it suffices to show the result for $k$ algebraically closed . . . but it may be too large to embed into $\mathbb{C}$. Perhaps one can write down a universal Hopf algebra on $X$ over some finitely generated $\mathbb{Q}$-scheme base, and then check on an algebraically closed fiber to reduce to $\mathbb{C}$).

A: Yes, and they're not even so exotic. If $\mathfrak{g}$ is a nilpotent Lie algebra over a field of characteristic zero then the Baker-Campbell-Hausdorff formula terminates so it defines a polynomial group law on $\mathfrak{g}$ regarded as an affine space, which over $\mathbb{R}$ or $\mathbb{C}$ produces the corresponding simply connected nilpotent Lie group. For a more explicit example you can consider the $3$-dimensional Heisenberg group
$$\left[ \begin{array}{ccc} 1 & x & z \\ 0 & 1 & y \\ 0 & 0 & 1 \end{array} \right]$$
whose multiplication defines a nonabelian polynomial group law on $\mathbb{A}^3$ (over any field), namely
$$(x_1, y_1, z_1) \ast (x_2, y_2, z_2) = (x_1 + x_2, y_1 + y_2, z_1 + z_2 + x_1 y_2).$$
This comes from applying the above construction to the $3$-dimensional Heisenberg Lie algebra (up to some minor change of coordinates); that $x_1 y_2$ term corresponds to the only nontrivial bracket in the Lie algebra. Alternatively this construction can be described as a central extension of $\mathbb{G}_a^2$ by $\mathbb{G}_a$ in the category of affine group schemes.
I'd guess that every polynomial group law on $\mathbb{A}^n$ arises this way in characteristic zero (up to change of coordinates) but I don't know a proof.
If instead of group laws you'd asked for formal group laws, which corresponds to working at the formal completion of affine space at the origin, then examples can be constructed from any finite-dimensional Lie algebra (by using BCH), and in characteristic zero this is known to be an equivalence of categories.


text:
Q: I need to create a text file and send it to an ftp server I am currently working a program where you use a verification code to log-in to an account.  I need help sending a file with the string of numbers to a server I have.
for example:
Send "thisfile.txt" to ftp://myserver.com/thisfile.txt
I currently have
Imports System.IO.File
Public value = rnd.Next(1000, 9999)
Public vcode As Int32 = rndvalue
File.CreateText("vcode.vlo")

A: .Net has a FtpWebRequest class built-in that you can use to upload files via FTP.
MSDN contains a useful example How to: Upload Files with FTP, it's in C# but is easily converted to VB.Net:
Sub Main()
    ' Get the object used to communicate with the server.
    Dim request = CType(WebRequest.Create("ftp://www.contoso.com/test.htm"), FtpWebRequest)
    request.Method = WebRequestMethods.Ftp.UploadFile

    ' This example assumes the FTP site uses anonymous logon.
    request.Credentials = New NetworkCredential("anonymous", "janeDoe@contoso.com")

    ' Copy the contents of the file to the request stream.
    Dim sourceStream = New StreamReader("testfile.txt")
    Dim fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
    sourceStream.Close()
    request.ContentLength = fileContents.Length

    Dim requestStream = request.GetRequestStream()
    requestStream.Write(fileContents, 0, fileContents.Length)
    requestStream.Close()

    Dim response = CType(request.GetResponse(), FtpWebResponse)

    Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription)

    response.Close()
End Sub

A: here is a function for uploading any file to ftp server
Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)
Dim _FileInfo As New System.IO.FileInfo(_FileName)

' Create FtpWebRequest object from the Uri provided
Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)

' Provide the WebPermission Credintials
_FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)

' By default KeepAlive is true, where the control connection is not closed
' after a command is executed.
_FtpWebRequest.KeepAlive = False

' set timeout for 20 seconds
_FtpWebRequest.Timeout = 20000

' Specify the command to be executed.
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

' Specify the data transfer type.
_FtpWebRequest.UseBinary = True

' Notify the server about the size of the uploaded file
_FtpWebRequest.ContentLength = _FileInfo.Length

' The buffer size is set to 2kb
Dim buffLength As Integer = 2048
Dim buff(buffLength - 1) As Byte

' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

Try
    ' Stream to which the file to be upload is written
    Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()

    ' Read from the file stream 2kb at a time
    Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)

    ' Till Stream content ends
    Do While contentLen <> 0
        ' Write Content from the file stream to the FTP Upload Stream
        _Stream.Write(buff, 0, contentLen)
        contentLen = _FileStream.Read(buff, 0, buffLength)
    Loop

    ' Close the file stream and the Request Stream
    _Stream.Close()
    _Stream.Dispose()
    _FileStream.Close()
    _FileStream.Dispose()
Catch ex As Exception
    MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

example of using the code
UploadFile("C:/text.txt" , "ftp:example.com/file/text.txt" , "Ftpusername" , "Ftppassword")


text:
Q: What is the Eclipse equivalent of Visual Studio's build configurations? I'm porting some Windows code to Android.
The Visual Studio project has various different build configurations for different versions of the application, (e.g. full version vs. demo).
What is the standard way to achieve this in Eclipse? The vast majority of the code will be the same for the different versions, but there will be small differences, e.g. native code preprocessor definitions in Android.mk, slight differences in some of the Java code, different output filenames.
Should I just set up separate projects, and use my Android.mk files and Eclipse's Properties -> Java Build Path to point at the shared code?

A: Eclipse CDT provides multiple configurations (try right click on project -> Build Configurations). But this only works for native projects, or for the C++ part of mixed projects, like the Android projects with Native Support.


text:
Q: Abstract types in pointcuts I'd like to intercept method calls with a certain signature with an Aspect.
My pointcut should look something like this:
execution(public Result * (Input))"
But Result and Input are abstract.
Would this pointcut also match all Methods, that return a subtype of Result and work with a subtype of Input? Because that's my intention.

A: Very nearly. You need to add a plus sign immediately after the type name.
execution(public Result+ * (Input+))

Here is an example from AspectJ doc. Spring uses a restricted version of the AspectJ syntax.
pointcut callToUndefinedMethod():
    call(* AbstractFacade+.*(..))
    && !call(* AbstractFacade.*(..));

And here is the (terse) documentation

SubtypePattern - all types in SubtypePattern, a pattern with a +.


text:
Q: how can i render html file in node.js i have tried to render html file but i got this error . i have login.html within public folder.how to render html file.thanks in advance.
my server side coding
var express = require('express');

var app = express();

app.configure(function(){

  app.set("view options", {layout: false});

  app.use(express.static(__dirname + '/public'));

 });

app.get('/', function(req, res) {

    res.render('login.html');

});

app.listen(8000)

Error: Failed to lookup view "login.html"
at Function.render (/home/aware/local/src/node_modules/express/lib/application.js:493:17)
at ServerResponse.render (/home/aware/local/src/node_modules/express/lib/response.js:753:7)
at /home/aware/local/src/health/demo2.js:17:9
at callbacks (/home/aware/local/src/node_modules/express/lib/router/index.js:161:37)
at param (/home/aware/local/src/node_modules/express/lib/router/index.js:135:11)
at pass (/home/aware/local/src/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/home/aware/local/src/node_modules/express/lib/router/index.js:170:5)
at Object.router [as handle] (/home/aware/local/src/node_modules/express/lib/router/index.js:33:10)
at next (/home/aware/local/src/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at resume (/home/aware/local/src/node_modules/express/node_modules/connect/lib/middleware/static.js:60:7)

A: The closest you can get to using html for node views is EJS (Embedded JavaScript)
This way you write your normal HTML, pass your data through node and display them using tags like: <%= var %>
http://embeddedjs.com/
https://github.com/visionmedia/ejs

A: You can render HTML page with Nodejs using Embedded JavaScript(ejs).
here you can go through -the Documentation of ejs
for using ejs, first of you create directory with the name views, In that directory create a file with .ejs extension.

A: The files you keep inside your public folder will not be rendered because they are set as static, so they will be served as is. All other files outside of this will be rendered. Remember to set the rendering engine.

A: I just came in contact with connect today & wanted to solve a simillar issue, serving a simple HTML file. In my case, I wanted to display a 404 when any previous middlewares hadn't finished the request.
I create a function, show404 and then you can do something like app.use(show404). Here's my CoffeScript for that mostly inspired in connect errorHandler source code.
show404 = (req, res, next) ->
    res.statusCode = 404
    res.setHeader 'Content-Type', 'text/html; charset=utf-8'
    html_path = require("path").resolve('.tmp/404.html')
    require('fs').readFile html_path, (err, data)->
        throw err if err
        console.log "DATA:", data
        res.end data


text:
Q: Autocommit example in MySQL I try to follow an example as below, but I get a different result, being that the second select in session A returns the new row inserted by Session B.
The example is from http://dev.mysql.com/doc/refman/5.6/en/innodb-consistent-read.html. I am using 5.5.
           Session A              Session B

           SET autocommit=0;      SET autocommit=0;
time
|          SELECT * FROM t;
|          empty set
|                                 INSERT INTO t VALUES (1, 2);
|
v          SELECT * FROM t;
           empty set
                                  COMMIT;

           SELECT * FROM t;
           empty set

           COMMIT;

           SELECT * FROM t;
           ---------------------
           |    1    |    2    |
           ---------------------
           1 row in set

Update
I changed in both session A and B for transaction as below, but the problem still exists.
SET autocommit=0;   -- I think this line is redundant given the line below
set transaction isolation level read committed;
start transaction;

Any idea?


text:
Q: How to write laravel query with left join and a inner join? I have following tables, and want to do left join with a condition and another inner join from the left joined table,
User table

id  |  name
 1     john
 2     sam
 3     cecil

Roles table

id | name
 1  admin
 2  editor

model_has_roles table

role_id  | model_type | model_id
  1         App\User       1
  2         App\User       2

What I want
Do a left join between user table and model_has_roles table on user.id and model_has_roles.model_id column, if model_type is 'App\User' and then another inner join between Roles table and model_has_roles table for role_id and Roles.id column. So result should be like this,

id | name | role

 1   john   admin
 2   sam    editor
 3   cecil   -

I tried following query but not working correctly,
 DB::table('users')->select('id', 'name', 'email', 'created_at', 'role_id')
            ->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'users.id')
            ->where('model_has_roles.model_type', '=', 'App\User')
            ->paginate(1);

If you can please help me to write an eloquent query for this.
Thanks
P.S: Actually, I'm using spatie/laravel-permission, and trying to get all the users with their role name.

A: This should work just fine:
App\User::with('roles')->get();


text:
Q: How to filter specific datasets by using another dataset? Im using ms sql-server. By using this base data:
CREATE TABLE test(column_1, column_2)
INSERT INTO test
VALUES (1,1),(2,3),(2,1),(2,3),(3,1),(3,3),(3,3),(3,1),(3,1),(3,3),(4,3),(4,1),(5,3),(5,3),(5,3),(6,3),(6,3)

Is there a way to select only datasets that have a 3 in column_2, but only if there is another dataset with the same number in column_1 and a 1 in column_2?
So it should look like this in the end:
CREATE TABLE result(column_1, column_2)
INSERT INTO test
VALUES (2,3),(2,3),(3,3),(3,3),(3,3),(4,3)

Its a combination of these two filters:
1
SELECT *
FROM table1
WHERE column_2 = 3
ORDER BY column_1

2
SELECT DISTINCT column_1
FROM table1
WHERE column_2 = 1

I tried putting Query 2 in another column, but I cant use that new column as a condition.
SELECT *, (SELECT T2.column_1 WHERE T2.column_2 = 1 ORDER BY T2.column_1) AS colcheck
FROM test T1, test T2
WHERE T1.column_2 = 3 and T2.colcheck = T1.column_1
ORDER BY T1.column_1

A: This query will make your desired output:
SELECT * FROM Test T1
WHERE
  column_2 = 3 AND EXISTS(SELECT 1 FROM Test WHERE column_1 = T1.column_1 AND column_2 = 1)
ORDER BY
  column_1

A: As well as a self-join like the other answer, another option is a window aggregate:
SELECT *
FROM (
    SELECT *,
        cnt = COUNT(CASE WHEN column_2 = 1 THEN 1 END) OVER (PARTITION BY column_1)
    FROM test
) t
WHERE column_2 = 3 AND cnt > 0;


text:
Q: Dash Plotly: How to filter Data Frame by date with DatePickerRange? I use Dash Plotly for data visualization. I already have the data frame and chart which displays the correct data.
Now I want to filter data and update the chart when the user filters data using the date picker.
Here is my code:
df = pd.read_csv('Sample_Data2.csv')
df["date_x"] = pd.to_datetime(df["date_x"]).dt.date

dfp = (
        df.groupby([df["date_x"], df["Categories of event"]])
        .size()
        .unstack("Categories of event", 0)
        .assign(Events=lambda d: d.sum(axis=1))
    )

graph = px.line(dfp, markers=True).update_layout(
    xaxis={'dtick': 'D'},
)

Graph layout:
html.Div(className='graph', children=[
            dcc.Graph(
                id='graph',
                figure=graph,
                responsive=True,
                animate=True,
            )
        ]),

Datepicker component:
html.Div(children=[
            dcc.DatePickerRange(
                id='date_filter',
                start_date=df['date_x'].min(),
                end_date=df['date_x'].max(),
                min_date_allowed=df['date_x'].min(),
                max_date_allowed=df['date_x'].max(),
            ),
        ]),

Callback:
@app.callback(
    Output('graph', 'figure'),
    Input('date_filter', 'start_date'),
    Input('date_filter', 'end_date'),
    prevent_initial_call=True,
)
def update_graph(start_date, end_date):
    min_date = df['date_x'].min()
    min_date = start_date

    max_date = df['date_x'].max()
    max_date = end_date
    df_date = pd.date_range(min_date, max_date, freq='D')

    dfp = (
        df.groupby([df_date, df["Categories of event"]])
        .size()
        .unstack("Categories of event", 0)
        .assign(Events=lambda d: d.sum(axis=1))
    )

    graph = px.line(dfp, markers=True).update_layout(
        xaxis={'dtick': 'D'},
    )

    return graph

The data frame grabs the date_x column and displays the chart, but I couldn't do it with a date picker that generates min_date and max_date.
update:
Forgot to provide data:
id  date_x  Agency  Relevance_x Human_Validation    Event   Categories of event start date  end date    Duration    Issue   Local-National  Location_Category   Location_Province   Oganizer_type   CivilSocietySector  MainPoliticalSector CS_Location_Category    CS_Location_Province    size_of_participants    Arena_type  Arena_Province
45803   1/1/2018 7:19   ILNA    Yes 1   Protest Violent protests    12/29/2017  12/29/2017  1   Economic    National    Town    Khuzestan   Unknown None    Neutral National    NONE    unknown Streets Khuzestan
45817   1/1/2018 7:46   ILNA    Yes 1   Protest Confrontational protests (illegal and non violent)          1   Labour  Local   City    Azerbaijan, East    Workers Labour  Neutral Province Center Azerbaijan, East    medium group <50    Working places  Azerbaijan, East
45531   1/1/2018 18:17  ILNA    Yes 1   Protest Violent protests            1   Economic    National    City    Isfahan Unknown None    Neutral National    NONE    unknown Streets Isfahan
45529   1/1/2018 18:23  ILNA    Yes 1   Protest Violent protests            1   Economic    National    Province Center Markazi Unknown None    Neutral National    NONE    unknown Streets Markazi
45448   1/2/2018 6:36   ILNA    Yes 1   Protest Violent protests            1   Economic    National    Province Center Kurdistan   Unknown None    Neutral National    NONE    unknown Streets Kurdistan
45299   1/2/2018 10:05  ILNA    Yes 1   Protest Confrontational protests (illegal and non violent)          1   Economic    National    Capital Tehran  Unknown Student Movement    Neutral Capital Tehran  unknown University campuses Tehran
45029   1/3/2018 6:43   ILNA    Yes 1   Protest Violent protests            1   Economic    National    Town    Kermanshah  Unknown None    Neutral National    NONE    unknown Streets Kermanshah
44950   1/3/2018 8:49   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    Province Center Bushehr GONGO   Progovernment   Conservative    National    Bushehr unknown Streets Bushehr
44935   1/3/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    Province Center Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
44935   1/3/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    City    Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan
44935   1/5/2018 9:22   ILNA    Yes 1   Protest Demonstrative protests (legal and nonviolent)           1   Political   National    City    Khuzestan   GONGO   Progovernment   Conservative    National    Khuzestan   unknown Streets Khuzestan

A: *

*you have not provided sample data so I have synthesized some

*in callback it's as simple as filtering the dataframe with start_date and end_date
import pandas as pd
import numpy as np
import dash
import plotly.express as px
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash

# generate some sample data...
df = pd.DataFrame(
    {
        "date_x": pd.date_range("1-jan-2021", periods=200),
        "y": np.linspace(30, 50, 200) * np.random.uniform(0.95, 1.05, 200),
    }
)

app = JupyterDash(__name__)
app.layout = dash.html.Div(
    [
        dash.dcc.DatePickerRange(
            id="date_filter",
            start_date=df["date_x"].min(),
            end_date=df["date_x"].max(),
            min_date_allowed=df["date_x"].min(),
            max_date_allowed=df["date_x"].max(),
        ),
        dash.dcc.Graph(id="graph"),
    ]
)

@app.callback(
    Output("graph", "figure"),
    Input("date_filter", "start_date"),
    Input("date_filter", "end_date"),
)
def updateGraph(start_date, end_date):
    if not start_date or not end_date:
        raise dash.exceptions.PreventUpdate
    else:
        return px.line(
            df.loc[
                df["date_x"].between(
                    pd.to_datetime(start_date), pd.to_datetime(end_date)
                )
            ],
            x="date_x",
            y="y",
        )

# Run app and display result inline in the notebook
app.run_server(mode="inline")


text:
Q: WebRTC видеосвязь Не получается создать видеосвязь, ссылку получает, но не отображает:
HTML:
<video id="localVideo" width="360" height="240" autoplay="true"></video>
<video id="remoteVideo" width="360" height="240" autoplay="true"></video>

JS:
var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var sessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription || window.msRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia;

var onePeer = new peerConnection();
var twoPeer = new peerConnection();

onePeer.onaddstream = function(obj) {
    document.getElementById("localVideo").src = window.URL.createObjectURL(obj.stream);
}

function error(err) {
    //Error
}

function initialize() {
    navigator.getUserMedia(
        {video:true},
        function(stream){
            onePeer.onaddstream({stream: stream});
            onePeer.addStream(stream);

            onePeer.createOffer(function(offer) {
                    onePeer.setLocalDescription(new sessionDescription(offer), function() {
                                        // Пытаюсь принять:
                    remote(offer);
                    }, error);
            }, error);
        },
        function(error){console.log("Failed to get access to local media. Error code was " + error.code);}
    );
}

//Получает ссылку - но не отображает, почему?
twoPeer.onaddstream = function(obj) {document.getElementById("remoteVideo").src = window.URL.createObjectURL(obj.stream);};

function remote(obj) {
    twoPeer.setRemoteDescription(new sessionDescription(obj), function() {
            twoPeer.createAnswer(function(answer) {
                twoPeer.setLocalDescription(new sessionDescription(answer), function() {
                    // ANSWER
                }, error);
            }, error);
    }, error);
}

setTimeout(initialize, 1);

Консоль выдает ошибку:

ICE failed, see about:webrtc for more details

A: Обмен SDP не достаточен для установки соединения, надо реализовать обмен ICE кандидатами https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/WebRTC_basics
Пример открытия видео потока с использование библиотеки Easy-API https://plnkr.co/edit/4sVzu7?p=preview
<!DOCTYPE html>


text:
Q: AppEngine-OAuth-Library LinkedIn - Grant more permissions I use the AppEngine-OAuth-Library to get user information from LinkedIn, but how do I grant for more permissions than the default basic profile.
The LinkedInClient class has this constructer:
OAuthClient.__init__(self,
    LINKEDIN,
    consumer_key,
    consumer_secret,
    "https://api.linkedin.com/uas/oauth/requestToken",
    "https://api.linkedin.com/uas/oauth/accessToken",
    callback_url)

I have tried this instead:
https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress
But it gives an Internal Server Error, when I make a request. It works perfect with the default basicprofile request. Some ideas on what is wrong?
Thanks in advance :)

A: You have to give additional params in the oauth.py. Where you put a dictionary with the key 'Scope' and the value should be the permission you want. If you want more than 1 permission, make a space in the value like so 'r_basicprofile r_emailaddress'


text:
Q: Qualifier screen size small does not work for dimens I am new to Android development and I am currently working on supporting different screen sizes and pixel densities for my app. Now, I have a button with the height @dimen/button_height.
In dimens.xml I have the following resource:
<resources>
    <dimen name="button_height">55dp</dimen>
</resources>

Now, I tried the app on different screen sizes and noticed, that, for example, on 3.3" WQVGA, the button is too big. This device is 240x400 px ldpi, which is, 320x533 dp.
I read App resources overview and Support different Screen Sizes (I have to say that to me it is still not 100% clear how to support every devices configurations). According to that, the screen-size of this device is small, so I made another resource file dimens.xml (small) with
<resources>
    <dimen name="button_height">30dp</dimen>
</resources>

Now, when I try this on the emulator, the button is still 55dp high. So, what did I understand wrong? What would be a better approach to support smaller devices?

A: Basically,
Firstly understand the difference between px, dp,sp etc.
Prefer below link
https://stackoverflow.com/a/2025541/6997819
1)
To support multiple screen sizes
You need to create
values-hdpi
values-xhdpi
values-xxhdpi
values-xxhdpi

NOTE: I am suggesting four basic apart from above there are few more.

every values directory will have their own dimen.xml file
Suppose,
dimen.xml file inside values-hdpi have
<dimen name="button_height">55dp</dimen>

then in dimen.xml file inside values-xhdpi you should ideally increase the size
<dimen name="button_height">60dp</dimen>

Now, when you will execute the code the device will automatically pick based on their screen density.
2) Refer below link
https://github.com/intuit/sdp
This will ommit your above struggle.
The mechanism is same, but provided the gradle that will be easy to import and use as well.

A: you can use ssp library to scale font size and sdp library to scale dimention size.


text:
Q: How to change syntax for color and fill color in tkz-eulide In tkz-euclide, points are filled in grey with a black outline. I can setup points to be completely black by using
\tkzSetUpPoint[fill=black]

Now what I would like to have a new keyword rot so that when I type
\tkzDrawPoint[red](P)

it is equal to typing
\tkzDrawPoint[color=red,fill=red](P)

The Problem I see here, is that red is defined and works for example for
\tkzDrawSegment[red](P_1,P_2)
\tkzLabelSegment[red](P_1,P_2){$s$}

MWE:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tkz-euclide}
\begin{document}
\begin{tikzpicture}
  \tkzDefPoint(0,0){P_1} \tkzDefPoint(1,0){P_2}
  \tkzDrawPoint(P_1)
  \tkzDrawPoint[red](P_2)
  \tkzLabelSegment[red](P_1,P_2){$s$}
\end{tikzpicture}
\end{document}

A: correct syntax for change color of points is for example \tkzDrawPoint[color=red](P_2) (for red point border) or \tkzDrawPoints[fill=blue!30](P_2, P_3) for changing fill (observe how is defined color). so try:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tkz-euclide}
\begin{document}
\begin{tikzpicture}
  \tkzDefPoint(0,0){P_1} \tkzDefPoint(1,0){P_2} \tkzDefPoint(2,0){P_3}
  \tkzDrawPoint(P_1)
  \tkzDrawPoints[color=red](P_2)          % <---
  \tkzDrawPoints[color=red,fill=red](P_3) % <---
\end{tikzpicture}
\end{document}

A: So here is my temporary solution to this.
\makeatletter
\pgfkeys{drawpoint/.cd,
  red/.style={color=red,fill=red}
}
\pgfkeys{/tikz/.cd,
  red/.style={color=red},
  Red/.style={color=red,fill=red!30,opacity=0.3},
}
\makeatother

This now allows the use of those there defined colors not only for the command like \tkzDrawSegment but also for \tkzDrawPoint and \tkzDrawCircle
Example:
\documentclass{standalone}
\usepackage{tkz-euclide}
\usetkzobj{all}

\makeatletter
\pgfkeys{drawpoint/.cd,
  red/.style={color=red,fill=red}
}
\pgfkeys{/tikz/.cd,
  red/.style={color=red},
  Red/.style={color=red,fill=red!30,opacity=0.3},
}
\makeatother

\begin{document}
\begin{tikzpicture}
  \tkzDefPoints{0.5/0.5/A,1.5/0.5/B,1.5/1.5/C,0.5/1.5/D,1/1/M}
  \tkzDrawPoint[red](M)
  \tkzDrawPolygon(A,B,C,D)
  \tkzMarkAngle[Red,size=0.3cm](D,C,B)
  \tkzDrawCircle[Red](A,M)
\end{tikzpicture}
\end{document}


text:
Q: Using EF transaction across libraries I have this class A that begins an EF transaction where UserDb is my DbContext
 using (DbContextTransaction dbTransaction = UserDb.Database.BeginTransaction(IsolationLevel.ReadUncommitted))

Then I have several inserts and there is a need to call another library [which essentially lives on the same server in the bin folder] to do another insert.
new ExtLibrary().CreatePoweruser(3, UserDb);

As you can see I am passing the same connection. And this statement is within the top using which I thought would mean that everythign is in the same transaction.
Extlibrary code:

Data.Entities.User UserEntity = new Data.Entities.User            {
            UserTypeId =34,

            CreatedDate = DateTime.Now,
            CreatedBy = "mk92Test",
                       };
        UserDb.Users.Add(UserEntity);
        UserDb.SaveChanges();

Everything works unless the ExtLibrary insert fails. Control comes back to the parent class which has rollback code on exception and I get an The underlying provider failed on rollback. But the first set of inserts certainly do rollback even after this exception.
Please advise.


text:
Q: Probability of two vertices to be connected in G(n,p) A question I asked at math.SE without elliciting an answer.
Let $G(n,p)$ be an Erdős–Rényi graph on $n$ vertices. Is there an explicit expression for the probability $P_{n,p}(u,v)$ that two fixed (distinct) vertices $u,v$ lie in the same connected component of $G(n,p)$?
I'm familiar with the standard asymptotic results about connected components in Erdős–Rényi graphs but was unable to find explicit results for $P_{n,p}$ for finite $n$. I expect these probabilities to be polynomials in $p$ of degree $n(n-1)/2$ but did not succeed in determining the coefficients for general $n$ and $p$.
I fed the values of $P_{n,1/2}$, for $n=2,3,4,5$, into OEIS, but did not obtain a match.
Edit (14 March 2014)
After Brendan McKay's helpful comment, I found the formula
$$
R_n(p) = \sum_{j=1}^{n-1}{\binom{n-1}{j-1}(1-p)^{j(n-j)}R_j(p)},\quad R_1(p)=1,
$$
for the all-terminal reliability polynomial $R_n$ of the complete graph on $n$ vertices (i.e. the probability that the graph remains connected after deleting edges with probability $p$) and the formula
$$
T_n(p) = \sum_{j=2}^{n}{\binom{n-2}{j-2}(1-p)^{j(n-j)}R_j(p)}
$$
for the 2-terminal reliability polynomial (i.e. the probability that vertices 1 and 2 are in the same connected component after deleting edges with probability $p$).
The experimentalist that I am, I used the first recursion to compute $R_n$ for a few values of $n$ and tried to guess a pattern for its coefficients.
What I found is that $\frac{R_n(1-p)}{(1-p)^{n-1}}$ is a polynomial of degree $(n-2)(n-1)/2$ and that the coefficients of its monomials with small exponent seem to be given by
$$
[p^i]\frac{R_n(1-p)}{(1-p)^{n-1}} = \color{blue}{\binom{n-2+i}{n-2},\quad i=0,1,\ldots,n-2}.\tag{*}
$$
For the monomials with large exponents there appear to exist polynomials $\mathfrak{p}_j$ of degree $j$ such that, for $\color{green}{i=\frac{(n-2)(n-1)}{2}-n+1,\ldots,\frac{(n-2)(n-1)}{2}}$,
$$
[p^i]\frac{R_n(1-p)}{(1-p)^{n-1}}=\color{green}{\frac{(n-1)!}{\left[2\left(\frac{(n-2)(n-1)}{2}-i\right)\right]!!}\mathfrak{p}_{\frac{(n-2)(n-1)}{2}-i}(n)},\tag{**}
$$
where !! denotes the double factorial.
The first few polynomials $\mathfrak{p}_j$ appear to be given by
$$
\begin{array}{c|c}
j&\mathfrak{p}_j\\\hline
0 & 1 \\
1 & n-2\\
2 & n^2-3 n\\
3 & n^3-3 n^2-2 n\\
4 & n^4-2 n^3-5 n^2-18 n\\
5 & n^5-5 n^3-80 n^2+4 n\\
6 & n^6+3 n^5+5 n^4-195 n^3-86 n^2-848 n\\
7 & n^7+7 n^6+35 n^5-315 n^4-476 n^3-6132 n^2+160 n
\end{array}
$$
The leading coefficients seems to be one; the next-to-leading coefficient in $\mathfrak{p}_j$, i.e. $[p^{j-1}]\mathfrak{p}_j$, appears (tentatively) to be given by $j(j-5)/2$. I haven't had a chance to look at the other coefficients yet.
Unfortunately, the two formulas (*) and (**) cover only a small proportion of the quadratically many coefficients of $\frac{R_n(1-p)}{(1-p)^{n-1}}$, as indicated in the next coefficient table.
$$
\scriptsize{
\begin{array}{c|cccccccccccccccccccccc}
n,i & 0 & 1 & 2 & \ldots\\\hline
2 & \color{blue} 1\\
3 & \color{blue} 1 & \color{blue}2\\
4 & \color{blue} 1 & \color{blue}3 & \color{blue}6 & \color{green}6\\
5 & \color{blue}1 & \color{blue}4 & \color{blue}{10} & \color{blue}{20} & \color{green}{30} & \color{green}{36} & \color{green}{24}\\
6 & \color{blue}{1} & \color{blue}{5} & \color{blue}{15} & \color{blue}{35} & \color{blue}{70} & \color{green}{120} & \color{green}{180} & \color{green}{240} & \color{green}{270} & \color{green}{240} & \color{green}{120}\\
7 & \color{blue}{1} & \color{blue}{6} & \color{blue}{21} & \color{blue}{56} & \color{blue}{126} & \color{blue}{252} & \color{red}{?} & \color{red}{?} & \color{red}{?} & \color{green}{1610} & \color{green}{2100} & \color{green}{2520} & \color{green}{2730} & \color{green}{2520} & \color{green}{1800} & \color{green}{720}\\
8 & \color{blue}{1} & \color{blue}{7} & \color{blue}{28} & \color{blue}{84} & \color{blue}{210} & \color{blue}{462} & \color{blue}{924} & \color{red}{?} & \color{red}{?} & \color{red}{?} & \color{red}{?} & \color{red}{?} & \color{red}{?} & \color{red}{?} & \color{green}{24640} & \color{green}{29400} & \color{green}{32970} & \color{green}{34230} & \color{green}{31920} & \color{green}{25200} & \color{green}{15120} & \color{green}{5040}
\end{array}
}
$$
Up to $n=6$, the reliability polynomial of $K_n$ is correctly computed by (*) and (**) but beyond that a growing chunk of coefficients is missing in the middle.
Questions:
What are the polynomials $\mathfrak{p}_j$? How can one compute the $\color{red}?$ coefficients?

A: Explicit expressions for the all-terminal reliabilty were established back in 1959 by Gilbert.
Gilbert, E. N. Random graphs. Ann. Math. Statist. 30 1959 1141--1144. MR0108839 (21 #7551)


text:
Q: TortoiseSVN "Can't Set position pointer in file \SVN\db\revs\0\4 An attempt was made to move the file pointer before the beginning of the file" I am working on an SVN C++ project that was working without issues with a remote SVN repository, but it started giving me the following errors errors
"Can't Set position pointer in file \SVN\db\revs\0\4 An attempt was made to move the file pointer before the beginning of the file"
And this happened when I try to commit or update or check out the code
I tried the followign steps, and neither one worked

*

*Clean-up

*Delete trunk + make a new trunk from local code

*Delete entire SVN repository and create a new one from local code

None of this worked, and the same error still comes up.
Everything I looked up said it was a server-side SVN error, but I tried making a repository on the same computer and it still gave me these problems.
Other projects check in and check out fine.
The other issue I have is that it doesn't report which file is the problematic file, is there a way to view the logs and determine if its a file that is causing this problem?
Thanks,
-D

A: I tried re-creating another repository on the same network drive and it gave me the same error. When I re-created that repository locally, there was no error.
This leads me to believe it's a networking or firewall issue

A: You may have .svn files in your local code that might be giving you some trouble. You should try looking for these hidden files and getting rid of them.


text:
Q: Parametric representation for triangle mesh I have worked on triangle mesh for a while. The mesh is reconstructed from range images captured via one 3D scanner. Currently I am very interested in using parametric surfaces to represent one mesh. It says from one book that Parametric surfaces are defined by a vector-valued parameterization function that maps a 2D parameter domain to the surface.  However, the parameter domain is always written as (u, v) instead of (x,y). In my view, parameter domain(x,y) is very straightforward.
In computer-aided geometric design where NURBS surface is popularly employed, the NURBS surface is represented by parameter domain (u,v), is it difficult to find the parameter domain(u,v) from cartesian coordinates of points?


text:
Q: Find a recursive relation for the case of a length $n$ binary string where there are no three consecutive $0$'s.
Find a recursive formula for the following example. The number of binary strings of length $n$, such that there are no $3$ consecutive $0's$.

I started by considering the length $n$ as a block ($1$ row) with $n$ many columns. I started off by considering only the last column, marked $x$. Here's my working:

Int the case that the very last string is $0$, I think my working out is correct. Now, if the last string is $1$, then I'm left with $n-1$ without any further complications. Therefore, $a_n= 2a_{(n-1)}+a_{(n-2)}+a_{(n-3)}$. Is this correct?

A: Critique
The diagram in the question is correct, but the recursion drawn from it is slightly off. In the diagram, it is shown that each of the $a_n$ strings of length $n$ with out a '$000$' can be classified as follows:
It ends in a '$\boldsymbol{1}$':$\phantom{00}$ $\overbrace{\boxed{\phantom{0\times\times\times\times000\times}}\boxed{\times\vphantom{0}}}^{n-1}\!\,\boxed{1\vphantom{\times}}$ There are $a_{n-1}$ of these.
It ends in a '$\boldsymbol{10}$':$\phantom{0}$ $\overbrace{\boxed{\phantom{0\times\times00\times\times}}\boxed{\times\vphantom{0}}}^{n-2}\!\,\boxed{1\vphantom{\times}}\boxed{0\vphantom{\times}}$ There are $a_{n-2}$ of these.
It ends in a '$\boldsymbol{100}$': $\overbrace{\boxed{\phantom{0\times\times\times\times}}\boxed{\times\vphantom{0}}}^{n-3}\!\,\boxed{1\vphantom{\times}}\boxed{0\vphantom{\times}}\boxed{0\vphantom{\times}}$ There are $a_{n-3}$ of these.
Therefore, adding these cases up, we get
$$
a_n=a_{n-1}+a_{n-2}+a_{n-3}\tag1
$$
In the question, it seems that the intermediate tree node, i.e. $\overbrace{\boxed{\phantom{0\times\times\times\times}}\boxed{\times\vphantom{0}}}^{n-1}\!\boxed{0\vphantom{\times}}$, is being included in the counting, but that node is counted in the leaves below it.

Generating Function Approach
Let $x$ represent the atom '$1$', $x^2$ represent the atom '$10$', and $x^3$ represent the atom '$100$'.
$\left(x+x^2+x^3\right)^k$ counts the strings made up of $k$ atoms; the coefficient of $x^n$ telling the how many strings of length $n$ can be made from $k$ atoms. After adding up the contributions from all numbers of the atoms, we handle the strings starting with '$0$' and '$00$' by multiplying by $\left(1+x+x^2\right)$ to get the generating function for the number of strings that can be made up from any number of atoms is
$$
\begin{align}
\left(1+x+x^2\right)\sum_{k=0}^\infty\left(x+x^2+x^3\right)^k
&=\left(1+x+x^2\right)\sum_{k=0}^\infty\left(\frac{x-x^4}{1-x}\right)^k\\
&=\left(1+x+x^2\right)\frac1{1-\frac{x-x^4}{1-x}}\\
&=\left(1+x+x^2\right)\frac{1-x}{1-2x+x^4}\\[3pt]
&=\frac{1+x+x^2}{1-x-x^2-x^3}\\[9pt]
&=1+2x+4x^2+7x^3+13x^4+24x^5+\dots
\end{align}
$$
The denominator of $1-x-x^2-x^3$ gives the recurrence $a_n=a_{n-1}+a_{n-2}+a_{n-3}$.

A: To gather the comments:

*

*You are leaving out the $a$'s.  There is a difference between the meaning of $a_{n-1}$ and the value $(n-1)$.  On the one hand $a_{n-1}$ is the number of valid length $n-1$ strings we are wanting to count.  On the other hand $(n-1)$ is merely the length of a length $n-1$ string... not the count of them.

*You have a rogue $2$ which appeared which shouldn't have, perhaps from reading your image incorrectly.  It feels like when you went to break into cases you broke into the case where the final digit was a $1$ which accounts for $a_{n-1}$ of the total, and where you broke into where the final digit was a $0$.  You broke this second case down into two further subcases of sizes $a_{n-2}$ and $a_{n-3}$ respectively and added...  It felt like maybe you accidentally added a value intended to be for the second case before it was broken into subcases as well but this was unnecessary as we were adding the values for the subcases already so it should already by covered.
Additionally:

*

*You haven't written any initial conditions yet.

For initial conditions, a tip: it can be easier to deal with zero as it is far more convenient.  You can work with as one of the initial conditions that $a_0 = 1$.  It is worth making sure you fully understand why $a_0=1$, that there is in fact a unique length zero valid string, namely " ".
If that is too abstract for you to accept (though, you really should learn to come to terms with it sooner rather than later), then go ahead and count with your fingers how many valid strings there are of length $1$, $2$, and $3$ manually.  I discourage this however as it can be easy to make a mistake, especially for larger harder problems.
The fact that "0" is a valid string of length $1$ is also worth taking into account as otherwise this might have been missed by the formula (as I had done before my edit).
So... our final answer should have read:
$$a_n = a_{n-1}+a_{n-2}+a_{n-3}~~~~~\text{for all }n>2\\a_0 = 1~~~~a_1 = 2~~~~~a_2=4$$


text:
Q: Codeigniter blank page when load database So after while searching into stackoverflow, decide to write this question.
I'm working this time on Godaddy's hosting cPanel plan.
Uploaded a clean package of Codeigniter V 2.2.6 and the welcome message shows as it should.
I configured config.php with url and database.php with the correct connection data.
Until now, everything work as it should.
So after that load database to see if everything goes bien and the "blank screen of dead" appears if I refresh the page.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        $this->load->database();
        $this->load->view('welcome_message');
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

So after searching where it breaks, I found inside /system/core/Codeigniter.php in lines 300. Break before $CI = new $class();
/*
 * ------------------------------------------------------
 *  Instantiate the requested controller
 * ------------------------------------------------------
 */
    // Mark a start point so we can benchmark the controller
    $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
    $CI = new $class();

And Inside the log files, returned this lines
DEBUG - 2015-11-19 20:57:31 --> Config Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Hooks Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Utf8 Class Initialized
DEBUG - 2015-11-19 20:57:31 --> UTF-8 Support Enabled
DEBUG - 2015-11-19 20:57:31 --> URI Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Router Class Initialized
DEBUG - 2015-11-19 20:57:31 --> No URI present. Default controller set.
DEBUG - 2015-11-19 20:57:31 --> Output Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Security Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Input Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Global POST and COOKIE data sanitized
DEBUG - 2015-11-19 20:57:31 --> Language Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Loader Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Helper loaded: url_helper
DEBUG - 2015-11-19 20:57:31 --> Helper loaded: html_helper
DEBUG - 2015-11-19 20:57:31 --> Helper loaded: cms_helper
DEBUG - 2015-11-19 20:57:31 --> Helper loaded: drops_helper
DEBUG - 2015-11-19 20:57:31 --> Controller Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Model Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Model Class Initialized
DEBUG - 2015-11-19 20:57:31 --> Helper loaded: form_helper
DEBUG - 2015-11-19 20:57:31 --> Database Driver Class Initialized

I need to deploy a web made in other server and when I uploaded inside Godaddy the blank page appears, that's the reason why I upload a clean package of Codeigniter.
Anyone can help me?
Thanks in advance.

EDIT
Forgot to write the error report on index.php
define('ENVIRONMENT', 'development');

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'development':
            ini_set('display_errors',1);
            error_reporting(E_ALL);
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

A: Load database Library in application/config/autoload.php like follows:
$autoload['libraries'] = array('database');

Remove following line from your file:
$this->load->database();


text:
Q: SFML Sprite not displaying I recently started learning SFML and I am trying to display an image. The image is supposed to be displayed on the screen and be movable with arrow keys and WASD.
However, am getting a blank screen with an error Failed to load image "image.png". Reason: Unable to open file, when I display a bitmap it works. How can I fix this?
// ConsoleApplication8.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <SFML\Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "SFML works!", sf::Style::Resize | sf::Style::Default);
    sf::CircleShape shape(100.f);
    sf::Vector2i position(-9,0);
    shape.setFillColor(sf::Color::Green);
    sf::Texture texture;
    if (!texture.loadFromFile("image.png", sf::IntRect(10, 10, 32, 32)))
    {
        std::cout << "Could not load image\n";
        system("pause");

    }
    sf::Sprite Sprite;
    Sprite.setTexture(texture);
    while (window.isOpen())
    {

        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            switch (evnt.type)
            {
            case sf::Event::Closed:
                window.close();
                break;
            }
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)) {
            Sprite.move(0.0f, -1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) {
            Sprite.move(0.0f, 1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            Sprite.move(-1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            Sprite.move(1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) {
            Sprite.move(0.0f, -1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) {
            Sprite.move(0.0f, 1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) {
            Sprite.move(-1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) {
            Sprite.move(1.0f, 0.0f);
        }
        window.setPosition(position);
        window.clear();
        window.draw(Sprite);
        window.display();
    }

    return 0;
}

A: Make sure that image.png is in the correct place. \Visual Studio 2015\Projects\*ProjectName*\*ProjectName*
If it is in there try and put it in the directory with the executable in it.
\Visual Studio 2015\Projects\*ProjectName*\Debug(or release)


text:
Q: Angular JS Factory Variables is undefined I have been attempting to create a script that grabs session data from a PHP API using Angular JS to create authentication.
I have created a factory called User and in my loginController I use User.Initialise() to check whether the session in PHP has a user_id attached to it.
When using User.Initialise() in my loginController (bare in mine my session has a user attached to it) it will use $location.path("/dashboard") to change the route to the dashboard. The dashboard route has a controller that has the variable $scope.UserID which is assigned using User.Session.user_id, however, when I attempt to call User.Session it returns undefined, even though User.Initialise(); assigns it in the loginController.
Can anybody shed some light on this?
var $Gladium = angular.module("Gladium", ["ngRoute", "ngAnimate", "ngSanitize"]);

$Gladium.config(function($routeProvider, $locationProvider){

    $routeProvider.when("/",{
        templateUrl: "pages/login.html",
        controller: "loginController"
    }).when("/dashboard",{
        templateUrl: "pages/dashboard.html",
        controller: "dashboardController"
    }).when("/error/:error_code", {
        templateUrl: "pages/system_error.html",
        controller: "errorController"
    });

});

/* Controllers */
$Gladium.controller("dashboardController", function($scope, User){
    console.log("Services:");
    console.log(User.Session);

});
$Gladium.controller("loginController", function($scope, $location, User){

    User.Initialise().then(function(){
        $scope.Authenticate = true;
        if(User.loggedIn()){
            $location.path("/dashboard");
        }
    });

    /* Variables */
    $scope.Email;
    $scope.Password;

    $scope.Login = function(){
        if(User.logIn($scope.Email, $scope.Password)){
            $location.path("/dashboard");
            return true;
        }
    }

});
$Gladium.controller("errorController", function($scope, $routeParams){

    $scope.Errors = {
        "request": "We couldn't process that request at this time. Please try again later.",
        "unknown": "An unknown error occurred if this is persistant please contact technical support."
    };

    $scope.currentError =  $scope.Errors[$routeParams["error_code"]];

});

/* Factories */
$Gladium.factory("User", function($http, $location){

    var Session;
    var Error;

    return {

        Initialise: function(){
            return $http.get("core.php?do=getSession").then(function(requestData){

                if(requestData.data["requestStatus"] == 1){
                    Session = requestData.data.data;
                }else{
                    $location.path("/error/request");
                    return false;
                }

            });
        },

        loggedIn: function(){
            if(Session["user_id"] != 0){
                return true;
            }else{
                return false;
            }

        },

        logOut: function(){
            if(Session["user_id"] != 0 ){
                $http.post("core.php",{
                    do: "logout"
                }).then(function(requestData){
                    if(requestData.data["requestStatus"] == 1){

                    }else{

                    }
                });
            }else{
                console.warn("There is no user session to logout.");
            }
        },

        logIn: function(Email, Password){
            $http.post("core.php",{
                do: "login",
                email: Email,
                password: Password
            }).then(function(requestData){
                if(requestData.data["requestStatus"] == 1){

                    Data = requestData.data;

                    if(Data["actionStatus"] == 1){
                        Initialise();
                    }else{
                        Error = Data["Error"];
                        return false;
                    }

                }else{
                    $location.path("/error/request");
                    return false;
                }

                $location.path("/error/unknown");
                return false;
            });
        }

    }

});

A: I think that u just forget to return the Session variable which should be a property of User Service
....
$Gladium.factory("User", function($http, $location){

var Session;
var Error;

return {
    // return the Session so it can be accessed via User.Session, or it is a variable in private closure
    Session:Session
    Initialise: function(){
        return $http.get("core.php?do=getSession").then(function(requestData){

            if(requestData.data["requestStatus"] == 1){
                Session = requestData.data.data;
            }else{
                $location.path("/error/request");
                return false;
            }

        });
    },
....

UPDATE
Sorry the change above won't solve your problem since you are assigning the Session closure variable, which will not change User.Session.In this way it still remains undefined.
There are several ways for you to solve this problem.
One i think that is the most simple is to keep the Session private and access it via a get function User.getSession().
$Gladium.factory("User", function($http, $location){

var Session;
var Error;

return {
// use get function to get Session
getSession:function(){
  return Session;
},
Initialise: function(){
    return $http.get("core.php?do=getSession").then(function(requestData){

        if(requestData.data["requestStatus"] == 1){
            Session = requestData.data.data;
        }else{
            $location.path("/error/request");
            return false;
        }

    });
},
....

In this way u can access your Session by User.getSession().


text:
Q: How to use read-only borrowed Rust data by multiple Java threads? I have a struct Foo and FooRef which has references to data from Foo:
struct Foo { /* ... */ }

struct FooRef<'foo> { /* ... */ }

impl Foo {
    pub fn create_ref<'a>(&'a self) -> FooRef<'a> { /* ... */ }
}

Now Foo directly cannot be used in the logic; I need FooRef. Creating FooRef requires lots of computation, so I do it once just after creating the Foo instance. FooRef is immutable; it's only used for reading data.
Multiple threads needs to access this FooRef instance. How can I implement this? The calling threads are Java threads and this will be used with JNI. This prevents using a scoped threadpool, for example.
Another complication is that when I have to refresh the Foo instance to load new data into it. I then also need to recreate the FooRef instance as well.
How can this be achieved thread-safely and memory-safely? I tried messing around with pointers and RwLock but that resulted in a memory leak (the memory usage kept on adding on each reload). I am a Java developer that is a newbie to pointers.
The data in Foo is mostly text and about 250Mb. The FooRef is mostly strs and structs of strs borrowed from Foo.
My Java usage explanation
I use two long variables in a Java class to store pointers to Foo and FooRef. I use a static ReentrantReadWriteLock to guard these pointers.
If the data need to be updated in Foo, I acquire a write lock, drop FooRef, update Foo, create a new FooRef and update the ref pointer in Java.
If I need to read the data (i.e. when I am not updating Foo), I acquire a read lock and use the FooRef.
The memory leak is visible only when multiple Java threads are calling this code.
Rust:
use jni::objects::{JClass, JString};
use jni::sys::{jlong, jstring};
use jni::JNIEnv;

use std::collections::HashMap;

macro_rules! foo_mut_ptr {
    ($env: expr, $class: expr) => {
        $env.get_field(*$class, "ptr", "J")
            .ok()
            .and_then(|j| j.j().ok())
            .and_then(|ptr| {
                if ptr == 0 {
                    None
                } else {
                    Some(ptr as *mut Foo)
                }
            })
    };
}

macro_rules! foo_ref_mut_ptr {
    ($env: expr, $class: expr) => {
        $env.get_field(*$class, "ptrRef", "J")
            .ok()
            .and_then(|j| j.j().ok())
            .and_then(|ptr| {
                if ptr == 0 {
                    None
                } else {
                    Some(ptr as *mut FooRef)
                }
            })
    };
}

macro_rules! foo_mut {
    ($env: expr, $class: expr) => {
        foo_mut_ptr!($env, $class).map(|ptr| &mut *ptr)
    };
}

macro_rules! foo_ref {
    ($env: expr, $class: expr) => {
        foo_ref_mut_ptr!($env, $class).map(|ptr| &*ptr)
    };
}

#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "system" fn Java_test_App_create(_env: JNIEnv, _class: JClass) -> jlong {
    Box::into_raw(Box::new(Foo::default())) as jlong
}

#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "system" fn Java_test_App_createRef(env: JNIEnv, class: JClass) -> jlong {
    let foo = foo_mut!(env, class).expect("createRef was called on uninitialized Data");
    let foo_ref = foo.create_ref();
    Box::into_raw(Box::new(foo_ref)) as jlong
}

#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "system" fn Java_test_App_reload(env: JNIEnv, class: JClass) {
    let foo = foo_mut!(env, class).expect("foo must be initialized");
    *foo = Foo {
        data: vec!["hello".to_owned(); 1024 * 1024],
    };
}

#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "system" fn Java_test_App_destroy(env: JNIEnv, class: JClass) {
    drop_ptr(foo_ref_mut_ptr!(env, class));
    drop_ptr(foo_mut_ptr!(env, class));
}

#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "system" fn Java_test_App_destroyRef(env: JNIEnv, class: JClass) {
    drop_ptr(foo_ref_mut_ptr!(env, class));
}

unsafe fn drop_ptr<T>(ptr: Option<*mut T>) {
    if let Some(ptr) = ptr {
        let _foo = Box::from_raw(ptr);
        // foo drops here
    }
}

#[derive(Default)]
struct Foo {
    data: Vec<String>,
}

#[derive(Default)]
struct FooRef<'a> {
    data: HashMap<&'a str, Vec<&'a str>>,
}

impl Foo {
    fn create_ref(&self) -> FooRef {
        let mut data = HashMap::new();
        for s in &self.data {
            let s = &s[..];
            data.insert(s, vec![s]);
        }
        FooRef { data }
    }
}

Java:
package test;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class App implements AutoCloseable {
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final ReadLock readLock = lock.readLock();
    private final WriteLock writeLock = lock.writeLock();

    private volatile long ptr;
    private volatile long ptrRef;
    private volatile boolean reload;

    static {
        System.loadLibrary("foo");
    }

    public static void main(String[] args) throws InterruptedException {
        try (App app = new App()) {
            for (int i = 0; i < 20; i++) {
                new Thread(() -> {
                    while (true) {
                        app.tryReload();
                    }
                }).start();
            }

            while (true) {
                app.setReload();
            }
        }
    }

    public App() {
        this.ptr = this.create();
    }

    public void setReload() {
        writeLock.lock();
        try {
            reload = true;
        } finally {
            writeLock.unlock();
        }
    }

    public void tryReload() {
        readLock.lock();
        debug("Got read lock");

        if (reload) {
            debug("Cache is expired");

            readLock.unlock();
            debug("Released read lock coz expired");

            writeLock.lock();
            debug("Got write lock");

            try {
                if (reload) {
                    fullReload();
                }

                readLock.lock();
                debug("Got read lock inside write");
            } finally {
                writeLock.unlock();
                debug("Released write lock");
            }
        }

        readLock.unlock();
        debug("Released read lock");
    }

    private void fullReload() {
        destroyRef();
        debug("Dropped ref");

        debug("Reloading");
        reload();
        debug("Reloading completed");

        updateRef();
        debug("Created ref");
        reload = false;
    }

    private void updateRef() {
        this.ptrRef = this.createRef();
    }

    private native void reload();

    private native long create();

    private native long createRef();

    private native void destroy();

    private native void destroyRef();

    @Override
    public void close() {
        writeLock.lock();
        try {
            this.destroy();
            this.ptrRef = 0;
            this.ptr = 0;
        } finally {
            writeLock.unlock();
        }
    }

    private static void debug(String s) {
        System.out.printf("%10s : %s%n", Thread.currentThread().getName(), s);
    }

}

A: The problem that I was thinking as memory leak wasn't actually a memory leak. The issue was that the allocator was using thread local arenas. So, whatever thread was reloading 250MB of data was leaving the allocated space as is and not returning it to the system. This issue was not specific to JNI, but also happening in pure safe rust code. See Why multiple threads using too much memory when holding Mutex
The default number of arenas created defaults to 8 * cpu count = 64 in my case. This setting can be overridden by setting MALLOC_ARENA_MAX env variable.
So I resolved this issue by setting MALLOC_ARENA_MAX env variable to 1 . So, the approach I took is fine. It was just platform specific issue.
This issue was occurring only in Ubuntu in WSL. I also tried the same code without any tweaking on Windows 10 and it works perfectly without any issues.


text:
Q: Integrating Flask and ReactJS with the use of jQuery TL;DR: How am I able to integrate/implement a jQuery code(please see below) into ReactJS?
Greetings everyone. Amateur user of ReactJS and Flask here.
I'm just looking for a solution on how to integrate a jQuery code into ReactJS  or even other alternatives considering the implementation in the lifecycle becomes different into ReactJS.
Currently, this snippet (kindly see the boilerplate jQuery code below) communicates with Flask's CRUD operations very well which sends the chosen image from FileReader() in base64 form and responds with the corresponding prediction (by an ML model) when the #predict-button is pressed.

    <input id="image-selector" type="file">
    <button id="predict-button">Predict</button>

Predictions

foo1:

foo2:

foo3:

Not to mention, I don't need the FileReader() anymore as I have this function captureShot() from 'react-webcam' in ReactJS which returns a base64 encoded string of the current webcam image.
  captureShot = () => {
    const screenshot = this.webcam.getScreenshot();
    this.setState({ imageData: screenshot });

  }

These kind of questions arise:

*

*Can this be implemented in ReactJS?

*If so, how? Will it be through ComponentDidMount() or inside the render()?

*If not, is using Express the way to do the CRUD operations in ReactJS en route to Flask?

Any kind of help would be highly appreciated. Thank you very much for your time and consideration.

A: This question is probably too broad for SO, but the short answer is "yes" you can do this. To get you thinking in the React way is probably the best I can offer for an answer without building it for you.
Your image-selector div will become a React component.  It will have an onChange prop that will point to a custom class method where you can do the rest of your business logic.  Your predict-button will similarly become a component, this time with onClick as your prop.  Since you are running all your functions as a response to an action, you don't need any bootstrapped data in constructor or componentDidMount.
You can use native fetch or similar libraries to replace your $.post call too.  In the end you won't need any of your jQuery code, but if you convert your code piece-by-piece, you will get there and learn a lot along the way.  I suggest using Create React App for an easy way into the architecture.

A: My sheer excitement of asking this odd question surely have baffled three downvoters ha. Thank you for the kind advice @jmargolisvt, I've managed to do it and my Flask server can now finally communicate well with my ReactJS - project is donezo!
Here's the solution just in-case anyone's interested.
export default class App extends Component {
constructor(props){
    super(props);
    this.state = {
      bar: { foo1: null, foo2: null, foo3: null },
    }
  }

captureShot = () => {
    const screenshot = this.webcam.getScreenshot();
    let base64Image = screenshot.replace("data:image/jpeg;base64,","");
    this.setState({
      imageData: screenshot,
     });

    let message = {
      image: base64Image
    }

   fetch('http://127.0.0.1:5000/', {
    method: 'post',
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify(message)
    })
  .then((response) => {
    console.log(response);
    return response.json();
  })
  .then((data) => {
    this.setState( {
      bar: {
        foo1: (data.prediction.foo1.toFixed(3)),
        foo2: (data.prediction.foo2.toFixed(3)),
        foo3: (data.prediction.foo3.toFixed(3)),
      }
    })
  })
   .catch(error => this.setState({ error,  bar: { foo1: null, foo2: null, foo3: null }, }));
  }
}


text:
Q: toolbar title reset by Activity when using androidx.navigation using androidx.navigation the toolbar-title ist set automatically when using android.label in the nav_graph. this works fine until a configuration-change (e.g. rotate the device) happens. after this, the toolbar-title is reset to the app-title.
it seems that the activity is re-setting the title in Activity.onPostCreate() after navigation's ToolbarOnDestinationChangedListener has set it after the rotation.

A: You have to set up toolbar both with navigation graph and as a support action bar.
val appCompat = requireActivity() as AppCompatActivity
appCompat.setSupportActionBar(toolbar)
appCompat.setupActionBarWithNavController(navController)

Check this for more information.


text:
Q: Copy data from one Excel workbook to another I have created this piece of code, and I don't understand why I get an error

Subscript out of range

It dies when I try to set WsDest.
The two lines before I need, cause the destination file is optional, but the name of the sheet Excel file and sheet is always the same.
An example of what could be in W12 = "C:\Users\DKOMGOMG\Desktop\Etellerandet"
Sub Vopy_Paste_Below_Last_Cell()
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim 1CopyLastRow As Long
Dim 1DestLastRow As Long
Dim strFolder As string, strFile As String

Set wsCopy = Activewoork.Worksheets("output")
StrFolder = ActiveSheet.Range("W12").Value
StrFile = Dir(StrFolder & "\blablalba.xlsm")
Set wsDest = Workbooks("strFile").Worksheets("Ark2")

After this I have more code of course, but this is where I get stranded.
Don't know if I did the strfolder and strfile wrong? Hope someone can help!


text:
Q: Enter modal application state until the next click with Jquery After having limited success with drag&drop mainly because the sluggish and jumpy behavior of slow mobile devices, I want to implement a modal approach to moving an element from a to b like this:

*

*User clicks on an item. The item is visually marked by setting a css class.

*User clicks on a target item. The marked item is instantly moved to the target item.

Alternatively:

*User clicks anywhere but on a target item: marked item is unmarked and nothing else happens.

So the idea is to enter a modal state in (1) and leave the modal state in the (2) or the (3) action.
I have no problem implementing (1) and (2). What I don't now is how to best implement (3). To what should I bind a general "anywhere else" click?

A: I too had run into this problem long back. So I came up with this (hacky?) solution.
FIDDLE
Basically it uses a "proxy" div to simulate "anything but the content".
HTML

Button here

Button here

Button here

Button here

Button here

Button here

Button here

Button here

Button here

Button here

 CSS
#general_everywhere
{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    _background: blue;
    display: block;
}

.button
{
    position: relative;
    padding: 10px;
    width: 100px;
    margin: 5px;
    background: #efefef;
}

.clicked
{
    background: red;
}

 jQuery
$('.button').click(function(){
    $(this).toggleClass('clicked');
});

$('#general_everywhere').click(function(){
    $('.button').removeClass('clicked');
    alert('You clicked on everywhere! You are GOD!');
});

Hope it helps.


text:
Q: Using goto as a error handling strategy I had a code review recently and a debate began. Much of my code looks like this:
for (i = 1; i <= 3; i++)
        {
            DoubleValue = tODBCX->getDouble(KeyFieldCount + i, IsNULL, IsSuccess);
            if (IsNULL)
            {
                LoggerDrillHole::LogToDB(LOG_ERROR, L"Survey depth, dip and azimuth values can not be NULL.", __FUNCTIONW__);
                IsSuccess = false;
                goto EXIT;
            }
            else
            {
                if (i == 1)
                    Depth = DoubleValue;
                else if(i == 2)
                    DipDegrees = DoubleValue;
                else if (i == 3)
                    AzimuthDegrees = DoubleValue;
            }
        }

The contentious goto statement sparked debate. This code is contained within a function that begins life by initializing a local boolean variable IsSuccess = true and the function finally returns IsSuccess. The EXIT strategy looks after essential tidy up code;
EXIT:

    tODBCX->Close();
    if (Key != 0) free(Key);
    Key = 0;
    if (PriorKey != 0) free(PriorKey);
    PriorKey = 0;
    return IsSuccess;

There were several such goto EXIT statements adjacent to setting IsSuccess = false and logging to database and so on. The comment was made that this is disruptive to the flow of the code. One should instead use a do loop (infinite loop) and break out of that loop and then process all of the required instead of using the goto statement.
I intensely disliked the infinite loop strategy, but I could get used to it if it truly improves the readability. Is there a better way?

A: I wanted to mark this as a duplicate of this question. Still, it is not exactly the same, even though the solution is the same:
In C++, the best solution is to use RAII and transactional code. In C, the best solution is to use goto, with following a few rules (only use for return/cleanup, do not use goto to simulate loops, etc).
See my answer in the question mentioned above (basically, the solution is to use RAII and transactional code); this will eliminate completely the need for a goto cleanup/error handling block.

A: There is nothing wrong with using goto here. This is one of the few situations where it is the cleanest solution. (Another example would be breaking out of an inner loop.)
Using a do { ... } while (false) loop is an artificial solution that actually reduces the readability of the code.

A: In C, consider breaking your code into two functions... an outer function that does common intialisation and passes down the variables the inner function needs, such that the inner function can simply return the success status knowing the outer function will clean up.

In C++ it's usually a good idea to use scope guards so destructors ensure proper clean up.  Consider your:
 tODBCX->Close();

If tODBCX needs to live longer than the function call - so a Close() in the destructor doesn't help - then create a helper:
struct Odbc_Access_Guard
{
    Odbc_Access_Guard(ODBC& o) : odbc_(o) { }
    ~Odbc_Access_Guard() { odbc_.close(); }
    operator ODBC&() { return odbc_; }
    operator const ODBC&() const { return odbc_; }
    ODBC& odbc_;
};

Then inside your function:
Odbc_Access_Guard odbc(tODBC);
odbc.xyz();
if (whatever)
   return ...success expression...;

The same thing goes for your pointers: they should probably be shared pointers or guards using the logic above.  Then you can return any time without having to even think about where to go for the clean up code, and wondering if it's up to date with the current variable use.


text:
Q: Dynamically allocate ragged matrix I'm trying to make a generic function which will dynamically allocate 2D structure. Number of elements in every row doesn't have to be same for all rows. Structure is represented as a container type, whose elements are again of a container type (for example a set of lists). The type of elements of that inner container can also be arbitrary. Containers only support the begin, end, and size functions. Iterator operations must be supported for all iterator types. The function should first dynamically allocate the space for storing the 2D structure by the continuous allocation procedure, and then rewrite the elements of the structure it has accepted into the dynamic structure. The function returns a double pointer through which the elements of this structure can be accessed.
#include <iostream>
#include <set>
#include <list>
#include <vector>
template < typename tip >
  auto Make2DStructure(tip mat) {
    using tip_objekta = typename std::decay < decltype(mat[0][0]) > ::type;
    tip_objekta ** dynamic_mat = nullptr;
    int rows = 0, total = 0;
    for (auto i: mat) {
      rows++;
      for (auto j: i)
        total++;
    }
    int columns[rows];
    int k = 0;
    for (auto i: mat) {
      int num_of_colums = 0;
      for (auto j: i)
        num_of_colums++;
      columns[k] = num_of_colums;
      k++;
    }

    try {
      dynamic_mat = new tip_objekta * [rows];
      dynamic_mat[0] = new tip_objekta[total];
      for (int i = 1; i < rows; i++)
        dynamic_mat[i] = dynamic_mat[i - 1] + columns[i];
      for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns[i]; j++)
          dynamic_mat[i][j] = mat[i][j];
    } catch (...) {
      delete[] dynamic_mat[0];
      delete[] dynamic_mat;
      throw std::bad_alloc();
    }
    return dynamic_mat;
  }

int main() {
    std::vector<std::vector<int>>mat{
        {1,2},
        {3,4,5,6},
        {7,8,9}
    };
    int columns[3]={2,4,3};
  try {
    int ** dynamic_mat = Make2DStructure(mat);
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < columns[i]; j++)
        std::cout << dynamic_mat[i][j] << " ";
      std::cout << std::endl;
    }
    delete[] dynamic_mat[0];
    delete[] dynamic_mat;
  } catch (...) {
    std::cout << "Problems with memory";
  }
  return 0;
}

How could I modify this to work without indexing inside Make2DStrucure()?
Also, if I used std::set<std::list<int>> instead of std::vector<std::vector<int>> in main function I would have deduction problems. How could I modify this to work for different outside and inside container?

A: Here's one way to accomplish what you want:
#include <iterator>
#include <type_traits>

template <typename tip>
auto Make2DStructure(tip&& mat) {
    // create an alias for the value type:
    using value_type = std::decay_t<decltype(*std::begin(*std::begin(mat)))>;

    // allocate memory for the return value, the pointer-pointer:
    value_type** rv = new value_type*[mat.size()]; // C++17: std::size(mat)

    // Calculate the number of values we need to allocate space for:
    size_t values = 0;
    for(auto& inner: mat) values += inner.size();  // C++17: std::size(inner)

    // allocate the space for the values:
    value_type* data = new value_type[values];

    // loop over the outer and inner container and keep the index running:
    size_t idx = 0;

    for(auto& inner : mat) {
        // assign the outer pointer into the flat data block:
        rv[idx++] = data;
        for(auto& val : inner) {
            // assign values in the data block:
            *data++ = val;
        }
    }

    return rv;
}

With the use of std::size where indicated, this would work with plain arrays too, not only the container classes.


text:
Q: The Difference Between Deprecated, Depreciated and Obsolete There is a lot of confusion about this and I'd like to know, what exactly is the difference between depreciated, deprecated and obsolete, in a programming context, but also in general.
I know I could just look at an online dictionary, and I have, even at many, but they don't all agree, or there are differences in what they say. So I decided to just ask here, considering I also want an answer in a programming context.
If I understand right, deprecated means it shouldn't be used anymore, because it has been replaced by a better alternative, or just because it has been abandoned. Obsolete means it doesn't work anymore, was removed, or doesn't work as it should anymore. And depreciated, if I understand right, once more, has completely nothing to do with programming and just means something has a lowered value, or was made worse.
Am I right, or am I wrong, and if I am wrong, what exactly do each of these mean?

A: Records are obsolete, CDs are deprecated, and the music industry is depreciated.

A: With all due respect, this is a slight pet peeve of mine and the selected answer for this is actually wrong.
Granted language evolves, e.g., "google" is now a verb, apparently. Through what's known as "common use", it has earned its way into official dictionaries. However, "google" was a new word representing something heretofore non-existent in our speech.
Common use does not cover blatantly changing the meaning of a word just because we didn't understand its definition in the first place, no matter how many people keep repeating it.
The entire English-speaking computer industry seems to use "deprecate" to mean some feature that is being phased out or no longer relevant. Not bad, just not recommended. Usually, because there is a new and better replacement.
The actual definition of deprecate is to put down, or speak negatively about, or to express disapproval, or make fun of someone or something through degradation.
It comes from Latin de- (against) precari (to pray). To "pray against" to a 21st century person probably conjures up thoughts of warding off evil spirits or something, which is probably where the disconnect occurs with people. In fact, to pray or to pray for something meant to wish good upon, to speak about in a positive way. To pray against would be to speak ill of or to put down or denigrate. See this excerpt from the Oxford English Dictionary.

*

*Express disapproval of:
(as adjective deprecating) he sniffed in a deprecating way

*another term for depreciate ( sense 2).
he deprecates the value of children's television
What people generally mean to convey when using deprecate, in the IT industry anyway, and perhaps others, is that something has lost value. Something has lost relevance. Something has fallen out of favor. Not that it has no value, it is just not as valuable as before (probably due to being replaced by something new.) We have two words that deal with concept in English and the first is "depreciate". See this excerpt from the Oxford English Dictionary.

*

*Diminish in value over a period of time:
the pound is expected to depreciate against the dollar

*Disparage or belittle (something):
Notice that definition 2 sounds like deprecate. So, ironically, deprecate can mean depreciate in some contexts, just not the one commonly used by IT folk.
Also, just because currency depreciation is a nice common use of the word depreciate, and therefore easy to cite as an example, doesn't mean it's the only context in which the word is relevant.  It's just an example.  ONE example.
The correct transitive verb for this is "obsolete".  You obsolete something because its value has depreciated.
See this excerpt from the Oxford English Dictionary.
Verb - Cause something to be or become obsolete by replacing it with something new.
It bugs me, it just bugs me. I don't know why. Maybe because I see it everywhere. In every computer book I read, every lecture I attend, and on every technical site on the internet, someone invariably drops the d-bomb sooner or later. If this one ends up in the dictionary at some point, I will concede, but conclude that the gatekeepers of the English lexicon have become weak and have lost their way... or at the very least, lost their nerve. Even Wikipedia espouses this misuse, and indeed, defends it. I've already edited the page thrice, and they keep removing my edits.
Something is depreciated until it is obsolete.  Deprecate, in the context of IT, makes no sense at all, unless you're putting down someone's performance or work or product or the fact that they still wear parachute pants.
Conclusion:  The entire IT industry uses deprecate incorrectly.  It may be common use.  It may be some huge mis-understanding.  But it is still, completely, wrong.

A: In computer software standards and documentation, the term deprecation is used to indicate discouragement of usage of a particular software feature, usually because it has been superseded by a newer/better version. The deprecated feature still works in the current version of the software, but it may raise error messages or warnings recommending an alternate practice.
The Obsolete attribute marks a program entity as one that is no longer recommended for use. Each use of an entity marked obsolete will subsequently generate a warning or an error since they are no longer in use or does not exist.
EDIT:
depreciated : Not sure how this relates to programming

A: In the context of describing APIs and such, "depreciated" is a misreading, misspelling, and mispronunciation of "deprecated".
I'm thinking people have just seen "depreciated" so often in other contexts, and "deprecated" so rarely, that they don't even register the "i" or lack thereof.  It doesn't exactly help that their definitions are similar either.

A: You are correct.
Deprecated means that it is still in use, but only for historical purposes and it will be removed probably in the next big release. It is recommended that you do not use deprecated functions or features - even if they are present in the current library for example.
Obsolete means that is already out-of-use.
Depreciated means the monetary value of something has decreased over time. E.g., cars typically depreciate in value.
Also for more precise definitions of the terms in the context of the English language I recommend using https://english.stackexchange.com/.

A: Obsolete: should not be used any more
Deprecated: should be avoided in new code, and likely to become obsolete in a later version of the API
Depreciated: usually a typo for deprecated (depreciation is where the value of goods goes down over time, e.g. if you buy a new computer its resale value goes down month by month)

A: I wouldn't say obsolete means it doesn't work anymore. In my mind obsolete just means there are better alternatives. A thing becomes obsolete because of something else. Deprecated means you shouldn't use it, although there might not be any alternatives. A thing becomes deprecated because someone says it is -- it is prescriptive.

A: *

*"Obsolete" means "has been replaced".

*"Depreciated" means "has less value than its original value".

*"Deprecated" means to expressly disprove of and was popularised due to misspellings in two technical articles where the authors used deprecated without an "i".  One in 1999 and the other in 2002 referenced in the dictionaries as origins.

Prior to that time frame we were reading comments like // depreciated in API documentation including the MS MSDN.
The use of deprecated in the tech industry is therefore completely incorrect and evidence of how a technical writer can produce a bug that can live in a language and someone should finally put the bug to rest.