text:
Q: Changing ListViewItem background colour while using Material Design I'm fairly new to WPF and I've run into a problem with my app design. I have  UserControl with ListView and I need to change background colour of ListViewItems dynamically. When I add the following code into my ListView everything works fine.
<ListView.Resources>
    <Style TargetType="{x:Type ListViewItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status}" Value="NotStarted">
                <Setter Property="Background" Value="White" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status}" Value="Fail">
                <Setter Property="Background" Value="#FF6666" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status}" Value="Success">
                <Setter Property="Background" Value="#80FF80" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ListView.Resources>

The problem is that when I add Material Design into my App.xaml file, the colours stop to change.
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Any ideas how to solve this?

A: Correct answer in the comments.

A:  <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem" BasedOn="{StaticResource MaterialDesignGridViewItem}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding FirstName}" Value="John">
                        <Setter Property="Background" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListView.ItemContainerStyle>


text:
Q: How to convert xml to docx? I am working on an application with meteor, and need to replace specific words  in a docx document. I found a way to convert docx files to xml, the replacements I need to make, take place in the xml-file.
The question is, how can I restore docx-document after replacing those words in xml?

A: That depends heavily on the XML-dialect you are using to represent your data. The docx format itself is just a collection of xml and resource files, packed in a zip-container. If you rename your file from file.docx to file.zip you can extract it and see it for yourself.
Lets have a quick glance at the folder-structure in the container:

 docx
 |
 + _rels (...)
 + docProps (...)
 + word
 |  + media (...)
 |  + _rels (...)
 |
 |  - document.xml
 |  - footnotes.xml
 |  - styles.xml
 |  - footer(...).xml
 |  - header(...).xml
 - [ContentTypes].xml

The most important file is the document.xml. Here is the whole text and document-structure stored, as well as references to footnotes (defined in footnotes.xml), styles (style.xml) and resources (media-folder), header/footer-information and everything else.
The XML-dialect used by docx is: Wordprocessing XML (WML) from Microsoft. This XML-dialect is (from my experience) relativeley complex and hard to format correctly.
If your XML-file is already in WML then hooray, you are almost done. The only thing you have to do is pack your document.xml (or other resource files you have edited) back to the zip-container, or create a new container from the extracted and processed one. Don't forget to rename the .zip back to .docx if you did.
If you have an XML-file in another dialect (e.g. docbook; TEI; DITA), then you will have to write a converter from that dialect to Wordprocessing XML, to create a document.xml and other resource-files. And pack it back, as I described above. As far as I know there are no ready-to-use open-source converters of that kind.

A: You can do so by running the command zip -r new-doc-file-name.docx * you must be in the folder containing all xml files and required folders.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Teamcity build chain issue In teamcity I have separate configurations for building, deploying and testing a project. we would like to chain them together.Basically the 'build' configuration does a build triggered by version control check-in and 'deployment' configuration deploys the required project files on to the integration server and 'test' configuration runs automated tests on the integration server deployed files.
The source code is checked out only when the 'build' configuration is run and I want to use the code checked out by this configuration in the 'deployment' configuration and once this deploys the files into a particular directory, I want to run the 'test' configuration against these deployed files. To achieve this I hardcoded the paths in 'deployment','test' configuration settings in teamcity currently.
But when we chain them I want the 'deployment','test' configurations to automatically get the path to the checked out code and the path to the deployed files respectively.
I am not sure if this can be done using teamcity artifacts.Even if it is not sure how to configure it.
Could someone please help.
Thanks

A: The "Build" configuration should publish the source code files and the binaries that it compiles as artifacts. Then you can set up dependencies in the "Deployment" and "Testing" configurations that retrieve these artifacts. That way you should not need to hard-code the path to the source code files.
One additional thing to think about is build parameters which you can probably use to avoid hard-coding the path to the wherever the binaries are deployed.
Here are some links to some useful pages in the TeamCity documentation.
Artifacts
Artifact Dependencies
Build Parameters


text:
Q: Can a page_id and a post_id be same? Wordpress generates ID's for each page/post. Do pages in wordpress share the same ID column in the database as the posts? I mean, if a site has both posts and pages, can one or more page_ID's be same as some Post_ID's?

A: No, all posts, pages and other custom post types exist in the same table (wp_posts) and they all share the same ID column. The ID is unique to each entry regardless of its post type.


text:
Q: "ER_CON_COUNT_ERROR: Too many connections" Error with pool connections to mysql from node.js I have about 20 node.js files that use the following configuration to access my db:
var pool = mysql.createPool({
    host: databaseHost,
    user: databaseUser,
    password: databasePassword,
    database: databaseName,
    multipleStatements: true
});

The functions all use the following pattern:
pool.getConnection(function (err, connection) {
    if (err) {
        callback(err);
    } else {
        // Use the connection

        var sql = "...sql statement...";
        var inserts = [...inserts...];

        connection.query(sql, inserts, function (error, results, fields) {

            // And done with the connection.
            connection.release();

            // Handle error after the release.
            if (error) {
                callback(error);
            } else {
                callback(null, results);
            }
        });
    }
});

I recently started getting the error:
"ER_CON_COUNT_ERROR: Too many connections"

on calls to any of my functions.  I don't really understand the pool concept well enough.  If each function is creating a pool, does that create a separate pool each time that function is called?
I understand get connection and release connection.  Just don't really get the createPool.
I tried to log the following:
console.log(pool.config.connectionLimit);     // passed in max size of the pool
console.log(pool._freeConnections.length);    // number of free connections awaiting use
console.log(pool._allConnections.length);     // number of connections currently created, including ones in use
console.log(pool._acquiringConnections.length); // number of connections in the process of being acquired

the result was:
10
0
0
0

I can increase the number of connections but would like to have some better understanding of why the problem exists.

A: If your createPool is called inside functions everytime there has to be a query, then yes, it is grave! Instead, have a different file only for mysql connection. Write a class where you create a pool inside a function, and then in the constructor you could simply return the connection from the pool. That way, if you simply require this file anywhere in your project, and create an object of the class, you could then simply use it to query and release!


text:
Q: MOD em assembly Preciso fazer uma comparação para verificar se o número X é PAR ou IMPAR.

*

*Armazeno o número no registrador AX.

Como eu faço para saber que o conteúdo de AX é par ou impar?
Obs: Armazeno um número de 1 até 99.

A: tem muitas formas de saber se o numero é par ou impar em assembly, uma delas é trantando o numero em base2 (binario), quando o numero é par ele em binario termina em 0 e impar em 1, veja alguns exemplos
9 = 1001 (impar)
10 = 1010 (par)
11 = 1011 (impar)
56 = 111000 (par)
75 = 1001011 (impar)
65535 = 1111111111111111 (impar)

beleza agora como podemos ler apenas esse ultimo bit? para isso usamos a logica AND, na logica and apenas se ambos os bits forem verdadeiros ou seja 1 o retorno sera 1 caso contrario sera 0, nesse caso podemos simplesmente pegar o numero e fazer a operação and com o numero 1, se nessa operação retornar 1 quer dizer que o numero é impar ja que os dois bits é 1 que por sua vez vai retornar 1, se retornar 0 o numero é par, exemplo o numero 10
1010 = 10
0001 = 1
----
0000 = 0

outro exemplo com o numero 11
1011 = 11
0001 = 1
----
0001 = 1

como o resultado da operação é 0 podemos simplemente usar a instrução jz para pular para uma parte caso seja zero (par) ou jnz para pular caso seja diferente de 0 (impar)
mov ax,97
and ax,1
jz par
; aqui é impar

par:
; aqui é par

outra forma é pela divisão por 2, quando se divide um numero o resto é armazenado no registrador dx, então se o dx for o numero 0 é par ja que divisão por 2 em numeros par não tem resto, se for diferente de 0 ou seja 1 então é impar
mov ax,99
mov bx,2
idiv ax,bx
cmp dx,0
je par

par:

tem outras formas alem das citadas ^^


text:
Q: Unable to install gradle plugin in RAD 8 When trying to install Gradle plugin in RAD 8 (JDK 1.7) using "`Help->Install New Software->http://dist.springsource.com/release/TOOzLS/gradle -> Extensions ->Gradle IDE.
The installation fails with below error. How can I fix it?
An error occurred while collecting items to be installed
session context was:(profile=bootProfile, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
Problems downloading artifact: osgi.bundle,org.springsource.ide.eclipse.gradle.core,3.6.3.201411271013-RELEASE.
Error reading signed content:C:\Users\<name>\AppData\Local\Temp\signatureFile6349333368928430899.jar
An error occurred while processing the signatures for the file: C:\Users\<name>\AppData\Local\Temp\signatureFile6349333368928430899.jar
Problems downloading artifact: org.eclipse.update.feature,org.springsource.ide.eclipse.gradle.feature,3.6.3.201411271013-RELEASE.
Error reading signed content:C:\Users\<name>\AppData\Local\Temp\signatureFile3533168071782523038.jar
An error occurred while processing the signatures for the file: C:\Users\<name>\AppData\Local\Temp\signatureFile3533168071782523038.jar
Problems downloading artifact: osgi.bundle,org.springsource.ide.eclipse.gradle.toolingapi,3.6.3.201411271013-RELEASE.
Error reading signed content:C:\Users\<name>\AppData\Local\Temp\signatureFile6100590399698741916.jar
An error occurred while processing the signatures for the file: C:\Users\<name>\AppData\Local\Temp\signatureFile6100590399698741916.jar
Problems downloading artifact: osgi.bundle,org.springsource.ide.eclipse.gradle.ui,3.6.3.201411271013-RELEASE.
Error reading signed content:C:\Users\<name>\AppData\Local\Temp\signatureFile5626455591177320598.jar
An error occurred while processing the signatures for the file: C:\Users\<name>\AppData\Local\Temp\signatureFile5626455591177320598.jar
Problems downloading artifact: osgi.bundle,org.springsource.ide.eclipse.gradle.ui.taskview,3.6.3.201411271013-RELEASE.
Error reading signed content:C:\Users\<name>\AppData\Local\Temp\signatureFile4681470222750675595.jar
An error occurred while processing the signatures for the file: C:\Users\<name>\AppData\Local\Temp\signatureFile4681470222750675595.jar

A: This sounds like the same type of problem encountered here:
Problems downloading artifact - error reading signed content
The explanation there (uncheck the 'only show latest' box on the installation option) implies a version mismatch between the version of Eclipse you are using under the covers of Rational Application Developer 8, and the version required by the Gradle IDE plugin provided by Spring Source.  You probably need to investigate what version of Eclipse you are using and compare it to the requirements of Gradle IDE.


text:
Q: Google maps suggestions. filter suggestions based on first input I'm busy with google maps. All is working fine.
Got a map on the frontpage that draws a route, that comes from 2 user inputs.
Now i want to filter the suggestions from the second input, based on the location of the first input.
At the moment if in the first input a address in the netherlands is entered, suggestions start giving locations in USA, if you dont specify a full addres.
Is it possible to give a radius or something to the second input before google sends suggestions back?
All i found has a limit of 50KM, while most rides are more then 50KM.
Based on country isn't gonna work, as it is international.

A: radius is not a possible option, but you may define an area(LatLngBounds) around the place where the results should be preferred via the bounds-option of an Autocomplete.(a restriction is only possible for countries)
Such an area ma be calculated via google.maps.geometry.spherical.computeOffset
Example:

      function init() {

        var map = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 1,
            center: new google.maps.LatLng(0, 0),
            noClear: true,
            disableDefaultUI: true
          }),
          diagonal = 250, //length of the diagonal in km
          inputs = map.getDiv().querySelectorAll('input[id^="pac"]'),
          acs = [],
          area = new google.maps.Rectangle(),
          marker = new google.maps.Marker({
            animation: google.maps.Animation.DROP
          });

        for (var i = 0; i < inputs.length, i < 2; ++i) {
          map.controls[google.maps.ControlPosition.TOP_CENTER].push(inputs[i]);
          acs.push(new google.maps.places.Autocomplete(inputs[i]));
          if (i === 1) {
            //first input
            google.maps.event.addListener(acs[0], 'place_changed', function() {
              //when there is a valid place
              if (this.getPlace().geometry) {

                var center = this.getPlace().geometry.location,
                  bounds = new google.maps.LatLngBounds(center);
                //create a area around the  place
                bounds.extend(google.maps.geometry.spherical.computeOffset(center, diagonal / 2 * 1000, 135));
                bounds.extend(google.maps.geometry.spherical.computeOffset(center, diagonal / 2 * 1000, 315));

                //just a rectangle to visualize the used area
                area.setOptions({
                  map: map,
                  bounds: bounds
                });

                map.fitBounds(bounds);
                //set the prefered search-area for the 2nd autocomplete
                acs[1].setBounds(bounds);
              } else {
                acs[1].setBounds(null);
                area.setMap(null);
              }
            });
            //2nd input
            google.maps.event.addListener(acs[1], 'place_changed', function() {
              //when there is a valid place
              if (this.getPlace().geometry) {
                //draw a marker and set the center of the map
                var center = this.getPlace().geometry.location;
                map.setCenter(center)
                marker.setOptions({
                  map: map,
                  position: center
                })
              } else {
                marker.setMap(null);
              }
            });
          }
        }
      }
 html,
 body,
 #map_canvas {
   height: 100%;
   margin: 0;
   padding: 0;
 }
<div id="map_canvas">
  <input id="pac1">
  <input id="pac2">
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places,geometry&callback=init"></script>


text:
Q: Entity framework: detaching but keeping object graph I'm working in a disconnected scenario, but I noticed that disposing an object context does not release attached entities. As a result, subsequent operations often fail because of this.
So to solve this, I detach everything myself when the object context is being disposed:
public void Dispose()
{
   // detaching is not really needed, because we have short living object contexts
   var objectStateEntries =
       _context.UnderlyingContext.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged);
   objectStateEntries.ToList().ForEach(o => { if (o.Entity != null)
   {
     _context.UnderlyingContext.Detach(o.Entity);
   }});

   _context.Dispose();
   _context = null;
}

However, the side effect is that the object graph gets detached completely, but I really want to keep the graph!
It seems I don't find a solution for this, is it true that it can't be done?

A: We had this problem as well; you cannot have part of a graph attached to an EF context. Have you considered loading up data initially in a detatched state? The context is then used as a stateless repository of data and nothing else.
You can load up data as detatched initially as follows:
myDataContext.MyEntitySet.MergeOption = MergeOption.NoTracking;


text:
Q: Python. extracting string from file I have a file similar to this:
RANDOMTEXTSAMPLE*
$SAMPLERANDOMTEXT
RANDOMSAMPLE*TEXT

I'm trying to extract and put into a list all instances of "sample" that have * at the end.
I tried with something like this:
import re

with open('file1.txt') as myfile:
content = myfile.read()

text = re.search(r'[0-9A-Z]{7}\*', content)
with open("file2.txt", "w") as myfile2:
myfile2.write(text)

However I would only get me the first result it found.
Any recommendations on how can I get all the instances of sample that end with * in a list, without adding the * to the list will be appreciated.
Thanks
EDIT: small corrections

A: You can try this:
import re

samples = []

with open('file1.txt') as myfile:
    for line in myfile.readlines():
        if re.search(r'[0-9A-Z]{6}\*', line):
            samples.append(line)

# print('SAMPLES: ', samples)

with open("file2.txt", "w") as myfile2:
    for s in samples:
        myfile2.write(s)

A: From your question it is not clear if you want to match dollar sign at the end, or asterisk sign at the end, in any case you can solve problem using back references back-reference. If you don't know what they are, you can read more about back-references here.
import re
with open ("file1.txt", "r") as myfile:

    samples = []
    pattern = re.compile(r'([a-zA-Z]+)\*')
    for line in myfile.readlines():

        for matched_object in pattern.finditer(line):
           samples.append(matched_object.group(1))

This would give you list of samples. You can see  regex demo here.
Note:
Since it is not clear what are you trying to match, you may need to modify back reference in my regular expression in order to match your concrete input. Anyway, this code snipet should give you overall idea how this problem can be solved.


text:
Q: Does ASP.NET Session state work without cookies? According to MSDN:

By default, the SessionID value is stored in a non-expiring session
  cookie in the browser.

If I am trying to use Session State (I'm not using Cookieless Session IDs) and a users browser does not accept cookies, will Session State work?

A: According to this it is supported: http://msdn.microsoft.com/en-us/library/aa479314.aspx
<sessionState cookieless="true" />

The downside is that the session ID is placed in every URL used by the application:
http://yourserver/folder/(session ID here)/default.aspx

See this SO answer for additional details: Absolute URL Cookieless


text:
Q: How to interpret MCAR (missing completely at random) any papers that I can read? When dealing with missing data and Little's missing completely at random test, it's widely considered that if the test has a significance level of P>0.05 the data can be considered as MCAR.
But, I can't find a single paper that confirms that interpretation. All the papers just say that their values are higher than 0.05 so their data set is good and can reject the null hypothesis etc etc but they never confirm that where they got that "0.05" value. I was searching for hours. I found the following paper of Little (1988)
http://www.jstor.org/stable/2290157
I couldn't find anything in that paper that it states about significance (P) of greater than 0.05 can be considered as data completely missing at random. Am I looking for the wrong key words? can anyone help me? Are there any research papers that confirm this?
UPDATE: In a nutshell, I'm asking, I need evidence by research papers of "P>0.05 can be considered as the data is missing completely at random"

A: You're right to be skeptical. The whole business of interpreting a significance test's failure to reject a null hypothesis as evidence for the null hypothesis is illegitimate. It just means that on the particular metric your test considered, the data you have isn't extremely unlikely under the null hypothesis.
Furthermore, missingness completely at random is a strong assumption and should not be made merely on the basis of quantitative analyses of the data at hand (after all, the question is what's missing from what you have), but also on the qualitative question of how you think the data came to be missing.

A: Paul Allison's discussion of MCAR in his Sage monograph, Missing Data, has one of the clearest explanations of MCAR in the literature. For instance on p. 3, regarding a test of the MCAR mechanism hypothesis, he writes:

The data on Y are said to be missing completely at random if the
  probability of missing data on Y is unrelated to the value of Y
  itself or to the values of any other variables in the data set...it's
  easy to test this by dividing the sample into those who (...are vs
  those who are not missing...) and then testing for a mean difference.
  If there are, in fact, no systematic differences on the fully observed
  variables between those with data present and those with missing data,
  then the data are said to be observed at random. On the other hand,
  just because the data passes this test does not mean that the MCAR
  assumption is satisfied. Still there must be no relationship between
  missingness on a particular variable and the values of that
  variable...

So, to @Kodiologist's point, the assumptions for MCAR are strong and a simple test does not, in and of itself, satisfy those assumptions. They merely lend evidence in its support.

A:
UPDATE: In a nutshell, I'm asking, I need evidence by research papers of "P>0.05 can be considered as the data is missing completely at random"

MCAR, MAR and MNAR characterize the causal mechanism responsible for missing data.
If you were investigating some other question not related to missing data, and you got a p-value above 0.05, it would be wrong to say "P>0.05 proves that there is no effect".
For the same reason, P>0.05 does not prove that the missing data are MCAR, because p-values don't prove the absence (or presence) of effects, but indicate whether a model is consistent with some data.
Say you get a p-value of 0.04 using Little's MCAR test. That means, given that your missing data is MCAR, you would get the type of missing data pattern that you have in your data (or a more extreme pattern) 4 percent of time (in the context of repeated studies).
P = 0.38 => 38% of the time, you'd see this type of missing data pattern (or a more extreme one). So if you have good reasons to believe your missing data is MCAR, you might go ahead as if it were true, even though it might not be.


text:
Q: sending mail using pear I have installed pear and when sending mail, I get the following error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 6144 bytes) in C:\wamp\www\GamesRus\mail.php on line 2
I am running on windows 7. Here is my code:
$mail = Mail::factory("mail");

$headers = array("From"=>"me@example.com", "Subject"=>"Test Mail");

$body = "This is a test!";

$mail->send("jngichabe@yahoo.com", $headers, $body);

?>

A: Something in your script is using up RAM memory, so you're hitting the server limit of RAM usage (128 MB in your case). Try to find out what part of your code it is that's using so much memory.
Can it be that you have a large body, or trying to attach a really large file to the e-mail message?


text:
Q: Ubuntu: How to copy text from terminal which is running vim on ssh, into local clipboard There are many similar questions but none with an answer that works, and it should be trivial because it used to be.
Scenario:
on an Ubuntu desktop system, I am running a terminal where I have SSH'ed to a remote server. Normally, I can select text from the terminal (that is, "from" the remote server) with the mouse, and then copy it locally with CTRL+SHIFT+C (instead of CTRL+C as I would do in any app other than a terminal) and that copies the selection to the local clipboard, which I can then paste anywhere. And that would also allow me to paste it into the terminal itself (ar another one) with CTRL+SHIFT+V, which eventually pastes it to whatever is running on the remote server (including vim).
This used to work (with debian 8 on the remote server) ALSO when running vim on the remote server , so just to clarify: in my local ubuntu machine is a terminal; inside the terminal I've ssh'd to the remote server; on the server I'm running vim; so the contents of the file opened in vim on the remote server are visible in the terminal in my local machine. Ctrl+Shift+C used to allow me to copy the selection to the LOCAL clipboard on my local machine, which I would then be able to paste into a local text editor OR back into vim on the remote machine. This way, I could copy-paste from the remote vim to a local gedit, or viceversa, or from the remote vim back to the remote vim (via my local clipboard), or from a remote vim into another remote vim in another terminal, be it on the same or another server. I'm perfectly aware that the remote server would know nothing about copying and pasting in this scenario. The local system was just copying the text it was seeing in the terminal (which happened to be the output of something running via ssh on a remote machine), and then pasting it back into the terminal (which caused it to go through ssh into the remote machine). I know that, and it worked for me.
That does not work anymore (with debian 10 on the remote machine) when vim is involved. Now on the remote server I'm running Debian 10. Ctrl+Shift+C still works (copies to local clipboard) as long as on the remote server I'm NOT running vim. For example, I can use Ctrl+Shift+C to copy text from the remote console into my local clipboard. And Ctrl+Shift+V still works whether or not I'm in vim on the remote machine. However, when vim is open on the remote machine within the terminal, Ctrl+Shift+C does NOT copy to local clipboard.
My guess is that Ctrl+Shift+C is somehow captured by vim.
So how do I copy text from a terminal into the clipboard on ubuntu, when this terminal happens to be running ssh and vim happens to be open on the remote machine?
I know I can use y to "yank" (i.e. copy) and p to paste remotely in vim. However that's not what I'm looking for. That all happens remotely and only allows me to copy from vim to vim on the remote machine (maybe also from vim to something else on the remote machine, I don't care). That does not allow me to copy from vim on the remote machine to a text editor on the local machine.
I don't want a convoluted solution involving "yanking" from vim to something else on the remote machine and then ftp'ing a file to my local machine or something. That's garbage. I want to LOCALLY COPY whatever is seen locally in the terminal despite the fact that what happens to be running in the terminal is vim through ssh on a remote machine.
I used to be able to do that already. I still can with a remote server that is running debian 8. But not on a remote server that is running debian 10.
How can I do that?

A: What you're seeing is actually the result of :set mouse=a (or :set mouse=nvi) in Vim, which means Vim will tell the terminal it wants to capture and process mouse events, so they'll go to the remote Vim rather than stay with the local terminal.
So the problem is not actually that CTRL+SHIFT+C isn't working... But that it has nothing to copy, since there's no selection in the terminal, as the mouse events were sent to the remote Vim which used them to select a Visual block.
Debian 8 shipped Vim version 7.4, while Debian 10 ships Vim 8+ and starting with Vim 8 a new defaults.vim is shipped which runs when you have no vimrc file and will set mouse=a (or mouse=nvi) automatically, so perhaps that's where you're getting the setting from? Or if you do have a vimrc file, perhaps Debian now included this setting on the system vimrc file and that's where it's coming from...
You have a couple alternatives to solve this issue. One is to disable Vim capture of the mouse, with :set mouse=, which you can execute on a running Vim to confirm it fixes the issue for you, or add to your ~/.vimrc file to make that permanent. (If you're creating a new vimrc file for the first time, see the instructions in :help defaults.vim to preserve the defaults you've been otherwise using!)
Another option is that your terminal probably has a way to override mouse capture and use a local selection, even when the application running in the terminal has captured the mouse. That probably involves doing a selection while holding a modifier key, such as ALT or CTRL or perhaps SHIFT, so that the terminal knows you actually want the other behavior of the mouse for this particular action. Terminals might vary in which modifier key they use, but one of these is likely to trigger the behavior you want in yours. It's usually easy to tell, since mouse selection in a terminal is visually quite different from Visual mode in Vim. Once you have done the normal mouse selection using an override, you can then copy text using CTRL+SHIFT+C as you're used to. This approach gets you the benefits of both worlds, since you still get to use the mouse inside Vim, but when you actually want a selection for copy and paste, it's available to you.

A: I worked with tty terminals many years on Linux VPS-s. As filBranden already mentioned ssh from "Gnome Terminal" to a VPS is the preferred solution. But before I setup uwf and ssh services I work with tty terminal w/o mouse and pasting. One of the helpful solution I found to add following aliases to .bashrc:
alias f='sudo find / -iname'
alias h='history'
alias hgrep='history | grep'
alias htail='history | tail -n'
alias s='sudo'
alias path='echo -e ${PATH//:/\\n}'
alias ..='cd ..'

So, e.g. if you type hgrep sshd
output would be:

43 s service sshd restart

to restart sshd again would be: It is kind of paste
!43
and hit Enter
On Gnome Terminal I replace Ctrl+Shift+C by Ctrl+C the same replacement with +V and +FI use Ctrl+Z instead of Ctrl+C and during many years only old packages conflicted few times when I need to kill the hanging (disagreeing) Gnome terminal and restart a task again Also many terminal editors inherit Ctrl+C from Gnome terminal.


text:
Q: Connect4 game in java eclipse How can I check for a draw? I have managed to check for Both diagonals left and right and both horizontal and vertical. But I need an idea how to check for a draw. I know I need to check all buttons (buttons[6][7] in my case).
//Checking the Diagonal_right win

for (int i  = 0; i < 6 ; i ++){
    for (int j  = 0; j < 7; j ++){
        if ((i+1)==6 || (i+2)==6 || (i+3)==6){
            break;
        }

        if(imageName[i][j] == singleimageName &&
                imageName[i+1][j-1] == singleimageName &&
                imageName[i+2][j-2] == singleimageName &&
                imageName[i+3][j-3] == singleimageName){
            JOptionPane.showMessageDialog(null,""
                    + "You Have Won! \n"
                    + "Player Using " + singleimageName +
                    " Connected 4");
            clearGrid();

        }
    }
}

//Checking the Horizontal win

for (int i  = 0; i < 6; i ++){
    for (int j  = 0; j < 7; j ++){
        if ((i+1)==6 || (i+2)==6 || (i+3)==6){
            break;
        }

        if(imageName[i][j] == singleimageName &&
                imageName[i][j+1] == singleimageName &&
                imageName[i][j+2] == singleimageName &&
                imageName[i][j+3] == singleimageName) {
            JOptionPane.showMessageDialog(null,""
                    + "You Have Won! \n"
                    + "Player Using " + singleimageName +
                    "  Connected 4");
            clearGrid();

        }
    }
}

//Checking the Vertical win

for (int i  = 0; i < 6; i ++){
    for (int j  = 0; j < 7; j ++){
        if ((i+1)==6 || (i+2)==6 || (i+3)==6){
            break;
        }

        if(imageName[i][j] == singleimageName &&
                imageName[i+1][j] == singleimageName &&
                imageName[i+2][j] == singleimageName &&
                imageName[i+3][j] == singleimageName) {
            JOptionPane.showMessageDialog(null,""
                    + "You Have Won! \n"
                    + "Player Using " + singleimageName +
                    "  Connected 4");
            clearGrid();

        }
    }
}

A: // Check for a draw
boolean draw = true;
for (int i  = 0; i < 6; i ++) {
    for (int j = 0; j < 7; j ++) {
        if (imageName[i][j].getIcon() == null) {
            draw = false;
        }

if (draw) {
    JOptionPane.showMessageDialog(null, "It's a draw!");
    clearGrid();
}


text:
Q: How can my chat bubble point to the same spot on multiple screen sizes? It should always point to the same part of an image regardless of the size of the phone.  I thought that if I have this point for one resolution, I could calculate a ratio of x-coordinate:width and y-coordinate:height, then multiply these ratios by the screen dimensions to get my anchor point.  The image I was given is too large so I set a fixed height.  But if the image is of fixed height, the chat bubble would not point to the same part of the image.
For example, if I have one phone that is taller than the other, using the same ratio would make the chat bubble point to a taller pt in the image.  Is there a way around this?  Here is my layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<LinearLayout
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="Order"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp" />

    <ImageView
        android:id="@+id/wayfinder_image"
        android:layout_width="wrap_content"
        android:layout_height="275dp"
        android:src="@drawable/main_image"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:id="@+id/instructions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="@dimen/description_side_margins"
        android:layout_marginRight="@dimen/description_side_margins"
        android:textSize="16sp"
        android:text="@string/wayfinder_instructions"/>

    <Button
        android:id="@+id/wayfinder_ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/MyButton
        android:text="OK"
        android:layout_gravity="center_horizontal"
        android:visibility="gone"/>

</LinearLayout>

<TextView
    android:id="@+id/chat_bubble"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:background="@drawable/arrow_bottom_center"
    android:text="@string/caption"
    android:visibility="gone"/>
</FrameLayout>


text:
Q: st-gcn code in the colab, when I running the check code, the error will be like this below enter image description here
How could I do? Please ,thank you!
solve this problem, my environmnet is cuda9.0+python3.8+torchversion0.2.0+colab


text:
Q: php delete unverified users after certain amount of time mysql So I was wondering if there was a way to delete unverified users from my database after 24 hours of not being verified. So in my database there is a verified column that is 0 for unverified and 1 for verified. (My verification method is them clicking a link from an email I send them). I dont want spam users slowing down my database so I was wondering if there was a way to do this. Here is some demo code that I thought might help explain what I am talking about.
<?php
    if($verified === "0"){
       $sql="DELETE FROM users WHERE userid='$id'";
       // In 24 hours if verified still does not equal 1 they get deleted
       mysql_query($sql)
    }

?>

A: I don't think you should approach this by deleting the users.  Instead, maintain the time when you sent the email and use this to create an IsDeleted flag:
create view v_table as
    select t.*, ( EmailSentDateTime <= (date(now()) - interval 1 day) ) as IsDeleted
    from table t;

Or:
create view v_actives as
    select t.*
    from table t
    where EmailSentDateTime >= (date(now()) - interval 1 day);

You can then periodically delete the deleted records:
delete from table t
    where EmailSentDateTime <= (date(now()) - interval 1 day);

You can schedule this during a period when there is little active (perhaps Sunday morning).  You won't have to worry about deletes competing with other activities, if you schedule it well.  And, you won't have to worry about users "accidentally" remaining active, just because a job wasn't called exactly on schedule.

A: You can do this via Cron (if on *nix) or Tasks on Windows.
Sometimes on shared hosting you don't have access to either in which case you can execute a script every time your user accesses some part of your site (eg: logs in, or some not so frequent page) then query the DB for unverified people who have not verified for over x hours/days.
Then the logical step:
Delete all those who have not verified for X hours days.
This is not as efficient as running a cron every X hours, because the CRON/Task would run exactly (for example) 12am everyday so depending on how often your script runs, it could run the script every minute or every X days - but it would still get the job done.
If you don't want to run your main script and query the DB every X minutes/seconds etc you could create a textfile and store the last checked time there.
When someone visits your page, do a check on the textfile's date/time, if more than 24hrs have passed since you checked... run your check/delete script.


text:
Q: How do you name a component that both encrypts and decrypts depending on method you use? I would like to give a good name to class that will contain both methods for encryption and
decryption using the same alghoritm.
Does anyone have an idea for naming seemingly opposing expressions under one term?
I found a name for class that encodes and decodes a string of characters, ie. "codec" (COder-DECoder).
I dont want to use the codec term for encryption operations if I already used it for character encoding.
Methods will be something like:
NameOfTheClass.Encrypt(string plainText);
NameOfTheClass.Decrypt(string cipherText);

A: Such classes are usually named after the cipher they implement. If you have a base class with virtual methods that will be implemented by several different cipher classes, that class usually has a name like BlockCipher or something, depending on exactly what you are doing with it.

A: Is it an absolute logical requirement that encryption and decryption be the same operation? If not, I'd have both Encrypt and Decrypt methods, since they are different logical operations. If so, you can either use 'Crypt' or something that better describes the algorithm you're using or the reason you're using it.


text:
Q: Run a part of code only once in javascript I have a problem with a function that returns a specific prize. The prize is bound to SEO score of a webpage. Every webpage has a specific conditions that must be  achieved in order for us to get the prize for pushing the word in top 10 on google. The prize that is defined here is a one time deal, thats why it has to be executed only once and then never again after the goals are completed
If the goal for the prize is true then the prize is 3000. The problem is that this prize is a one time deal. So when this goal is completed and the user gets the 3000 prize thats it. If next time the goal is again reached the prize 3000 is not calculcated to the prize. For the goal to be true the variable "st"(the number of words that reached the first page in google) must be 15 or equal and lower than 20. The second prize is given if "st" is bigger or equal then 20. Both can happen only once, or both at the same time. Lets say that the first goal ( qual or bigger than 15, but lower than 20) is not reached, and if "st" is 21 both prizes are calculated (so 6000) once and then never again. For now I have two gloabal variabels that have a false value, and then the if else sentences to return the prize.
var prize1= false;
var prize2= false;

if (st >= 15 && st < 20) {
        prize1= true;
        if (prize1) {

        return 3000;
    }

}
else if (st <= 20 && prize1) {
    prize2= true;
    if (prize2) {

        return 3000;
    }

}

else if (st <= 20 && !prize1) {
    prize2= true;
    if (prize2) {

        return 6000;
    }

}

The problem is that this happens everytime when the goal is completed and not just only once.


text:
Q: Pasar el "Login" en java y base de datos estoy tratando de hacer un login en java y mysql pero a la hora de intentar pasar el login me falla y no se el por que... me tira el mensaje de"Errrror".
tengo un JFrame con el boton de login que seria este:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    //validar
    Usuario usu1=new Usuario(TxtUsuario.getText(),txtPassword.getText());
    try
    {
        Usuarios usuarios=new Usuarios();
        int res=-1;
        res=usuarios.BuscarPorNombre(usu1);

        if(res>=0)
        {
            frmPrincipal principal=new frmPrincipal();

            principal.setVisible(true);

            this.dispose();
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Errrror");
        }
    }
    catch(Exception ex)
    {
        JOptionPane.showMessageDialog(null, ex.getMessage());
    }

}
y esta clase de usuarios con este metodo:
public int BuscarPorNombre(Usuario nuevo)
{
    String sql="select NombreUsuario,PassUsuario from usuario where NombreUsuario=?";
    int res=-1;
    try
    {
        PreparedStatement st=cnn.getConexion().prepareStatement(sql);
        st.setString(1, nuevo.NombreUsuario);
        res=st.executeUpdate();

    }
    catch(SQLException ex)
    {
        //procesar
    }
    return res;
}

A: Para leer una consulta de bd necesitas un ResultSet:
    java.sql.Resultset rs = statement.executeQuery(sql);

y para ver si encontró algo:
    boolean encontróUsuario = rs.next();

Si quieres ver la contraseña del usuario, entonces después del rs.next() agregas:
    if (encontróUsuario) {
        String contraseña = rs.getString(2); //<<ya que es la segunda columna en tu consulta sql.
    }

Por otro lado yo no cacharía la sqlException en el método para buscar, porque así vas a confundir un "cliente no encontrado, o contraseña incorrecta" con un error de sql.
Además, estás creando un PerparedStatement en cada búsqueda, y pierdes el propósito del mismo, que es tenerlo ya preparado. Yo lo tendría ya creado y lo referenciaría en cada búsqueda. Algo tipo:
    public java.sql.PreparedStatement dameStatementDeBusqueda() {
        if (statement == null) {
           ///aquí creo el pstatment, pero solo una vez.
        }
        return statement;
   }


text:
Q: Is it possible to install gcc 5+ version on redhat 5? I have developed a qt application on Ubuntu 16 but for testing I need to run it on redhat 5. But I am using c++11 standard features in my code and gcc (very old version on redhat) does not recognise this. I need to know is it possible to install gcc version (anything above than 5.0) on redhat 5?
I have already searched online but most of the links take me to redhat 7. Please note that I cannot upgrade to rhel 7.


text:
Q: Kurento Custom Plugin : How to send events to java server asynchronously I am working on Kurento custom plugin, In which I have to make some curl web request and send the audio to a server and wait for server's response. I was wondering is there any way by which we can raise events to java server from kurento custom plugin synchronously. Shall I make asyc calls to raise events or make my curl calls async ?

A: Events fired from the media server are asynchronous. Requests, on the other hand, are synchronous, as there is only one thread attending incoming requests.
I would suggest an event-based asynchronous model in all parts, so you don't block your call to your app server. If you still want to do that, you might wrap your asynchronous event in a synchronous call. You might want to have a look at some helper classes that we use for our tests: the AsyncManager and the AsyncEventManager. You can find an example of usage in any of the tests, but maybe this one is closer to what you want to achieve.


text:
Q: Graphic adapter seems installed correctly but windows is using basic driver I have Windows 10 x64 Pro build 1511 with all latest updates.
My graphic adapter ( discrete ) is an ATI radeon HD 5450.
I have installed the latest drivers downloaded from AMD site.
But now under Device Manager i can see my graphic Adapter installed correctly , but when i click on Drivers Details , i get a message : No driver files are required or have been loaded for this device
When i right click on Desktop and go to Adapter properties , i see that Windows is using "Microsoft Basic Display driver".

How can i resolve this problem ?
Thank you !

A: The latest AMD driver only works for newer cards starting with the Radeon HD 77xx cards, not the older HD5xxx cards.
You need to install this special driver for the older HD5400 card


text:
Q: is there any other way to fit the bg using html I have an JPG image with size 1024 x 724. My page size is not fixed. My requirement is: If I resize the page then the background image should also resize and fit to the page.

A: You should do this with backgroud-size  in css
If you'd like to use CSS3, you can do it pretty simply using background-size, like so:
background-size: 100%;

in you div you can add the style directly without using a css  external file
<div style ="background-size: 100%;" ....> .... </div>

A: You need to make a 100% width b aground which must cover up you complete background.
So please add this css in you style.css file.
html {
  background: url(yourimage.jpg);
  background-size:cover;
  }


text:
Q: PHP APC 5.3.8 Hangs Page Request I had difficulty finding the newest version of php_apc.dll so I went ahead and compiled it myself. I had no issue getting it compiled using NTS v5.3.8. I had two separate files set up to test, one with a simple phpinfo() call on it and the other being the standard apc.php file that comes with the apc source files.
Strangely, when I would load the phpinfo() file it would work totally fine, but when I tried to access apc.php the webserver would hang until a timeout. I restarted the webserver, accessed apc.php and it worked just fine, but trying to go back to phpinfo() would cause the server to hang until timeout. It is probably worth noting that phpmyadmin and my own codeigniter application do not work period, even after a restart.
I have tried previous versions of apc with no luck; 5.3.5 with apc.stat = 0 works but I am in need of that feature as this is a development server, but I'm testing out some production type caching.
Noteworthy stuff:
Server is powered by Nginx 1.0.8 running PHP 5.3.8 (using fast-cgi). Everything works as intended with the exception of when apc is loaded.

A: You can download the php_apc.dll from http://downloads.php.net/pierre/
You can find there different versions of it.


text:
Q: Slow file transfer speeds I have a server that is running Ubuntu Server 14.04LTS and I am currently experiencing slow network transfer speeds. This server had been running without issue now for about 2 years and suddenly I am experiencing issues. Normally transferring a single file to this server I would get 100MB/s to 115 MB/s. Currently that speed can be obtained but only for a brief period of time. About halfway through a file transfer of 4GB the speed drops to about 50MB/s then the transfer locks up and then I get an error message that says "There was a problem accessing share" and i have to cancel the file transfer.
The server and machine that the file transfer is currently running though are both connected via Cat6 Gigabit Ethernet. The server has a hardware RAID 10 storage array so drive speed and network speed isn't an issue. Like I said earlier this system has had no issues for 2 years and suddenly this came up.

A: Network transfer speeds vary.

*

*Infrastructure - This limits what you can do on the network. LAN will be more stable than WiFi and a Gigabyte connection will have more capacity to transfer files over a local connection than a 10/100Mbps connection. The routing also matters. The more hops there is from client to server would cause delays.

*Client Device - The capacity of the client's device would also be a factor. Even if the server and the network infrastructure can handle 1Gbps or a 10Gbps connection, if the Client only runs a 10/100Mbps connection, then that would be as high as the connection would go.

*Files being transferred - The type of file being transferred would also move your speed up and down. If you are transferring one big zip file, the negotiated connection speed for that file would be higher compared to a folder with a bunch of small files inside. The server and client would need to negotiate and it will not negotiate 100Mbps for a 1Mbps pdf file (for example). Therefore, moving 100GB of small files would take longer to finish, and you would expect the negotiated speed to go up and down depending on file size, than a 100GB single file or chunks of several big files.

*Network Traffic - If the network is busy, then connection would slow down.

*Disk I/O - If the disk is busy or I/O is slow, this would also be a factor. Single the transferred files need to be saved/stored.
About your transfer locking up.
Check if you still have available storage space.


text: Q: Watch variables disappear in VSCode when debugging an STM32 project I've been trying to debug an STM32 project in VSCode. I'm able to start the debugger and add variables to the watch list. However, the moment I run the code, the watch variables disappear. Is there a way to view them in real-time as the code is running? Here is a short video of what happens.


text:
Q: Indexing a numpy 2D matrix Suppose, I have this:
import numpy as np

N = 5

ids = [ 1.,          2.,          3.,          4.,          5.,        ]
scores = [ 3.75320381,  4.32400937,  2.43537978,  3.73691774,  2.5163266, ]

ids_col = ids.copy()
scores_col = scores.copy()

students_mat = np.column_stack([ids_col, scores_col])

Now, I want to manually show the ids and scores of those students whose score is more than 4.0.
How can I make the following routine work?
print(students_mat([False, True, False, False, False]))

Error
>>> (executing file "arrays.py")
Traceback (most recent call last):
  File "D:\Python\arrays.py", line 25, in <module>
    print(students_mat([False, True, False, False, False]))
TypeError: 'numpy.ndarray' object is not callable

A: #you need to convert Boolean list to an array to be used when selecting elements.
print(students_mat[np.asarray([False, True, False, False, False])])
[[ 2.          4.32400937]]


text:
Q: Convert array of time into some interval of time array in javascript? I am implementing the graph in Canvas. So I have x-axis and y-axis. I am converting both values in array form. x-axis pointed to time and y-axis pointed to volume data.
You can see screen shots for more idea:

This graph plotted based on some array.

Previously I was getting value:

for Y-axis [377,622,42,188]
  for X-axis   ["02.20","4:30","08:50","09:10"]

So I picked start time of X-axis(02.20) and end time(9:10), Divided into hours like ["02.20","03:00","4:30","05:00","06:00","07:00","08:50","09:10"].
And Y-axis put 0 in the array if data is not there of Y-axis array, According to X-axis.
call.all('data').get('navigation').then(function(resp){
      setTimeout(function(){
        var totalVolumeArr = _.map(resp.data,function(res){ return res.tot});
        lineData2.labels = _.map(resp.data,function(res,idx){
          var time = [];
          if (typeof resp.data[idx - 1] !== 'undefined') {
            if (((resp.data[idx - 1])._id.hr + 1) !== res._id.hr) {
              for (var i = resp.data[idx - 1]._id.hr + 1; i < res._id.hr; i++) {                    time.push('0' +i + ':00');
              }
            }
          }
          var x =  time.push(('0' + res._id.hr).slice(-2) + ':' + (''+ res._id.slot).slice(-2)+'0');
          return  time;
        });

        var flatArray = [].concat.apply([],  lineData2.labels);
        _.map(resp.data,function(res,idx){
          var time=[];
          var tempArr=[];
          if (typeof resp.data[idx - 1] !== 'undefined') {
            if (((resp.data[idx - 1])._id.hr + 1) !== res._id.hr) {
              for (var i = resp.data[idx - 1]._id.hr + 1; i < res._id.hr; i++) {
                if(jQuery.inArray('0' +i + ':00', flatArray) !== -1)
                {
                  var indexValue='0' +i + ':00';
                  var indexPosition= flatArray.indexOf(indexValue);
                  totalVolumeArr.splice(indexPosition, 0, "0"); //push the 0 volume value into array of totalvolumearray
                }
              }
            }
          }
          return tempArr;
        })
    xAxisValue = flatArray;
    yAxisValue = totalVolumeArr;
});

Right now I want to rearrange  these two arrays flateArray and totalValumeArr.
You can think xAxisValue = ["02.20","4:30","08:50"]
              yAxisValue= [377,622,42]
Expacted out put:
**

xAxisValue =
  ["02:20","02:30","02:40","02:50","03:00","03:10","03:10","03:20","03:30","03:40","03:50","04:00","04:10","04:20","04:30","04:40","04:50","05:00","05:10","05:20","05:30","05:40","05:50","06:00","06:10","06:20","06:30","06:40","06:50","07:00","07:10","07:20","07:30","07:40","07:50","08:00","08:10","08:20","08:30","08:40"
  "08:50"]

**
 **

yAxisValue=
  [377,0,0,0,0,0,0,0,0,0,0,0,0,0,622,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,42]

**
Above code working fine if I want to see hourly basis. But Now I want to set data 10 minutes interval of time. If data is not there then time should be there with 0 data volume. Please share your logic. Which is the best approach?


text:
Q: Cannot shuffle an array inside an array PHP Basically my problem is that i cannot shuffle an array that is inside another array. To be more specific i want to shuffle the array that is the value of 'Variante de raspuns:':
$intrebari=array(

    array('Enunt:'=>'2+2=','Variante de raspuns:'=>array(2,5,6,4),'Raspuns corect:'=>4,'Punctaj obtinut:'=>'25p'),

    array('Enunt:'=>'2*2=','Variante de raspuns:'=>array(3,4,8,1),'Raspuns corect:'=>4,'Punctaj obtinut:'=>'25p'),

    array('Enunt:'=>'2/2=','Variante de raspuns:'=>array(1,3,4,8),'Raspuns corect:'=>1,'Punctaj obtinut:'=>'25p'),

    array('Enunt:'=>'2-2=','Variante de raspuns:'=>array(2,3,0,4),'Raspuns corect:'=>0,'Punctaj obtinut:'=>'25p')

);

The function i thought of is:
function amestecVariante(&$array){
    foreach($array as $intrebare){
        foreach($intrebare as $k=>$v)
           if($k=='Variante de raspuns:')
            shuffle($v);}
}

For now i only want to display the array with the shuffled 'Variante de raspuns:'. I have another function to display it so it goes something like this in the end:
amestecVariante($intrebari);
afisare($intrebari);

The problem is that the 'Variante de raspuns' array is not shuffled and it's displayed as it is initially. Also i really want to understand why my function doesn't work, i'm not looking for another solution unless mine is no good at all. Thank you in advance.

A: Do this instead:
function amestecVariante(&$array){
    foreach($array as &$intrebare){
        shuffle($intrebare['Variante de raspuns:']);
    }
}

Demo.
You don't have to iterate over the inner arrays - you just access the array to be shuffled directly (by key). But you do need to make PHP understand that you will modify this array within foreach - that's what reference in &$intrebare is for.


text:
Q: How to improve the security in webapp webapp structure

Code I have tried
Js login layer

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Info System</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

        <el-container>
            <el-main class="main">
                <el-input v-model="account"
                          type="text"
                          class="input"
                          placeholder="Account"
                          prefix-icon="el-icon-user"
                          maxlength=10 clearable>
                </el-input>

                <el-input v-model="password"
                          type="password">
                </el-input>

                <el-button type="success" @click="sign('/info/sign-in')">login in</el-button>
                <el-button type="success" @click="sign('/info/sign-up')">login up</el-button>
                <el-switch v-model="autoSign"
                           @change="changeAutoSign()"
                           active-color="#13ce66"
                           inactive-color="#909399"
                           active-text="auto login in">
                </el-switch>
            </el-main>
        </el-container>

Java controller layer
// */controller/UserController.java
@RestController
public class UserController {
    private final UserRepository repository;

    public UserController(UserRepository repository) {
        this.repository = repository;
    }

    // use response code 100~199
    @PostMapping("/info/sign-up")
    SignResponse signUp(@RequestBody User user) {
        if (repository.existsByAccount(user.getAccount())) {
            return new SignResponse(101, "");
        } else {
            user.updateToken();
            repository.save(user);
            return new SignResponse(100, user.getToken());
        }
    }

    // use response code 200~299
    @PostMapping("/info/sign-in")
    SignResponse signIn(@RequestBody User user) {
        if (!repository.existsByAccount(user.getAccount())) {
            return new SignResponse(201, "");
        }
        User realUser = repository.findByAccount(user.getAccount());
        if (realUser.getPassword().equals(user.getPassword())) {
            realUser.updateToken();
            repository.save(realUser);
            return new SignResponse(200, realUser.getToken());
        } else {
            return new SignResponse(202, "");
        }
    }
}

I know the info display in front-end is not safe, but I have no idea to do something in back-end.
If someone wants to attack my system and get information, it will be troublesome.
Problem

*

*How to improve the security of the login section? What strategy should I use?

*Other suggestions also help.

A: *

*You should try use SSL certificate on your front-end/back-end to ensure that data transferred is not visible explicitly, is private and integral link here.

*Maybe you should wonder about something like Basic Authentication. It's additional information in HTTP Header with credentials. Check this out.

*Never store passwords as plain text. Use something like BCrypt with random salt added. Try this.


text:
Q: MsBuild XmlPeek result splitting values In my MsBuild script (*.proj) I'm querying C# project using XmlPeek for build configurations and getting the value of Condition attribute of PropertyGroup. Here is the working code:
      <Target Name="xPeek">
    <XmlPeek Namespaces="<Namespace Prefix='msb' Uri='http://schemas.microsoft.com/developer/msbuild/2003'/>"
             XmlInputPath=" D:\source\MyProject.csproj"
             Query="/msb:Project/msb:PropertyGroup[contains(@Condition,'Debug')]/@Condition">
      <Output TaskParameter="Result" ItemName="Peeked" />
    </XmlPeek>

   <Message Text="%(Peeked.Identity)" />
  </Target>

And here is the output:

'Release    |AnyCPU' == 'Debug|AnyCPU'
  'Release    |AnyCPU' == 'Debug.v9|AnyCPU'
  'Release    |AnyCPU' == 'Debug.v10|AnyCPU'
  'Release    |AnyCPU' == 'Debug.v101|AnyCPU'

Now I need to split these on '==' and I'm confused here that how to create another ItemGroup or PropertyGroup while splitting the string.
%(Peeked.Identity).Split('==') doing nothing.
Question 1: How to use Split on this ItemGroup while splitting all its values?
Question 2: In addition, is it possible to get splitted values from XQuery used in XmlPeek?

A: The XmlPeek task doesn't allow addiontinal Xslt functions to be executed. Unfortunately there are no build-in string functions in msbuild.
I have two solutions for you: One with amn XslTranformation and one with an Exec of a command.
XslTransform
You can use the XslTransformation task to take your build file and run a transformation over it leveraging the substring-before and substring-after xslt functions. The output is stored in a file (test-xslt.out in my case) and with ReadLinesfromFile read and converted to Items.
There is one caveat: The variables are not replaced in this scenario whereas for the XmlPeek one they are.
The safexml encoded version looks like this:
   <XslTransformation XmlInputPaths = "test-xslttrans.csproj"
      XslContent="
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003"
>
   <xsl:output method="text" indent="yes" />

  <xsl:template match="text()|@*"/>

  <xsl:template match="/msb:Project/msb:PropertyGroup[contains(@Condition,'Debug')]">
<xsl:value-of select="substring-before(@Condition,'==')"/>
<xsl:text>
</xsl:text>
<xsl:value-of select="substring-after(@Condition,'==')"/>
<xsl:text>
</xsl:text>
  </xsl:template>
</xsl:stylesheet>   "
      OutputPaths = "test-xslt.out">

    </XslTransformation>

    <ReadLinesFromFile
              File="test-xslt.out" >
              <Output
                  TaskParameter="Lines"
                  ItemName="SplittedPeek"/>
    </ReadLinesFromFile>

    <Message Text="%(SplittedPeek.Identity)" />

for convenience here is the plain xslt:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003">

  <xsl:output method="text" indent="yes" />
  <xsl:template match="text()|@*"/>
  <xsl:template match="/msb:Project/msb:PropertyGroup[contains(@Condition,'Debug')]" >
<xsl:value-of select="substring-before(@Condition,'==')"/>
<xsl:text>
</xsl:text>
<xsl:value-of select="substring-after(@Condition,'==')"/>
<xsl:text>
</xsl:text>
  </xsl:template>
</xsl:stylesheet>

Command Exec
This solution writes your Peeked values to a file. By invoking the FOR /F commamnd of the command processor we can parse lines and split them within some strict boundaries which fitted well here. The output of the EXEC is written to a file split.txt. The ReadLinesFromFiles is used to read the values in an Item.
 <WriteLinesToFile
          File="test-xslt-write.out"
          Lines="@(Peeked)"
          Overwrite="true"
          Encoding="ASCII"/>

 <Exec Command="for /f "tokens=1* delims==" %%a in (test-xslt-write.out) do @echo %%a > split.txt"/>
 <Exec Command="for /f "tokens=1* delims==" %%a in (test-xslt-write.out) do @echo %%b >> split.txt"/>

<ReadLinesFromFile
          File="test-xslt.out" >
          <Output
              TaskParameter="Lines"
              ItemName="SplittedCmdPeek"/>
</ReadLinesFromFile>

<Message Text="%(SplittedCmdPeek.Identity)" />


text:
Q: Magento 1.9.3 call custom block in Payment Information Am using magento 1.9.3 here how to call custom block in payment information section.
This is my custom block code:
app\design\frontend\{theme_name}\default\layout\epayment.xml
<?xml version="1.0"?>
<layout version="0.1.0">
  <epayment_index_index>
    <reference name="root">
      <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
    <reference name="content">
      <block type="epayment/index" name="epayment_index" template="epayment/index.phtml"/>
    </reference>
  </epayment_index_index>
</layout>

app\design\frontend\{thene_name}\default\template\epayment\index.phtml
    <?php
    $customer_details = Mage::getSingleton('core/session')->getEpayment();

    $checkout_email = Mage::getSingleton('checkout/session')->getQuote()->getBillingAddress()->getEmail();
    foreach($customer_details as $customer_detail)
    {
        $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
        $sql = "SELECT * FROM epayment WHERE customer_email='".$customer_detail['customer_email']."'";
        $rows = $connection->fetchRow($sql);

        if($customer_detail['customer_email'] == $checkout_email) {
?>

            <?php
            if(Mage::getSingleton('core/session')->getLeftAmount() == false){
                $collapse = 'collapse';
            ?>
                <input id="epayment" value="" type="checkbox" name="payment[method]" title="Payment By Your EPayment" class="pull-left" autocomplete="off" data-toggle="collapse" data-target="#demo">
            <?php
            } else {
            $collapse = 'in';
            ?>
                <input id="epayment" value="" type="checkbox" name="payment[method]" title="Payment By Your EPayment" class="pull-left" checked="" autocomplete="off" data-toggle="collapse" data-target="#demo">
            <?php } ?>
               Payment By EPayment

    <div class="panel-body <?php echo $collapse; ?>" id="demo">

                Value of your Order
                <input type="text" name="cart_amount" id="cart_amount" value="<?php echo round(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); ?>">

                Amount available in Wallet
                <input type="text" name="epayment_amount" id="epayment_amount" value="<?php echo  $rows['epayment_balance']; ?>">

Remaining:  will be carried in your wallet

                Left Amount To Be Pay
                <input type="text" name="left_amount" id="left_amount" value="">

<?php } } ?>

I have try this code in payment information section but not showing:
app\design\frontend\{theme_name}\default\template\checkout\onepage\payment\methods.phtml
<?php
  echo $this->getLayout()->createBlock('epayment/index')->setTemplate('epayment/index.phtml')->toHtml();
?>

A: I think your below code is right
<?php
    echo $this->getLayout()->createBlock('epayment/index')->setTemplate('epayment/index.phtml')->toHtml();
?>

Please check yourindex.phtml file line by line check where error is


text:
Q: What is the best way to bind PhoneGap events (like backbutton) to views in ember.js I'm playing with PhoneGap and emberjs (trying to build "proof of concept" mobile/HTML5 application based on ember.js).
Ember.js itself works fine, but I haven't found any good way to "bind" PhoneGap events to views.
For instance, I would like to handle backbutton event and remove a view on it. It would be nice to define behavior in view class and call document.addEventListener when instance of the view is appended and call document.removeEventListener when view instance removed.

A: I did something like that on SC2.0 gist.
Take a look at the event dispatcher  to see how to add custom delegate events on views.
It should not be much difficult to inject this at the app start routine.
I hope it helps you.


text:
Q: problems with nivo slider light and menu dropdown Hi I have a problem with the nivo slider light in wordpress
and menu dropdown
When I try to down to the other "section" the menu dissapear
This is a problem with z-index or something??
Very thanks
The link is the above
http://www.pymedia.cl/st/

A: It seems like the issue is related to CSS of the <span> tags inside the <a> tags of your menu's <li>. Could you try just removing those spans temporarily or the CSS applied to them?


text:
Q: Hide table column with vue js Hello i need to hide or show columns of my datatable, I do not know what the good practice to do this, When columns checkboxes is checked the columns will shown and if it's not checked the column will be hidden?
I'm using vuetify
https://codepen.io/anon/pen/rmXwYG?editors=1010
This my script :
new Vue({
    el: '#app',
    data() {
      return {
        search: '',
        totalItems: 0,
        items: [],
        loading: true,
        pagination: {},
        columns: [],
        headers: [{
                text: 'Dessert (100g serving)',
                left: true,
                sortable: false,
                value: 'name'
            },
            {
                text: 'Calories',
                value: 'calories'
            },
            {
                text: 'Fat (g)',
                value: 'fat'
            },
            {
                text: 'Carbs (g)',
                value: 'carbs'
            },
            {
                text: 'Protein (g)',
                value: 'protein'
            },
            {
                text: 'Sodium (mg)',
                value: 'sodium'
            },
            {
                text: 'Calcium (%)',
                value: 'calcium'
            },
            {
                text: 'Iron (%)',
                value: 'iron'
            }
        ]
    }
    },
    watch: {
        pagination: {
            handler() {
                this.getDataFromApi()
                    .then(data => {
                        this.items = data.items
                        this.totalItems = data.total
                    })
            },
            deep: true
        }
    },
    mounted() {
        this.getDataFromApi()
            .then(data => {
                this.items = data.items
                this.totalItems = data.total
            })
    },
    methods: {
        getDataFromApi() {
            this.loading = true
            return new Promise((resolve, reject) => {
                const {
                    sortBy,
                    descending,
                    page,
                    rowsPerPage
                } = this.pagination

                let items = this.getUsers()
                const total = items.length

                if (this.pagination.sortBy) {
                    items = items.sort((a, b) => {
                        const sortA = a[sortBy]
                        const sortB = b[sortBy]

                        if (descending) {
                            if (sortA < sortB) return 1
                            if (sortA > sortB) return -1
                            return 0
                        } else {
                            if (sortA < sortB) return -1
                            if (sortA > sortB) return 1
                            return 0
                        }
                    })
                }

                if (rowsPerPage > 0) {
                    items = items.slice((page - 1) * rowsPerPage, page * rowsPerPage)
                }

                setTimeout(() => {
                    this.loading = false
                    resolve({
                        items,
                        total
                    })
                }, 1000)
            })
        },
        getUsers() {
            return [{
                    value: false,
                    name: 'Frozen Yogurt',
                    calories: 159,
                    fat: 6.0,
                    carbs: 24,
                    protein: 4.0,
                    sodium: 87,
                    calcium: '14%',
                    iron: '1%'
                },
                {
                    value: false,
                    name: 'Ice cream sandwich',
                    calories: 237,
                    fat: 9.0,
                    carbs: 37,
                    protein: 4.3,
                    sodium: 129,
                    calcium: '8%',
                    iron: '1%'
                },
                {
                    value: false,
                    name: 'Eclair',
                    calories: 262,
                    fat: 16.0,
                    carbs: 23,
                    protein: 6.0,
                    sodium: 337,
                    calcium: '6%',
                    iron: '7%'
                },
                {
                    value: false,
                    name: 'Cupcake',
                    calories: 305,
                    fat: 3.7,
                    carbs: 67,
                    protein: 4.3,
                    sodium: 413,
                    calcium: '3%',
                    iron: '8%'
                },
                {
                    value: false,
                    name: 'Gingerbread',
                    calories: 356,
                    fat: 16.0,
                    carbs: 49,
                    protein: 3.9,
                    sodium: 327,
                    calcium: '7%',
                    iron: '16%'
                },
                {
                    value: false,
                    name: 'Jelly bean',
                    calories: 375,
                    fat: 0.0,
                    carbs: 94,
                    protein: 0.0,
                    sodium: 50,
                    calcium: '0%',
                    iron: '0%'
                },
                {
                    value: false,
                    name: 'Lollipop',
                    calories: 392,
                    fat: 0.2,
                    carbs: 98,
                    protein: 0,
                    sodium: 38,
                    calcium: '0%',
                    iron: '2%'
                },
                {
                    value: false,
                    name: 'Honeycomb',
                    calories: 408,
                    fat: 3.2,
                    carbs: 87,
                    protein: 6.5,
                    sodium: 562,
                    calcium: '0%',
                    iron: '45%'
                },
                {
                    value: false,
                    name: 'Donut',
                    calories: 452,
                    fat: 25.0,
                    carbs: 51,
                    protein: 4.9,
                    sodium: 326,
                    calcium: '2%',
                    iron: '22%'
                },
                {
                    value: false,
                    name: 'KitKat',
                    calories: 518,
                    fat: 26.0,
                    carbs: 65,
                    protein: 7,
                    sodium: 54,
                    calcium: '12%',
                    iron: '6%'
                }
            ]
        }
    }
})

A: Short answer is use computed properties to decide what columns are going to be included.
Your data table is taking a list of headers and a list of items (rows). I've added a couple of computed properties to your Vue to return the list of columns that should be included in the data table results.
computed:{
  filteredHeaders(){
    return this.headers.filter(h => h.selected)
  },
  filteredItems(){
    return this.items.map(item => {
      let filtered = Object.assign({}, item)
      this.headers.forEach(header => {
        if (!header.selected) delete filtered[header.value]
      })
      return filtered
    })
  }
},

Notice that these computed values are using a property of the header called selected. I added that property to your list of headers to allow you to select the headers that are going to be included in the output.
{
  text: 'Fat (g)',
  value: 'fat',
  selected: true
},

Next, your checkboxes need to use that property as their model.
<v-checkbox v-bind:label="header.text" v-model="header.selected" :value="header.selected" ></v-checkbox>

Finally, you have a template for each row. I modified that to check to see if each column is enabled.
<template slot="items" scope="props">
  {{ props.item.name }}
  {{ props.item.calories }}
  {{ props.item.fat }}
  {{ props.item.carbs }}
  {{ props.item.protein }}
  {{ props.item.sodium }}
  {{ props.item.calcium }}
  {{ props.item.iron }}
</template>

And here is the showColumn method that is used in that template.
showColumn(col){
  return this.headers.find(h => h.value === col).selected
},

Finally, here is a working example.
Obviously this is not tuned or anything, it's just an initial "get it working" version. But it should get you going.

A: Just set the fields prop to define only the columns you wish to display.

A: Loop all the fields as well
example :

Enjoy.


text:
Q: InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly After deploying ASP.NET Core app to azure and opening the site, I get the following error:

InvalidOperationException: Could not find 'UserSecretsIdAttribute' on
  assembly '******, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'.

The exception details also include that the error happens at Startup.cs on this line of code:

builder.AddUserSecrets();

Thank you

A: I want to add to this answer, for those in my situation.
I am writing a .NET Core console app, trying to use the secrets manager (not sure it's meant for console apps). The only way I was able to rid myself of the error was using the assembly level attribute on the assembly where I was using the secrets manager.
As I said, I am not sure if the secrets manager is meant for console apps. So maybe there is an issue with .xproj files vs. .csproj files.

A: There was an update to the user secrets module just recently. Version 1.0.1 and up now requires you specify an assembly-level attribute for the id of the user secrets, or as a fallback, the way it was previously in project.json.
Here is the announcement on GitHub: https://github.com/aspnet/Announcements/issues/209
You can define the secrets id in the .csproj like this:
<PropertyGroup>
  <UserSecretsId>aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed</UserSecretsId>
</PropertyGroup>

This generates the following assembly-level attribute. Alternatively, instead of adding it in the .csproj file, you can of course add it yourself e.g. to Startup.cs:
[assembly: UserSecretsId("aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed")]

Also, you should use:
builder.AddUserSecrets<Startup>();

It will search for that attribute in the assembly of the given type, in this case I used the Startup class.
Note: this will be deprecated in 2.0: (1.0.2 and 1.1.1 have marked it obsolete)
builder.AddUserSecrets();

I checked the source code for the user secrets configuration, and calling AddUserSecrets() without the type does this:
var attribute = entryAssembly.GetCustomAttribute<UserSecretsIdAttribute>();
if (attribute != null)
{
     return AddUserSecrets(configuration, attribute.UserSecretsId);
}

// try fallback to project.json for legacy support
try
{
     var fileProvider = configuration.GetFileProvider();
     return AddSecretsFile(configuration, PathHelper.GetSecretsPath(fileProvider));
}
catch
{ }

// Show the error about missing UserSecretIdAttribute instead an error about missing
// project.json as PJ is going away.
throw MissingAttributeException(entryAssembly);

It's trying to find the UserSecretsId attribute on your assembly, and failing that, checking if it could find it in project.json. Then (as commented) returns an error about the missing attribute as they wouldn't want to complain about project.json anymore as it is being deprecated.

A: My .NET Core 3.1 Worker Service required additional setup (more than a Web project).
In Program.cs in the CreateHostBuilder method I needed this:
.ConfigureAppConfiguration((ctx, builder) =>
                {
                    // enable secrets in development
                    if (ctx.HostingEnvironment.IsDevelopment())
                    {
                        builder.AddUserSecrets<Worker>();
                    }
                })

But (unlike my Web project) I explicitly needed to add this nuget package:
install-package Microsoft.Extensions.Configuration.UserSecrets

After that I could access secrets.


text:
Q: Is there any way to get a collection of all the javax.sql.DataSource that are configured as beans within a Spring Application/Container? Given that one can construct a datasource bean as follows:
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url2}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="dataSource3" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url3}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

Is there a way to get a collection of all these datasources without having to explicitly reference the beans through their identifier? e.g. getBean("dataSource3"). Does the container or the application context offer any help here?
In essence given a configuration file with all beans already defined, in spring is it possible to implement?
Collection<DataSource> getAllRegisteredDataSources();

Many Thanks

A: Yes there are two approaches you can take to solving this problem.
The first approach, basic approach, would be to create a master configuration and auto-wire additional configurations and through the auto-wired context you can construct the collection of Datasources
  @Configuration
  @Import({ DataSourceAConfig.class }) // Import additional configuration files as required
  public class MasterConfig {

          @Autowired DataSourceAConfig dataSourceAConfigContext;

            @Bean public List<DataSource> getAllDataSources(){
                 DataSource dataSourceA = dataSourceAConfigContext.getDataSourceBean()
                 // Add data in sequentially way, one after the other
                return Arrays.asList(dataSourceA);
     }
  }

The second approach; the approach that I recommend would be to have a look at the actuator services that are shipped with Spring boot applications, in particular those around the metrics.
http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html
They give additional information beyond the number of active data sources; including resource utilisation and health checks.
Hope it helps.


text:
Q: How to query Xml file using java I am having Xml file which contains about 50 Tables  <tables></tables>. All tables are linked to each other.
<table name="Information">
        <row>
            <field name="aggregateMID">123</field>
            <field name="MID">345</field>
            <field name="sequenceNum">1</field>
        </row>
        <row>
            <field name="aggregateMID">123</field>
            <field name="MID">346</field>
            <field name="sequenceNum">2</field>
        </row>
</table>

Can it be possible to query xml according to linking and fetch all required information? Please suggest what methods and API's will help me to do this job.

A: You can parse the XML file using a Java DOM Parser.

you can try this.

try {
    Document document = builder.parse(new FileInputStream("c:\\table.xml"));
} catch (SAXException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

You can refer these links:
http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/
http://www.journaldev.com/1194/java-xpath-tutorial-with-examples

A: I assume you have good reason not to use XPATH/XSLT directly.
If you want sql like queries, may be you can take a look at XQUERY
Also, please remember that Xquery doesn't come with JAVA by dafault. You have to download a suitable implementation jar from internet

A: The answer is probably XQuery, but we can't be sure until we see the question.


text:
Q: Is there any way to put iMac to sleep (or other low power mode) while using it in target display mode? When I connect to my mid-2010 27" iMac in Target Display Mode, fans hum and hard disks spin (with occasional I/O). Being logged out in iMac's macOS doesn't help.
Is it possible to lower this unnecessary power drag or at least minimize the noise? Can I boot iMac as a dumb-display?

A: No, you cannot go into low power mode while in Target Display mode.
While your iMac is "acting" as a "passthrough" for you display signals you are not bypassing the logic board and GPU to connect to the display.  The iMac display is still connected to the internal logic board and GPU and that GPU is required to display images on the screen.
The fans are coming on because the SMC in the iMac has calculated (based on input from the temp sensors) that it has reached a certain temperature threshold and it needs to cool down.  Remember, your GPU and logic board is hard at work taking DispayPort and/or Thunderbolt input and converting it to displayable graphics.
If you want a "dumb" monitor, the best option is to get a dumb monitor.


text:
Q: INT_4_BYTES macro definition is the macro INT_4_BYTES is a standard one and defined in one of the .h files that come with the compiler?
Same question regarding the int32 typedef.

A: Don't know about INT_4_BYTES or int32 (which do not look standard at all, they might be specific to some compiler or library); if you're looking for standard types for 32-bit integers, you might want to #include <stdint.h> and use the int32_t (singed) and uint32_t (unsigned) types.

A: If you have an IDE that you are coding in, you may be able to right click on the element and traverse to the definition.  Then see where it is defined.
Visual Studio: Right Click -> "Go To Definition (F12)"
Eclipse: Right Click -> "Open Declaration (F3)"


text:
Q: ERROR streaming.StreamJob: Job not successful I install Hadoop 2.9.0 and I have 4 nodes. The namenode and resourcemanager services are running on master and datanodes and nodemanagers are running on slaves. Now I wanna run a python MapReduce job. But Job not successful!
Please tell me what should I do?
Log of running of job in terminal:
hadoop@hadoopmaster:/usr/local/hadoop$ bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.9.0.jar -file mapper.py -mapper mapper.py -file reducer.py -reducer reducer.py -input /user/hadoop/* -output /user/hadoop/output
18/06/17 04:26:28 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead.
18/06/17 04:26:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
packageJobJar: [mapper.py, /tmp/hadoop-unjar3316382199020742755/] [] /tmp/streamjob4930230269569102931.jar tmpDir=null
18/06/17 04:26:28 INFO client.RMProxy: Connecting to ResourceManager at hadoopmaster/192.168.111.175:8050
18/06/17 04:26:29 INFO client.RMProxy: Connecting to ResourceManager at hadoopmaster/192.168.111.175:8050
18/06/17 04:26:29 WARN hdfs.DataStreamer: Caught exception
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1249)
    at java.lang.Thread.join(Thread.java:1323)
    at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:980)
    at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:630)
    at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:807)
18/06/17 04:26:29 WARN hdfs.DataStreamer: Caught exception
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1249)
    at java.lang.Thread.join(Thread.java:1323)
    at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:980)
    at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:630)
    at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:807)
18/06/17 04:26:29 INFO mapred.FileInputFormat: Total input files to process : 4
18/06/17 04:26:29 WARN hdfs.DataStreamer: Caught exception
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1249)
    at java.lang.Thread.join(Thread.java:1323)
    at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:980)
    at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:630)
    at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:807)
18/06/17 04:26:29 INFO mapreduce.JobSubmitter: number of splits:4
18/06/17 04:26:29 INFO Configuration.deprecation: yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
18/06/17 04:26:29 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1529233655437_0004
18/06/17 04:26:30 INFO impl.YarnClientImpl: Submitted application application_1529233655437_0004
18/06/17 04:26:30 INFO mapreduce.Job: The url to track the job: http://hadoopmaster.png.com:8088/proxy/application_1529233655437_0004/
18/06/17 04:26:30 INFO mapreduce.Job: Running job: job_1529233655437_0004

18/06/17 04:45:12 INFO mapreduce.Job: Job job_1529233655437_0004 running in uber mode : false
18/06/17 04:45:12 INFO mapreduce.Job:  map 0% reduce 0%
18/06/17 04:45:12 INFO mapreduce.Job: Job job_1529233655437_0004 failed with state FAILED due to: Application application_1529233655437_0004 failed 2 times due to Error launching appattempt_1529233655437_0004_000002. Got exception: org.apache.hadoop.net.ConnectTimeoutException: Call From hadoopmaster.png.com/192.168.111.175 to hadoopslave1.png.com:40569 failed on socket timeout exception: org.apache.hadoop.net.ConnectTimeoutException: 20000 millis timeout while waiting for channel to be ready for connect. ch : java.nio.channels.SocketChannel[connection-pending remote=hadoopslave1.png.com/192.168.111.173:40569]; For more details see:  http://wiki.apache.org/hadoop/SocketTimeout
    at sun.reflect.GeneratedConstructorAccessor38.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:824)
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:774)
    at org.apache.hadoop.ipc.Client.getRpcResponse(Client.java:1497)
    at org.apache.hadoop.ipc.Client.call(Client.java:1439)
    at org.apache.hadoop.ipc.Client.call(Client.java:1349)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:227)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:116)
    at com.sun.proxy.$Proxy82.startContainers(Unknown Source)
    at org.apache.hadoop.yarn.api.impl.pb.client.ContainerManagementProtocolPBClientImpl.startContainers(ContainerManagementProtocolPBClientImpl.java:128)
    at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:422)
    at org.apache.hadoop.io.retry.RetryInvocationHandler$Call.invokeMethod(RetryInvocationHandler.java:165)
    at org.apache.hadoop.io.retry.RetryInvocationHandler$Call.invoke(RetryInvocationHandler.java:157)
    at org.apache.hadoop.io.retry.RetryInvocationHandler$Call.invokeOnce(RetryInvocationHandler.java:95)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:359)
    at com.sun.proxy.$Proxy83.startContainers(Unknown Source)
    at org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher.launch(AMLauncher.java:122)
    at org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher.run(AMLauncher.java:307)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.hadoop.net.ConnectTimeoutException: 20000 millis timeout while waiting for channel to be ready for connect. ch : java.nio.channels.SocketChannel[connection-pending remote=hadoopslave1.png.com/192.168.111.173:40569]
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:534)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:687)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:790)
    at org.apache.hadoop.ipc.Client$Connection.access$3500(Client.java:411)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1554)
    at org.apache.hadoop.ipc.Client.call(Client.java:1385)
    ... 19 more
. Failing the application.
18/06/17 04:45:13 INFO mapreduce.Job: Counters: 0
18/06/17 04:45:13 ERROR streaming.StreamJob: Job not successful!
Streaming Command Failed!

A: OK. I found the reason of problem. In fact, the following error should be resolved:

hadoopmaster.png.com/192.168.111.175 to hadoopslave1.png.com:40569
  failed on socket timeout exception

So just did:
sudo ufw allow 40569


text:
Q: Are there any implementations/examples of hierarchical classifiers? Currently, I'm using Scikit-learn in Python 3.6 to classify data with a 7-8 classes (e.g. [C, A.1, A.2, B.3, B.1.1, B.1.2, B.2.1, B.2.2] represented by dark borders below) but I started realizing that there is an inherent hierarchy in these groups that could be used during classification.  I was going to write my own algorithm but I don't want to reinvent the wheel if one exists.
Does an algorithm that can predict class-labels in hierarchical manner like this exist (preferably in Python)? If not, are there any examples of an approach like this being used?  It reminds me of layers in a neural network but I do not have nearly enough samples for a neural net.
For example, A.1 and A.2 in Level-1 are subgroups of Level-0_A.  Level-0_C has no subgroups.

A: I couldn't find an implementation of Hierarchical Classification on scikit-learn official documentation. But I found this repository recently. This module is based on scikit-learn's interfaces and conventions. I hope this will be useful.
https://github.com/globality-corp/sklearn-hierarchical-classification
It's possible to install it with pip:
pip install sklearn-hierarchical-classification

A thorough usage example is provided in the repo .

A: If anyone stumbles across this, check out the package I developed to handle this type of data.
Here's the tutorial investigating antibiotic resistance
The peer-reviewed publication is Espinoza-Dupont et al. 2021

A: We just released a new library compatible with scikit-learn to create local hierarchical classifiers.
It can be easily installed with pip install hiclass or conda install hiclass. Documentation and examples can be found at https://gitlab.com/dacs-hpi/hiclass.
I hope this will be useful for future readers. :)