text:
Q: Error trying parsing xml using python : xml.etree.ElementTree.ParseError: syntax error: line 1, In python, simply trying to parse XML:
import xml.etree.ElementTree as ET
data = 'info.xml'
tree = ET.fromstring(data)

but got error:
Traceback (most recent call last):
File "C:\mesh\try1.py", line 3, in <module>
tree = ET.fromstring(data)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1312, in XML
return parser.close()
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1665, in close
self._raiseerror(v)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1517, in _raiseerror
raise err
xml.etree.ElementTree.ParseError: syntax error: line 1, column 0

thats a bit of xml, i have:
<?xml version="1.0" encoding="utf-16"?>
<AnalysisData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BlendOperations OperationNumber="1">
 <ComponentQuality>
  <MaterialName>Oil</MaterialName>
  <Weight>1067.843017578125</Weight>
  <WeightPercent>31.545017776585109</WeightPercent>

Why is it happening?

A: You're trying to parse the string 'info.xml' instead of the contents of the file.
You could call tree = ET.parse('info.xml') which will open the file.
Or you could read the file directly:
ET.fromstring(open('info.xml').read())


text:
Q: JQuery interactive map A JQuery neewbie here having a bit of a headache making a JQuery solution.
I am trying to make an interactive map of the world. The user is able to mouseover a marker (spesific spot on the map), which makes a info box fadeIn with the name and some information about the place. As i leave the marker with the cursor, the box fadesOut again.
The code under is the html markup with anchor tags for the country Norway, the same with f example Germany, Italy, Britian and so on, but with different positions of course.

Norway - Scandinavia

            lorem ipsum lorem ipsum lorem ipsum

Iran Republic - Asia

            lorem ipsum lorem ipsum lorem ipsum

The JQuery so far:
$(document).ready(function(){
    $('a.marker').mouseover(function(){
        var $link = $(this);
        var countryName = $link.data('info');
        var linkPosition = $link.position();
        var infoBoxTopPos = linkPosition.top - 130 + "px";
        var infoBoxLeftPos = linkPosition.left - 120+ "px";
        var container = $('.info' + '#' + countryName).html();
        $('a.marker').removeClass('current');
        $link.addClass('current');
        $('.info_box').html(container).css({
            'top' : infoBoxTopPos,
            'left' : infoBoxLeftPos
        }).show();
    }).mouseleave(function(){
        /*$('.info_box').fadeOut(100);*/
    });
});

The problem here is, whenever i hover over a marker, it gives me 2 identical info boxes, instead of only 1. As i inspect it with Firebug, both boxes are of the same div. I know that ive display:none it from CSS, so could it be that when JQuery runs, it displays a new .info_box, as well as the "hidden" one? Because of the addCLass maybe?
As you can see in the image below, the white marker with the info_box over it is correct, but i dont see why the 2nd info_box appears down to the right?

I am a bit confused and rather stuck at the moment, i cant seem to "get it".
Any help, tips or tricks would be universally appreciated.

A: This should not be a problem once the box u wnat to show have a uniq ue I'd.
Step1
Creat all div u want to use in the map and give them the same classname but different I'd set this class aa to be display none
Eg

norway is a nice country

Step2
The so called marker, u can use html button for it style it with css to make it beautiful. And give it a value eg
    Norway
Step 3
Jquery will look like this
$("body").on('mouseover','.marker',function()

{

$('.aa').hide();

$("#"+this.value).show();

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Root user denied insert on specific column in MySQL via SQL Server LinkedServer I'm trying to insert a record from an SQL Server into a MySQL instance that's connected as a linked server.
Here's basically what I'm doing:
INSERT INTO OPENQUERY(LINKED_SERVER,
        'SELECT
        id,
        claimed
        FROM MySQLTable;'
    )
    SELECT
        Id,
        '0'--claimed
    FROM
        MSSQLTable

And I'm getting this error:

The OLE DB provider "MSDASQL" for linked server "LINKED_SERVER" could not INSERT INTO table "[MSDASQL]" because of column "claimed". The user did not have permission to write to the column.

The linked server is currently configured to use the root user on the MySQL database and I've checked the privileges using GRANT and they seem fine:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD '******' WITH GRANT OPTION

The 'claimed' column is an enum column defined as "enum('1','0')". I have a feeling that it's the enum aspect that's messing things up, but I don't know why.
I use a similar process to insert data elsewhere so I know that it should work in principle, but I just can't figure out why this column is being such a pain!

A: It would appear that this is a known issue with older versions of MySQL linked servers and OPENQUERY isn't the right tool for the job. Instead I rewrote the query to use EXEC (INSERT...) AT [LINKED_SERVER], and it worked like a charm.
This syntax is available from SQL Server 2005 onwards.
The more you know...


text:
Q: Will C# inline these functions? I'm writing a performance-critical application in C# and the core operation is weight calculations. The function looks like this:
public void ForEachWeight(Action<int, int, float> action)
{
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            action(lower, upper, Weights[(lower * UpperLayerSize) + upper]);
        }
    }
}

And it gets called in dozens of places with various simple functions like:
if (activationMethod == ActivationMethod.Binary) {
    ForEachWeight((lower, upper, weight) => upperLayer.Values[upper] += weight;
} else {
    ForEachWeight((lower, upper, weight) => upperLayer.Values[upper] += lowerLayer.Values[lower] * weight);
}

All the calls are done from within the same class so all the variables are accessible. Can C# inline these function calls? I'm thinking for example the above calls can be inlined to something like this:
if (activationMethod == ActivationMethod.Binary) {
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            upperLayer.Values[upper] += weight;
        }
    }
} else {
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            upperLayer.Values[upper] += lowerLayer.Values[lower] * weight);
        }
    }
}

If it doesn't it means tens of thousands of extra function calls which I think are a huge overhead. If this gives even a 10% speed boost it's totally worth it. I can't easily benchmark by manually inlining them for comparison since I'd have to rewrite a lot of code.
So my question is CAN C# inline these calls? And if so, how can I find out IF they have been inlined?

A: You can use MethodImplOptions.AggressiveInlining inside this attribute : http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimplattribute.aspx

A: Inlining happens at JIT compilation, so you need to inspect code at runtime to observe inlining. This can be done using the debugger, but keep in mind that if the CLR detects the presence of a debugger various optimizations are disabled, so you need to attach the debugger after the method has been compiled.
Please see these answers for some info on how you can find the method using WinDbg/SOS.


text:
Q: Deploying Grafana as a FARGATE service in an AWS ECS cluster I'm having some issues with a Grafana deployment. After deploying Grafana, I cant change the default password for the admin account, which you have to do the first time you launch Grafana. I log in with the default credentials, then get prompted to enter a new password. When I do, I get an "unauthorized" error. Looking at the browsers console, it seems to give a 404 error when I try to submit a new password.
I'm using an RDS instance to store Grafana user data. The RDS instance is in the same subnet as the ECS cluster. I've attached the AmazonRDSDataFullAccess policy to the ECS task role but that did not help. I also tried making the RDS instance publicly available but that was also not helpful.
I'm using Grafana version 6.5.0. I was using the latest 7.1 but downgraded hoping it would solve my current issue.

A: Firstly make sure your RDS database has a security group allowing inbound access from the ECS cluster. This will grant you the inbound access to the RDS database that are required.
As Fargate is serverless, a node could be destroyed so any local configuration would be gone. As you're using RDS you should make sure you're using environment variables to specify the DB connection details.
Finally add these to your task definition, using the environment item. For secrets such as password for the RDS db use the secrets option.


text:
Q: Create a specific structure of array in C++ I want to create a structure in C++ in which some of its elements are arrays (as the following code). I would like to allow the user to declare the number of variables, i.e., nVar, from the console (like what commented in the main function). This is while C++ forces me to declare a constant and global variable for nVar.
Is there a way to resolve my problem? Many thanks in advance.
#include <iostream>
using namespace std;

const int nVar = 50;

struct Particle{
    double ObjVal;
    double BestObjVal;
    double Position[nVar];
    double Velocity[nVar];
    double BestPosition[nVar];
};

int main() {
// int nVar;
// cout << "Enter the number of variables: " << endl;
// cin >> nVar;
...
}

A: You want to create arrays of dinamic size.
You need pointers.
struct Particle{
  double objVal;
  double bestObjVal;
  double* position;
  double* velocity;
  double* bestPosition;
};

A pointer is the memory address of a variable of the specific type.
In this example, you point to the position of the first double value of an array.
In the body :
Particicle p;
...
std::cin >> nVar;
p.velocity = new double[nVar];

The code mean : i want nVar doubles and save the first position in velocity.
So, velocity[0] has address velocity, velocity[1] has address velocity + sizeof(double) and so on...
Look for C++ array with dynamic size


text:
Q: some kind of caching in google chrome? i have simple question, the following code show some button ("press") and ask the user "how old are you?" if the user answer number greater than 20, the code write to the page "nice".
The question is in a loop so the code ask 7 times this question.
The issue ( my question) is : the "nice" appears AFTER the loop is finished, why? it is like some caching.
why it does not appears when the command "document.writeln("nice") is execute?
This phenomenon is just when i run it from chrome, it does not happen in EDGE or IE. what can i set in CHROME that this kind of CACHING will not occur?
 thanks

<!DOCTYPE html>

<meta charset="UTF-8">

<input type="button" value="press" onclick="run()">

A: Add a break; to exit the loop if the number is greater than 20.

<!DOCTYPE html>

<meta charset="UTF-8">

<input type="button" value="press" onclick="run()">

A: I believe this is a result of different browsers having different behavior with when and how they allow the document.write call to change the DOM.
It looks like firefox changes the document right away, and chrome waits for the currently executing function to finish before making the change.
There is pretty widespread advice to avoid document.write altogether. See https://stackoverflow.com/a/25398255/121660 for a pretty good explanation.
Changing your snippet to use:
document.body.innerHTML+="nice
" instead of document.write Doesn't really fix it for me either. Odd.
Using setTimeout(function(){document.write("nice")},0) also doesn't work for me.

A: This works for me in all browsers. The key is to not let the function run for a long, long time, but to let the browser have a break to do things like redraw the document. setTimeout(xxx,0) means "run this thing as soon as you can get it scheduled to run again", and the browser can update things in-between.

<!DOCTYPE html>

<meta charset="UTF-8">

<input type="button" value="press" onclick="run(1)">


text:
Q: Why should transcendental functions and their arguments be dimensionless? While looking for the answer on the internet I came across an answer giving this explanation
 "Another way of seeing clearly why an exponential's argument should be dimensionless is to Taylor expand: $\exp(x)=1+x+x^2/2+\cdots$ Every term has a different dimension if x is dimensionful, and hence cannot be summed."
But this is not a proof in the sense we do in mathematics!
So can anyone provide with a mathematically sound proof?

A: No proof is needed, it's true simply by definition of units. When dealing with units in any physics calculation, we generally respect the following unofficial axioms that define units:
1) A unit is treated as a variable in any calculation
2) Any number that is linear in a specific unit (with no intercept) is said to be a quantity of "those units".
So if "m" is a unit, that means that we can only classify a quantity as having "units of m" if it is of the form $k \text{m}$ for some unitless number $k$. Respecting the definition above, we see that $x = e^{2 \text{m}} = 1 + 2 \text{m} + 2 \text{m}^2 + \frac{4}{3} \text{m}^3 + \cdots$ is not strictly of form $k \text{m}$, thus by the definition above, it can't be said to have "units of m".
Aside from that definition, I don't think "units" has a formal definition in pure mathematics (perhaps someone will point me out wrong here), so without that formal definition, you can't make a proof. You need a definition like the one I wrote above.

A: You can think of the equation of motion
$s(t) = s(0) + v(0) t + \frac{a}{2} t^2$
as a Taylor expansion of the function $s(t)$ around $t=0$, exact for constant acceleration. The coefficients of this series are $s(0)$, $v(0)$ and $a$ ($=a(0)$) and have different units.
When you expand a function $f(x)$ in Taylor series, the coefficients are given by
$a_n = \frac{1}{n!} \left[\frac{d^n f(x)}{dx^n}\right]_{x=x_0}$
and so they have units of $f$, $f/x$, $f/x^2$, $f/x^3$, etc.
So, the correct expansion of $exp(x)$ for $x$ in meters is
$exp(x) = 1 m + x + \frac{1}{2m} x^2 + \frac{1}{6m^2} x^3 + ... $
For instance,
$exp(2m) = 1 m + 2m + \frac{1}{2m} 4 m^2 + \frac{1}{6m^2} 8 m^3 + ... $
If you want to keep the expansion as simple as
$exp(x) = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + ... $,
you'd better have a dimensionless $x$.
Besides, a unit should be treated as a multiplication factor. Different functions treats multiplied factors different ways. For example,
$log(4.18 J) = log(4.18) + log(J)$ and
$e^{4.18 J} = (e^{J})^{4.18} = (e^{4.18})^{J}$.
That's too complicated and usually avoided in formulas of natural sciences.
In some equations involving entropy, the logarithm is divided as in $log(ab) = log(a) + log(b)$, such that the arguments $a$ and $b$ are dimensional. The Wikipedia page [Sackur-Tetrode equation]1 has an example of such equations, but also a justification for it:

Strictly speaking, the use of dimensioned arguments to the logarithms
is incorrect, however their use is a "shortcut" made for simplicity.
If each logarithmic argument were divided by an unspecified standard
value expressed in terms of an unspecified standard mass, length and
time, these standard values would cancel in the final result, yielding
the same conclusion. The individual entropy terms will not be
absolute, but will rather depend upon the standards chosen, and will
differ with different standards by an additive constant.


text:
Q: "pg" Ruby gem is throwing a "prepared statement already exists" error from Resque Apparently the pg gem uses prepared statements for Postgres. I have seen fixes for Unicorn to ensure that each process uses it's own db connection like so:
after_fork do |server, worker|
  ActiveRecord::Base.establish_connection
end

But I have no idea how to make this work with Resque.

A: I found the answer. Please look at Christian Fazzini's answer here:
Rails Resque workers fail with PGError: server closed the connection unexpectedly
The error is different, but Christian's solution is the same, and it works.


text:
Q: How to resolve React-Jsx/html input error -$NaN.undefined I'm having a bit of an issue implementing an input field that will take a number which is subtracted from another computed value within an html table setup. I observed that when i type any 3 digit number as VAT, Everything works fine, but soon as i type beyond 3 digit, i get "$NaN.undefined"
I want to know what i'm missing here, would appreciate an help. I added type='number' thinking that would help, but it didnt. I also run the code without the 'toMoney()' function, it still throws the same error. I tried changing type to text, same result still.
  const [rfq, setRfq] = useState({
    rate_1: '',
    rate_2: '',
    ..............// rest of code
  });

 useEffect(() => {
    // fetch data from an API based on ID here
    if (!data.length) {
      axios
        .get(`url`)

        .then(
          (res) => {
            setData(res.data);
          },
          (err) => {
            alert('An error occured! Try refreshing the page.', err);
          }
        );
    }
  }, [data.length, id]);

  const toMoney = (value) => {
    return accounting.formatMoney(accounting.unformat(value), {
      symbol: '',
      precision: 2,
    });
  };

return (
 {data &&
          data.map((quote) => (

.............................// rest of code

                      Sub-Total

                      $

                        {toMoney(
                          rfq.rate_1 * quote.quantity_1 +
                            rfq.rate_2 * quote.quantity_2 +
                            rfq.rate_3 * quote.quantity_3 +
                            rfq.rate_4 * quote.quantity_4 +
                            rfq.rate_5 * quote.quantity_5 +
                            rfq.rate_6 * quote.quantity_6
                        )}

                      VAT

                        <input
                        type='number'
                          style={{ textAlign: 'right' }}
                        //   value={rfq.vat}
                          name="vat"
                          onChange={handleChange}
                        />

                      Total

                      $

                        {toMoney(
                          parseInt(rfq.rate_1 * quote.quantity_1) +
                            parseInt(rfq.rate_2 * quote.quantity_2) +
                            parseInt(rfq.rate_3 * quote.quantity_3) +
                            parseInt(rfq.rate_4 * quote.quantity_4) +
                            parseInt(rfq.rate_5 * quote.quantity_5) +
                            parseInt(rfq.rate_6 * quote.quantity_6) -
                            toMoney(rfq.vat)
                        )}

)}
)
}

[![with 3 digit][1]][1]

A: I just figured out the mistake.
I replaced this
 {toMoney(
                          parseInt(rfq.rate_1 * quote.quantity_1) +
                            parseInt(rfq.rate_2 * quote.quantity_2) +
                            parseInt(rfq.rate_3 * quote.quantity_3) +
                            parseInt(rfq.rate_4 * quote.quantity_4) +
                            parseInt(rfq.rate_5 * quote.quantity_5) +
                            parseInt(rfq.rate_6 * quote.quantity_6) -
                            toMoney(rfq.vat) //here is the error
                        )}

with
 {toMoney(
                          parseInt(rfq.rate_1 * quote.quantity_1) +
                            parseInt(rfq.rate_2 * quote.quantity_2) +
                            parseInt(rfq.rate_3 * quote.quantity_3) +
                            parseInt(rfq.rate_4 * quote.quantity_4) +
                            parseInt(rfq.rate_5 * quote.quantity_5) +
                            parseInt(rfq.rate_6 * quote.quantity_6) -
                            parseInt(rfq.vat)   //replaced toMoney with parseInt
                        )}

Finally, I changed the initial state to 0 ; vat:"" to vat:0. that fixed it


text:
Q: Why does updating a set with map object destroy the map object? The following code shown below:
y=set()
y.update([1])
x=map(chr, [65, 66, 67, 68])
for ch in x:
    print(ch)
print(y)

Outputs:

A
B
C
D
{1}

Which is expected. However, when I update the y set with the x map object, it destroys the map object. This is shown here with this code:
y=set()
y.update([1])
x=map(chr, [65, 66, 67, 68])
y.update(x)
for ch in x:
    print(ch)
print(y)

which outputs:

{'C', 1, 'D', 'A', 'B'}

When my expected output is this:

A
B
C
D
{'C', 1, 'D', 'A', 'B'}

The variable x is no longer there and destroyed?
Can someone explain this please?
and also how do I keep the x map object after updating the y set?

A: In Python 2, map would return a list. In Python 3, it returns a special kind of object, which can only be iterated once.
If you want to iterate it multiple times, you can transform it to a list.
x = list(map(chr, [65, 66, 67, 68]))


text:
Q: Apresentar uma caixa de texto formatada para preenchimento Bom dia
Senhores, pesquisei na internet inteira mas acho que não soube me expressar por isso venho lhes perguntar…
tenho um comando VB para alterar o ip do win7 mas gostaria que o comando perguntasse qual ip eu gostaria de colocar segue comando…
' ## Script para alterer ip da Placa de Rede ##

Set objWMIService = GetObject("winmgmts:\.\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

strIPAddress = Array("10.10.0.7") 'Coloque o IP fixo
strSubnetMask = Array("255.255.255.0") 'Coloque a Mascara de SubNet

strGateway = Array("10.1.1.1") 'Coloque o Gateway
strGatewayMetric = Array(1)

strDNS = Array("200.204.0.10","200.204.0.138") 'Coloque o IP DNS

For Each objNetAdapter in colNetAdapters
    errEnable = objNetAdapter.EnableStatic(strIPAddress, strSubnetMask)
    errGateways = objNetAdapter.SetGateways(strGateway, strGatewaymetric)
    objNetAdapter.SetDNSServerSearchOrder strDNS
Next

Na parte strIPAddress = Array("10.10.0.7") 'Coloque o IP fixo gostaria que abrisse uma caixa de texto pra o usuário alterar o final ou se não for possível o ip inteiro, por exemplo:
10.10.0.___

A: A forma mais simples é utilizando um inputbox. Exemplo:
ip = InputBox("Coloque o IP fixo", "Mudar IP")

Uma outra forma mais trabalhosa mas que traria resultados estéticos melhores seria fazer um form e chamar ele retornando o resultado pra sua variavel.


text:
Q: Irrelevant Search query output in Apache Solr and Cassandra I am working on Apache Cassandra in which I configured Apache Solr for partial search.
I am running 2 queries and getting different result.
select id from emp where solr_query = 'number:9';

This query gives me 0 result.
In another query select id from emp where solr_query = 'number:9*';
This query gives me correct result.
Note :-  All records in "number" column have first digit as 9.
Please let me know the possible solution.

A: You are getting the correct result. A search for : returns the exact match result. If you had an item where the number was 9, you'd get that as a result.
Your second query is a wildcard that says give me all numbers that begin with 9. That is the one you want to use. Another example would be to use number:9 - this returns all results that contain a digit 9.


text:
Q: if $f\in D$ show that $f'+p\cdot f\in D$ Denote by $D$ the set of all real univariate polynomials all of whose roots are real,if $f\in D$,for any real number $p\in R$,show that
$$f'+p\cdot f\in D$$
I konw $$(e^{px}f)'=e^{px}(f'+pf)$$

A: Let $n$ be the degree of $f$ and $\{x_i\}_{i=1}^n\subset\Bbb R$ its roots. Then $f(x)=C\prod_{i=1}^n(x-x_i)$. We may assume without loss of generality that $C=1$, and in particular that $f$ has real coefficients.
If $p=0$ the result is a direct consequence of Rolle's theorem.
If $p\ne0$, then $f'+p\,f$ has degree $n$ and real coefficients. By Rolles's theorem, $(e^{px}f)'$ has at least $n-1$ real roots, and since the exponential function does not vanish, $f'+p\,f$ has at least $n-1$ real roots. Since $f'+p\,f$ has real coefficients and complex root come in pairs, all roots of $f'+p\,f$ must be real.


text:
Q: Antlr4: The type or namespace name 'XPathLexer' could not be found I am trying to understand Antlr CS code on VS 2010 with Antlr4.Runtime.net40-client and  Antlr4BuildTasks.net40 projects out of all .net framework versions.
The later is building fine but in case of first one I get The type or namespace name 'XPathLexer' could not be found. I believe it is because of XPathLexer.g4 not working, hence lexer and parser are not created.
Also am I wrong to suppose that Antlr4BuildTasks job is to build the other?
I made unnecessarily small change in XPathlexer.g4 grammar to see if shows some file generation but it didn't.
Can someone guide me to set up .net framework v4 projects on Visual studio?


text:
Q: Special Characters are not being removed So Im having an issue where my code will not remove special characters except spaces. I have tried subtracing indexes and even adding index and it still will not work. I have tried an input "BANANA & PEEL" and it wont work.
        String strMessage = input.nextLine();

        String strChars = " !@#$%^&&*() ";

        for(int i = 0; i < strMessage.length() - 1; i++)
            for(int j = 0; j < strChars.length(); j++) {
                if(strChars.charAt(j) == strMessage.charAt(i)) {
                    strMessage = strMessage.substring(0, strMessage.indexOf(strMessage.charAt(i))) + strMessage.substring(strMessage.indexOf(strMessage.charAt(i+1)));
                    break;
                }
            }

        System.out.println(strMessage);

So my output should be BANANAPEEL

A: I think this way it will work quite well:
            Scanner input = new Scanner(System.in);
            String strMessage = input.nextLine();
            String strChars = " !@#$%^&&*()";
            String temp = "";
            boolean isInStrChars = false;

            for (int i = 0; i < strMessage.length(); i++){
                isInStrChars = false;
                for (int j = 0; j < strChars.length(); j++) {
                    if (strChars.charAt(j) == strMessage.charAt(i)) {
                        isInStrChars = true;
                    }
                }
                if(!isInStrChars){
                    temp+=strMessage.charAt(i);
                }
            }
            System.out.println(temp);

I just created a 'temp'-String, and only if a character from the original String is NOT inside the String strChars, it will be added to the 'temp'-String.
EDIT: of course you can set the temp-String as the original strMessage at the end:
strMessage = temp;

A: You can use String Tokenizer class for separating your string.
StringTokenizer t = new StringTokenizer(strMessage," !@#$%^&&*()");
while(t.hasMoreElements()){
System.out.print(t.nextToken()+""); }

suppose strMessage = "hello$#& w orl#d";
the output is helloworld

A: Use StringTokenizer----
 StringTokenizer st1 =
             new StringTokenizer("hello$#& w orl#d", " !@#$%^&&*()");
        while (st1.hasMoreTokens())
            System.out.print(st1.nextToken());

Output - helloworld

A: you could simply use String class' replaceAll(String regex, String replacement)
Something like below
public static void main(String[] args) {
    String source = "hel!lo$#& w orl#d";
    String replacementChar = " |!|@|#|\\$|%|^|&|(|)|\\*"; //Add you char separated by OR( |)

    String s = source.replaceAll(replacementChar, "");

    System.out.println(s);

}

output:
helloworld
Edit:
As discussed in comments you don't want to use RegEx and only want to retain alphabets probably you can solve same using Character.isAlphabetic
 public static void main(String[] args) throws IOException {
        String strMessage = "BANANA & PEEL";

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strMessage.length(); i++) {

            if (Character.isAlphabetic(strMessage.charAt(i))) {
                builder.append(strMessage.charAt(i));
            }
        }
        String finalString = builder.toString();

        System.out.println(finalString);

    }

A: use a lambda function which removes all characters passed as string
String strMessage = "BANANA & PEEL";
String strChars = " !@#$%^&&*()";

deleteChars.apply( strMessage, strChars );  // BANANAPEEL

find deleteChars here


text:
Q: MySQL Fetch highest value by key and then add rank to it I'm trying to create a mysql query that looks through my scoreboard for a given playerid and then finds their highest score and then adding a rank to that score.
I've come quite close to what I'm trying to achieve with this code:
SELECT PlayerUUID, `iGamescore` as score, FIND_IN_SET( iGamescore, (
SELECT GROUP_CONCAT( iGamescore
ORDER BY iGamescore ASC )
FROM crystm_gameScoreboard )
) AS rank
FROM crystm_gameScoreboard
WHERE PlayerUUID =  '4c8984f3-651a-48bc-ad1a-879624380fab'
LIMIT 1

Returns:

But I do know that this player has played multiple times and is therefore multiple times in the scoreboard. As seen here:

So the issue here is that yes, it does find the player and gives the rank correctly.. However, since it exists multiple times, it saves the very first score instead of the highest score. How would I fix my query to correct for this or would you instead of creating a new score every time they create a highscore for themselves, just update their previous record in the scoreboard?
Thanks in advance

A: To get the highest score you need a GROUP BY:
SELECT
   PlayerUUID,
   MAX(`iGamescore`) as score
   RANK() OVER (ORDER BY MAX(`iGamescore`) DESC) as Rang
FROM crystm_gameScoreboard
GROUP BY PlayerUUID
ORDER BY 3 ASC

The order by 3 ASC makes the list sorted by rank

A: This post solved it:
MySQL - Rank user amongst list of top high-scores
Had everything I was looking for. I dont know why I could not find this post but when searching, keywords are important haha.
Thanks for inputs tho.


text:
Q: jQuery: Changing div ID not working I'm back already and google-fu has brought me nothing.
I'm trying to make a sort of image gallery and i need to reset the divs dynamically on my slider but I'm having no luck, here's the process:

*

*click 'left'

*left div moves forward.

*central divs ID gets called 'left' and vice versa, (using a temp ID to stop two divs having the same ID)

*the css is reset as if it never happened except for the image being different.

My problem is that they seem to be resetting completely to their original state, as if the ID change never happened, any ideas?
Here's the JSFiddle
and here's the offending code:
    $('.navigationLeft').click(function() {
    console.log("yay");
    $( '#left' ).animate({
        marginLeft: selWidth
    }, 500, "linear",  function() {
        // Animation complete.
        $( '#center' ).attr('id', 'temp');
        $( '#left' ).attr('id', 'center');
        $( '#center' ).attr('id', 'left');
        $( '#left' ).css('width', '900px');
        $( '#left' ).css('height', '400px');
        $( '#left' ).css('overflow', 'hidden');
        $( '#left' ).css('position', 'relative');
        $( '#left' ).css('left:', '-900px');
        $( '#left' ).css('overflow', 'hidden');
        $( '#left' ).css('z-index', '2');
        $( '#center' ).css('width', '900');
        $( '#center' ).css('height', '400');
        $( '#center' ).css('position', 'absolute');
        $( '#center' ).css('overflow', 'hidden');
        $( '#center' ).css('z-index', '1');
    });
    //reset positions and change images
});

A:  tag is not a valid tag cause images don't have a closing tag.
Also, jQuery is much more fun that you might think!
My suggestion is to not create  tags at all, let JavaScript do it for us, we're using an Array of images URL, after all.
Instead of jQuery's .animate(), use CSS transition!

jQuery(function($) {

  const gallery = {
    one: [ // (P.S: In HTML use data-gallery="one")
      'http://placehold.it/900x400/0bf/fff&text=1',
      'http://placehold.it/900x400/f0b/fff&text=2',
      'http://placehold.it/900x400/bf0/fff&text=3',
      'http://placehold.it/900x400/b0f/fff&text=4',
    ], // you can add more name:[] sets for other galleries
  };

  $('[data-gallery]').each(function(i, gal) {

    const name = $(gal).data('gallery');
    if (!Object.prototype.hasOwnProperty.call(gallery, name)) return;

    const $slides = $(gallery[name].map(url => $('', {src: url})[0]));
    const tot = $slides.length; // Store how many images we have
    let c = 0; // Current slide Counter

    $('.slides', gal).append($slides); // Append created slides

    $(".prev, .next", gal).on('click', function() {
      c = ($(this).is('.next') ? ++c : --c) < 0 ? tot - 1 : c % tot;
      $slides.css({
        transform: `translateX(-${c*100}%)`
      })
    });

  });

});
/*QuickReset*/*{margin:0;box-sizing:border-box}html,body{min-height:100%;font:14px/1.4 sans-serif;}

/* Gallery */

[data-gallery] .slides {
  display: flex;
  position: relative;
  overflow: hidden;
  height: 170px;
}

[data-gallery] .slides > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: 0.4s;
}

  <button class="prev" type="button">PREV</button>
  <button class="next" type="button">NEXT</button>

P.S: As a side-note, the following
    $( '#left' ).css('width', '900px');
    $( '#left' ).css('height', '400px');
    $( '#left' ).css('overflow', 'hidden');

is a bit verbose. Instead pass an object literal {} like:
    $( '#left' ).css({width:900, height:400, overflow:"hidden"});


text:
Q: Why is my pullup resistor more noise immune than a pull down? I have a circuit that appears to have some noise problems related to stepper motors I'm driving. When I changed some switches to use pull up instead of pull down resistors, I get better results. Why?
I'm using a PCF8574 digital IO expander for some limit switches. It has an interrupt pin that goes LOW on any transition from the limit switches. The limit switches are mounted on an aluminum frame with no more than 3' of wire. Several of the limit switches are within 1 inch next to a stepper motor, being driven at no more than 2.2A. Digital inputs are pulled low via 10Kohm, and the limit switches connect digital signals to 3.3V. Logic voltage does not seem to be a problem. The stepper motor and limit switch lines are sometimes ran next to each other (no cable shielding).
When I power my stepper motors, the interrupt pin goes nuts (my uC resets interrupt via a read request). As in, the IO expander detects high->low and/or low->high transitions when none of the limit switches are being pressed.
Limit switch state is correctly transmitted if I'm not powering the motors. Problem is only when motors are on.
Stepper motor drivers have adequate capacitors (470uF), and all digital logic have small caps nearby.
When I change from a pull down to a pull up resistor on the digital inputs, the interrupt does not go crazy.
Why do pullup resistors work better for my limit switches?

A: PCF8574 I/O already has pull-ups in it, in the form of a 'weak 100 µA current source'.

If you try to pull the input down with 10 kΩ then the 100 μA internal pullup current flowing through your pull-down resistor will raise the open-circuit input voltage by 1 volt, reducing your noise margin.
With a 10k pull-up you are improving the noise margin because your resistor and the internal pull-up are working together instead of fighting each other.


text:
Q: PDF rendering in Rmarkdown2/ I have just installed the newest overnight build of Rstudio(0.98.939) Rmarkdown on 14.04 Ubuntu, (please take several bows Rstudio folks - you have transformed the user experience!).(SessionInfo below). The simple script (just a table and a plot of the cars dataset) renders perfectly in HTML and Word , but in PDF I get the following enigmatic error... "framed.sty' not found"..
I would welcome suggestions or is this a bug in need of reporting?:
Here is the rmarkdown log:
processing file: Preview-25bc4ab5a01f.Rmd
  |.............                                                    |  20%
  ordinary text without R code

  |..........................                                       |  40%
label: unnamed-chunk-1
  |.......................................                          |  60%
  ordinary text without R code

  |....................................................             |  80%
label: unnamed-chunk-2 (with options)
List of 1
 $ echo: logi FALSE

cropping ./Preview-25bc4ab5a01f_files/figure-latex/unnamed-chunk-2.pdf
PDFCROP 1.38, 2012/11/02 - Copyright (c) 2002-2012 by Heiko Oberdiek.
==> 1 page written on `./Preview-25bc4ab5a01f_files/figure-latex/unnamed-chunk-2.pdf'.
  |.................................................................| 100%
  ordinary text without R code

/usr/lib/rstudio/bin/pandoc/pandoc Preview-25bc4ab5a01f.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output Preview-25bc4ab5a01f.pdf --template /home/rob/R/x86_64-pc-linux-gnu-library/3.1/rmarkdown/rmd/latex/default.tex --highlight-style tango --latex-engine pdflatex --variable geometry:margin=1in
output file: Preview-25bc4ab5a01f.knit.md

pandoc: Error producing PDF from TeX source.
! LaTeX Error: File `framed.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.31 \definecolor

Error: pandoc document conversion failed with error 43
Execution halted

SessionInfo():
R version 3.1.0 (2014-04-10)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_CA.UTF-8        LC_COLLATE=en_CA.UTF-8
 [5] LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8
 [7] LC_PAPER=en_CA.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4 digest_0.6.4     ggplot2_1.0.0    grid_3.1.0
 [5] gtable_0.1.2     htmltools_0.2.4  MASS_7.3-33      munsell_0.4.2
 [9] plyr_1.8.1       proto_0.3-10     Rcpp_0.11.2      reshape2_1.4
[13] rmarkdown_0.2.46 scales_0.2.4     stringr_0.6.2    tools_3.1.0
[17] yaml_2.1.13

A: I had this same symptom on Debian Jessie,
sudo apt-get install texlive-latex-extra
was sufficient for me.

A: I tried the answers above in my ubuntu and it didn't work, finally I found that yihui developed the tinytex package, the only thing you have to do is run the following code:
install.packages(c('tinytex', 'rmarkdown'))
tinytex::install_tinytex()

and you are set, this works cross platform
Cheers


text:
Q: Validar registros Java si existe o No Necesito saber cuál es la manera de que me valide si existe o no algún registro en una base de datos.
Este es el código de buscar (no hay error en sí):
public void buscar(String id_usu) {
        try {
            conectar conexion = new conectar();
            Connection con = conexion.getconectar();
            String sentencia = "SELECT * FROM evaluacion_antropometrica WHERE id_usu="+id_usu+" ";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(sentencia);
            while (rs.next()) {
                for (int i = 0; i < 18; i++) {
                    row[i] = rs.getObject(i + 1);
               }
            }
              JOptionPane.showMessageDialog(null,"Identificacion: "+row[1]+"\nPeso :"+row[2]+"\nEstatura:"+row[3]+"\nmedida brazo izquierdo:"+row[4]+"\nmedida brazo derecho:"+row[5]+"\nmedida pecho:"+row[6]+"\nmedida pierna izquierda:"+row[7]+"\nmedida pierna derecha:"+row[8]+"\nmedida cintura:"+row[9]+"\npantorrilla izquierda:"+row[10]+"\npantorrilla derecha:"+row[11]+"\nimc resultado:"+row[12]+"\ncuello:"+row[13]+"\nimcverificar:"+row[14]+"\nMedida gluteos:"+row[15]+"\nMedida antebrazo izquierdo:"+row[16]+"\nMedida antebrazo derecho:"+row[17]);

         //  JOptionPane.showMessageDialog(null,"Estatura usuario: "+row[1]+"\nPeso usuario:"+row[2]+"\nmedida brazo izquierdo:"+row[3]+"\nmedida brazo derecho:"+row[4]+"\nmedida pecho:"+row[5]+"\nmedida pierna izquierda:"+row[6]+"\nmedida pierna derecha:"+row[7]+"\nmedida cintura:"+row[8]+"\npantorrilla izquierda:"+row[9]+"\npantorrilla derecha:"+row[10]+"\nimcresultado:"+row[11]+"\ncuello:"+row[12]+"\nimc verificar:"+row[13]+"\nIdentificacion:"+row[14]+"\nMedida gluteos:"+row[15]);
            conexion.desconectar();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    } // cierra buscar

A: A nivel de rendimiento, hacer un SELECT * ... para verificar si un registro existe es una mala práctica.
Supongamos una tabla con 10, 20 ó 150 columnas... ¡estás seleccionado todas las columnas solamente para determinar si hay registros!
Yo crearía un método, el cual quizá formaría parte de mi clase Connection (la que use para conectarme a la base de datos), que reciba dos parámetros: una instrucción SQL y el valor a filtar. El mismo método se puede adaptar para que reciba instrucciones SQL con o sin datos a filtar, o para que filtre en base a varios criterios  en vez de uno solo, pasándole los parámetros en un array. De ese modo utilizarías ese método cada vez que necesites verificar si un registro existe en la BD.
Entonces, en la clase Connection... o como se llame, podrías crear un método como este:
public boolean ifExists(String sSQL, int nId) {
    PreparedStatement ps = dbConn.prepareStatement(sSQL);
    ps.setString(1, id);
    ResultSet rs = ps.executeQuery();
    return rs.next();
}

Usamos el método next() de la  Clase Resultset el cual devolverá false si no encuentra registros o por el contrario devolverá true.
Ejemplo de uso:
If (db.ifExists ("Select 1 from nombteTabla where id = ?;")){
//Existe registro
}else{
//No hay registros
}

*

*db sería el objeto Conexion, el mismo que usarías para conectarte a la BD

*SELECT 1 ... es una de las formas para simplificar una consulta cuando sólo se quiere evaluar si hay registros. Hay otras como SELECT COUNT(*), seleccionar el id, etc... Según el manejador de BD y la estructura de las tablas puede haber una ligera variación en cuanto al rendimiento según uses una u otra.

A: Yo lo realizo de la siguiente forma espero te ayude es simple
public  boolean dbexisteRegistro(Connection Conn, String id_a_buscar){
         Statement oSt = null;
         ResultSet oRs = null;
         String sSQL= " ";
         boolean dbexisteRegistro= false;

         try{
             Conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
             sSQL = "SELECT * FROM Nombre_de_tu_tabla WHERE ID_A_BUSCAR='" + id_a_buscar + "'";

             oSt = Conn.createStatement();
             oRs = oSt.executeQuery(sSQL);

             if(oRs.next()){
                if(oRs.getRow() > 0){
                    dbexisteRegistro= true;
                }
             }

             if (oSt != null) {oSt.close();oSt = null;}
             if (oRs != null) {oRs.close();oRs = null;}
         }catch(SQLException err){

             oSt = null;
             oRs = null;
             sSQL=null;
         }catch(Exception err){

             oSt = null;
             oRs = null;
             sSQL=null;
         }finally{
             oSt = null;
             oRs = null;
             sSQL=null;
         }
         return dbexisteRegistro;
 }

A:         Connection con = new Conexion().getConexion();
        Statement stm = con.createStatement();
        ResultSet rs = stm.executeQuery("SELECT * FROM tabla WHERE campo_id = 1");
        if(rs.last()){
            //Existe
        }
        else{
            //No Existe
        }

A: Esta forma de hacerlo es muy similar a la de @A. Cedano, sin embargo, en el método del compañero hay que usar un throws SQLExceptiony por ende definir la excepción a la hora de llamar al método, cosa que con el siguiente método ya no se debe hacer.
Declaración del método
public boolean verificarPaciente(int idPaciente) {
        boolean res = false;
        String verificar = "SELECT k_numdocumento FROM paciente WHERE k_numdocumento = "+idPaciente;
        try{
            ps = cn.conectar().prepareStatement(verificar);
            rs = ps.executeQuery();
            if(rs.next())
                res = true;
        } catch(Exception e){
            System.err.print("Ha ocurrido un error: "+ e.getMessage());
        }
        finally{
            ps = null;
            cn.close();
        }
        return res;
    }

Llamar el método
if(sc.verificarPaciente(Integer.parseInt(Id.getText())))
    JOptionPane.showMessageDialog(this," El usuario ya existe");
else
    JOptionPane.showMessageDialog(this," El usuario no existe");

A: Yo lo hice de la siguiente forma y funciona a la perfección, espero les funcione el pequeño aporte:
Conexion cnx = new Conexion();
PreparedStatement ps = null;
ResultSet res;
String sql = "SELECT COUNT(id_mensaje) FROM mensajes WHERE id_mensaje= "+id_mensaje+"";
ps = connection.prepareStatement(sql);
res = ps.executeQuery();
if (res.next()) {
    String count  = res.getString("count(id_mensaje)");
    System.out.println(count);
}


text:
Q: Writing a date from a pandas_datareader to database results in -1999 I have written a simple python application to read stock prices from google using the pandas_datareader and store them in the database. I find it strange that when I write the dataset the dates are correct however when I extract the date and use it in an update statement, the date is messed up. Here is my code (excluding import statements and logic) and results:
df = webd.DataReader('WTB.L', 'google', dtStart, dtEnd)
print(df.head())

              Open    High     Low   Close  Volume
Date
2012-03-02  1687.0  1687.0  1672.0  1672.0  341944
2012-03-05  1666.0  1684.0  1660.0  1665.0  333824

lastPriceDateX = pd.to_datetime(df['Date'].tail(1).item())
lastPriceDateY = lastPriceDateX
lastPriceDate = lastPriceDateY.strftime('%d-%m-%Y').isoformat()
print('Last Price Date {}'.format(lastPriceDate))

Last Price Date 21-03-2017
Looks good so far, the date format is exactly as I wanted it! Now I write the date  into the SQLITE database: date is stored as -1999
The dataset is written to SQLite database, this has the correct date format:
"12667" "2017-03-16 00:00:00"   "WTB.L" "3926.0"    "3936.0"    "3882.0"    "3909.0"    "441329"
"12668" "2017-03-17 00:00:00"   "WTB.L" "3908.0"    "3926.0"    "3892.0"    "3903.0"    "642291"
"12669" "2017-03-20 00:00:00"   "WTB.L" "3907.0"    "3917.0"    "3883.32"   "3916.0"    "175681"
"12670" "2017-03-21 00:00:00"   "WTB.L" "3921.0"    "3926.0"    "3888.0"    "3914.0"    "315763"
Code to write this dataset:
df.to_sql('tblStockPricesGoogle', conn,
          if_exists='append', index=False,
          index_label=None, chunksize=None, dtype=None)

I could write a python function to take the latest date from the prices table and write it to the last price. However, I would like to understand why this date prints correctly but it does not write to the database correctly.
Thank you all very much.

More code:
#Gets data from google.
    try:
        print('Try')
        df = webd.DataReader('WTB.L', 'google', dtStart, dtEnd)
        print(df.head())
        df.insert(0,"Symbol", sy)

        df = df.reset_index()

        if df.empty :
            print('DataFrame is empty. There could be various issues. No updates.')

        else :
            print(df.head(1))
            print("Starting update:")

            #Call update function and pass dataframe.

            if sql3.saveDFtoSQL(df):
                #update table with last price, date, updated date etc.

                index is also returned.
                lastPrice = df['Close'].tail(1).item()
                lastPriceDateX = pd.to_datetime(df['Date'].tail(1).item())
                lastPriceDateY = lastPriceDateX
                lastPriceDate = lastPriceDateY.strftime('%d-%m-%Y')
                print("Updated {} prices, task done!".format(sy))
                print('Last  Price {}'.format(lastPrice))
                print('Last Price Date {}'.format(lastPriceDate))
                                    lastUpdate = dt.date(today.year,today.month,today.day).isoformat()
                print('LastUpdate attribute:',lastUpdate)
                sql3.updateListLastUp(sy,lastUpdate,lastPrice,lastPriceDate)

def updateListLastUp(symbol,date,lastPrice,lastPriceDate):

    try:
        strUpdate = 'UPDATE tblList SET lastUpdate="{}", LastPrice={},LastPriceDate={}, GetData=0 WHERE Ticker="{}"'.format(date,lastPrice,lastPriceDate,symbol)
        conn = sq3.connect(sql_file)
        conn.execute(strUpdate)
        conn.commit()
        return 'Done'

    except sq3.Error as er:

        print('Failure to update DataSet:', er)
        return er.tostring()

A: In:
strUpdate = 'UPDATE tblList SET lastUpdate="{}", LastPrice={},LastPriceDate={}, GetData=0 WHERE Ticker="{}"'.format(date,lastPrice,lastPriceDate,symbol)

You're using string interpolation (a big faux pas as it's insecure as well as leads to surprising results if values aren't escaped appropriately) to construct your query string, so what the DB engine sees is "2017-03-15" which is interpreted as 2017 - 3 - 15 and calculates the value which is 1999 etc...
All your problems will go away if you use query parameters, eg:
strUpdate = 'update tblList set lastUpdate=?, lastPrice=?, lastPriceDate=?, GetData=0 where Ticker=?'
# ...
conn.execute(strUpdate, (date, lastPrice, lastPriceDate, symbol))


text:
Q: Delete multiple documents from an index in ElasticSearch with value of one of items - 7.8 version my doc in elsticsearch is like below
    "hits" : [
      {
        "_index" : "MyIndex",
        "_type" : "_doc",
        "_id" : "Lxh7THMBycWRIeJFdwbZ",
        "_score" : 1.0,
        "_source" : {
          "@timestamp" : "2020-07-14T13:10:26.087+0430",
          "message" : "elk: customer inserted: id=5",
          "traceId" : "ABC",
          "severity" : "INFO",
          "thread" : "http-nio-8095-exec-2"
        }
      }
]

I want to delete All docs in one index that  "traceId" : "ABC" with java code.
I use Elasticsearch 7.8 and my client is RestHighLevelClient.
please guide me.

A: The below sample code should help. You can refer to the links below to go through the API and understand what needs to be done in steps.
Basically every request sent via Java would have below two parts.

*

*Something similar to HttpClient for every request sent to elasticsearch i.e. High Level Rest Client.

*API Specific Query which in our case is Delete by Query
As for your example, note that I'm assuming that traceId.keyword is the field of type keyword and hence I'm using TermBuilder i.e. Term Query. If it is of type text I've mentioned Match Query in the comment, you would have to use that.
Sample Code
import java.io.IOException;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;

public class DeleteBasedOnQuery {

    public static void main(String[] args) throws IOException {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        deleteQueryUsingMatch(client);

        client.close();

    }

    private static void deleteQueryUsingMatch(RestHighLevelClient client) throws IOException {

        //Mention index name
        DeleteByQueryRequest request = new DeleteByQueryRequest("my_delete_index");
        request.setConflicts("proceed");
        request.setBatchSize(100);
        request.setRefresh(true);

        //Term Query to Delete the document. Note the field name and value in below code
        request.setQuery(new TermQueryBuilder("traceId.keyword", "ABC"));

        //Match Query to Delete the Document
        //request.setQuery(QueryBuilders.matchQuery("traceID", "abc"));

        //Execute the request to delete based on above details
        BulkByScrollResponse bulkResponse = client.deleteByQuery(request, RequestOptions.DEFAULT);

        //By this time your delete query got executed and you have the response with you.
        long totalDocs = bulkResponse.getTotal();
        long deletedDocs = bulkResponse.getDeleted();

        //Print the response details
        System.out.println("Total Docs Processed :: " +  totalDocs);
        System.out.println("Total Docs Deleted :: " +  deletedDocs);

    }

}


text: Q: Background на Canvas unity В юнити есть Canvas с режимом Overlay. Он идеален для того чтобы сделать, например, загрузочный экран, когда изображение выводится поверх всего. Но как сделать с его помощью задний фон, который не будет меняться? UI перекрывает все и сортировать это я могу только относительно других UI элементов, относительно простых gameObject-ов изображение всегда на переднем плане. Как убрать изображения с Canvas на задний план, чтобы обычные GameObject отображались спереди него? Именно в режиме Overlay это как нибудь возможно?


text:
Q: How to weight features when doing text mining? I have a case where I'm doing text mining over a list of product titles. In particular I want to run a clustering algorithm. But I also have some information about those products that I think can add a lot of information like the category of the product (if the product is a car, a furniture, etc)
When doing the vectorization of the text data I get a big number of text features ~100.000 and I am pretty sure the category information contains much more information than one single text token so the question is what is a reasonable weight for the category information when fitting a model using both the text features and the category information.

A: For obvious reasons we cannot determine the weight for you.
Because there is no mathematical correct weight.
It's entirely up to you to increase the weight of some features you believe to be more important.


text:
Q: disable scrolling to the left when it reaches a certain value So I want to disable scrolling to the left scroll left reaches the maximum. But it can still be scrollable to the right.
Currently this is my code
if (width - scrollLeft < 400) {
  event.target.scrollLeft = width - 400;
}

A: Best solution would be to handle this with css.
Just give the parent a max-width


text:
Q: R Shiny dashboard with leaflet maps: image query functionality on my second tab doesn't work I have an R Shiny dashboard with 2 tabs. Each tab displays a raster.
Image query works on the first tab, but not on the second.
On the second tab it shows a small empty space where the queried data should be displayed, but no values.
If I remove the image query from the first tab, then it works on the second.
I have ensured I have the latest updates of all the required packages.
I am running the latest RStudio (1.2.5001) and R (3.6.1).
Any help is appreciated.
I have created a minimal example shinyapp for which the image query fails on the second tab:
library(raster)
library(leaflet)
library(shiny)
library(leafem)
library(shinydashboard)

filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
r2 <- r*2

#Set up the Shiny app
ui <-function(request) {dashboardPage(
  dashboardHeader(title="Test"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Tab1", tabName = "Tab1"),
      menuItem("Tab2", tabName = "Tab2")
    )
  ),
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "Tab1",
              leafletOutput("MyMap")
      ),

      # Second tab content
      tabItem(tabName = "Tab2",
              leafletOutput("MyMap2")
      )
    )
  )
)}
server <- function(input, output, session) {

#Draw the first map
 output$MyMap <- renderLeaflet({
    leaflet() %>%
     addRasterImage(r,layerId= "A") %>%
     addImageQuery(r, position="topleft", layerId = "A")
  })

#Draw the second map
  output$MyMap2 <- renderLeaflet({
   leaflet() %>%
     addRasterImage(r2,layerId= "B") %>%
     addImageQuery(r2, position="bottomleft", layerId = "B")
 })
}
shinyApp(ui, server)


text:
Q: SQL housekeeping tasks on Herkoku I'm not sure how to do this...
I have a database which contains a messages and categories tables.
The categories table has a field which has a count of the number of messages related to it.
Sometimes however I need to deactivate (active = 0) a message, at the moment this doesn't then update the category table... I will implement this is in the end but for the time I would just like to run a script perhaps daily that goes through all the categories, counts up the messages and updates the field.
What the best way of doing this?
Thanks in advance
Chris

A: If you are happy to do this manually you can create a Rake task. Push to Heroku, then execute using "heroku rake".
You could also use delayed_job, which Heroku supports. This does however cost you money $0.05 an hour. Given that it won't run very often or for very long, might be quite cheap.
The only other way I have done this stuff is to make a controller that wraps the logic and then call this. You can use one of the many and various ping services to trigger the call (these services are generally setup to request a page in your site) or setup a cron to use wget or curl to make the request.


text:
Q: How to split into train/test keeping a single row in the training set? Stratified function R equivalent in Python My dataset has categorical variables with only one observation in a class, in R this observation belongs to the training set, but in python return error. How to allocate this row in train automatically?
R script
> dataset = data.frame(target = c(100,200,300), Var1 = c("a","b","b"))
> split <- stratified(dataset,c("Var1"), 0.70, keep.rownames=TRUE, bothSets=TRUE)
> train <- split$SAMP1
> train
   rn target Var1
1:  1    100    a
2:  3    300    b
> test <- split$SAMP2
> test
   rn target Var1
1:  2    200    b

Python
data = [[100, 'a'], [200, 'b'], [300, 'b']]
dataset = pd.DataFrame(data, columns=['Target', 'Var1'])
train, test = train_test_split(dataset, stratify = dataset[['Var1']], train_size = 0.7)
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.


text:
Q: Google spreadsheet If statement I am having trouble understanding the IF statement.
What I am trying to do is (in php):
    if(isEmpty($cellA) && isNotEmpty($cellB){
        $cellA = CurrentDate;
    }

My attempt at doing this in the spreadsheet is:
    =IF(ISBLANK($A3), IF(ISBLANK($B3),"",$A3 = NOW()) ,"")

I get an error error: Circular dependency detected
Thank you in advanced.

A: The circular dependency will occur if you put that formula in either A3 or B3 because the formula will be referencing the cell that contains the formula, which would recursively go on forever.  Think of a very simple example - the formula =A1 in cell A1. When the formula is evaluated, it sees that its value should be the value of A1 (which is the current cell). It then finds A1 on the sheet and tries to get its value, but as we just saw, the formula is =A1, so it would then go to cell A1 (where we already are) again and try to calculate the value. This process would put you into an infinite loop, and Spreadsheets prevents this from happening by not calculating anything when it notices a cell is referencing itself, and instead warning you of a circular reference.
Also, since you can't assign values to arbitrary cells from within a formula, that $A3 = NOW() part is just a boolean evaluation that will return True or False. The general syntax (which it looks like you have) is IF(<condition>, <value_if_true>, <value_if_false). What you are doing in PHP is actually more suited to AppScript, which is a JavaScript-esque programming language built into Google Docs. Using this you would be able to do what you look for - otherwise, you would have to create a separate column and do the calculations there. Hope that helps :)


text:
Q: Why can't I create extension methods for static classes? When I try to create an extension method for the File class, I get an error telling me that I cannot do this because the class is static. However, I don't see why this stops the creation of an extension method, what implication is there?
Thanks

A: Extension methods are called on an instance of an object.
myObj.ExtensionMethod();

If you have a static class, you can't have an instance of it.  Therefore, there's nothing to call the extension method on.

A: Because an extension method by design must take an instance of the class it is extending as its first parameter. And obviously you can't pass an instance of File because it is a static class and cannot have instances.

A: Stated in reverse, if you look at the definition of any extension method, the first parameter is always the instance of the object upon which it is called evidenced by the this keyword. Logically this behaviour cannot work on a static class because there is no instance present.
Sample of an extension method - see first param this
public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

A:
Why can't I create extension methods for static classes?

Because the C# dev team didn't implement that feature (yet). F# has chosen to implement it though.
Same thing for extension properties. F# has them and Boo has had them since (at least) 2006.


text:
Q: How do I use this Cordova Plugin? "Cordova Audio Stream Plugin" ? I have been trying to figure out this for days, but I do not know why but I cannot seem to know how to use this plugin.  There is not much documentation on this github.
https://github.com/keosuofficial/cordova-audio-stream-plugin
What I have done so far/tried
I added the plugin via
cordova plugin add https://github.com/keosuofficial/cordova-audio-stream-plugin.git
I added stream.js in my index.html
I added this function my code
var my_stream = new Stream("http://audio.scdn.arkena.com/11689/goo_150739.mp3", onSuccess, onError);
// Play audio
my_stream.play();

function onSuccess() {
    console.log("playAudio():Audio Success");
}

function onError(error) {
    alert('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

I receive an error
undefined is not a constructor (evaluating 'new Stream("http://audio.scdn.arkena.com/11689/goo_150739.mp3", onSuccess, onError)'), http://192.168.200.121:8100/js/app.js, Line: 14


text:
Q: Cauchy Mean Value Theorem I am trying to finish the proof started in the first comment of this post.
I have that $$h'(x)=g'(x)[f(b)-f(a)]-f'(x)[g(b)-g(a)]$$ then $$h'(c)=g'(c)[f(b)-f(a)]-f'(c)[g(b)-g(a)]=0$$ by Rolle's theorem. Then
$$g'(x)[f(b)-f(a)]=f'(x)[g(b)-g(a)]$$
But then I am stuck...
Do I just simply show by algebra that $$\frac{f(b)-f(a)}{g(b)-g(a)}=\frac{f'(c)}{g'(c)}$$ and I am done?

A: From $g'(c)[f(b)-f(a)]-f'(c)[g(b)-g(a)]=0$ we get
$g'(c)[f(b)-f(a)]=f'(c)[g(b)-g(a)]$
It follows that
$\frac{f(b)-f(a)}{g(b)-g(a)}=\frac{f'(c)}{g'(c)}$
(if you have the equation $xy=uv$ then $x/u=v/y$ provided that $u \ne 0 \ne y$


text:
Q: How convert TFRecordDataset item to image? I have a issue with converting tfrecords back to images:
def _parse_test_image_function(img):
    image_feature_description = {
        'image/file_name': tf.io.FixedLenFeature([], tf.string),
        'image/encoded_image': tf.io.FixedLenFeature([], tf.string),
    }
    return tf.io.parse_single_example(img, image_feature_description)

test_dataset = tf.data.TFRecordDataset(temp_path)
test_dataset = test_dataset.map(_parse_test_image_function)

print(tf.__version__)
images = test_dataset.take(1)
print(images)

2.5.0
<TakeDataset shapes: {image/encoded_image: (), image/file_name: ()}, types: {image/encoded_image: tf.string, image/file_name: tf.string}>

Fields in image_feature_description are correct
also I saw this
Converting TFRecords back into JPEG Images
But this is not very helpful for me because some of functions which is used in answers outdated.

A: You can get the image as numpy array by using the below code.
import numpy as np
import PIL.Image as Image
gold_fish=Image.open('/content/gold.jpeg')
gold_fish=np.array(gold_fish)

Thank You.


text:
Q: git - merge big branch by one commit at a time I have branch test. I want to merge it into development. test has a lot of commits. I'm afraid of possible conflicts, so I decided to merge by one commit at a time. I know I can use git cherry-pick to merge one commit into another branch (or some range of commits).
When development was N commits behind test, I tried to cherry-pick the oldest commit, pushed it to remote, then recognized that development is ahead of test by one commit. I expected that development would be behind by N-1 commits instead. I guess, with cherry-pick I'll mess up my git history.
How can I merge two branches with minimal risks of getting conflicts?

A: I think that what you're looking for is git rebase that :

Reapply commits on top of another base tip

It takes each commit and replay it.
Here is a more complete demonstration : https://www.youtube.com/watch?v=a_msiOrYLgM


text:
Q: Hyper-v ISCSI Network Setup I have Hyper-v installed on Windows Server 2012 R2.
We are using 2 x Dell R730xd's with 8 NICS (4x10GigE 4x1GigE) per host. I would like to dedicate 2 NICS to our ISCSI network, however I am unsure as to how i should do this.
Initially i had planned to create a NIC team on each HOST for two of the 10GigE's and connect that to a vSwitch labeled 'Storage' however, I have read several articles that say not to/do this (link). My primary goal is to ensure redundancy and throughput.
I am very confused by these three statements:
· The Technet statement that basically quotes "iSCSI + NIC Teaming not supported" is still true for all teaming solutions, with the EXCEPTION of the Windows Server 2012 inbox NIC Teaming solution we provide.
· If iSCSI Initiator is used with dedicated NICs such as in a stand-alone and/or Failover Clustering environment, then NIC Teaming should not be used (because it adds no benefit over MPIO for dedicated NICs).
· If iSCSI Initiator is used in a shared NIC scenario (see figure below) such as in a Hyper-V 2012 environment, then iSCSI Initiator used over the Hyper-V switch (and over NIC Teaming) is supported.
Should i use two separate NICS connected to two different vSwitches or, can i go ahead and configure a NIC team on the host as initially planned.
Is there a another/better way for me to setup the iSCSI network?

A: Start by realizing that ISCSI is made for networks. Redundancy is built into the protocol, as is using multiple NIC for performance. This is called "Multi Path" (MPIO) and is fully supported by Windows. No need to use a virtual switch (which would not work on a stream anyway as every data stream can only go to one NIC), instead set up multi pathing properly.
Then use native NIC directly from the host and all will be fine.


text:
Q: Removing the 2d point that are close to each others I would like to remove the coordinates that lie close to each other or if it is just a duplicate.
For example,
x = [[9, 169], [5, 164],[340,210],[1020,102],[210,312],[12,150]]

In the above list, the first and second element lies close to each other. How do I remove the second element while preserving the first one?
Following is what I have tried,
def process(input_list, thresh=(10, 10)):
    buffer = input_list.copy()
    n = 0
    prev_cx, prev_cy = 0, 0
    for i in range(len(input_list)):
        elem = input_list[i]
        cx, cy = elem
        if n == 0:
            prev_cx, prev_cy = cx, cy
        else:
            ab_cx, ab_cy = abs(prev_cx - cx), abs(prev_cy - cy)
            if ab_cx <= thresh[0] and ab_cy <= thresh[1]:
                del buffer[i]
        n += 1
    return buffer

x = [[9, 169], [5, 164], [340, 210], [1020, 102], [210, 312], [12, 150]]
processed = process(x)
print(processed)

The problem is that it doesn't recursively check if there are any other duplicates since it only checks the adjacent coordinates. What is an efficient way of filtering the coordinate?
Sample Input with thresh = (10,10):
x = [[12,24], [5, 12],[100,1020], [20,30], [121,214], [15,12]]

Sample output:
x = [[12,24],[100,1020], [121,214]]

A: Your question is a bit vague, but I'm taking it to mean:

*

*You want to compare all combinations of points

*If a combination contains points closer than a threshold

*Then remove the point further from the start of the input list

Try this:
import itertools

def process(input_list, threshold=(10,10)):
    combos = itertools.combinations(input_list, 2)
    points_to_remove = [point2
                        for point1, point2 in combos
                        if abs(point1[0]-point2[0])<=threshold[0] and abs(point1[1]-point2[1])<=threshold[1]]
    points_to_keep = [point for point in input_list if point not in points_to_remove]
    return points_to_keep

coords = [[12,24], [5, 12],[100,1020], [20,30], [121,214], [15,12]]
print(process(coords))

>>> [[12, 24], [5, 12], [100, 1020], [121, 214]]

The way this works is to generate all combinations of points using itertools (which leaves the points in the original order), and then create a list of points to remove using the threshold. Then it returns a list of points not in that list of points to remove.
You'll notice that I have an extra point than you. I simply copied what seemed to be your intended functionality (i.e. both dy AND dx <= thresh for point removal). However, if I change the line with the AND statement to remove point if dy OR dx <= thresh, I get the same output as your sample.
So I'm going to ask you to recheck your sample output.
BTW, it might be useful for you to confirm if checking for x and y proximity separately is what you really want. So as a bonus, I've included a version using the Euclidean distance as well:
import itertools
import math

def process(input_list, threshold=100):
    combos = itertools.combinations(input_list, 2)
    points_to_remove = [point2 for point1, point2 in combos if math.dist(point1, point2)<=threshold]
    points_to_keep = [point for point in input_list if point not in points_to_remove]
    return points_to_keep

coords = [[12,24], [5, 12],[100,1020], [20,30], [121,214], [15,12]]
print(process(coords))

>>> [[12, 24], [100, 1020], [121, 214]]

This version fits your original sample when I used a threshold radius of 100.

A: I'd split this up a bit different. It's also tricky of course because of the way you have to modify the list.
def remove_close_neighbors(input_list, thresh, position):
  target_item = input_list[position]
  return [item for i, item in enumerate(input_list) if i == position or not is_close(target_item, item, thresh)]

This will remove all the "duplicate" (or close) points, other than the item under consideration.
(Then define is_close to check the threshold condition)
And then we can go over our items:
def process(input_list, thresh):
  pos = 0
  while pos < len(input_list):
    input_list = remove_close_neighbors(input_list, thresh, pos)
    pos += 1

This is by no means the most efficient way to achieve this. Depends on how scalable this needs to be for you. If we're talking "a bajillion points", you will need to look into clever data structures and algorithms. I think a tree structure could be good then, to group points "by sector", because then you don't have to compare each point to each other point all the time.


text:
Q: Show that every function is integrable in a nonempty space with Dirac's measure.
Let $X$ be a nonempty set and $\delta_a$ the Dirac measure $(a \in X)$. Show that every function $f$ is integrable and that
  $$\int_X f \delta_a = f(a)$$

For the second part, I first assumed that $f :X \rightarrow [0, \infty]$. Then there exists an increasing sequence $(s_n)_n$ of simple functions such that $\lim_n s_n = f$, and also, we have that
$$\int_X f \delta_a = \lim_n \int_X s_n \delta_a$$
So for a fixed $n$, $s_n$ has a representation of the form
$$s_n = \sum_{i=1}^m a_i\chi_{A_i}$$
where $A_1 \cap A_j = \emptyset$ if $i \neq j$. Then
$$\int_X s_n \delta_a = \sum_{i=i}^ma_i \delta_a(A_i) = \sum_{i=1}^ma_i\chi_{A_i} = s_n(a)$$
Therefore, taking limits, since $(s_n)_n \rightarrow f$, we have the result. For non negative functions $f: X \rightarrow [-\infty, \infty]$ I believe it will be the same applied to its positive and negative part $f^+$ and $f^-$.
If this is fine (which I'm unsure of), I'm just left with the first part, that so far I have been unable to prove. A function $f :X \rightarrow [-\infty, \infty]$ is integrable if the integral exists and is finite, or if $\int_X |f| < \infty$. Any hint on how to proceed would be highly appreciated. Thank you in advance!


text:
Q: send socket request from one component to different component There is a two different component. One is patient and another is Doctor. The doctor can be on any page. When patient fires join event from his page to a particular doctor(e.g abc), the node server will then catch that event and will send JoinAccept event to 'abc doctor'. Following doctor should get notification that following patient wants to connect with you.
To achieve this, I could able to send 'Join' event up to server but could not able to listen JoinAccept event on doctor's end.
This is what I have done
context.js
import io from "socket.io-client";

import { SOCKET_URL } from "constants/url";

const SocketContext = React.createContext();

const SocketProvider = ({ children }) => {
  const [socketClient, setSocketClient] = React.useState();
  const [socketUpdated, setSocketUpdated] = React.useState(false);
  React.useEffect(() => {
    const socket = io(SOCKET_URL);
    setSocketClient(socket);
    return () => {
      io.disconnect();
    };
  }, []);

  React.useEffect(() => {
    console.log("socketClient", socketClient);
    if (socketClient) {
      const tokenData =
        !!localStorage.token &&
        JSON.parse(atob(localStorage.token.split(".")[1]));
      if (tokenData.user) {
        console.log("user", tokenData.user);
        socketClient.emit("clientData", tokenData.user);
        socketClient.on("connected", msg => {
          console.log("connected");
          setSocketUpdated(true);
        });
        // setSocketUpdated(true);
      }
    }
  }, [socketClient]);

  console.log("socket updated", socketUpdated);

  return (
    <>
      <SocketContext.Provider value={{ socket: socketClient, socketUpdated }}>
        {children}
      </SocketContext.Provider>
    </>
  );
};

export { SocketContext, SocketProvider };

Patient.js (it will fire Join event)
const Patient = () => {
  const { socket } = React.useContext(SocketContext);
  React.useEffect(() => {
    const data = {
      to: "abcdoctor@gmail.com",
      from: "patient@gmail.com",
      message: "Join a call"
    };

    socket.emit("Join", data);
  }, [socket]);

  return (

Patient

  );
};

Doctor.js
const DoctorParentComponent = () => {
  return (
    <>
      <SocketProvider>

Navbar

        <DoctorRoutes />
      </SocketProvider>
    </>
  );
};

DoctorPage.js
const DoctorPage = () => {
  const [msg, setMessage] = React.useState("");
  const { socket, socketUpdated } = React.useContext(SocketContext);
  console.log("Doctor socket", socket, socketUpdated);

  React.useEffect(() => {
    console.log("socket", socket);
    if (socket !== undefined) {
      console.log("socket join", socket);
      socket.on("JoinAccept", message => {
        debugger;
        console.log("message", message);
        setMessage(message);
      });
    }
  }, [socket]);

  return (

Doctor

  );
};

server.js
io.of("/sockets").on("connection", socket => {
      console.log("socket connection is made!!!", socket.id);

      socket.on("clientData", clientData => {
        console.log(clientData, "CLEITN DATA");
        socket.emit("connected", "connected");
      });
      socket.on("Join", data => {
        const msg = {
          message: "I am joining"
        };
        console.log("socket", socket.id);
        console.log("I am Joining", data);
        socket.broadcast.to(data.to).emit("JoinAccept", msg);
      });
}

In my case the server gets Join event from patients and then sends event to requested doctor but doctor page is unresponsive. I mean doctor page does not listens the changes i.e it could not listens socket event JoinAccept so that it can join patient's request.
UPDATE
changing
socket.on("Join", data => {
    const msg = {
        message: "I am joining"
    };
    console.log("socket", socket.id);
    console.log("I am Joining", data);
    socket.broadcast.to(data.to).emit("JoinAccept", msg);
});

to following works
socket.on("Join", data => {
    const msg = {
        message: "I am joining"
    };
    console.log("socket", socket.id);
    console.log("I am Joining", data);
    io.of("/sockets").emit("JoinAccept", msg)
});

But I want to emit 'JoinAccept' event only for a particular doctor which patient has requested for from join events.

A: On DoctorPage.js socket is an object, if you put this object as the only variable in the dependency array it's going to run as a loop.
Try switching to the socket id instead, so:
  React.useEffect(() => {
    console.log("socket", socket);
    if (socket !== undefined) {
      console.log("socket join", socket);
      socket.on("JoinAccept", message => {
        debugger;
        console.log("message", message);
        setMessage(message);
      });
    }
  }, [socket.id]);


text:
Q: Transfer files from C - A using scp I want to transfer a directory from C to A
where, A - local system/machine (Windows)
B - Jump Server/Host
C - Host (Ubuntu) (There is test directory on this host which I need to get into my local windows machine)
Any help would be appreciated.

A: scp -J user@B user@A:directory .

Or if you use this connection more frequently, it's convenient to add an entry to ~/.ssh/config:
Host A
   User user
   ProxyCommand ssh B -W %h:%p

then scp A will work transparently


text:
Q: Could not execute editor for vi vim and gedit I am getting the following error message when I am trying to do
git rebase -i <commit no.>

Unknown option -w
Run 'gedit --help' to see a full list of available command line options.
Could not execute editor

From the other posts of stack overflow I tried out the following things:

*

*changed default editor to vim, gave path as /usr/bin/vim

*did the same thing for vi and gedit

loaded ~/.zshrc using source ~/.zshrc but still getting the same issue.
What else can I try to get rid of this error.

A: The editor of your shell is set by
export EDITOR=vim

To set the editor in your gitconfig, one can use
git config --global core.editor vim


text:
Q: Storing Multiple Data in Laravel I am trying to think of a way that a user can add a type(medical) on the frontend but a verifier has to approve that record? i can't seem to figure out the best solution for this, does anyone have any suggestions on how to make this work? It's getting stored in the medical table but not in Verifier table.
In Simple words, I am using the medicalRecord Controller to stored medical and Verifier details.
'document_id' = the medical_id;
'submitted_by' = who created the record
  public function store Request $request, $id)
{

    if (auth_user_cannot(Capability::CREATE_DRIVER_MEDICAL_RECORD)) {
        return redirect($group['name'] . "/" . $group['userId']);
    }

    $all = $request->all();

    if ($request->hasFile('myfile')) {
        $result = upload($request->file('myfile'), 'nonzip', 'Medical');
        $all['upload'] = $result['upload'];
        $all['uploadId'] = $result['uploadId'];
    }

    // u'll need to save the medical to the user first, then save the verifier to the medical.

    $driverMedical = DriverMedicalRecord::create($all);

   // Then for the relation;
    $medical  =  $driverMedical->find($id);
    $verificationData = DocumentVerification::create( [
        'document_id' => $medical,
        'submitted_by'=> Auth::id(),
    ]) ;

    $request->user()->posts()->save($post);

    $driverMedical->verifier()->save($verificationData);

A: set a flag in the same table and change its value when it got verified.
ex: is_verfied it should be 0 when it is not approved when it got approved change it to 1 (this is what i understand from your question)


text:
Q: How do I create and draw an array of images on a canvas using Javascript? I am trying the following code to allow me to create an image, allow custom values attached to it and draw in on an HTML canvas. It doesn't seem to be working though.
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
function CreateObject(objectImage){
    lastIndex++;
    PlanObjects[lastIndex] = new PlanObject(lastIndex,currentSlide,24,24,24,24,objectImage);
    context.drawImage(PlanObjects[lastIndex].img,PlanObjects[lastIndex].posX,PlanObjects[lastIndex].posY);
}

var PlanObjects = [];
var lastIndex = -1;
var currentSlide = 0;

function PlanObject(id, slide, width, height, posX, posY, img){
    this.id = id;
    this.slide = slide;
    this.width = width;
    this.height = height;
    this.posX = posX;
    this.posY = posY;
    this.img = new Image(img);
}

CreateObject("imgs/icons_star.png");

HTML:
<div id="mainCanvasDiv"><canvas width="800" height="600" id="mainCanvas"></canvas>

I expect to create the object, store it in the array of PlanObjects (with it's customer values) and draw it onto the canvas but it doesn't seem to do that.

A: 1) The input parameters for the image constructor are width and height. And you must separately set the source:
var myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);

[ https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image ]
2) Loading an image is asynchronous, so you need to handle the load event:
PlanObjects[lastIndex].img.addEventListener('load', function() {
  context.drawImage(PlanObjects[lastIndex].img, PlanObjects[lastIndex].posX, PlanObjects[lastIndex].posY)
});

[ https://developer.mozilla.org/en-US/docs/Web/Events/load ]
[ https://jsfiddle.net/bvupyroc/ ]

A: I had to modify the new Image line to fix the problem
var canvas = document.getElementById('mainCanvas');
canvas.width = canvas.scrollWidth;
canvas.height = canvas.scrollHeight;
var context = canvas.getContext('2d');
function CreateObject(objectImage){
    lastIndex++;
    PlanObjects[lastIndex] = new PlanObject(lastIndex,currentSlide,24,24,24,24,objectImage);
    context.drawImage(PlanObjects[lastIndex].img,PlanObjects[lastIndex].posX,PlanObjects[lastIndex].posY);
}

var PlanObjects = [];
var lastIndex = -1;
var currentSlide = 0;

function PlanObject(id, slide, width, height, posX, posY, img){
    this.id = id;
    this.slide = slide;
    this.width = width;
    this.height = height;
    this.posX = posX;
    this.posY = posY;
    this.img = new Image();
    this.img.src = img;
}

CreateObject("./imgs/icons_star.png");


text:
Q: Grounding Neutral Off Grid Solar Is it recommended to ground the neutral line in an off grid solar system?
A nonisolated inverter would be by definition wired this way, right?
I believe that in home electrical systems neutral is connected to ground in one location. There is a ground bus and a neutral bus and they are linked in one location near the main home supply and the earth connection.
As I understand it when grounding the neutral line,

*

*If there is an earth fault on the neutral line nothing happens

*If there is an earth fault on the live line the inverter circuit breaker will trip. (if no other protection trips first)

If you do not ground the neutral line a GND fault will either ground the neutral line or the live line. I believe the disadvantage being that if the live line is grounded it is confusing for future problems unless there is an indication of the fault.
In a home system is there more danger because of the higher voltage transmission lines?
Would there be a difference if there was or was not a GFDI (Ground Fault Protector)?
REF-1
REF-2


text:
Q: Plot the relationship of each column to a singular column in a table I have one table of derived vegetation indices for 63 sample sites from different satellites. this gives me a table with 63 observations(sample sites) and 56 variables(1 Sample ID, 50 vegetation indices, 4 Biomass and 1 LAI). The last 5 columns of the table are the biomass and LAI, and the first column is the sample ID.
I want to generate a plot showing the relationship between a single vegetation index and one of the biomass parameters.
I am able to do this using the plot function, for one observation and variable at a time.
plot(data$Dry10, data$X8047EVImea)

I don't want to run this code 50 times and again by 5 sets for each biomass and LAI parameter.
Is there a way to loop or nested loop this plot function so that I can generate 200 graphs at once?
Also, I will place a regression line in each plot to see what vegetation index will best represent the amount of biomass present at the sample site.
This is my first post on stackoverflow, so please don't hesitate to request more information on the problem if I have missed something.

A: As noted in my comment you can accomplish this with a faceted plot in the ggplot2 package. This does require a little bit of data re-arrangement that can be accomplished with the reshape2 package. Here is some code that will be close to what you want to do but since I don't completely know your data formats it might take some fixes:
library(ggplot2)
library(reshape2)
library(dplyr)

vegDat <- data[,2:51]
bioDat <- data[,52:55]
## melt the data.frames so the biomass and vegetation headers are now variables
vegDatM <- melt(vegDat, variable.name='vegInd', value.name='vegVal')
bioDatM <- melt(bioDat, variable.name='bioInd', value.name='bioVal')
## Join these datasets to create all comparisons to be made
gdat <- bind_cols(vegDatM[rep(seq_len(nrow(vegDatM)), each=nrow(bioDatM)),],
    bioDatM[rep(seq_len(nrow(bioDatM)), nrow(vegDatM)),])
## plot the data in a faceted grid
ggplot(gdat) + geom_point(aes(x=vegVal, y=bioVal)) + facet_grid(vegInd ~ bioInd)

Note that since there are 50 plots you may want to open a divice with a large height (or width if you swap the facet) i.e. pdf('foo.pdf', heigth=20). Hope this gets you on the right track.


text:
Q: Match the single letter x, that is placed immediately right after a number I need C# regex so it matches letter X right after number. P.S. 12XX should not match (because of XX).
For example, "This is ABC 15x DEF", it should match "15x"

A: If I understand you correctly, what you want is the following regex:
[\d]+x[^x]

This matches 1 or more digits, followed by the literal letter "x" and anything that is not x.
Feel free to replace x with [a-z] or [a-zA-Z] if you want any lowercase / uppercase letter instead of a specific letter x. You can also replace the last part, the negated set [^x], with the aforementioned replacements (resulting in [^a-z] or similar).
Also, have a look at regexr.com for instructions how to use regex.
//EDIT: to cover all possible cases (as discussed in the comments) use the following regex:
[\d]+x(?=$|[^x])

The aforementioned, first version of the regex wouldn't match if the input string was 15x, because there is no "letter other than x" afterwards (which is what [^x] asks) - there's simply nothing at all, i.e. the string doesn't match.
The "new" regex, however, asks whether the "character" after the match is either not x, or the end of the string (which can be matched with $).
It is also viable to use negative lookahead ((?!something)) as in @Justinas Marozas answer, which only matches if something doesn't match after the string (therefore "negative"). It also doesn't include something in the matched string / result (therefore "lookahead").
The final regex would, therefore, be:
[\d]+x(?!x)

Using the second regex mentioned at the beginning of this edit yields the same results and is just as correct, though - it's just a little longer.
Thanks to @hvd for the feedback on and improvements to my answer!

A: If you're expecting 15x be surrounded by white space:
@"\b\d+x\b"

If you're not expecting 15x be surrounded by whitespace:
@"(?<!\d)\d+x(?!x)"

\b - word boundary; \d - digit;
(?<!pattern) - negative lookbehind; (?!pattern) - negative lookahead;
Shorthand character reference
Look ahead/behind reference
And if you want to also catch 15X - pass RegexOptions.IgnoreCase flag or replace x with [Xx].


text:
Q: Как объединить два элемента ArrayList в один элемент Допустим, у меня есть список ArrayList<String>, который содержит элементы:
[0] <название_пары_1>
[1] <преподаватель_1>
[2] <название_пары_2>
[3] <преподаватель_2>

Нужно изменить список так, чтобы получилось следующее.
[0] <название_пары_1> <преподаватель_1>
[1] <название_пары_2> <преподаватель_2>

Как это сделать?

A: Алгоритм такой:
1. Создаёте новый список.
2. Добавляете в нулевую ячейку нового списка сумму нулевой и первой ячеек старого списка.
3. Повторяете это действие нужное число раз для следующей ячейки нового списка и каждой пары ячеек старого списка.

A: Если вы хотите изменить именно исходный список, то используйте сложение строк и метод удаления элемента из списка remove, который для удобства возвращает значение удаляемого элемента
    // каким то образом получаем исходный список
    List<String> list = new ArrayList<>();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");

    // попарно суммируем элементы и удаляем ненужные, пока список не кончиться
    for (int i =0; i<list.size(); i++) {
        list.set(i, list.get(i) + list.remove(i+1));
    }

    // смотрим результат
    System.out.println(list);

A: Шаги:

*

*Создаем список

*Перебираем индексы первого списка с шагом 2

*Добавляем в новый список конкатенацию текущего и следующего за ним элемента

Код:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");

List<String> newList = new ArrayList<>();

for (int i = 0; i < list.size(); i += 2) {
    newList.add(list.get(i) + list.get(i + 1));
}

System.out.println(newList); // [AB, CD]


text:
Q: Ошибка при установке sentry-laravel Делаю по гайду с документации https://docs.sentry.io/platforms/php/guides/laravel/
Прописываю composer require sentry/sentry-laravel
Успешно устанавливаю
Далее нужно настроить DSN, прописываю "php artisan sentry:publish --dsn=https://examplePublicKey@o0.ingest.sentry.io/0", как в гайде.
И во время запуска теста получаю следующее
DSN discovered from Laravel config or .env file!
Sending test event...
There was an error sending the event.
Please check if your DSN is set properly in your .env as SENTRY_LARAVEL_DSN or in your config file config/sentry.php.
Не могу понять в чем дело, что не так с DSN, как исправить ошибку?

A: В общем как я и думал, вот в этом месте "https://examplePublicKey@o0.ingest.sentry.io/0" тут нужен свой уникальный ключ, который дадут при регистрации.
Так что чтобы решить ошибку нужно зарегистрировать и получить свой уникальный DSN.


text:
Q: Boot repair hanging on purge kernels then reinstall last kernel I'm running 14.04.3 from live cd trying to move grub from a failing hard drive that had windows on it that's no longer used (sda).  I plan on taking out this hard drive when I'm done.  I'm trying to move the bootloader/grub to my good hard drive with my current ubuntu installation (sdb).  I got the partition with ubuntu (sdb1) shrunk and prepended a new partition to with ext4 file system (sdb3).  I used boot repair to default to sdb1 for the OS and to put grub on sdb3.
It was going well until it hit:
Purge kernels then reinstall last kernel sdb1 (ins).  This may require several minutes.
It has been stuck at this for over an hour.  Not sure what to do here, if its safe to stop it, or to restart (either through GUI or Alt+SysRq+REISUB).

A: Ended up cancelling this and mounting the new drive, and chroot into the mounted drive and running the commands from there.


text:
Q: PyCharm: How to run syncdb and sql commands? When working with Django you can sync the database like this:
python manage.py syncdb

and also check the created SQL like this:
python manage.py sql bookmarks

How do I do the above thorugh the PyCharm IDE instead of the terminal?
Thanks,

A: Tools | Run manage.py Task...:

A: Take the instructions for running the test suite and modify it for you own commands.  Also, see the generic setup guide.

A: The above dialog can also be called by keybindings. CTRL ALT R on Windows and ALT R on a Mac


text:
Q: javascript: onload and onerror called together I'm new to JavaScript and therefore confused for the variable scope...
I'm trying to load an image, and replace it with another URL when it doesn't exist.
I have to do it in pure JavaScript.
Here I got 2 versions extremely alike, but they perform differently. The only thing in common is: they don't work. The 3rd version requires a refresh and doesn't work under IE. d is the object with number attribute, which has no problem.
Here is what they have in common
.attr("xlink:href", function (d) {
  var img = new Image();

Here the Version 1: Both onload and onerror are called. However d receives the src, unfortunately it's always the generic.jpg.
  function onLoadHandler() {
     d.src = "http://.../peopleimages/" + d.num + ".jpg";
     alert(d.name + " onload called");
  }
  function onErrorHandler() {
     d.src = "http://.../images/generic.jpg";
     alert(d.name + " onerror called");
  }
  img.onload = onLoadHandler();
  img.onerror = onErrorHandler();
  img.src = "http://.../peopleimages/" + d.num + ".jpg";
  return d.src;
  }

Here the Version 2: Depending on the existance of the image, either onload or onerror is called. But the value of d.src is undefined when alert.
  img.onload = function () {
     alert(d.name + " : loaded");
     d.src = "http://.../peopleimages/" + d.num + ".jpg";
  }
  img.onerror = function () {
     alert(d.name + " : failed");
     d.src = "http://.../images/generic.jpg";
  }

  img.src = "http://.../peopleimages/" + d.num + ".jpg";
  alert(d.src);//undefined
  return d.src;
  }

Here the Version 3: it works but not the first time. I have to do refresh to get the images correctly. Perhaps it returns before the image is loaded completely.
  img.src = "http://.../peopleimages/" + d.num + ".jpg";
  return img.complete ? "http://.../peopleimages/" + d.num + ".jpg" : "http://.../images/generic.jpg";
  }

A: You are calling the functions, not assigning!
img.onload = onLoadHandler();
img.onerror = onErrorHandler();

needs to be
img.onload = onLoadHandler;
img.onerror = onErrorHandler;

A: The problem with your second example is that the image callbacks are fired when the image loads, after your other code has been evaluated.  I'm really not sure what your code accomplishes, but try something like this.
  img.onload = function () {
     alert(d.name + " : loaded");
     d.src = "http://.../peopleimages/" + d.num + ".jpg";
     return doSomething(this, d);
  }
  img.onerror = function () {
     alert(d.name + " : failed");
     d.src = "http://.../images/generic.jpg";
     return doSomething(this, d);
  }

  function doSomething(img, d) {
     img.src = "http://.../peopleimages/" + d.num + ".jpg";
     alert(d.src);
     return d.src;
  };


text:
Q: alarm service receiver android public class MyBroadcastReceiver  extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar c = Calendar.getInstance();
        hour=c.get(Calendar.HOUR_OF_DAY);
        minute=c.get(Calendar.MINUTE);
        Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
        String date = sdf.format(calendar.getTime());
        String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
        minochaDevicePolicyManager.resetPassword(str,0);
    }
}

Hey guys, So the issue here is that i need to create a class for this receiver and i have no clue on how to do so. i need this to be linked with my main activity class as the variables are over there(ex minochaDevicePolicyManager). How to do so. Yes i tried to look up on the net and i came up with this website but it wasnt really helpful.
How to do so?
Here is my alarm service in the main activity -> onCreate
Context context=getApplicationContext();
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, MyBroadcastReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60, alarmIntent);

Now how to do it. i need a class for my receiver and it has to be linked to the main activity

A: You need a singleton object available from both MainActivity and MyBroadcastReceiver.
Add a new App.java class as follows
package ....;

import android.app.Application;

public class App extends Application {
    public DevicePolicyManager minochaDevicePolicyManager;

    @Override
    public void onCreate() {
        super.onCreate();

        minochaDevicePolicyManager = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
    }
}

Then modify your AndroidManifest.xml to reference the App class
<application
    android:name="App" ...>

Then within both your MainActivity and MyBroadcastReceiver when you want to use the DevicePolicyManager instance do the following;
Add a member variable at the top of both classes
private fullpackagename.App app;

Get a reference to it within your MainActivity OnCreate and MyBroadcastReceiver OnReceive methods using the following
this.app = ((App) getApplicationContext());

To use the instance just refer to app.minochaDevicePolicyManager
app.minochaDevicePolicyManager.resetPassword(str,0);

A: Even though you are asking for a single reference to minochaDevicePolicyManager since I'm guessing you are not using it that frequently there's no reason you can't just create a new instance within the MyBroadcastReceiver using the context passed in.
public class MyBroadcastReceiver  extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar c = Calendar.getInstance();
        hour=c.get(Calendar.HOUR_OF_DAY);
        minute=c.get(Calendar.MINUTE);
        Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
        String date = sdf.format(calendar.getTime());
        String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);

        DevicePolicyManager minochaDevicePolicyManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);

        minochaDevicePolicyManager.resetPassword(str,0);
    }
}