text:
Q: Change input format in dynamic table: dropdown, number, date I'm working on dynamic 3 column table that has 3 input text type : Product, quantity and date
This works good but i want to change type format:

*

*Product column => Dropdown type

*Quantity column => number type

*Date column => Date type (dd-mm-yyyy)
How i do change it?
Thank you
Original source: link
Code online:  https://jsfiddle.net/bvotcode/r61ptxe9/7/
HTML

Product
Quantity
Date

Car
10
20/12/2021

<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">

Book
22
26

<input type="button" id="edit_button2" value="Edit" class="edit" onclick="edit_row('2')">
<input type="button" id="save_button2" value="Save" class="save" onclick="save_row('2')">
<input type="button" value="Delete" class="delete" onclick="delete_row('2')">

Laptop
44
19/01/2022

<input type="button" id="edit_button3" value="Edit" class="edit" onclick="edit_row('3')">
<input type="button" id="save_button3" value="Save" class="save" onclick="save_row('3')">
<input type="button" value="Delete" class="delete" onclick="delete_row('3')">

<input type="text" id="new_product">
<input type="text" id="new_quantity">
<input type="text" id="new_date">
<input type="button" class="add" onclick="add_row();" value="Add Row">

CSS
.pt-3-half { padding-top: 1.4rem; }

Javascript
function edit_row(no)
{
 document.getElementById("edit_button"+no).style.display="none";
 document.getElementById("save_button"+no).style.display="block";

 var product=document.getElementById("product_row"+no);
 var quantity=document.getElementById("quantity_row"+no);
 var date=document.getElementById("date_row"+no);

 var product_data=product.innerHTML;
 var quantity_data=quantity.innerHTML;
 var date_data=date.innerHTML;

 product.innerHTML="<input type='text' id='product_text"+no+"' value='"+product_data+"'>";
 quantity.innerHTML="<input type='text' id='quantity_text"+no+"' value='"+quantity_data+"'>";
 date.innerHTML="<input type='text' id='date_text"+no+"' value='"+date_data+"'>";
}

function save_row(no)
{
 var product_val=document.getElementById("product_text"+no).value;
 var quantity_val=document.getElementById("quantity_text"+no).value;
 var date_val=document.getElementById("date_text"+no).value;

 document.getElementById("product_row"+no).innerHTML=product_val;
 document.getElementById("quantity_row"+no).innerHTML=quantity_val;
 document.getElementById("date_row"+no).innerHTML=date_val;

 document.getElementById("edit_button"+no).style.display="block";
 document.getElementById("save_button"+no).style.display="none";
}

function delete_row(no)
{
 document.getElementById("row"+no+"").outerHTML="";
}

function add_row()
{
 var new_product=document.getElementById("new_product").value;
 var new_quantity=document.getElementById("new_quantity").value;
 var new_date=document.getElementById("new_date").value;

 var table=document.getElementById("data_table");
 var table_len=(table.rows.length)-1;
 var row = table.insertRow(table_len).outerHTML="
"+new_product+"	"+new_quantity+"	"+new_date+"	<input type='button' id='edit_button"+table_len+"' value='Edit' class='edit' onclick='edit_row("+table_len+")'> <input type='button' id='save_button"+table_len+"' value='Save' class='save' onclick='save_row("+table_len+")'> <input type='button' value='Delete' class='delete' onclick='delete_row("+table_len+")'>
";

 document.getElementById("new_product").value="";
 document.getElementById("new_quantity").value="";
 document.getElementById("new_date").value="";
}

A: You're using the type="text" for all of the <input> tags. You should consider changing the type of the inputs in your edit_row function.

*

*For numbers, the type of input should be number;

*For dates, date;

*And finally, to render a dropdown box, the best solution is to use a <select> tag instead of an <input>. Don't forget to write all the options of your dropdown inside of <option> tags (which should be all inside of one <select> tag); Here you can find a simple explanation on how to use the <select> tag.


text:
Q: Does Raku have a global interpreter lock (GIL)? The Wikipedia article Global interpreter lock indicates that Raku has a global interpreter lock.
This contradicts Curtis Poe's response to Are any companies planning to use Perl 6?.
I suspect that the Wikipedia article is wrong - but maybe it is more complicated than that. Can somebody explain?

A: With some googling I've found some additional evidence that Perl 6 indeed has no GIL:
As the creator of Perl himself stated in an interview:

[...] For developers who are already sophisticated, they'll see that most of the problems endemic to the currently available dynamic languages are solved in Perl 6. We understand lexical and dynamic scoping. We detect most typos at compile time. We don't have a global interpreter lock.

Source: Perl creator Larry Wall: Rethought version 6 due this year
Some more evidence:

*

*https://news.ycombinator.com/item?id=10640765

*https://www.reddit.com/r/perl6/comments/3goq1a/not_having_gil_truly_multithreading/

*https://www.reddit.com/r/perl/comments/337h4c/should_i_also_learn_perl6_knowing_ruby_and_python/
I don't know why, but the addition of Perl 6 to the Wikipedia article was done two weeks ago and maybe it needs to be reverted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't hear any sound with ion.sound on Firefox/Chrome I'm having trouble with using with plugin, even if the code is quite simple, my browser can't seem to play anything :(

*

*Some context :

*

*Computer is a laptop with windows 10

*Browsers are Firefox 43.0.4 and Chrome 48.smthg

and code looks like this

*

*sounds.js
// init bunch of sounds
ion.sound({
    sounds: [
        {
            name: "beer_can_opening",
            ended_callback: function () {
                console.log("ended")
            },
            ready_callback: function () {
                console.log("ready")
            }
        },
        {name: "bell_ring"},
        {name: "branch_break"},
        {name: "button_click"}
    ],

    // main config
    path: "sounds/",
    preload: true,
    multiplay: true,
    volume: 0.9,
    loop: 10
});

// play sound
ion.sound.play("beer_can_opening");

*index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <script src="jquery-1.12.0.min.js"></script>
    <script src="ion.sound.min.js"></script>
    <script src="sounds.js"></script>
    <script src="sorcery.js"></script>
    <link type="text/css" rel="stylesheet" href="style.css"/>
    <meta lang="fr" xml:lang="fr" content="text/html;charset=UTF-8" http-equiv="Content-Type">
    <title>Sword & Sorcery</title>
</head>

*Finally the folder sounds is there, beer_can_opening.aac/ogg/mp3 too.

*In both browser's console I'm getting "ready" but not "ended" not matter how long I wait

*No other errors whatsoever :(

*The demo at http://ionden.com/a/plugins/ion.sound/en.html (like any other demos the author posted ) work great

Help greatly appreciated, this plugin should do the work nicely, I'd really like to use it :)

A: This was an autoplay bug. Was fixed in latest release: https://github.com/IonDen/ion.sound/issues/71


text:
Q: Computing conditional expectation of ordered normal random variables There are $m$ normally distributed, independent random variables $N_1, \ldots, N_m$ with distinct means $\mu_1, \ldots \mu_m$ and standard deviations $\sigma_1, \ldots, \sigma_m$. Then, we observe a permutation of the numbers $\pi = \{1, \ldots, m\}$. How can we efficiently compute the conditional expectation of the random variables in same ordering as this permutation? Added bonus: how can we compute the conditional variance?
An example:

*

*we have four independent random variables $N_1, N_2, N_3, N_4$, all with different means and variances.

*We are given the permutation $\pi = (3, 1, 2, 4)$.

*What's $\mathbf{E}((N_1, N_2, N_3, N_4) \mid N_3 > N_1 > N_2 > N_4)$?

One way to do this is by Gibbs sampling: we can sample from the conditional distribution $(N_1, N_2, N_3, N_4) \mid N_3 > N_1 > N_2 > N_4$ by doing the following:

*

*Initialize some arbitrary values $x_i^0$ such that $x_3^0 > x_1^0 > x_2^0 > x_4^0$

*For $t = 1 \ldots M$, choose a random index $i$.

*$x_{\pi_i}^t \sim \text{TruncatedNormal}(\mu_{\pi_i}, \sigma_{\pi_i}, x_{\pi_{i-1}}^{t-1}, x_{\pi_{i+1}}^{t-1})$, with lower/upper bounding values $-\infty$ or $\infty$ if $i=1$ or $i=m$, respectively, and $x^t = x^{t-1}$ otherwise

*Compute the mean and variance of the $x^t$ after some break-in period.

The above is basically an MCMC method that walks over the conditional distribution to obtain an average computationally. The question is, is there a more efficient, faster, or better way to compute this expectation?
This question is related to this one on math.stackexchange about computing the probability of a particular ordering, which it turns out can be done using the multivariate normal CDF (for which there exist numerical methods.)

A: In case anyone's interested, I have implemented computing this expectation in two ways

*

*via a multivariate normal integral, using Alan Genz' MVNEXP FORTRAN library:
(Check out the conditionalExp method down the page)

*Via Gibbs sampling, using a truncated normal distribution for MCMC (also check out this paper)

In regards to @whuber's comment, the integration is NOT necessarily the faster approach; the Gibbs sampling is numerically simpler and can be sped up significantly by using fast (but less accurate) versions of the univariate normal. The multivariate normal integral is also tricky to use and has a tradeoff between accuracy and speed...just like the Gibbs sampler.
In preliminary testing, it's inconclusive which one is faster for a given accuracy.


text:
Q: error: ISO C++ forbids declaration of 'TimerExeption' with no type I'm getting this error when trying to throw an exception of type TimerException in my timer.cpp file. here is timer_exception.h
  1 #ifndef TIMER_EXCEPTION_H
  2 #define TIMER_EXCEPTION_H
  3
  4 #include <iostream>
  5 #include <string>
  6
  7 class TimerException{
  8         friend std::ostream &operator <<(std::ostream &os, const TimerException e){
  9                 std::cout << " *** TIMER EXCEPTION *** " << e.message;
 10                 return os;
 11         }
 12 public:
 13         TimerExeption(std::string message) : message(message) {}
 14 private:
 15         std::string message;
 16 };
 17
 18
 19 #endif

and here is my timer.cpp file where the TimerException is being instantiated
  1 #include <ctime>
  2 #include "timer.h"
  3 #include "timer_exception.h"
  4
  5 void Timer::start(){
  6         if(timer != 0) throw TimerException("Timer already started");
  7         this->timer = clock();
  8 }

A: Simple typo. You're missing a 'c' in your constructor's name.
13         TimerExeption(std::string message) : message(message) {}
//               ^^^

A: Your constructor has a typo.  TimerExeption, the c is missing.


text:
Q: What is the fastest way to save and load a large data in Python 3? I'm currently using pickle to save some big data which contains many numpy matrices of size 10k*10k. Even though I use several similar (separate) python files, whenever I save the data, the size of the saved dat file is always 4 GB. So, is that just a coincidence or it can't save more than this amount?
Also, when I load the data it uses more than 90% of the memory, which is not useful to me. I have heard of cpickle and joblib, here a comparison of them: What are the different use cases of joblib versus pickle?
I would like to reduce memory usage. Should I switch to the joblib? What would be the fastest way?
Thanks for any suggestions.
p.s. I use Python 3.8 on Ubuntu 20.04 with Spyder IDE.


text:
Q: Best way to structure a site with media to keep it separate from the base code. ( Opinion based ) I've recently have taken a new server under my wing that has an interesting installation of django on it. The previous developer mixed in the media uploads with the static content and in other modules created it's own directory on the root file level of the project. My first reaction to this was general annoyance. ( I'm a huge fan of modular development. ) However after working to 'correct,' it's raised a question.
Even though this question is tagged with django, feel free to post response according to java and asp.net.
How do you set up your static files? Do you stack everything inside a static directory or do you take the time link each modular independently?
One of my tricks for every django app I start is, in the init.py of said app I put the following.
import os
from django.conf import settings as djsettings
TEMPLATES_DIR = (os.path.join(os.path.dirname(__file__),'./templates'),)
djsettings.TEMPLATES_DIR += TEMPLATES_DIR

A: I don't think your trick is really needed (anymore).
If you use django.template.loaders.app_directories.Loader (docs)
you can put a template dir in your app dir and Django will check it for your app-specific templates
And starting with Django 1.3 you can use the staticfiles app to do something similar with all your static media files. Check the docs for the staticfiles-finders
So finally, thanks to the collectstatic management command, you're now able to keep your static media files modularized (for easier development and distribution), yet you still can bundle them at a centralized place once it is time to deploy and serve your project.

A: Right now I'm in the habit of putting a static folder in each app directory containing its static files.  I keep templates in each app directory under templates.  I alias the static path when putting the app behind nginx or apache.
One thing that I'm starting to do more of is putting static files such as javascript, css, or images behind a CDN like S3.


text:
Q: Random Forest feature importance: how many are actually used? I use RF twice in a row.
First, I fit it using max_features='auto' and the whole dataset (109 feature), in order to perform features selection.
The following is RandomForestClassifier.feature_importances_, it correctly gives me 109 score per each feature:
[0.00118087,  0.01268531,  0.0017589 ,  0.01614814,  0.01105567,
0.0146838 ,  0.0187875 ,  0.0190427 ,  0.01429976,  0.01311706,
0.01702717,  0.00901344,  0.01044047,  0.00932331,  0.01211333,
0.01271825,  0.0095337 ,  0.00985686,  0.00952823,  0.01165877,
0.00193286,  0.0012602 ,  0.00208145,  0.00203459,  0.00229907,
0.00242616,  0.00051358,  0.00071606,  0.00975515,  0.00171034,
0.01134927,  0.00687018,  0.00987706,  0.01507474,  0.01223525,
0.01170495,  0.00928417,  0.01083082,  0.01302036,  0.01002457,
0.00894818,  0.00833564,  0.00930602,  0.01100774,  0.00818604,
0.00675784,  0.00740617,  0.00185461,  0.00119627,  0.00159034,
0.00154336,  0.00478926,  0.00200773,  0.00063574,  0.00065675,
0.01104192,  0.00246746,  0.01663812,  0.01041134,  0.01401842,
0.02038318,  0.0202834 ,  0.01290935,  0.01476593,  0.0108275 ,
0.0118773 ,  0.01050919,  0.0111477 ,  0.00684507,  0.01170021,
0.01291888,  0.00963295,  0.01161876,  0.00756015,  0.00178329,
0.00065709,  0.        ,  0.00246064,  0.00217982,  0.00305187,
0.00061284,  0.00063431,  0.01963523,  0.00265208,  0.01543552,
0.0176546 ,  0.01443356,  0.01834896,  0.01385694,  0.01320648,
0.00966011,  0.0148321 ,  0.01574166,  0.0167107 ,  0.00791634,
0.01121442,  0.02171706,  0.01855552,  0.0257449 ,  0.02925843,
0.01789742,  0.        ,  0.        ,  0.00379275,  0.0024365 ,
0.00333905,  0.00238971,  0.00068355,  0.00075399]

Then, I transform the dataset over the previous fit which should reduce its dimensionality, and then i re-fit RF over it.
Given max_features='auto' and the 109 feats, I would expect to have in total ~10 features instead, calling rf.feats_importance_, returns more (62):
[ 0.01261971, 0.02003921, 0.00961297, 0.02505467, 0.02038449,
0.02353745, 0.01893777, 0.01932577, 0.01681398, 0.01464485,
0.01672119, 0.00748981, 0.01109461, 0.01116948, 0.0087081 ,
0.01056344, 0.00971319, 0.01532258, 0.0167348 , 0.01601214,
0.01522208, 0.01625487, 0.01653784, 0.01483562, 0.01602748,
0.01522369, 0.01581573, 0.01406688, 0.01269036, 0.00884105,
0.02538574, 0.00637611, 0.01928382, 0.02061512, 0.02566056,
0.02180902, 0.01537295, 0.01796305, 0.01171095, 0.01179759,
0.01371328, 0.00811729, 0.01060708, 0.015717 , 0.01067911,
0.01773623, 0.0169396 , 0.0226369 , 0.01547827, 0.01499467,
0.01356075, 0.01040735, 0.01360752, 0.01754145, 0.01446933,
0.01845195, 0.0190799 , 0.02608652, 0.02095663, 0.02939744,
0.01870901, 0.02512201]

Why? Shouldn't it returns just ~10 features importances?

A: You misunderstood the meaning of max_features, which is

The number of features to consider when looking for the best split

It is not the number of features when transforming the data.
It is the threshold in transform method that determines the most important features.

threshold : string, float or None, optional (default=None)
The threshold value to use for feature selection. Features whose importance is greater or equal are kept while the others are discarded. If "median" (resp. "mean"), then the threshold value is the median (resp. the mean) of the feature importances. A scaling factor (e.g., "1.25*mean") may also be used. If None and if available, the object attribute threshold is used. Otherwise, "mean" is used by default.


text:
Q: How to load multiple excel files with multiple sheets in to one dataframe in python We're trying to make an automatic program, that can take multiple excel files with multiple sheets from a folder, and append them to one data frame.
Our problem is that we're not quite sure how to do this, so the process becomes most automatic. And since the sheets varies in names, we can't specify any variable for them.
Alle of the files are *.xlsx, and the code has to load a arbitrary number of files.
We have tried with different types of codes, primarily using pandas, but we can't seem to append them in one data frame.
import numpy as np
import pandas as pd
import glob
all_data = pd.DataFrame()
for f in glob.glob("*.xlsx"):
    df = pd.read_excel(f)
    all_data = all_data.append(df, ignore_index=True)

# now save the data frame
writer = pd.ExcelWriter('output.xlsx')
all_data.to_excel(writer)
writer.save()

sheet1 = xls.parse(0)

We expect to have one data frame with all data, such that we can use data and extract different features and make statistics.

A: The documentation of pandas.read_excel states:
*sheet_name : str, int, list, or None, default 0
Strings are used for sheet names. Integers are used in zero-indexed sheet positions. Lists of strings/integers are used to request multiple sheets. Specify None to get all sheets.
Available cases:

*

*Defaults to 0: 1st sheet as a DataFrame

*1: 2nd sheet as a DataFrame

*"Sheet1": Load sheet with name "Sheet1"

*[0, 1, "Sheet5"]: Load first, second and sheet named "Sheet5" as a dict of DataFrame
None: All sheets.*

I would suggest to try the last option, being pd.read_excel(f,sheet_name = None). Otherwise you might want to create a loop and pass indexes vs. the actual sheet names, this way you don't have to have prior knowledge of the .xlsx files.


text:
Q: Understanding Ruby Rendering I am very new to ruby on rails and I am using Ruby version 1.9 and its newer syntax.
I have managed to create a small application where I store statistics in 1 large database table.  This table can be viewed and edited with no problems via rails.
Now, I am trying to add several different mini views of this table to the Home page, Where I might list the top 10 users by upload then download.
I have successfully created the 1st for upload, is there away I can use the same code with different query options.

*

*Are there any good tutorials in this area?

*Is it relatively easy to add graphs from the same table on to the home page?

*Is it possible to make the homepage refresh when ever a change occurs in the database table?

*I know I am probably asking very basic questions so any pointers to good tutorials or books would be of great help.

A: *

*Read this tutorial on basics how to render templates in ror.

http://guides.rubyonrails.org/layouts_and_rendering.html
http://api.rubyonrails.org/classes/AbstractController/Rendering.html

*

*For chart you can use this, github.com/ankane/chartkick

*Page should refresh when any changes detected in database, for that you can visit ActionController::Live of rails casts.

http://api.rubyonrails.org/classes/AbstractController/Rendering.html

A: *

*For Rails Tutorials you can find out these
http://www.tutorialspoint.com/ruby-on-rails/
http://ruby.railstutorial.org/ruby-on-rails-tutorial-book

*Coming to Charts you can use gruff gem it is very easy to implement and for dynamic charts you can go for highcharts
http://www.highcharts.com/
https://github.com/topfunky/gruff

A: Give this a try.
The Rails View: Create a Beautiful and Maintainable User Experience
- by John Athayde and Bruce Williams
http://pragprog.com/book/warv/the-rails-view


text:
Q: How to trigger CPU burst operation? I am working on a piece of hardware design verification, which includes CPU(ARC), Design( containing AHB), and SRAM connecting to the AHB bus.
I want to know if CPU can do burst write on the SRAM via AHB bus. If yes, how to implement it.
Here are some details of my work:

*

*connection
CPU -> AHB -> SRAM

*C code
//piece of C code to write 4 DWs into the SRAM
wr(add0, DW0)
wr(add0+4, DW0)
wr(add0+8, DW0)
wr(add0+12, DW0)

The above C code do only single write to the SRAM via AHB.
In order to do burst write, what should I consider about? Should I refer to the ARC manual for a burst function? Or add some FLAGS to compiler to optimize it to a burst operation? Essentially I want to know how does CPU implement the burst write.


text:
Q: Python Bbcode to HTML translation i'm working with python 3.4.4 32bits (work rules), and i'm implementing a program that takes bbcode lines from a .txt file, and then converting those into a HTML lines, to be readed for PyQt5 elements with Qt.RichText. For me is not allowed  to type HTML lines in thoses .txt files, so i just need to take those bbcode lines, read them, translated into a HTML that's all. I've tried to use the bbcode module, version 1.0.31, specifically the function bbcode.render_html(bbcodeContent) the problem is: that function doesn´t recognize most of the normal bbcode lines such as tables for example, that means, this functions doesn't translate properly to HTML tables.
To be specific if a have in the bbcodeContent variable the following:
[table border=1 align=center]
[tr]
[td align=center colSpan=2][b][i]text[/i][/b][/color][/td]
[/tr]
[tr]
[td]text[/td]
[td]text[/td]
[/tr]
[/table]

The result at the printing of the function bbcode.render_html(bbcodeContent) is:
[table border=1 align=center]

[tr]

[td align=center colSpan=2]text[/td]

[/tr]

[tr]

[td]text[/td]

[td]text[/td]

[/tr]

[/table]

That is clearly not properly HTML as suppose, but as said, not only tables, but most of the simple bbcodes are not recognized. for the past input the expected output could be:

text

text	text

The question hier is clear: How can i correct this problem with this bbcode module? I'm doing something wrong?
Now i'm using a new python module called bbcodepy.py founded hier https://github.com/vishnevskiy/bbcodepy installed manually and did some modifications and now the complete issue is solved, but that module is so old to trust in, that means i really want to try the official bbcode module. Can you give a hand with it?


text:
Q: How to Get User Story for a Task Using Visual Studio REST API I'm trying to use Visual Studio's API to gather information about work items for a Visual Studio Online team into an Excel doc. I can get the work items' information as well as whether each item is a User Story, Task, or Bug by using API calls to extract its json fields. However, I can't figure out how to get the "parent" User Story for a Task or a Bug. E.g. a task will be within a User Story section on my work board, but I don't see any field that corresponds to that story within the work item's possible json keys.
The keys I can see for a work item are these:
['System.AuthorizedDate',
 'System.WorkItemType',
 'System.Title',
 'System.IterationLevel1',
 'System.IterationLevel2',
 'System.History',
 'System.AreaId',
 'System.NodeName',
 'Microsoft.VSTS.Common.ActivatedDate',
 'System.IterationId',
 'System.IterationPath',
 'System.PersonId',
 'System.AssignedTo',
 'System.AuthorizedAs',
 'System.Id',
 'System.Reason',
 'System.CreatedBy',
 'Microsoft.VSTS.Common.StateChangeDate',
 'Microsoft.VSTS.Common.Priority',
 'System.Watermark',
 'Microsoft.VSTS.Common.ActivatedBy',
 'System.AreaPath',
 'System.State',
 'System.ChangedDate',
 'System.AreaLevel1',
 'System.CreatedDate',
 'System.TeamProject',
 'System.Rev',
 'System.ChangedBy',
 'System.RevisedDate']

None of their values corresponds to anything that matches a User Story's text or provides a url to a User Story's json.
Does anyone know how to get parent (User Story) of a task or a bug using API calls?

A: Add "expand=all" or "expand=relations" in your request url will show the linked work items and "System.LinkTypes.Hierarchy-Reverse" type point to the Parent work item.
Example:
https://xxxxx.visualstudio.com/defaultcollection/_apis/wit/workitems?ids=47&$expand=relations&api-version=1.0


text:
Q: How can i get the second to last element of a Sequence? Clojure i know how to get the last element with the function last but is it possible to get the second to last element of a Sequence?
(defn last
  [args]
   (last args))
(last [1 2 3 4]) ;;--> 4 but i want it to return 3

A: Use reverse, take-last, butlast or nth (this one seems to be the fastest):
(defn second-to-last1 [s]
  (second (reverse s)))

(second-to-last1 (range 100))
=> 98

(defn second-to-last2 [s]
  (first (take-last 2 s)))

(second-to-last2 (range 100))
=> 98

(defn second-to-last3 [s]
  (last (butlast s)))

(second-to-last3 (range 100))
=> 98

(defn second-to-last4 [s]
  (nth s (- (count s) 2) nil))

(second-to-last4 (range 100))
=> 98


text:
Q: Django: Display data from other table I'm having a hard time displaying some datas from two or three tables. So this is my code for showing all the data only from Device table.
def device(request):
    if request.method == 'GET':
        queryset = Device.objects.all()
        if queryset:
            data = {"queryset": queryset}
            return render(request, 'device/device.html', data)
        else:
            return render(request, 'device/device.html')

And I want to add some data from other table, how do I insert it here?

A: Just make the queries and put the results in the render context, and refer to those in your template.
    return render(request, 'device/device.html', {
        "devices": Device.objects.all(),
        "thingabobs": Thingabob.objects.all(),
        "chili_pickles": Pickle.objects.filter(flavor="chili"),
        "plain_pickles": Pickle.objects.filter(flavor="plain"),
    })

A: If the objects in the various tables have sets of fields in common and it's these which the list view is going to display, then you can pass a mixed list of objects from different tables to be rendered. Also, in the template language, reference to a non-existent object field is not an error. {{obj.nosuchfield}} successfully renders as a null string.
So you might pass
context['vehicle_list'] = list(
    Cars.objects.filter(colour='green', available__range = [date1, date2]
  )) + list(
    Vans.objects.filter(colour='green', available__range = [date1, date2]
  ))

This is of course begging the question about whether cars and Vans should be separate tables, or Vehicles with a vehicle_type field. But sometimes, the answer is simply that its a bad choice in retrospect, but far too hard to change now.
Incidentally, properties (@property) on a model can be used to create field-name aliases for the purposes of display code, but they won't work for queryset filtering.


text:
Q: One foreign key references multiple primary keys I have two tables with single primary key columns in each of those two tables and another table (table 3) which has a foreign key that refers both of those above primary key's columns.
Now I want to insert records into table 3 if it present in either of those two primary key tables.
Note: I don't want to create a new table that is combination of primary key tables and add reference to that newly created table

A: As Erwin Brandstetter stated here
Rules for FK constraints
To answer the question in the title and at the end of your text:
"I would still like to know how to have one foreign key referencing two primary keys."
That's impossible.

*

*A FOREIGN KEY constraint can only point to one table and each table can only have one PRIMARY KEY constraint.

*Or you can have multiple FOREIGN KEY constraints on the same column(s) referencing one PRIMARY KEY of a (different) table each. (Rarely useful.)
However, a single PK or FK can span multiple columns.
And a FK can reference any explicitly defined unique (set of) column(s) in the target, not just the PK. The manual:

A foreign key must reference columns that either are a primary key or form a unique constraint.

A multicolumn PK or UNIQUE constraint can only be referenced by a multicolumn FK constraint with matching column types.
Basic advice:

*

*How to implement a many-to-many relationship in PostgreSQL?

A: insert into table3 (col1, col2 ...)
(select col1, col2 ... from table1
union
select col1, col2 ... from table2);

You can optionally put where clauses or split the SQL into 2, instead of a union.
This is standard ANSI SQL and should work on any DBMS


text:
Q: Сравнение дат с помощью JPA criteria API Мне нужно получить данные из базы. Есть две переменные LocalDate startDate и LocalDate endDate.
Запрос может быть:
startDate-null- нужно выбрать все записи от startDate по текущую дату.
null-endDate-нужно выбрать все записи до endDate.
startDate-endDate- выбрать все записи от startDate до endDate.
null-null- выбрать все записи.
Метод поиска в базе:
    CriteriaBuilder cb = manager.getCriteriaBuilder();
        CriteriaQuery<Supply> query = cb.createQuery(Supply.class);
        Root<Supply> supplyRoot = query.from(manager.getMetamodel().entity(Supply.class));
        List<Predicate> predicates = new ArrayList<Predicate>();
    if(startDate!=null && endDate!=null){
            Predicate betweenPredicate = cb.between(supplyRoot.<LocalDate>get("arrivalDate"), startDate, endDate);
            predicates.add(betweenPredicate);
        }else if(startDate!=null && endDate == null){
            Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(supplyRoot.<LocalDate>get("arrivalDate"), startDate);
            predicates.add(greaterThanPredicate);
        } else if(startDate == null && endDate!= null){
            Predicate lessThanPredicate = cb.lessThanOrEqualTo(supplyRoot.<LocalDate>get("arrivalDate"), endDate);
            predicates.add(lessThanPredicate);
        }
        if(!predicates.isEmpty()){
        query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
        query.select(supplyRoot);
        }
        return manager.createQuery(query).getResultList();

Проблема в том что при поиске между двумя датами возвращается только первое значение из базы. Например в базе есть дата 25.12.2016. Если сделать запрос на выбор с 24.12.2016 по 26.12.2016 то не находит ничего.
База MySQL, тип столбца date.
Подскажите где может быть проблема?


text:
Q: How to set width of DataGridTemplateColumn by content? I am a new in WPF and my question is there a way to set width of column by the most width item in this column?
When I run my app this column looks like this

Word <EXISTING CALIBRATIO is shrink. This word should be shown entirely like <EXISTING CALIBRATION>
Like when drop down list is open

My code for this column is
<DataGridTemplateColumn Header="{x:Static res:Resources.geo_calib_folder}">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <ComboBox x:Name="Cb_geometry_calibration"
                                                  ToolTip="{x:Static res:Resources.tooltip_chosen_geometry_calibration_folder}"
                                                  PreviewMouseWheel="Cb_PreviewMouseWheel"
                                                      SelectionChanged="Cb_geometry_calibration_SelectionChanged"
                                                      ItemsSource="{Binding Path=GeoCalibrationFolders}"
                                                      SelectedItem="{Binding Path=SelectedGeoCalibrationFolder}"
>
                                                <ComboBox.ItemTemplate>
                                                    <DataTemplate>
                                                        <TextBlock
                                                        Text="{Binding Path=UIRepresentation}" />
                                                    </DataTemplate>
                                                </ComboBox.ItemTemplate>

                                                <ComboBox.Style>
                                                    <Style TargetType="ComboBox">
                                                        <Style.Triggers>
                                                            <DataTrigger Binding="{Binding IsGeoCalibFolderBold}"
                                                                         Value="True">
                                                                <Setter Property="FontWeight" Value="Bold"/>
                                                            </DataTrigger>
                                                        </Style.Triggers>
                                                    </Style>
                                                </ComboBox.Style>

                                                <ComboBox.ItemContainerStyle>
                                                    <Style TargetType="ComboBoxItem">
                                                        <Setter Property="FontWeight" Value="Normal"/>
                                                    </Style>
                                                </ComboBox.ItemContainerStyle>
                                            </ComboBox>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>

So, question is there a way to resize this column dynamically according to content?
P.S. I understand that I can hardcode this value like width = 300, but I would like to find a way to make it dynamically.

A: According to this duplicate post, you can't do it directly in XAML.  It requires some code behind or attached behaviors because the combobox resolves its width prior to the retrieval of its collected items.


text:
Q: Find TOP 10 latest record for each BUYER_ID for yesterday's date This is the below table
CREATE TABLE IF NOT EXISTS TestingTable1
(
BUYER_ID BIGINT,
ITEM_ID BIGINT,
CREATED_TIME STRING
)

And this is the below data in the above table-
BUYER_ID    |    ITEM_ID       |    CREATED_TIME
------------+------------------+-----------------------
1015826235      220003038067        2012-07-09 19:40:21,
1015826235      300003861266        2012-07-09 18:19:59,
1015826235      140002997245        2012-07-09 09:23:17,
1015826235      210002448035        2012-07-09 22:21:11,
1015826235      260003553381        2012-07-09 07:09:56,
1015826235      260003553382        2012-07-09 19:40:39,
1015826235      260003553383        2012-07-09 06:58:47,
1015826235      260003553384        2012-07-09 07:28:47,
1015826235      260003553385        2012-07-09 08:48:47,
1015826235      260003553386        2012-07-09 06:38:47,
1015826235      260003553387        2012-07-09 05:38:47,
1015826235      260003553388        2012-07-09 04:55:47,
1015826235      260003553389        2012-07-09 06:54:37,
34512201        597245693           2012-07-09 16:20:21,
34512201        8071787728          2012-07-09 15:19:59,
34512201        5868222883          2012-07-09 08:23:17,
34512201        2412180494          2012-07-09 22:21:11,
34512201        2422054205          2012-07-09 06:09:56,
34512201        1875744030          2012-07-09 19:40:39,
34512201        5639158173          2012-07-09 06:58:47,
34512201        5656232360          2012-07-09 07:28:47,
34512201        959188449           2012-07-09 08:48:47,
34512201        4645350592          2012-07-09 06:38:47,
34512201        5657320532          2012-07-09 05:38:47,
34512201        290419656539        2012-07-09 04:55:47,

If you see the above data in the table, there are only two UNIQUE BUYER_ID and corresponding to those I have ITEM_ID AND CREATED_TIME. I need only 10 latest record basis on the time for the day before today's date whenever I will be firing this query (meaning yesterday's date) for each BUYER_ID.
So for this BUYER_ID - 34512201 I need 10 latest record for each BUYER_ID basis on CREATED_TIME for yesterday's date only.
And each BUYER_ID can have any day's data. But I am specifically interested for day before  today's data(means yesterday's date always) by checking at the CREATED_TIME
Find TOP 10 latest data for each BUYER_ID for yesterday's date. Below is the sample output I should be getting corresponding to each BUYER_ID.
Sample Output.
BUYER_ID    |    ITEM_ID       |    CREATED_TIME
------------+------------------+-----------------------
34512201        2412180494          2012-07-09 22:21:11
34512201        1875744030          2012-07-09 19:40:39
34512201        597245693           2012-07-09 16:20:21
34512201        8071787728          2012-07-09 15:19:59
34512201        959188449           2012-07-09 08:48:47
34512201        5868222883          2012-07-09 08:23:17
34512201        5656232360          2012-07-09 07:28:47
34512201        5639158173          2012-07-09 06:58:47
34512201        4645350592          2012-07-09 06:38:47
34512201        2422054205          2012-07-09 06:09:56
1015826235      210002448035        2012-07-09 22:21:11
1015826235      260003553382        2012-07-09 19:40:39
1015826235      220003038067        2012-07-09 19:40:21
1015826235      300003861266        2012-07-09 18:19:59
1015826235      140002997245        2012-07-09 09:23:17
1015826235      260003553385        2012-07-09 08:48:47
1015826235      260003553384        2012-07-09 07:28:47
1015826235      260003553381        2012-07-09 07:09:56
1015826235      260003553383        2012-07-09 06:58:47
1015826235      260003553389        2012-07-09 06:54:37

I am working with Hive and Hive supports SQL like syntax. So I need to make sure the SQL should work in Hive environment too.
Can anyone help me with this?
Update:-
I am using the below query and I need to get top 10 latest from the below query and need to add one more qualifier for date check, means in where clause for yesterday's date- I cannot use TOP 10 here as Hive doesn't support TOP 10 sql syntax. I need some other way to do this problem.
SELECT * FROM TestingTable1 WHERE ORDER BY buyer_id, created_time DESC;

One More UPDATE:-
I wrote this below query with the use of RANK UserDefinedFunction.
SELECT buyer_id, item_id, created_time, rk
FROM (
    SELECT buyer_id, item_id, rank(item_id) as rk, created_time
    FROM testingtable1
    DISTRIBUTE BY buyer_id, item_id
    SORT BY buyer_id, item_id, created_time desc
) a
WHERE rk < 10
ORDER BY buyer_id, created_time, rk;

And this is the RANK UDF functions in Java-
package com.example.hive.udf;
import org.apache.hadoop.hive.ql.exec.UDF;

    public final class Rank extends UDF{
        private int  counter;
        private String last_key;
        public int evaluate(final String key){
          if ( !key.equalsIgnoreCase(this.last_key) ) {
             this.counter = 0;
             this.last_key = key;
          }
          return this.counter++;
        }
    }

And above query is not work the way I wanted to, some sort of twist has to be made I guess in that query.
Is there any way to do this without using any UDF in HiveQL?

A:   SELECT FIRST 10 *
    FROM TestingTable1
   WHERE buyer_id = 34512201
ORDER BY created_time DESC;

A: I am late answering this and I am sure you must be knowing the use of row_number function with Hive. Just an addition as a reference to previously good discussion.
select * from
(select buyer_id,item_id,created_time, row_number() over(partition by buyer_id over
created_time asc) row_num from yourtable)tab
where tab.row_num<=5;

A: select *
from (select buyer_id,item_id,created_time,row_num() over (partition by buyer_id order by created_time DESC)) a
where a.row_num<=10


text:
Q: Merge Two files of columns but insert columns of second file into columns of first file Assume two files with same amount of columns.
file_A:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

and
file_B:

A B C D E
A B C D E
A B C D E
A B C D E
A B C D E

I want to merge two files in order like
file_C:

1 A 2 B 3 C 4 D 5 E
1 A 2 B 3 C 4 D 5 E
1 A 2 B 3 C 4 D 5 E
1 A 2 B 3 C 4 D 5 E
1 A 2 B 3 C 4 D 5 E

I have found a solution in the community like this
paste file_A file_B | awk '{print $1,$6,$2,$7,$3,$8,$4,$9,$5,$10}'

But considering amount of columns is like 100 for each file or not constant, I want to know if there is a better method.
Thanks in advance.

A: You can use a loop in awk, for example
paste file_A file_B | awk '{
    half = NF/2;
    for(i = 1; i < half; i++)
    {
        printf("%s %s ", $i, $(i+half));
    }
    printf("%s %s\n", $half, $NF);
}'

or
paste file_A file_B | awk '{
    i = 1; j = NF/2 + 1;
    while(j < NF)
    {
        printf("%s %s ", $i, $j);
        i++; j++;
    }
    printf("%s %s\n", $i, $j);
}'

The code assumes that the number of columns in awk's input is even.

A: Use this Perl one-liner after paste to print alternating columns:
paste file_A file_B | perl -F'\t' -lane 'print join "\t", @F[ map { ( $_, $_ + ( @F/2 ) ) } 0 .. ( $#F - 1 ) /  2 ];'

Example:
Create tab-delimited input files:
perl -le 'print join "\t", 1..5 for 1..2;' > file_A
perl -le 'print join "\t", "A".."E" for 1..2;' > file_B
head file_A file_B

Prints:
==> file_A <==
1       2       3       4       5
1       2       3       4       5

==> file_B <==
A       B       C       D       E
A       B       C       D       E

Paste files side by side, also tab-delimited:
paste file_A file_B | perl -F'\t' -lane 'print join "\t", @F[ map { ( $_, $_ + ( @F/2 ) ) } 0 .. ( $#F - 1 ) /  2 ];'

Prints:
1       A       2       B       3       C       4       D       5       E
1       A       2       B       3       C       4       D       5       E

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.
-F'/\t/' : Split into @F on TAB, rather than on whitespace.
$#F : last index of the array @F with the input fields, split on tab.
0 .. ( $#F - 1 ) /  2 : array of indexes of the array @F, from the start (0) to half of the array. These are all indexes that correspond to file_A.
map { ( $_, $_ + ( @F/2 ) ) } 0 .. ( $#F - 1 ) /  2 : map takes the above array of indexes from 0 to half of the length of @F, and returns a new array, with twice the number of elements. Its elements alternate: (a) the index corresponding to file_A ($_) and (b) that index plus half the length of the array ($_ + ( @F/2 )), which is the corresponding index from file_B.
@F[ map { ( $_, $_ + ( @F/2 ) ) } 0 .. ( $#F - 1 ) /  2 ] : a slice of array @F with the specified indexes, namely alternating fields from file_A and file_B.
SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perldata: Slices

A: With one awk script parsing the files:
FNR==NR {
    rec[NR] = $0
    next
}

{
    split(rec[FNR], fields)
    for (i=1;i<=NF;i++) $i = fields[i] FS $i
    print
}

Usage:
awk -f tst.awk file_A file_B


text:
Q: JHipster 504 Gateway Timeout when trying to call a microservice Registry Overview
One instance of my microservice is down and when I try to make a rest call to that microservice it won't work even though alot of other instances are up and running.
I don't quite understand and the error logs don't help much either. Do I need to manually switch to another instance? I thought its the job of the registry to take care of these things?
I haven't changed anything in the service class:
public resourceUrl = SERVER_API_URL + 'productms/api/products';

find(id: number): Observable<EntityResponseType> {
    return this.http.get<IProduct>(`${this.resourceUrl}/${id}`, { observe: 'response' });
}

regards


text:
Q: QT Visual Studio plugin fails automatic moc with non-standard header extensions I am currently trying to port a very large project to QT. Many of the headers in this project use the file extension .hh . I would ideally like to avoid having to rename all of these files, but it appears to be causing some issues for the QT Visual Studio plugin. I am using Visual Studio 2012 and QT 5.5.
I have set up a trivial project to test this problem. If i define a class in a .h file that inherits from QObject and contains the Q_OBJECT macro the Custom Build instructions are automatically added to the files properties and moc'd files are automatically generated. If i rename the file to have a .hh extension no Custom Build instructions are generated and no moc'd files are generated.
I have attempted adding hh to the "Filter" property of the folder/filter containing my header files. This seems to result in the Custom Build instructions being applied to the headers, the correct files being generated by MOC, but not automatically included into the solution. This results the build failing with linker errors.
I would be surprised if this wasn't configurable some how. Has anyone had any success with custom file extensions before?


text:
Q: Does high standard error and high r-square imply spurious regression? Does a regression passed on time series data with one independent variable and one dependent variable which yields parameters with very high standard errors (t-values) and also a high r-squared imply that the regression results are spurious and that there is no real correlation between the variables?
The model is: $ln(y_t)=a+bln(x_t)$,
$R^2>0.95$
edit: just to clarify, these standard errors arent just high but are also high in comparison to their equivalent parameter estimates.
Thank you for any help.


text:
Q: How to use Apache Camel aggregator I have a very simple use case in which I want to put together a collection of stings and trying to use aggregator EIP for this. However when trying to start up the route it complains it cannot find an Aggregator Strategy:
java.lang.IllegalArgumentException: AggregationStrategy or AggregationStrategyRef must be set on Aggregate

below is how I can reproduce the issue:
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class AggregatorTest extends CamelTestSupport {
    private static final List<String> LIST = Arrays.asList(new String[] {"one", "two", "three"});
    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .split().body()
                        .setHeader("cheese", constant("camembert"))
                        .aggregate(constant("all"))
                        .to("mock:end");
            }
        };
    }

    @Test
    public void shouldAggregateStrings() throws Exception {
        sendBody("direct:start", LIST);
    }
}

Of course a very easy way to fix this would be to create an Aggregation Strategy implementation and configure my route to use it. However I would like to understand why the way is set up now does not work. According to the camel documentation on here :

By default Camel uses DefaultAggregationCollection and
  UseLatestAggregationStrategy, so this simple example will just keep
  the latest received exchange for the given correlation Expression

I also noticed DefaultAggregationCollection is no longer part of the camel core. So what I am missing here?

A: That is the old documentation. The correct documentation is at: http://camel.apache.org/aggregator2
eg the list of EIPs has links to the correct documentation: http://camel.apache.org/eip
You can find examples from those links, and as well in this little example: https://github.com/apache/camel/blob/master/examples/camel-example-aggregate/README.md
And the Camel in Action books has an EIP chapter where the aggregator is covered in much more details as well: http://camel.apache.org/books

A: I made a small video to demonstrate this EIP pattern using SpringBoot and Camel.
Have a look here: https://youtu.be/IdGuGGVv51Q


text:
Q: When to use .length vs .length() Ok so I have this code:
public class Test {
    public static void main(String[] args) {

        String[] people = {"Bob", "Billy", "Jim"};
        int sum = 0;

        for(int i = 0; i < people.length; i++) {
            sum += people[i].length();
        }
    }
}

My question is why people[i].length() is .length() and not .length. I thought to get the length of an array you use .length and not .length(). Do you use .length() because you are trying to get the length of a string and not an array? P.S. I am a beginner, so this may seem very obvious to you, but it isn't to me.

A: .length is an array property. .length() is a method for the class String (look here).
When you are looping, you are looping for the length of the array using people.length.
But when you are using people[i].length(), you are accessing the string at that position of the array, and getting the length of the string, therefore using the .length() method in the String class.
However, just to confuse you more, a String at its core is just an array of chars (like this: char[]). One could make the argument that .length should work as well, considering it is an array of characters, however, it is a class and that is the reason .length will not work. Showing empty parameters shows it's a method, and showing no parameters shows that it's a property (like a static variable in a class).

A: They're two completely different things.
.length is a property on arrays.  That isn't a method call.
.length() is a method call on String.
You're seeing both because first, you're iterating over the length of the array.  The contents of the array are String, and you want to add up all of their lengths, so you then call the length on each individual String in the array.

A: .length is for Arrays, and .length() for Strings
Array's length is a field, while the String's length is in a function - .length()


text:
Q: Get the jquery index of same element class within different containers On the event "click", I would like to get the index of an element that can be in multiple container. The index position returned should be calculated relatively to its container and not to the body tag.
I wrote an example here: http://jsfiddle.net/zUGcK/
My problem is that when I click on the lines in the second block container, the line index returned are: 3, 4, 5 whereas I would like 0, 1, 2 to be returned.
What should I change in the jquery index() arguments to get 0, 1, 2 returned for each line in both containers?
Thanks
http://jsfiddle.net/zUGcK/
$('.line').click(function()
{
    alert('index: '+$(this).index('.container .line'));
});

block #1

line #0

line #1

line #2

block #2

line #0 (index 3 returned instead of 0)

line #1 (index 4 returned instead of 1)

line #2 (index 5 returned instead of 2)

A: You can use this to get the index value for elements within it's container
$(function()
{
    $('.line').click(function()
    {
        //alert('index: '+$(this).index('.container .line'));

        alert($(this).closest('.container').find('.line').index(this));
    });
});

You have to use this syntax of $.index
.index( element )
element The DOM element or first element within the jQuery object to look for.

Working Fiddle

A: Updated index with $this.
 $('.line').click(function()
{
    var $this=$(this);
   var indx= $this.parent('.container').find('.line').index($this);

    alert('index: '+indx);
});


text:
Q: Invalid Number is returned by Regexp_replace I want to remove titles like Dr., Mr. Jr. from name. Regexp_replace should Search and remove Dr. Mr. Jr and search should be case insensitive, final output should not have . or , or extra spaces in name.
select regexp_replace('DR. Mr. Mr Dr Radha Jr Jr. Krishnan Jr.','(Dr|Mr|Jr)(\W|\w|$|,)',1,0,'i')
from dual

I am getting invalid number error.

A: You forgott what to replace with between pattern and 1
select regexp_replace('DR. Mr. Mr Dr Radha Jr Jr. Krishnan Jr.','(Dr|Mr|Jr)(\W|\w|$|,)','',1,0,'i')
from dual

A: The following query will remove multiple empty spaces and trim the leading space too:
SELECT TRIM(REGEXP_REPLACE(
         REGEXP_REPLACE('DR. Mr. Mr Dr Radha Jr Jr. Krishnan Jr.', '(Dr|Mr|Jr)(\W|\w|$|,)', '', 1, 0, 'i')
       , ' {2,}', ' ')) AS "Result"
FROM Dual

It will return the result as Radha Krishnan
Demo on db<>fiddle

A: Your solution lacks in two aspects.
The more important is that you may cut of the leading "titles" from names:
select regexp_replace('DR. Mr. Mr Dr Dradha Jr Jr. Mrishnan Jr.','(Dr|Mr|Jr)(\W|\w|$|,)','',1,0,'i')
from dual

which returns a not expected result
dha  shnan

The remedy is to allow only the non word characters (\W) and end of line ($) after the title.
If you enforce optional space or begin of the line (^) before  the title, you get rid of the second problem the spaces left after the remove of titles
select regexp_replace('DR. Mr. Mr Dr Dradha Jr Jr. Mr, Mrishnan Jr.',
  '( *|^)(Dr|Mr|Jr)(\W|$)','',1,0,'i')
from dual

Dradha Mrishnan


text:
Q: When Using Postgresql JDBC, INSERT statement that will result in 0 rows being inserted When Using Postgresql JDBC, Insert row with executeUpdate statement but result was zero. I found that data was inserted. API document tells that executeUpdate method return affected row count.
mSqlInsertEventHist = "INSERT INTO " + DatabaseTables.EVENT_HIST +
" ( event_id, mntr_id, mntr_zone, mntr_name, mntr_class_name, mntr_class_sub_type, host_name, ip_addr, " +
"   metric_id, metric_name, perf_name, object_name, event_type, event_master_id, " +
"   event_name, event_level, event_msg, threshold, event_recv_day, event_reco_dt, event_recv_dt," +
"   event_saved_dt, blackout_yn, msg_filter_yn ) " +
" VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + " now() " + ", ?, ? ) ";

mPstmtInstEvtHist.setLong(1, eventid);
mPstmtInstEvtHist.setInt(2, mntrid);
mPstmtInstEvtHist.setString(3, mntrZone);
mPstmtInstEvtHist.setString(4, mntrname);
mPstmtInstEvtHist.setString(5, mntrClsName);
mPstmtInstEvtHist.setString(6, mntrClsSubType);
mPstmtInstEvtHist.setString(7, hostname);
mPstmtInstEvtHist.setString(8, ipAddr);
mPstmtInstEvtHist.setInt(9,     Integer.parseInt((String)dataobj.get(MQConstants.METRIC_ID)));
mPstmtInstEvtHist.setString(10, metricname);
mPstmtInstEvtHist.setString(11, perfname);
mPstmtInstEvtHist.setString(12, objectname);
mPstmtInstEvtHist.setString(13, dataType);
mPstmtInstEvtHist.setInt(14,
Integer.parseInt((String)dataobj.get(MQConstants.EVENT_MASTER_ID)));
mPstmtInstEvtHist.setString(15, eventname);
mPstmtInstEvtHist.setString(16, eventlvl);
mPstmtInstEvtHist.setString(17, evtMsg);
mPstmtInstEvtHist.setObject(18, jsonObj);
mPstmtInstEvtHist.setInt(19,
Integer.parseInt((String)dataobj.get(MQConstants.EVENT_RECV_DAY)));
mPstmtInstEvtHist.setTimestamp(20, colTs);
mPstmtInstEvtHist.setTimestamp(21, rcvTs);
mPstmtInstEvtHist.setString(22,
(String)dataobj.get(MQConstants.BLACKOUT_YN));
mPstmtInstEvtHist.setString(23,
(String)dataobj.get(MQConstants.MSG_FILTER_YN));
rtn = mPstmtInstEvtHist.executeUpdate();
if ( rtn == 1  ) {//NOPMD
    Debug.getLogger().trace("Inserted Event into {} => {}, {}, {} "
   ,DatabaseTables.EVENT_HIST , mntrid, eventname, eventlvl);
} else {
    Debug.getLogger().warn("Failed to insert Event into {} => {}",
    DatabaseTables.EVENT_HIST, Debug.getString(jobj));
}

A: It might be that you have a trigger-based partitioning in your database, as described here in PostgreSQL manual.
It's happening completely on the DB side, except that it always returns "0 rows inserted".
Check your DB schema for partitioning triggers in DatabaseTables.EVENT_HIST table.


text:
Q: Bitmask multiple values in int64 I'm using https://github.com/coocood/freecache to cache database results, but currently I need to dump bigger chunks on every delete, which costs multiple microseconds extra compared to targeted deletion. fmt.Sprintf("%d_%d_%d") for a pattern like #SUBJECT_#ID1_#ID2 also costs multiple microseconds. Even tho that doesn't sound like much, in the current ratio of the cache's response time that a multitude slower than it currently is.
I was thinking of using the library's SetInt/GetInt which works with int64 keys instead of strings.
So let's say I'm storing in a #SUBJECT_#ID1_#ID2 pattern. The Subject is a table or query-segment-range in my code (e.a. everything concern ACL or Productfiltering).
Let's take an example of Userright.id is #ID1 and User.id is #ID2 and Subject ACL. I would build it as something like this:
// const CACHE_SUBJECT_ACL = 0x1
// var userrightID int64 = 0x1
// var userID int64 = 0x1
var storeKey int64 = 0x1000000101

fmt.Println("Range: ", storeKey&0xff)
fmt.Println("ID1  : ", storeKey&0xfffffff00-0xff)
fmt.Println("ID2  : ", storeKey&0x1fffffff00000000-0xfffffffff)

How can I compile the CACHE_SUBJECT_ACL/userrightID/userID into the storeKey?
I know I can call userrightID 0x100000001, but it's a dynamic value so I'm not sure what's the best way to compile this without causing more overhead than formatting the string as a key.
The idea is that in a later state when I need to flush the cache I can call a small range of int64 calls instead of just dumping a whole partition (of maybe thousands of entries).
I was thinking of adding them to each other with bit shifting, like userID<<8, but I'm not sure if that's the safe route.
If I failed to supply enough information, please ask.

A: Packing numbers to an int64
If we can make sure the numbers we want to pack are not negative and they fit into the bit range we're reserving for them, then yes, this is a safe and efficient way to pack them.
An int64 has 64 bits, that's how many we can assign to the parts we want to pack into it. Often the sign bit is not used to avoid confusion, or an unsigned version uint64 is used.
For example, if we reserve 8 bits for subject, that leaves 64-8=56 bits for the rest, 28 bits for each ID.
                   | ID2         | ID1         |SUB|
Encoded key bits:  |f f f f f f f|f f f f f f f|f f|

Note that when encoding, it's recommended to also use a bitmask with bitwise AND to make sure the numbers we pack do not overlap (arguable, because if the components are bigger, we're screwed anyway...).
Also note that if we're also using the sign bit (63th), we have to apply masking after the bitshift when decoding, as shifting right "brings in" the sign bit and not 0 (sign bit is 1 in case of negative numbers).
Since we used 28 bits for both ID1 and ID2, we can use the same mask for both IDs:
Use these short utility functions which get the job done:
const (
    maskSubj = 0xff
    maskId   = 0xfffffff
)

func encode(subj, id1, id2 int64) int64 {
    return subj&maskSubj | (id1&maskId)<<8 | (id2&maskId)<<36
}

func decode(key int64) (sub, id1, id2 int64) {
    return key & maskSubj, (key >> 8) & maskId, (key >> 36) & maskId
}

Testing it:
key := encode(0x01, 0x02, 0x04)
fmt.Printf("%016x\n", key)
fmt.Println(decode(key))

Output (try it on the Go Playground):
0000004000000201
1 2 4

Sticking to string
Originally you explored packing into an int64 because fmt.Sprintf() was slow. Note that Sprintf() uses a format string, and it takes time to parse the format string and format the arguments according to the "rules" laid out in the format string.
But in your case we don't need this. We can simply get what you originally wanted like this:
id2, id1, subj := 0x04, 0x02, 0x01
key := fmt.Sprint(id2, "_", id1, "_", subj)
fmt.Println(key)

Output:
4_2_1

This one will be significantly faster as it doesn't have to process a format string, it will just concatenate the arguments.
We can even do better; if none of 2 arguments being next to each other are string values, a space is automatically inserted, so it's really enough to just list the numbers:
key = fmt.Sprint(id2, id1, subj)
fmt.Println(key)

Output:
4 2 1

Try these on the Go Playground.
Utilizing fmt.AppendInt()
We can improve it further by using fmt.AppendInt(). This function appends the textual representation of an integer to a byte slice. We can use base 16 so we'll have more compact representation, and also because the algorithm to convert a number to base 16 is faster than to base 10:
func encode(subj, id1, id2 int64) string {
    b := make([]byte, 0, 20)

    b = strconv.AppendInt(b, id2, 16)
    b = append(b, '_')
    b = strconv.AppendInt(b, id1, 16)
    b = append(b, '_')
    b = strconv.AppendInt(b, subj, 16)

    return string(b)
}

Testing it:
id2, id1, subj := int64(0x04), int64(0x02), int64(0x01)
key := encode(subj, id1, id2)
fmt.Println(key)

Output (try it on the Go Playground):
4_2_1

A: Seemed to have figured it out:
const CacheSubjectACL = 1
var userrightID int64 = 8
var userID int64 = 2
storeKey := CacheSubjectACL + (userrightID << 8) + (userID << 36)

fmt.Println("storeKey: ", storeKey)
fmt.Println("Range   : ", storeKey&0xff)
fmt.Println("ID1     : ", storeKey&0xfffffff00>>8)
fmt.Println("ID2     : ", storeKey&0x1ffffff000000000>>36)

Gives:
 storeKey:  137438955521
 Range   :  1
 ID1     :  8
 ID2     :  2

storeKey builds the int64 masked. And the masking with a new shift the other way around fishes the old values out of the int64 again.
Because storeKey&0x1ffffff000000000>>36 runs to the end anyway, storeKey>>36 will suffice too as there are no bits on the further left.


text:
Q: Setting Git in Rstudio I'm trying to launch Git on Rstudio.
I was following this instructions:
http://www.geo.uzh.ch/microsite/reproducible_research/post/rr-rstudio-git/
I installed git and I have the path for its executable file on my disk.
I set this in global options.
Unfortunately after having R-studio restarted () the Git icon did not appear, so basically Git is not working.

A: Try this in RStudio:

*

*Tools > Global Options > Git / SVN;

*point to the location of your Git executable:


text:
Q: Cast Dialog to AlertDialog I had the exact same code in antoher project, but it continues to crash here. I have implementation 'com.android.support:design:26.1.0' in my gradle. I'm really unsure of what the problem is. I've tried switching the gradle version, changing from v7 Dialog to the app Dialog. All fails regardless
java.lang.ClassCastException: android.app.Dialog cannot be cast to android.support.v7.app.AlertDialog
                      at com.example.weather.CreateCityDialog.onResume(CreateCityDialog.java:58)

import android.app.Dialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CreateCityDialog extends DialogFragment {
    public interface NewCityHandler {
        void onNewCityCreated(String cityName);
    }

    private NewCityHandler newCityHandler;
    private EditText etName;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof NewCityHandler)
            newCityHandler = (NewCityHandler) context;
        else
            throw new RuntimeException("Error");
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add new city");

        View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);

        etName = rootView.findViewById(R.id.etName);

        builder.setView(rootView);

        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        return super.onCreateDialog(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        final AlertDialog d = (AlertDialog) getDialog();
        if (d != null) {
            Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(etName.getText())) {
                        newCityHandler.onNewCityCreated(etName.getText().toString());
                        d.dismiss();
                    } else {
                        etName.setError("Empty field");
                    }
                }
            });
        }
    }
}

A: You have to return AlertDialog from onCreateDialog().
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add new city");

    View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);

    etName = rootView.findViewById(R.id.etName);

    builder.setView(rootView);

    builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    });
    return builder.create();
}


text:
Q: AWS VPN Connection I got notification from aws Customer vpn connection issues

You have new non-redundant VPN connections One or more of your vpn
  connections are not using both tunnels. This mode of operation is not
  highly available and we strongly recommend you configure your second
  tunnel. View your non redundant VPN connections.

Any suggestions for these issues?

A: You can ignore this warning your tunnels are redundant.
A single AWS VPN connection has two tunnels. AWS VPN automatically fails over to the second tunnel in case of maintenance or failure.
The reason you are getting that error is that both peer ips are not up simultaneously some devices give you this ability such as cisco ASA running in Active/Active (Be sure to use asymmetric routing if this is the case).
AWS VPN Knowledge center


text:
Q: Will hash_equals ever return true for two different strings? Is there any situation where two different strings passed into hash_equals() would return true? Are "hash collisions" an issue with hash_equals?

A: hash_equals just appears to be poorly named. It strictly does a string comparison and does not involve hashing (thus no possibility of hash collisions).
I believe the name comes from a common use case for a timing-attack safe string comparison function, which is to compare two strings representing hashes.


text:
Q: What files go in grails-app/assets versus web-app I am just getting started with Grails and trying to understand when to put files in grails-app/assets/{stylesheets|images|javascript} versus putting things in web-app/{css|images|js}.

A: In short, if you want your front-end resources to be managed by the Asset Pipeline plugin, you should put them in grails-app/assets. If you don't, you should put them under web-app.


text:
Q: Knockout validation: Dynamic constraints I'm using Durandal, which in turn leverages off of Knockout.
I want to be able to Change validation lengths dynamically

Fiddle
The fiddle seems to be behaving slightly different than my "working" solution, but its still not doing what I'm wanting/expecting it to.
Viewmodel JS:
[Attempt 1]
define(function () {

   var self = this;

   self.userInfo = {
        IdOrPassportNumber: ko.observable().extend({
            required: true,
            pattern: {
                message: 'A message',
                params: /some regex/
            }
        }),
        IdType: ko.observable()
    },

    self.isIdValid = ko.validatedObservable({
         IdOrPassportNumber: self.userInfo.IdOrPassportNumber
    });

    self.userInfo.IdOrPassportNumber.subscribe(function (value) {
          if (isIdValid.isValid()) {
               console.log('YOLO!');
          }
    });

    self.userInfo.IdType.subscribe(function (value) {
        console.log(value);
        if (value === 'Passport') {
            self.userInfo.IdOrPassportNumber.extend({ maxLength: 15 });
        } else {
            self.userInfo.IdOrPassportNumber.extend({ maxLength: 13 });
        }
    });

    var viewModel = {
        userInfo: self.userInfo
    };

    viewModel["errors"] = ko.validation.group(viewModel.userInfo);
    viewModel["errors"].showAllMessages();

    return viewModel;
});

What seems to be happening is that when i start typing i get the max & min validation of 13, but if i continue typing the validation changes to 15. I have tried another route of, setting the  min & max length in the initial observable extend EG, just after the regex, and then setting the min and max length to use an observable, to no success.
[Attempt 2]
   self.userInfo = {
       IdOrPassportNumber: ko.observable().extend({
            maxLength: self.maxLength(),
            minlength: self.maxLength()
       }),
       IdType: ko.observable()
   },

   self.maxLength = ko.observable();

   self.userInfo.IdType.subscribe(function (value) {

          if (value === 'Passport') {
             self.maxLength(15)
          } else {
              self.maxLength(3)
          }
    });

A: Here is the solution that worked for me:
I made use of the custom validation feature, more specifically the
 single use custom validation as this wont be re-used elsewhere.
[Attempt 3]
    self.userInfo = {
        IdOrPassportNumber: ko.observable().extend({
            required: true,
            pattern: {
                message: 'A message',
                params: /some regex/
            },
            validation: {
               validator: function (val) {
                   if (self.userInfo.IdType() === 'Id') {
                      return val.length === 13;
                   } else {
                      return val.length === 15;
                   }
                },
               message: function () {
                  if (self.userInfo.IdType() === 'Id') {
                    return 'Required: 13 characters';
                  } else {
                    return 'Required: 15 characters';
                  }
               }
            }
        })
     }

A: You were so close :-)
You must provide the observable itself, not the unwrapped value. So just remove the () from maxLength() - the validation library will automatically unwrap it for you.
self.userInfo = {
   IdOrPassportNumber: ko.observable().extend({
        maxLength: self.maxLength,
        minlength: self.maxLength
   }),
   IdType: ko.observable()
},

Here's another example with dynamic regex patterns.
    zipPostalPattern = ko.pureComputed(() => this.countryCode() === 'US' ? '^\\d{5}(?:[-\\s]\\d{4})?$' : '');
    zipOrPostal: KnockoutObservable<string> = ko.observable('').extend(
    {
        required: true,
        pattern: {
            message: 'This is not a valid postcode for the country',
            params: this.zipPostalPattern
        }
    });

or (if you don't want a message).
    zipPostalPattern = ko.pureComputed(function() { return this.countryCode() === 'US' ? '^\\d{5}(?:[-\\s]\\d{4})?$' : ''});
    zipOrPostal: KnockoutObservable<string> = ko.observable('').extend(
    {
        required: true,
        pattern:  self.zipPostalPattern
    });

Important: If you don't want a custom message don't just remove the message parameter and leave pattern = { params: this.zipPostalPattern } because it won't work. If you don't have a message you must set the Regex/string directly for the pattern parameter.
Or of course you can just define the computed observable in place (here it's ok to call countryCode() as a function because that's how computed's work)
    zipOrPostal: KnockoutObservable<string> = ko.observable('').extend(
    {
        required: true,
        pattern:  ko.pureComputed(function() {
                     return self.countryCode() === 'US' ? '^\\d{5}(?:[-\\s]\\d{4})?$' : ''
                  })
    });

A: consider this
self.iDNumber = ko.observable('').extend({
        required: {
            params: true,
            message: 'ID Number is a required field.',
            insertMessages: false
        },
        SouthAfricanIDNumber: {
            message: 'Please enter a valid South African ID number.',
            onlyIf: function() {
                return self.identityType() === 'SAID';
            }
        }
    });

where SouthAfricanIDNumber is a custom validation that uses regex.


text:
Q: Цикл for в python. Как сократить Нужно заменить код
walkRight = [pygame.image.load('sprite/right_1.png'), pygame.image.load('sprite/right_2.png'),
            pygame.image.load('sprite/right_3.png'), pygame.image.load('sprite/right_4.png'),
            pygame.image.load('sprite/right_5.png'), pygame.image.load('sprite/right_6.png')]

на менее громоздкий. Например так:
my_list = [1, 2, 3, 4, 5, 6]
for i in range(len(my_list)):
    walkRight = my_list[pygame.image.load('sprite/right_[i].png')]

У меня не получается

A: walk_right = [pygame.image.load('sprite/right_%s.png' % (i+1))
              for i in range(6)]


text:
Q: JavaScript modified some value in original JSON I have:
const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]
parsedData.map((item, i) => ({
  ...item,
  key: `modified ${item.key}`
}));
console.log(parsedData);

What I'm trying is to get parsedData array modified and get:
[
  { id: 1, key: 'modified asdas'},
  { id: 2, key: 'modified asdas'},
]

But I'm getting the same array in the console.log

A: a map will return a new array you need to capture it in different variable
const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]

const newData = parsedData.map((item, i) => ({
  ...item,
  key: `modified ${item.key}`
}));

console.log(newData);

A: map returns the modified array; it does not mutate the original.
You should be logging the result returned by map:

const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]
let res = parsedData.map((item, i) => ({
  ...item,
  key: `modified ${item.key}`
}));
console.log(res);

Alternatively, you can use forEach:

const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]
parsedData.forEach((item, i) => (parsedData[i] = {
  ...item,
  key: `modified ${item.key}`
}));
console.log(parsedData);


text:
Q: Google Analytics API and UI Report Users data not matching I've extensively searched in forum and after that putting this question so that someone might be able to help me.
Scenario:
In Google analytics dashboard, we have created logical categories based on keywords within PagePath. For instance, if my PagePath contains keyword \sports\ we call it Sports Section category.
We capture the User count weekly from UI as shown below :

I am now trying to move this data in MySQL db using Talend Open Studio Data Integration.
I am using a componenttgoogleanalyticsinput where I can feed Dimensions and Metrics.
Problem:
I analyzed 2 days of data and found the following observation:
Date     All User   Sports  Auto
01-Jun  2220088   325174    51825   (visible in image chart)
02-Jun  2950015   256390    80472   (not visible in above chart)
Total   5170103   581564    132297  (sum of above)
API :   5170103   581564    132297  (received from API)
UI :    4910532   553400    129652  (shown in UI)

So, the data on chart matches with what I'm getting from API BUT they both do not match with what is shown in UI number.
I visited this link to understand what those numbers mean on Google UI.
Problem is, what dimension and metrics should I take so that my API values matches with UI number?
I tried to take ga:PagePath, ga:Date as dimension and ga:Users, ga:pageViews as metrics but they're not working for me.


text:
Q: How to Restore photos on SD card I deleted 40 some photos from my SD card in my camera.  I thought I saved them on my desktop.  Using 12.04 LTS.  Is there a way to restore the photos??  My wife is pissed.  Nothing has been over written on the card.
Thanks

A: TestDisk / PhotoRec
Yes, use the tool photorec; you'll be able to recover pretty much any file.
You should make sure that the SD card is read only as writing to it can corrupt any possibility of recovering data.
In Ubuntu, open a terminal and run:
$ sudo apt install testdisk
$ sudo photorec


text:
Q: How to change the button color on click? I have change iconic button color when clicking on it, default iconic button color is primary color when I clicked on the iconic button it should change primary color to red color. That working fine for me, now after clicking the hidden buttons will display one is cancel button  and other is save button up to here it is working fine now, when I clicked cancel button the button which is red color should change to primary but cancel button is closing and color of the iconic button is not changing

<kendo-grid-command-column headerClass="data-list-header-cell" title="Delete" width="5" filterable="false">
    <ng-template kendoGridCellTemplate let-site>
      <button mat-icon-button color="primary" (click)="onDelete(data)" [ngClass]="{'selectedRemoveButton':data.isClicked}">
        <mat-icon>remove_circle</mat-icon>
      </button>

      // these are icon button if clicked on this button it will change color and also show 2 buttons cancel and save.

      <ng-container *ngIf="showButtons">
    <span class="rightButtons">
      <button class="mat-button menu-button" (click)="cancel()">
        <mat-icon>block</mat-icon> CANCEL
      </button>
      <button class="mat-button primary-button" (click)=" save()">
        SAVE
      </button>
    </span>
  </ng-container>
.selectedRemoveButton {
  color: red
}
 onDelete(data: any) {
    if (data.isClicked) {
      this.dataList.push(data);
    }
    data.isClicked = !data.isClicked;
    this.showButtons = !this.showButtons;
    console.log(data.Id);
  }

  //these is where i am first clicking on button when i click on these button color will change to red

  cancel(): void {
    this.showButtons = false;
  }
  //if presse on cancel button is disappearing but color have to change red to primary
  save() {

      this.Service.datalist(data.Id).subscribe(
          data => {
            this.dataList = data;
            console.log(data);
          });

  }
  //this is save button

please help me in this

A: use ngClass to add classes dynamically.
<button class="mat-button menu-button" [ngClass]="removeStyles" (click)="cancel()">

removeStyles = "";
cancel(): void {
  this.showButtons = false;
  this.removeStyles= "selectedRemoveButton"
}

A: If you are not getting that change is because you miss something there.
Try to approach it adding a variable at the time you click on the button, like this.
[ngClass]="changBtnColor ? classNameColorActual : classNameColorAfterClick" (click)="changeColor()"
.classNameColorActual{ color:red}
.classNameColorAfterClick{color:blue}

Meaning that the function
changeColor(): void {
     this.changBtnColor = !this.changBtnColor ;     // this should change the color of the
                                     // button every time is clicked
  }

You should use a custom class to give them the styles but if you don't want it you should also use the native classes of the element, to achieve this go to dev tools in chrome and search that class.
I hope it should help you.


text:
Q: Do all user mode processes started in Windows go through CreateProcess? Is there any bottleneck above the physical the cpu and HAL? Or are there multiple ways a process could start under Windows XP, Vista, or 7, that don't invovle CreateProcess at some point?

A: Given the comment on your question:

Building an Anti-Executable driver, just planning, wondering if controlling createprocess would be enough.

No it wouldn't be enough if security is your concern. There is NtCreateProcess below that one for example. And those aren't the only ones.
The best way provided by the system is a file system filter driver. In fact the WDK comes with samples that require only a moderate amount of change to do what you're asking. Since you asked about XP you can use a minifilter if you can get away with support for XP SP1 and later.
PsSetLoadImageNotifyRoutine and PsSetCreateProcessNotifyRoutine are unfortunately only notifications. So they don't allow to do anything about the event that they notify about. And you really shouldn't attempt to work around this.
In the old times I have seen some clever implementations using SSDT hooks on ZwCreateSection that would exchange the returned handle with one to an executable that shows an error message. Since the executable itself sees the original command line, it can then show a nice error message informing the user that the command has been banned for reasons xyz. However, with Vista and later and even on XP and 2003 64bit (x64), it's going to be harder to write the SSDT hooks. Not to mention that everyone would frown upon it, that it requires quite extensive experience to get it right (and even then it often has flaws that can cause havoc) and that you can forget any certifications you may be aspiring for in the Windows Logo process.
Conclusion: use a file system filter driver to deny access to unwanted executables. With a minifilter the learning curve will be moderate, with a legacy filter I'll recommend you take a few courses first and then start your first attempts.

A: Looking through a quick disassembly of CreateProcess, it appears that the two main things it does are:

*

*Call NtCreateUserProcess (this is syscall 0xAA) to actually create the process structures in the kernel (PEB, etc.)

*Start the new process with a call to NtResumeThread (syscall 0x4F).

The Windows Internals books certainly detail this process very well.
I'm not sure if there are designated hooks in the kernel which would allow you to create your anti-executable driver.  It used to be that you could hook the "System Service Dispatch Table" to change how these system calls behaved. But now, technologies like PatchGuard prevent a driver from doing this (and allowing the system to run).


text:
Q: Negativity of an analytic function on $[0,1)$ I want to show the following function is negative for $z\in [0,1)$:
$$f(z) = -1 + z^2(z-1) + 2\sum_{k=0}^\infty (-1)^k z^{(2k+1)^2+1}. $$
By Tauberian theorem, I know that $\lim_{z\to 1^-}f(z)=0$. I also know that $\lim_{z\to 1^-} f'(z)=1$ so there is a close enough neighborhood of $1$ that $f$ is always negative. However, I want to give more details to show the negativity of the function $f$. I have included a plot of $f$ below. The function diverges at $x=1$, hence it is not easy to estimate it by truncating the series for $z\to 1$.

A: Very close to $z=1$ we have
$$z^{(2k+1)^2+1}=1+\left((2 k+1)^2+1\right) (z-1)+(2 k+1)^2 \left(2 k^2+2
   k+1\right) (z-1)^2+O\left((z-1)^3\right)$$ Ignoring the higher order terms
$$\sum_{k=0}^\infty (-1)^k z^{(2k+1)^2+1}=(z-2) z+\frac{3}{2}\quad \implies \quad f(z)=(z-1) \left(z^2+2 z-2\right)$$ which is negative.
Ckecking the summation

*

*for $z=\frac{95}{100}$, the numerical value is $0.503482$ while the above approximation gives $\frac{201}{400}=0.502500$

*for $z=\frac{99}{100}$, the numerical value is $0.500105$ while the above approximation gives $\frac{5001}{10000}=0.500100$
I have serious divergence problems when I try to make the expansion to $O\left((z-1)^4\right)$.
If it was
$$\sum_{k=0}^\infty (-1)^k z^{(2k+0)^2+1}=\frac{1}{2} z \left(\vartheta _4\left(0,z^4\right)+1\right)$$ the plot of the two $f(z)$ are quite similar. May be, an idea here ?


text:
Q: Método setActivated() onBindViewHolder() He estado leyendo la documentación oficial de android y he visto que mediante la implementación del método setActivated() en el onBindHolder de un RecyvlerView se pueden dar por ejemplo, valores iniciales a los elementos de un girdLayout, como el color de una celda en concreto en función de una variable de la activity.
He estado buscando por internet y no encuentro ningún repositorio de código al respecto y no sé cómo implementarlo.
¿Alguien puede guiarme?
Gracias
En el onBind con este código si me marca bien las personas ocupadas:
public class RecyclerViewAdapter extends RecyclerView.Adapter<Basico.RecyclerViewHolders> {
private List itemList;
private Context context;
        public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
            this.itemList = itemList;
            this.context = context;
        }

        @Override
        public Basico.RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

            View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
            Basico.RecyclerViewHolders rcv = new Basico.RecyclerViewHolders(layoutView);
            return rcv;
        }

        @Override
        public void onBindViewHolder(MBasico.RecyclerViewHolders holder, int position) {
            holder.ocupado.setText(itemList.get(position).getName());
            holder.foto.setImageResource(itemList.get(position).getPhoto());

                switch (position)
                {

                    case 0:
                        if (p.getOcupado()==1)
                        {
                            holder.fondo.setBackgroundColor(Color.parseColor("#ffbe00"));
                            holder.name.setTextColor(Color.parseColor("#ffffff"));
                        }
                        break;

                }
        }

        @Override
        public int getItemCount() {
            return this.itemList.size();
        }

    }

Pero en el onclick no me detecta bien si está ocupado o no, siempre empieza con pulsado =0 y luego pasa a 1, independientemente del valor devuelto por getOcupado().
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView name;
        public ImageView foto;
        public RelativeLayout fondo;

        public RecyclerViewHolders(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
            name = (TextView) itemView.findViewById(R.id.name);
            foto = (ImageView) itemView.findViewById(R.id.foto);
            fondo = (RelativeLayout) itemView.findViewById(R.id.fondo_item);
        }

        @Override
        public void onClick(View view) {

                switch (getAdapterPosition())
                {
                    case 0:
                        if (p.getOcupado()==1)
                        {
                           pulsado=1;
                        }
                        break;
                }

            if (pulsado == 0) {
                pulsado = 1;
                fondo.setBackgroundColor(Color.parseColor("#ffbe00"));
                name.setTextColor(Color.parseColor("#ffffff"));

                switch (getAdapterPosition()) {
                    case 0:
                        p.setOcupado(1);
                        break;

            } else {
                pulsado = 0;
                fondo.setBackgroundColor(Color.parseColor("#ffffff"));
                name.setTextColor(Color.parseColor("#ffbe00"));

                switch (getAdapterPosition()) {
                    case 0:
                        p.setOcupado(0);
                        break;

                }
            }

        }
    }

A: Puedes crear un array de int global.
 int[] ocupados = new int[n];

En este array pondrás el 0 o el 1 en función de si está ocupado o no (tiene uno el objeto en la variable). N será el número de items.
En el onCreate() de la activity deberás dar valores a este vector en función de lo que recibas:
if (p.getOcupado()==1)
 {
     ocupados[0]=1;
 }
else
{
     ocupados[0]=;

En tu método onBind puedes hacer esto:
@Override
        public void onBindViewHolder(Basico.RecyclerViewHolders holder, int position) {
           name.setText(itemList.get(position).getName());
           foto.setImageResource(itemList.get(position).getPhoto());

                switch (position)
                {

                    case 0:
                        if (p.getOcupado()==1)
                        {
                               holder.fondo.setBackgroundColor(Color.parseColor("#000000"));
                               name.setTextColor(Color.parseColor("#ffffff"));
                        }
                        break;

....

y en el onCLick() deberás consultar el array ocupados para saber si tiene 1 o 0:
 if (ocupados[getAdapterPosition()] == 0) {
                ocupados[getAdapterPosition()]=1;
                fondo.setBackgroundColor(Color.parseColor("#000000"));
                name.setTextColor(Color.parseColor("#ffffff"));

                switch (getAdapterPosition()) {
                    case 0:
                        p.setOcupado(1);
                        break;
              }

} else {
                ocupados[getAdapterPosition()]=0;
                fondo.setBackgroundColor(Color.parseColor("#ffffff"));
                name.setTextColor(Color.parseColor("#000000"));

                switch (getAdapterPosition()) {
                    case 0:
                        p.setOcupado(0);
                        break;
}


text:
Q: Why its not rendering welcome page when I click Sign in button? app.js
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');

const app = express();

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', "ejs");

mongoose.set('strictQuery', false);

mongoose.connect("mongodb://localhost:27017/friendDB", { useNewUrlParser: true });

// Create Schema
const friendSchema = new mongoose.Schema({
    email: String,
    password: Array,
});

// Create Model through Schema
const Friend = new mongoose.model("Friend", friendSchema);

app.get('/', (req, res) => {
    res.render("home");
})

app.get('/SignUp', (req, res) => {
    res.render('SignUp');
})

app.get('/SignIn', (req, res) => {
    res.render('SignIn');
});

app.get('/welcome', (req, res) => {
    res.render('welcome');
})

// app.get("/signInFail", (req,res)=>{
//     res.render("signInFail");
// });

app.post('/SignUp', (req, res) => {
    // console.log(req.body.username);
    // console.log(req.body.password);
    const newFriend = new Friend({
        email: req.body.username,
        password: req.body.password,
        confirmPassword: req.body.password
    });

    newFriend.save((err) => {
        if (err) {
            console.log(err);
        } else {
            res.render("welcome");
        }
    })

});

app.post('/SignIn', (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    Friend.findOne({ email: username }, function (err, foundFriend) {
        if (err) {
            console.log(err);
        } else {
            if (foundFriend) {
                if (foundFriend.password === password) {
                    res.render("welcome");
                 }
            }
        }
    });

});

// app.post("/SignIn", (req,res)=>{
//    const username = req.body.username;
//    const password = req.body.password;

//    Friend.findOne({email:username}, (err, foundFriend)=>{
//     if(err){
//         console.log(err);
//     }else{
//         if(foundFriend){
//             if(foundFriend.password === password){
//                 res.render("welcome");
//             }
//         }
//     }
//    });
// });

app.listen(3000, () => {
    console.log('server listening at port 3000');
})

welcome.ejs
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Welcome</title>
    <link rel="stylesheet" href="css/styles.css">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

        <form>

Hurray!

You've Signed In successfully.

© 2022

        </form>

SignIn.ejs
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <title>SignIn</title>

            <form action="/SignIn" method="post">

Sign-In

                    <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com" name="username">
                    Email address

                    <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password">
                    Password

                        <input type="checkbox" value="remember-me"> Remember me

                    Sign Up

                    <button class="w-50 btn btn-lg" type="submit"
                        style="margin-left: 15px;background-color: rgb(236, 76, 18);color:aliceblue;">Sign In</button>

© 2022

            </form>

It's not showing any error, it was working when I first tried it but after some time, when I tried to sign in with the same username and password the loader is just keep loading not showing the welcome page.
I think there is some problem in this code:
app.post('/SignIn', (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    Friend.findOne({ email: username }, function (err, foundFriend) {
        if (err) {
            console.log(err);
        } else {
            if (foundFriend) {
                if (foundFriend.password === password) {
                    res.render("welcome");
                 }
            }
        }
    });

});

But I'm unable to figure out what it is.


text:
Q: How do I reinitialize a singleton that I don't have full control over in the middle of an app? I have a compiled external library that I'm using in my (Objective-C++) code. This library has a singleton class to store some information throughout the duration of the application being used. I really need a way to be able to remove the loaded information and reload it in the middle of the application. Or to reload the application so that this singleton is reinitialised.
In the header files there is no way to reset the class information.
The way I get an instance of it is:
Singleton::getInstance();

In the header file this is shown as:
static Singleton& getInstance();

I would like a way to be able to delete this instance and reinitialise another instance.
Is there any way to do this? This singleton is only being used on one (the main) thread.
Extra information
When the application first loads I have to call:
Singleton::getInstance().load();

so that it loads information from the Documents directory of the app and create an internal structure. I replace those files in the Documents directory in the middle of the application running and I want it to reinitialise. If I call the above function again I get an error because the person who wrote this library doesn't allow the load function to be called twice.
I tried some stuff like:
delete &Singleton::getInstance();

but I don't know how I should reinitialise it afterwards. As calling
Singleton::getInstance();

crashes the app.

A: Unless the API is providing you a way to do it, it's probably impossible.
But I would have try to rerun the "load" function after I call the delete...

A: Try instantiating the Singleton from within a dinamic link library, instead of from within your own application. If you need to reinstantiate, unload the dll (or .so depending on the OS you are running on) module and reload it.
Not sure if this works though, but I guess it is worth a try.
Later edit: just noticed the iOS tag. Don't know if iOS has dynamic loadable modules, so my answer may not apply.