text:
Q: Changing the order of crossreferences in biblatex footnotes I'm trying to use biblatex-dw and the crossref functionality to make my bibliography more structured and easier to edit. I'm using the mvcollection, collection, and incollection types for the inheritance/tree structure. My problem is that when I define things as in the MWE below, the footnote comes out wrong.
What I want to achieve -- but only for the archival document types -- is to organize the data into a hierarchy, starting with the most detailed (i.e. the specific document) and ending with the leaste detailed (i.e. the archive institution where the archive is situated):
document - volume - archive - archive institution
Therefore, the date would look strange at the end of the line as it refers to the document and not the archive institution. I think it looks much better if the data is clustered. But for normal references like books and articles, I agree the default biblatex ordering is great.
See image example below.
Update: I also tried this with biblatex-chicago and the same thing happens there.
\documentclass{article}
\usepackage[backend=biber,citestyle=verbose-ibid,style=footnote-dw,autocite=footnote,idembibformat=dash,idemtracker=false,pageref=true,xref=true, date=iso8601]{biblatex}

\begin{filecontents*}{refs.bib}
@mvcollection{MA,
    title = {Museum archives},
}

@collection{ClockExhib,
    crossref = {MA},
    title = { Clocks Project},
}

@incollection{foo,
    crossref = {ClockExhib},
    author = {Committee},
    title = {Meeting notes},
    volume = 1,
    date = {1979-11-19},
}

\end{filecontents*}
\bibliography{refs}

\begin{document}

This is a document.\autocites{foo}

\end{document}

I want to change the order of the details (and as a bonus also learn how to change the field separators...commas, dots, or whatever).
Any ideas would be much appreciated.
By the way, I really want to stick to biblatex-dw.
Actual output of footer:

Desired output:


text: Q: Existence of connection with full holonomy Suppose $P$ is a $G$ principal bundle over a connected manifold $M$. I am struggling with a question: Does always exist a connection $\omega$ with holonomy being equal $G$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load image from database in orbeon form I have created webservice that produce xml which contain student id and image in encoded string:
<formDetail>
<documentId>333333</documentId>
<encodedImage>
 image in encode string
</encodedImage>
</formDetail>

I want to display this information in initial form load
 in orbeon form I have following model
<xf:model>
    <xf:instance id="formDetails-instance">
        <formDetails xmlns="">
            <formDetail>
                <documentId/>
                <encodedImage/>
            </formDetail>
        </formDetails>
    </xf:instance>

    <xf:instance id="formDetail-template">
        <formDetail xmlns="">
            <documentId/>
            <encodedImage/>
        </formDetail>
    </xf:instance>

    <xf:submission id="load-data-submission" method="get"
      serialization="none" mediatype="application/xml"
      resource="http://localhost:8080/webformservice/services/config/xml/barcode/333333"
      replace="instance" instance="formDetail-template"/>
  </xf:model>

in body I have set value as follows
      <xf:group ref="formDetail">
        <xf:input ref="formId">
            <xf:label ref="instance('formDetail-template')/formId"/>
        </xf:input>
       <xh:img class="site-navigation" src="xxf:instance('formDetail-template')/formDetail/encodeImage"/>
      </xf:group>

Image is not display
How can I load image from DB basically I want to load data from webservice with image detail as byte stream (encoded string) and display it in orbeon form

A: If the URL of the image is reachable from the browser, you can do it this way:
<xh:img
    class="site-navigation"
    src="{xxf:instance('formDetail-template')/formDetail/encodeImage}"/>

Otherwise, instead of using xh:img, try the following:
<xf:output
    mediatype="image/*"
    ref="xxf:instance('formDetail-template')/formDetail/encodeImage"/>


text:
Q: problem with missing values for calculating the median I'm having problem with managing with NAs to calculate median by using multiple matrix.
This is an example of the code and data I'm working on:
#Data example

m1 = matrix(c(2, 4, 3, 1),nrow=2, ncol=2, byrow = TRUE)
m2 = matrix(c(NA, 5, 7, 9),nrow=2, ncol=2, byrow = TRUE)
m3 = matrix(c(NA, 8, 10, 14),nrow=2, ncol=2, byrow = TRUE)

Median calculation

apply(abind::abind(m1, m2, m3, along = 3), 1:2, median)
         [,1] [,2]
     [1,] NA    5
     [2,]  7    9

As expected the the function doesn't return a value for cells which contains NAs.
The problem is that if I replace NAs with 0 I'll get an output like this:
#Data example
m1 = matrix(c(2, 4, 3, 1),nrow=2, ncol=2, byrow = TRUE)
m2 = matrix(c(0, 5, 7, 9),nrow=2, ncol=2, byrow = TRUE)
m3 = matrix(c(0, 8, 10, 14),nrow=2, ncol=2, byrow = TRUE)

Median calculation

apply(abind::abind(m1, m2, m3, along = 3), 1:2, median)
         [,1] [,2]
     [1,]  0    5
     [2,]  7    9

I'm trying instead to get an output where cells which reports NAs are just skipped so that only values are take into consideration. As in the example, if I have cells with NA, NA, 2 I would expect to get 2 as result while (out of the example) for cells with NA,2,5 I would expect 3.5 as result.
         [,1] [,2]
     [1,]  2    5
     [2,]  7    9

Do you have an idea of how I could get this results? Any suggestion would be appreciated, thanks.

A: Just pass the argument na.rm=TRUE inside apply
apply(abind::abind(m1, m2, m3, along = 3), 1:2, median, na.rm = TRUE)

Output:
     [,1] [,2]
[1,]    2    5
[2,]    7    9

A: Perhaps you should drop de NA's first? Try adding na.rm = TRUE


text:
Q: In Node.js, how can I return a Promise from vm2? I have some asynchronous JavaScript code, which I'd like to run using vm2 / NodeVM.
The code tests two functions: a user-submitted function evenAndOdd and a pre-defined function solution using Node's built-in assert library.
My question is, how can I get the my resolved Promise out of vm.run()?
The Aynchronous Code
This is the test code I want to turn into a string and run using vm2:
const assert = require('assert');

function evenAndOdd(arr) {
  return [arr.filter(el => el % 2 === 0).sort(), arr.filter(el => el % 2 === 1).sort()];
};

function solution(arr) {
  return [arr.filter(el => el % 2 === 0).sort(), arr.filter(el => el % 2 === 1).sort()];
};

const runTest = async () => {

  return new Promise((resolve, reject) => {

    const map = new Map();
    const tests = 10;

    for (let i = 0; i < tests; i++) {

      let randLength = parseInt(Math.random() * 19 + 1);
      let randArray = [...Array(randLength)].map(e => ~~(Math.random() * randLength));

      const test = async () => {
        return assert.deepEqual(evenAndOdd(randArray), solution(randArray));
      }

      const description = "TEST CASE: evenAndOdd([" + randArray + "}]) EXPECT: [[" + solution(randArray)[0] + "], [" + solution(randArray)[1] + "]] GOT: [[" + evenAndOdd(randArray)[0] + "], [" + evenAndOdd(randArray)[1] + "]]";

      test()
        .then(() => {
          map.set(description, true);
          if (map.size === tests) {
            resolve(map);
          };
        })
        .catch(() => {
          map.set(description, false);
          if (map.size === tests) {
            resolve(map);
          };
        })
    }
  })
}

If I append the following code, I get exactly what I want logged to the console:
runTest().then((result) => {
  console.log(result)
});

The vm Code
My question is, how do I get the resolved promise from vm.run()?
const { NodeVM } = require('vm2');

  const vm = new NodeVM({
    console: 'inherit',
    sandbox: {},
    require: {
      external: true,
      builtin: ['assert'],
      import: ['assert'],
      root: "./",
    },
  });

const result = vm.run(stringifiedJavaScript, 'vm.js');

Right now, the result variable above is undefined.

A: NodeVM.run() executes the code and returns the module created by the execution, which can then be accessed by the host code. In order to access the result of the computation in the processed code, you should assign it to module.exports.
Consider the following example:
const {NodeVM} = require("vm2");
const vm = new NodeVM();

const vmExports = vm.run('module.exports.pr = Promise.resolve(42);');

vmExports.pr.then(x => console.log(x));

The variable vmExports holds the module exported by the run call, and the field vmExports.pr holds the promise produced by the sandboxed script. The exported promise is thenable or can be awaited to access the resolved values.

A: You can also directly return the promise from your code.
Setting the wrapper option to none will return the value returned by the code as stated here https://github.com/patriksimek/vm2#nodevm

wrapper - commonjs (default) to wrap script into CommonJS wrapper, none to retrieve value returned by the script.

For example,
const vm = new NodeVM({
  wrapper: 'none'
})

const vmRes = await vm.run('return Promise.resolve(100)')

console.log(vmRes) // 100


text:
Q: Windows 8.1 install, lost programs installed on non-C drives I had a Windows 8 machine that I recently upgraded to 8.1.  It seems like most of the applications that I had installed to an E drive are now completely or partially forgotten by Windows 8.1-- I've had to reinstall quite a few.
In this case, SQL Server Express 2012 instances no longer show up in my services list and I am unable to connect to them.  Other SQL Server services remain, such as the browsing service.  As far as I can tell, it looks like all of the SQL server components are still in the 'programs and features' section of the control panel, but my media has been deleted from the temp folders so there is no easy way to repair.
Is there a way to tell Windows 8.1 to refresh the list of installed apps without losing data?
I do have backups, and I will create a new 8.1 backup prior to testing any suggestions.
My computer has an SSD for the OS, but I've been offloading non-OS apps to a larger 1 TB drive to save space on the SSD.

A: You can refresh the whole system without losing data through the "NewUI control pannel"
Here is an article on this topic:
http://www.pcmag.com/article2/0,2817,2410848,00.asp

A: I wound up downloading the SQL Server 2012 Express installation from microsoft again, which included Service Pack 1.  There was an option to repair instances, and now things seem to be working.
The only error I received when repairing referenced something about not being able to map security logins.  You get an option to 'cancel' or 'retry,' and I just cancelled all of the popups with that error message.


text:
Q: Pattern matcher returns unexpected values could you take a look at the pattern (java) in the below result.
I expect the result should give me 3 group value, but instead it gave me 2 values only
I think i missed something.
package com.mycompany.testapp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author bo17a
 */
public class NewClass {
    public static void main(String[] args){
        Pattern mPattern = Pattern.compile("^love (.*?) way you (.*?)$");
        Matcher matcher = mPattern.matcher("love the way you lie");
        if(matcher.find()){
            String[] match_groups = new String[matcher.groupCount()];
            System.out.println(String.format("groupCount: %d", matcher.groupCount()));
            for(int j = 0;j<matcher.groupCount();j++){
                System.out.println(String.format("j %d",j));
                match_groups[j] = matcher.group(j);
                System.out.println(match_groups[j]);
            }
        }

    }
}

The result I got is:
2
love the way you lie
the

but my expected result should be:
3
love the way you lie
the
lie

update
i tried to add up one number of group as suggested in replies:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.testapp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author lee
 */
public class NewClass {
    public static void main(String[] args){
        Pattern mPattern = Pattern.compile("^love (.*?) way you (.*?)$");
        Matcher matcher = mPattern.matcher("love the way you lie");
        if(matcher.find()){
            String[] match_groups = new String[matcher.groupCount()];
                System.out.println(String.format("groupCount: %d", matcher.groupCount()));
                for(int j = 0;j<=matcher.groupCount();j++){
                    System.out.println(String.format("j %d",j));
                    match_groups[j] = matcher.group(j);
                    System.out.println(match_groups[j]);
                }
        }
    }

}

The result is different from yours:
groupCount: 2
j 0
love the way you lie
j 1
the
j 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at com.mycompany.testapp.NewClass.main(NewClass.java:24)
Command execution failed.

I have tried on windows 10 JDK 8 Mac OS JDK 8. So, could this be a bug in Java, because you and I have different result for the same code?
update 2
Thank you friends,
I found my mistake. The problem is: groupCount return the number of group match (except for the whole string match). So the correct code should be
String[] match_groups = new String[matcher.groupCount()+1];
System.out.println(String.format("groupCount: %d", matcher.groupCount()));
for(int j = 0;j<=matcher.groupCount();j++){
    System.out.println(String.format("j %d",j));
    match_groups[j] = matcher.group(j);
    System.out.println(match_groups[j]);
}

A: My guess is that, you wish to also capture the full match as a group,
^(love (.*?) way you (.*?))$

Or just add 1 to your counter:
Test 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression{

    public static void main(String[] args){

        Pattern mPattern = Pattern.compile("^love (.*?) way you (.*?)$");
        Matcher matcher = mPattern.matcher("love the way you lie");
        if(matcher.find()){
            String[] match_groups = new String[matcher.groupCount() + 1];
                System.out.println(String.format("groupCount: %d", matcher.groupCount() + 1));
                for(int j = 0;j<matcher.groupCount() + 1;j++){
                    System.out.println(String.format("j %d",j));
                    match_groups[j] = matcher.group(j);
                    System.out.println(match_groups[j]);
                }
        }

    }
}

Output
groupCount: 3
j 0
love the way you lie
j 1
the
j 2
lie

Test 2
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression{

    public static void main(String[] args){

        final String regex = "^(love (.*?) way you (.*?))$";
        final String string = "love the way you lie";

        final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

Output
Full match: love the way you lie
Group 1: love the way you lie
Group 2: the
Group 3: lie

RegEx Circuit
jex.im visualizes regular expressions:

A: Apparently, matcher.groupCount() returns 2 in your case, so you only construct array of two strings and copy groups with numbers less than 2 into it, which are group 0 (the whole string) and group 1 ("the"). If you add 1 to matcher.groupCount() throughout your whole code, it works as expected.


text:
Q: eclipse fails to "build workspace" on large android files...? i have a severe problem with eclipse, where i need to compile a somewhat larger class. by "larger" i mean, the class has about 5000 lines of code...
problem is that on saving this project, eclipse takes several seconds (30-40) to "build the workspace". to be exact, it says "50%" and keeps saying that for 30-40 seconds. then, it breaks with the following error:
[console]:
[2010-07-09 15:28:39 - Dex Loader] Unable to execute dex: null
[2010-07-09 15:28:39 - myProject] Conversion to Dalvik format failed: Unable to execute dex: null
[problems window]:
Conversion to Dalvik format failed: Unable to execute dex: null
this error is reproducible and keeps popping up until i comment out several thousands LOC, so that the file still has this 5k LOC, but ~2000 of them are comments. THEN it works...
i know that 5000 LOC are no really good programming style, but i need to do it this way for now ... (i have to write this much records to a sqlite database and since sqlite doesnt feature multiple sql-queries in one rawQuery-command i have to execute a single rawQuery() for each and every data record i need to push into the db.... - until i write a file reader to read this data from a file (that needs verification etc)), i'm stuck with this solution...)
how do i get eclipse and the android sdk to accept files this big?
(system: ubuntu 10.04 x86, eclipse 3.6)

A: I believe the size of a class's bytecode must not exceed 64k in Dalvik. You'll have to split the class into smaller ones.


text:
Q: Assign value to checkboxes Hye there, I new with vba here.
I want to use checkboxes to link with the series collections of a chart. I put the check boxes in a sheet which contain the chart altogether. I have a lot of checkboxes here to be assigned to "true" value.
Private Sub Controls_Initialize()

     'Make default for checkboxes
      CheckBox1.Value = True
      CheckBox2.Value = True
      CheckBox3.Value = True
      CheckBox4.Value = True
      CheckBox5.Value = True
      CheckBox6.Value = True
      CheckBox7.Value = True
      CheckBox8.Value = True
      CheckBox9.Value = True
      CheckBox10.Value = True
      CheckBox11.Value = True
      CheckBox12.Value = True
      CheckBox13.Value = True
      CheckBox14.Value = True
      CheckBox15.Value = True
      CheckBox16.Value = True
      CheckBox17.Value = True
      CheckBox18.Value = True
      CheckBox19.Value = True
      CheckBox20.Value = True
      CheckBox21.Value = True
      CheckBox22.Value = True
      CheckBox23.Value = True
      CheckBox24.Value = True
End Sub

I have tried this code but can't
For i = 1 to 24
     Controls("CheckBox" & i).Value = True
Next i

The questions are
1. Is there any other code that can make it simple?
2. How to link the check boxes with the series collection in the activechart? Example, if the checkbox return value false, the series collection will be deleted/hide(perhaps?). And when it returns value true, the series collection of the same data will be added back in the chart. I would like to make the chart interactive.
If there is any reference that I can reviewed, do tell me.
Thanks in advance.
Regards.

A: Alright, so assuming from what you've given, I'd think the problem is that the interpreter doesn't know i is an integer.
To fix this, we can implement something along the lines of Dim i As Integer to implement i as an integer.

We could try this:

Dim i As Integer
For i = 1 to 24
     Controls("CheckBox" & i).Value = True
Next i


text:
Q: How can I make InputBox only accept numbers The code is just asking for the pass rates for 6 different colleges.  The rate must be a value between 1 and 100.
I would like it to only allow numbers.  I have tried using IsNumeric, but I must not be using it correctly.  Here's what I have so far:
For i As Integer = 0 To 5
    passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
    While passRate(i) > 100 Or passRate(i) < 0
        MsgBox("Error must be a number and be between 0 and 100")
        passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
    End While
Next i

A: use this function for check value
Private Function IsInputNumeric(input As String) As Boolean
        If String.IsNullOrWhiteSpace(input) Then Return False
        If IsNumeric(input) Then Return True
        Dim parts() As String = input.Split("/"c)
        If parts.Length <> 2 Then Return False
        Return IsNumeric(parts(0)) AndAlso IsNumeric(parts(1))
End Function

and use like this
For i As Integer = 0 To 5

    passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
    If IsInputNumeric(passRate(i)) Then
        'handle numeric input
    Else
        'handle not a number
    End If
    While passRate(i) > 100 Or passRate(i) < 0
        MsgBox("Error must be a number and be between 0 and 100")
        passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")

    End While

A: I see a couple of things to note.

*

*IsNumeric does not test for just an integer.  It will return true
for "1.5"  since it is numeric.  I am assuming that you are looking
for an integer value of 1 to 100 as an input result.

*An input box returns an string.  Some form of parsing (implicit or explicit)     must happen if you are going to compare it to an integer type.

To avoid that conversion you could use a simple RegEx.  This one will validate it to be an integer between 1 and 100:
Function IsValid(Byval inputString as String) as Boolean
    Dim validValues As New Regex("^[1-9]?[0-9]{1}$|^100$")
    Return validValues.IsMatch(inputString )
End Function

Admitily RegEx can be a bit much... So here is another way to check that the input string will cast to an integer and if so is it between 1 and 100 in value.
Function IsValid(Byval inputString as String) as Boolean
  Dim result As Boolean = False
  Dim inputAsInteger as Integer = 0
  If Integer.TryParse(value, inputAsInteger) Then
     result = inputAsInteger > 0 And inputAsInteger <= 100)
  End If
  Return result
End Function

You can call either of these like so:
   Dim validInput as Boolean = False
   While Not validInput
      validInput = IsValid(InputBox("Enter the pass rate for " & colleges(i) & " college")
   Loop

A:  Private Sub txbDwellTime_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbDwellTime.KeyPress
    pNumDecOnly(e)
    'txbDwellTime.Text = ""
End Sub

Public Sub pNumDecOnly(ByVal e As System.Windows.Forms.KeyPressEventArgs)
    If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 46) Then
        'good job do nothing we only allow positive Decimal numbers in this field
        'Asc(e.KeyChar) 48 Through 57 i.e. 0 through 9 Or Asc(e.KeyChar) 46 (dot= .)
    Else
        e.Handled = True
        MsgBox("Only Positive Decimal Numbers Allowed this field")
    End If
End Sub

This will allow only positive Decimal numbers using the ASCII Table, you should be able to modify this for your own use


text:
Q: $state.reload doesn't refresh view I've got the following piece of code:
launch.controller('HeaderController', ['$scope', '$state','$timeout', function($scope, $state, $timeout){
    $scope.reloading = false ;

    $scope.reload = function(){
        $scope.reloading = true;
        $state.reload();
        $timeout(function(){
            $scope.reloading = false;
            $scope.$apply()
        }, 2000);
    }
}]);

And the following template:
<img src="assets/img/refresh.svg" ng-class="{'reloading': reloading == true}">

When I do not use $scope.reload(), it is perfectly reflected in the view. However, as soon as I use the function, the view doesn't recognize the boolean being changed.
I've checked whether the function is running at all, and it does; Adding a console.log after $state.reload() works just fine.
Also the view actually does doe a reload of the data.
What's the problem here..?

A: $state.reload() is an alias of
$state.transitionTo($state.current, $stateParams, {
  reload: true, inherit: false, notify: false
});

So you set $scope.reloading = true; and immediately reload the state, resetting the controllers, so the view doesn't have time to change the indicator, because it all happens to fast.
So what I suggest is using a flag of some sort, to allow you to show the visual indicator using sessionStorage:
launch.controller('HeaderController', ['$scope', '$state','$timeout', function($scope, $state, $timeout){
    $scope.reloading = sessionStorage.getItem('reloading') === 'true';

    if( $scope.reloading ) {
        sessionStorage.removeItem('reloading');

        $timeout(function(){
            $scope.reloading = false;
        }, 2000);
    }

    $scope.reload = function(){
        sessionStorage.setItem('reloading', 'true');
        $state.reload();
    }
}]);

What I did here is that when you reload the page, you first set a reloading flag in the session, and then reload the page. When the controller is created I set $scope.reloading by the value in the session ($scope.reloading = sessionStorage.getItem('reloading') === 'true';), if it was set - the flag is removed from the session, and hide the indicator in the view after 2 seconds (Using the $timeout service).
FYI - There is a ngStorage module for angularjs so you can use it when you need to manage the storage in your app.


text:
Q: FTP installation Is there a possibility to install GUI ftp on ubuntu(EX: filezilla server on windows)
I have tried gadminproftpd but it is not working properly.
Suggest some other tool.

A: I suggest you to install proftpd and webmin.
You will get web based access for ftp server configuration
Instalation of proftpd
 sudo apt-get install proftpd

Installation of webmin
First you need add Webmin official repository and make sure that all packages are up to date.
sudo nano /etc/apt/sources.list

And add the following lines:
 deb http://download.webmin.com/download/repository sarge contrib
 deb http://webmin.mirror.somersettechsolutions.co.uk/repository sarge contrib

Fetch and install the GPG key:
sudo wget http://www.webmin.com/jcameron-key.asc
sudo apt-key add jcameron-key.asc

Install Webmin with the following command:
sudo apt-get update
sudo apt-get install webmin -y

You can access the webmin panel using web browser. Webmin use 10000 as its default port. https://ip-address:10000 then login as super user or root access priviliges. If you are using a firewall, please open port 80 and 10000 to enable access to the control panel.
Then once logged in using the menu system browse to Webmin configuration the select Webmin modules.

ProFTPD is a standard module in Webmin so we need to select standard module in Webmin then browse to select the module

You will then be presented with all the standard modules. Browse to ProFTPD and install it.

At the end you will get web based tool for proftpd configuration.

More you have here


text:
Q: Convert a hex string to a byte in Java In Java, how can a hexadecimal string representation of a byte (e.g. "1e") be converted into a byte value?
For example:
byte b = ConvertHexStringToByte("1e");

A: You can use Byte.parseByte("a", 16);
but this will work only for values up to 127,
values higher then that will need to cast to byte, due to signed/unsigned issues
so i recommend to transfer it to an int and then cast it to byte
(byte) (Integer.parseInt("ef",16) & 0xff);

A: Integer.parseInt(str, 16);

A: Byte.parseByte will return a byte by parsing a string representation.
Using the method with the (String, int) signature, the radix can be specified as 16, so one can parse a hexadecimal representation of a byte:
Byte.parseByte("1e", 16);


text:
Q: log4net not working in a windows service I have a console app which I am converting into a windows service. As a console app my log4net logging is working fine. But converting it into a windows service, my log4net logging has stopped working.
I have added this to my assemblyInfo.cs in the service project:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

This is my service class with onstart and onstop:
private static log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Builder _builder;

        public YCSWebServerService()
        {
            InitializeComponent();
            _builder = new Builder();
        }

        protected override void OnStart(string[] args)
        {
            _log.Info("YCSWebServerService started");
            _builder.Start();
        }

        protected override void OnStop()
        {
            _log.Info("YCSWebServerService stopped");
            _builder.Stop();
        }

I have a "specific" log4net config file added to my service project:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>

  </configSections>

  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="EventLogAppender" />
    </root>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
      <threshold value="DEBUG" />
      <applicationName value="Lantic YCS WebServer" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="(%-5level %date{hh}:%date{mm}:%date{ss} [%thread] %logger [%property{NDC}] ) %message %n" />
      </layout>
    </appender>
  </log4net>

</configuration>

Any ideas or tips?

A: Did you just add a log4net section to your app.config file? In your question you mentioned that you have "specific log4net config file", but the sample you gave looks like the whole contents of app.config.
If app.config is the case then you could have simpler string in AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Also adding requirePermission="false" to the section in my app.config helped me when I fixed similar problem with log4net not logging to file for Windows Service (see extra attribute - requirePermission="false"):
<configuration>
  <configSections>

  </configSections>

A: Some things to try:
Does the user running the service have write permissions?
Are any exceptions getting logged to the windows logs?
Have you tried running the service in debug mode to see if Log4net is
   throwing any exceptions?

A: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=293617
http://social.msdn.microsoft.com/Forums/en-US/windowsgeneraldevelopmentissues/thread/5bef59bc-a28f-4e6d-8ddb-730e12764162
In Windows Vista, Windows XP SP 2, Windows Server 2003, 2008 and Windows 7 a user needs Administrator rights to access the Security Log. Now when log4net tries to create a Event Log Source, all Logs are checked if it already exists. So with a Windows Service, the user of the Windows Server would need Administrator rights (which is not good).
Solution: configure a explicit Source in the log4net configuration (as you did: <applicationName value="Lantic YCS WebServer" />, Lantic YCS WebServer is your Source) and create this Source in you Setup (because Setup-User should have Administrator rights).

A: Well this question was asked long time back, I have a suggestion which may be of some help to anyone looking for a solution to this issue. If you are converting console app to windows service... you must have created an installer for installing the app. When you install the app, it creates a installation folder for the service usually under ProgramFile..... (Check it when you are installing your service..it gives you the path to the installation directory). If in your web.config file you have provided path to Log file as "Log\Log.txt", then there will be a folder(Log) in the installation folder with your Log file(Log.txt). You are wasting your time if you are looking for log file in your application folder.


text:
Q: Setting focus to already opened Tab of Internet Explorer from C# program using .net 2.0 I have two questions.

*

*How can I set focus to already opened Tab of Internet Explorer from C# program using .net 2.0.

*How can I open a new URL in a new Tab of running Internet Explorer instance (not in new window.) from C# program.
I can only use .net up to 2.0.
Your help will be appreciated.

A: Here is the code how to activate tab based on URL address of the tab.  I tested and it works fine.  You can add your functionality how to activate tab based on Text/Description, etc.  If you need have it running under .net 2.0 then change var to specific type.
Here is an actual code itself.  I wrapped it in separate class.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Accessibility;

namespace IETabsInteraction
{
    internal class TabActivator
    {
        #region Nested type: OBJID

        private enum OBJID : uint
        {
            OBJID_WINDOW = 0x00000000,
        }

        #endregion

        #region Declarations

        private const int CHILDID_SELF = 0;
        private readonly IntPtr _hWnd;
        private IAccessible _accessible;

        [DllImport("oleacc.dll")]
        private static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint id, ref Guid iid,
                                                             [In, Out, MarshalAs(UnmanagedType.IUnknown)] ref object
                                                                 ppvObject);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass,
                                                  string lpszWindow);

        [DllImport("oleacc.dll")]
        private static extern int AccessibleChildren(IAccessible paccContainer, int iChildStart, int cChildren,
                                                     [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] object[] rgvarChildren, out int pcObtained);

        #endregion

        #region Constructors

        internal TabActivator(IntPtr ieHandle)
        {
            _hWnd = ieHandle;
            AccessibleObjectFromWindow(GetDirectUIHWND(ieHandle), OBJID.OBJID_WINDOW, ref _accessible);

            CheckForAccessible();
        }

        private TabActivator(IAccessible acc)
        {
            if (acc == null)
                throw new Exception("Could not get accessible");

            _accessible = acc;
        }

        #endregion

        private TabActivator[] Children
        {
            get
            {
                var num = 0;
                var res = GetAccessibleChildren(_accessible, out num);

                if (res == null)
                    return new TabActivator[0];

                var list = new List<TabActivator>(res.Length);

                foreach (object obj in res)
                {
                    var acc = obj as IAccessible;

                    if (acc != null)
                        list.Add(new TabActivator(acc));
                }

                return list.ToArray();
            }
        }

        private int ChildCount
        {
            get { return _accessible.accChildCount; }
        }

        /// <summary>
        /// Gets LocationUrl of the tab
        /// </summary>
        private string LocationUrl
        {
            get
            {
                var url = _accessible.accDescription[CHILDID_SELF];

                if (url.Contains(Environment.NewLine))
                    url = url.Split('\n')[1];

                return url;
            }
        }

        private void CheckForAccessible()
        {
            if (_accessible == null)
                throw new Exception("Could not get accessible.  Accessible can't be null");
        }

        internal void ActivateByTabsUrl(string tabsUrl)
        {
            var tabIndexToActivate = GetTabIndexToActivate(tabsUrl);

            AccessibleObjectFromWindow(GetDirectUIHWND(_hWnd), OBJID.OBJID_WINDOW, ref _accessible);

            CheckForAccessible();

            var index = 0;
            var ieDirectUIHWND = new TabActivator(_hWnd);

            foreach (var accessor in ieDirectUIHWND.Children)
            {
                foreach (var child in accessor.Children)
                {
                    foreach (var tab in child.Children)
                    {
                        if (tabIndexToActivate >= child.ChildCount - 1)
                            return;

                        if (index == tabIndexToActivate)
                        {
                            tab.ActivateTab();
                            return;
                        }

                        index++;
                    }
                }
            }
        }

        private void ActivateTab()
        {
            _accessible.accDoDefaultAction(CHILDID_SELF);
        }

        private int GetTabIndexToActivate(string tabsUrl)
        {
            AccessibleObjectFromWindow(GetDirectUIHWND(_hWnd), OBJID.OBJID_WINDOW, ref _accessible);

            CheckForAccessible();

            var index = 0;
            var ieDirectUIHWND = new TabActivator(_hWnd);

            foreach (var accessor in ieDirectUIHWND.Children)
            {
                foreach (var child in accessor.Children)
                {
                    foreach (var tab in child.Children)
                    {
                        var tabUrl = tab.LocationUrl;

                        if (!string.IsNullOrEmpty(tabUrl))
                        {
                            if (tab.LocationUrl.Contains(tabsUrl))
                                return index;
                        }

                        index++;
                    }
                }
            }

            return -1;
        }

        private IntPtr GetDirectUIHWND(IntPtr ieFrame)
        {
            // For IE 8:
            var directUI = FindWindowEx(ieFrame, IntPtr.Zero, "CommandBarClass", null);
            directUI = FindWindowEx(directUI, IntPtr.Zero, "ReBarWindow32", null);
            directUI = FindWindowEx(directUI, IntPtr.Zero, "TabBandClass", null);
            directUI = FindWindowEx(directUI, IntPtr.Zero, "DirectUIHWND", null);

            if (directUI == IntPtr.Zero)
            {
                // For IE 9:
                //directUI = FindWindowEx(ieFrame, IntPtr.Zero, "WorkerW", "Navigation Bar");
                directUI = FindWindowEx(ieFrame, IntPtr.Zero, "WorkerW", null);
                directUI = FindWindowEx(directUI, IntPtr.Zero, "ReBarWindow32", null);
                directUI = FindWindowEx(directUI, IntPtr.Zero, "TabBandClass", null);
                directUI = FindWindowEx(directUI, IntPtr.Zero, "DirectUIHWND", null);
            }

            return directUI;
        }

        private static int AccessibleObjectFromWindow(IntPtr hwnd, OBJID idObject, ref IAccessible acc)
        {
            var guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessibleobject obj = null;
            object obj = null;

            var num = AccessibleObjectFromWindow(hwnd, (uint) idObject, ref guid, ref obj);

            acc = (IAccessible) obj;

            return num;
        }

        private static object[] GetAccessibleChildren(IAccessible ao, out int childs)
        {
            childs = 0;
            object[] ret = null;
            var count = ao.accChildCount;

            if (count > 0)
            {
                ret = new object[count];
                AccessibleChildren(ao, 0, count, ret, out childs);
            }

            return ret;
        }
    }
}

To execute this code use:
var hWnd = (IntPtr)ie.HWND;
new TabActivator(hWnd).ActivateByTabsUrl("www.stackoverflow.com");

To answer your second question.  You will need to find ie that you have already running:
    private static void OpenTabInExistingIE()
    {
        var shellWindows = new ShellWindows();

        // check if IE is open
        if (shellWindows.Count > 0)
            ((InternetExplorer)shellWindows.Item(0)).Navigate2("www.stackoverflow.com", 2048);
    }

For all these code you will have to add reference to SHDocVw.dll and
#using SHDocVw;

Here are flags for Navigate2 method
Enum BrowserNavConstants
    navOpenInNewWindow = 1
    navNoHistory = 2
    navNoReadFromCache = 4
    navNoWriteToCache = 8
    navAllowAutosearch = 16
    navBrowserBar = 32
    navHyperlink = 64
    navEnforceRestricted = 128
    navNewWindowsManaged = 256
    navUntrustedForDownload = 512
    navTrustedForActiveX = 1024
    navOpenInNewTab = 2048
    navOpenInBackgroundTab = 4096
    navKeepWordWheelText = 8192
    navVirtualTab = 16384
    navBlockRedirectsXDomain = 32768
    navOpenNewForegroundTab = 65536
End Enum


text:
Q: pyspark merge two dataframe with added items/condition I have two dataframes as below.
If a person buys something, we can also recommend similar products.
df1 has a list of items bought by each person.
df2 has recommended add-on products.
For example "Gopu" buys bun, then I have to recommend "butter" and "jam"
If there is no added_product item (from df2) then it need not appear in the output. For (e.g) "Gopu" buys an item "biscuit" but there is no add on item to recommend from df2. Hence it will not appear in the output table. Thanks
Simple df1.df2 join by left is not working for me.
df1:
name  product
Gopu  biscuit
Gopu  bun
Gopu  ink
Aish  ball
Aish  doll
Aish  bun
Aish  ink
Colin bun
Colin handsanitize
Colin paper

df2:
product added-product
bun     butter
bun     jam
ink     cloth
ink     bib
paper   pen
doll    barbie

Expected output:
Name    added-product
Gopu    butter
Gopu    jam
Gopu    cloth
Gopu    bib
Aish    barbie
Aish    butter
Aish    jam
Aish    cloth
Aish    bib
Colin    butter
Colin    jam
Colin    pen

Thanks.

A: dfnew=df1.join(df2,(df1.product==df2.product),"cross").select('name','added-product').orderBy('name')

dfnew.show()
+-----+-------------+
| name|added-product|
+-----+-------------+
| Aish|       butter|
| Aish|          jam|
| Aish|        cloth|
| Aish|          bib|
| Aish|       barbie|
|Colin|          jam|
|Colin|          pen|
|Colin|       butter|
| Gopu|       butter|
| Gopu|        cloth|
| Gopu|          jam|
| Gopu|          bib|
+-----+-------------+


text:
Q: Dynamic Pivot Tables MS SQL 2008 I'm trying to create a dynamic pivot table to get results in different columns rather than rows.
This is the table I'm using to test
CREATE TABLE [dbo].[Authors](
[Client_Id] [nvarchar](50) NOT NULL,
[Project_Id] [nvarchar](50) NOT NULL,
[Person_Id] [int] NOT NULL,
[Author_Number] [int] NOT NULL,
[Family_Name] [nvarchar](50) NULL,
[First_Name] [nvarchar](50) NULL,
)

INSERT INTO Authors (Client_Id, Project_Id, Person_Id, Author_Number, Family_Name, First_Name)
VALUES ('TEST','TEST',12345,1,'Giust','Fede')
INSERT INTO Authors (Client_Id, Project_Id, Person_Id, Author_Number, Family_Name, First_Name)
VALUES ('TEST','TEST',12345,2,'Giust','Fede')
INSERT INTO Authors (Client_Id, Project_Id, Person_Id, Author_Number, Family_Name, First_Name)
VALUES ('TEST','TEST',12346,1,'Giust','Fede')
INSERT INTO Authors (Client_Id, Project_Id, Person_Id, Author_Number, Family_Name, First_Name)
VALUES ('TEST','TEST',12346,2,'Giust','Fede')
INSERT INTO Authors (Client_Id, Project_Id, Person_Id, Author_Number, Family_Name, First_Name)
VALUES ('TEST','TEST',12346,3,'Giust','Fede')

So far I get the results like this
CLIENT_ID   PROJECT_ID  PERSON_ID   AUTHOR_NUMBER   FAMILY_NAME FIRST_NAME
TEST        TEST        12345       1               Giust       Fede
TEST        TEST        12345       2               Ma          Ke
TEST        TEST        12346       1               Jones       Peter
TEST        TEST        12346       2               Davies      Bob
TEST        TEST        12346       3               Richards        Craig

I need the results to come out like this, and to be dynamic because sometime I can have 2 authors, or 10 authors.
CLIENT_ID   PROJECT_ID  PERSON_ID   FAMILY_NAME_1   FIRST_NAME_1    FAMILY_NAME_2   FIRST_NAME_2        FAMILY_NAME_3   FIRST_NAME_3
TEST        TEST        12345       Giust           Fede            Ma              Ke

TEST        TEST        12346       Jones           Peter           Davies          Bob                 Richards            Craig

I've been trying to use this code, but keep getting errors
SQL Fiddle

A: Here are a few suggestions to solve your issue.
First, your current code is unpivoting all of the columns in the table, you only need to UNPIVOT the Family_Name and First_Name columns.  As a result I would not use a variable to get this list of columns, just hard-code the two columns you need to unpivot.
Then to get the list of columns to PIVOT, alter the code to use both the Author_number and then a string with the column names Family_Name and First_Name:
select @colsPivot = STUFF((SELECT ',' + QUOTENAME(c.col + '_'+cast(Author_Number as varchar(10)))
                    from Authors
                    cross apply
                    (
                      select 'Family_Name' col, 1 so union all
                      select 'First_Name', 2
                    ) c
                    group by col, author_number, so
                    order by author_number, so
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

This gives a list of cols:
|                                                                                COLUMN_0 |
------------------------------------------------------------------------------------------------
| [Family_Name_1],[First_Name_1],[Family_Name_2],[First_Name_2],[Family_Name_3],[First_Name_3] |

Making these changes to your code the final query will be
DECLARE @colsPivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @colsPivot = STUFF((SELECT ',' + QUOTENAME(c.col + '_'+cast(Author_Number as varchar(10)))
                    from Authors
                    cross apply
                    (
                      select 'Family_Name' col, 1 so union all
                      select 'First_Name', 2
                    ) c
                    group by col, author_number, so
                    order by author_number, so
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query
  = 'select Client_id, Project_id, Person_Id, '+@colsPivot+'
      from
      (
        select Client_id, Project_id, Person_Id,
          col+''_''+cast(Author_Number as varchar(10)) col, val
        from
        (
          select Client_id, Project_id,
            Person_Id,
            Author_Number,
            Family_Name,
            First_Name
          from Authors
        ) s
        unpivot
        (
          val
          for col in (Family_Name, First_Name)
        ) u
      ) x1
      pivot
      (
        max(val)
        for col in ('+ @colspivot +')
      ) p'

exec(@query)

See SQL Fiddle with Demo. This gives a result:
| CLIENT_ID | PROJECT_ID | PERSON_ID | FAMILY_NAME_1 | FIRST_NAME_1 | FAMILY_NAME_2 | FIRST_NAME_2 | FAMILY_NAME_3 | FIRST_NAME_3 |
-----------------------------------------------------------------------------------------------------------------------------------
|      TEST |       TEST |     12345 |         Giust |         Fede |            Ma |           Ke |        (null) |       (null) |
|      TEST |       TEST |     12346 |         Jones |        Peter |        Davies |          Bob |      Richards |        Craig |


text:
Q: Jest how to check async response I'm new to Jest and React so this should be a very simple question to answer...  I have an api-endpoint I'd like to check that I can hit.  I picked Axios as a client to try this and created the following test:
describe('Api Tests', () => {
  it('can perform an axios request', () => {
    console.log('Here goes!');

    const resp = axios.get('api-endpoint');
    console.log(resp);
    expect(resp).toBeDefined();

    console.log('Done...');
  });
});

Thankfully, the test passes, but with the following output:
 PASS  src\api\api.test.js
  Api Tests
    √ can perform an axios request (39ms)

  console.log src\api\api.test.js:15
    Here goes!

  console.log src\api\api.test.js:23
    Promise { <pending> }

  console.log src\api\api.test.js:25
    Done...

How do I test a simple request (WITHOUT MOCKING) so that I can get back a response that I can then interrogate?

A: I have nice and easy method , maybe you will like it too. Just keep it simple.
`import axios from 'axios';
  axios.get('url goes here')
  .then(response =>{console.log(response)})`

Maybe find helpful to you.

A: Since axios.get returns a promise you should instruct Jest to wait for the response to return.
it('can perform an axios request', async () => {
  const resp = await axios.get('api-endpoint');
  expect(resp).toBeDefined();
});

or without async functions:
it('can perform an axios request', () => {
  return expect(axios.get('api-endpoint')).resolves.toBeDefined();
});


text:
Q: Error on conversion from TestNg....Deprecated reflection to load ObjectFactory getting on running codes with Test Data factory which getting data from excel sheet.
Error:

*

*Use deprecated reflection to load ObjectFactory.(after execution from cucumber feature)

2.ArrayIndexOutOfBoundException(after execution from runner class-testNg)
How to fix the issue
using excel sheet in scenario outline with TestNg


text:
Q: Difference between interior and set of accumulation points I don't understand the difference between the interior of a set, and the set of all its accumulation points.
My understanding of an accumulation point is any point in a set which has an epsilon neighborhood around it, which is contained in the set- not necessarily implying that the accumulation point itself is in the set.
From what I can gather, the interior is identical. Can someone explain the difference?

A: There is no necessary relationship between the two sets.
Let $A$ be a set in a topological space $X$. A point $x$ is in the interior of $A$ if there is an open set $U$ such that $x\in U\subseteq A$; in particular this implies that $x\in A$. A point $x$ is an accumulation point of $A$ if for each open set $U$ containing $x$, $U\cap(A\setminus\{x\}\ne\varnothing$; in words, if every open nbhd of $x$ contains at least one point of $A$ different from $x$. This does not imply that $x\in A$.
Take the space $\Bbb R$ with the usual topology as a familiar example. The set $\Bbb Z$ has empty interior: for any $n\in\Bbb Z$, no matter how small an $\epsilon>0$ you take, $(n-\epsilon,n+\epsilon)\nsubseteq\Bbb Z$, so $n$ is not in the interior of $\Bbb Z$. $\Bbb Z$ also has no accumulation points: if $x\in\Bbb R\setminus Z$, there is an integer $n$ such that $n<x<n+1$, and $(n,n+1)$ is then an open nbhd of $n$ that contains no point of $\Bbb Z$; and if $n\in\Bbb Z$, $(n-1,n+1)$ is an open nbhd of $n$ that contains no point of $\Bbb Z\setminus\{n\}$. In this case the interior of the set is its set of accumulation points: each is the empty set, $\varnothing$. But now consider the following sets:

*

*The set $\left\{\frac1n:n\in\Bbb Z^+\right\}$, on the other hand, has empty interior and exactly one accumulation point, $0$.

*$\Bbb Q$ also has empty interior, and every real number is an accumulation point of $\Bbb Q$.

*$[0,1]$, $[0,1)$, and $(0,1)$ all have interior $(0,1)$, and all have $[0,1]$ as their set of accumulation points.
(In each case you should try to prove the assertions.)
If we look at $\Bbb Z$ as a space in its own right, with the discrete topology, then every subset of $\Bbb Z$ is open, and no point of $\Bbb Z$ is an accumulation point of any subset of $\Bbb Z$. Thus, if $A\subseteq\Bbb Z$, then the interior of $A$ is $A$ itself, but $A$ has no accumulation points.

A: I assume that you're working with subsets of the real line with the usual topology.
The definition you gave for accumulation point is actually the definition for interior point, and it does imply that the point lies in the set. Indeed, an $\epsilon$-neighborhood of a point $x$ is an interval of the form $(x-\epsilon,x+\epsilon)$ with $\epsilon>0,$ and $x$ readily lies in any such interval, so $x$ lies in any set that contains such an interval.
We say that a point $x$ is an accumulation point of a set $A$ if every $\epsilon$-neighborhood of $x$ intersects $A$ at a point distinct from $x$. This does not mean that every epsilon neighborhood of $x$ is contained in $A$--it's possible that no $\epsilon$-neighborhood of $x$ is contained in $A,$ which means that accumulation points need not be interior points.
For an example to see that the interior and set of accumulation points are not the same, consider $[0,2]\setminus\{1\}$. The interior of the set is $(0,1)\cup(1,2),$ but the set of accumulation points is $[0,2]$. The point $1$ is an example of a non-interior accumulation point.
For another example, consider the set $\{0\}\cup\{\frac1n:n\in\Bbb Z^+\}.$ No point of this set has a neighborhood contained in the set, so the interior is empty, but it can be shown that $0$ is the unique accumulation point. So, even if an accumulation point is in the set, it need not be an interior point.


text:
Q: How to make selected one button in a list of button? I have more than one button in a LinearLayout and they all have different click option. I want to make when I choose one of them it will selected and change its background then I select the other one first ones selected gone and new one turn selected and background will change. I have 8-9 button or more. How can I do that?
This is action_main.xml
  <HorizontalScrollView
        android:id="@+id/horScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="horizontal">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="5dp">

            <ImageButton
                android:id="@+id/spaceship"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/spaceship" />
            <ImageButton
                android:id="@+id/mask"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                app:srcCompat="@drawable/mask" />
        </LinearLayout>
  </HorizontalScrollView>

This is Main.java
 ImageButton spaces = findViewById(R.id.spaceship);
        spaces.setBackgroundColor(Color.TRANSPARENT);
        spaces.setOnClickListener(view -> {

            if(getChecked())
                spaces.setBackgroundColor(Color.TRANSPARENT);
            else
                spaces.setBackgroundColor(Color.DKGRAY);

            setChecked(!check);

            modelLoader.loadModel(this, R.raw.sample_ship);
            setRenderable(spaceShipRendeble);
        });
 ImageButton mask = findViewById(R.id.mask);
        mask.setBackgroundColor(Color.TRANSPARENT);
        mask.setOnClickListener(view -> {

            if(getChecked())
                mask.setBackgroundColor(Color.TRANSPARENT);
            else
                mask.setBackgroundColor(Color.DKGRAY);

            setChecked(!check);
            modelLoader.loadModel(this,R.raw.mask);
            setRenderable(maskrendeble);
        });

Firstly, I set check variable "false".
For example, one button selected, and it turn gray, than I choose another button turns gray and first selected will turn transparent. But I can't do it.

A: You can check for one ImageButton for the condition whether it is checked. Base on that you can make all other setChecked() false.I have use the same for setting values of RadioButtons.
if (Friends != null) {
                        Friends.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (isChecked) {
                                    friend_source = "Friend";
                                    Newspaper.setChecked(false);
                                    Facebook.setChecked(false);
                                    Zomato.setChecked(false);
                                    RadioSource.setChecked(false);
                                }

                            }
                        });
                    }

A: Create a resourse file that has different colours for the different states of teh button.
btn_bg_states.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_focused="true">
    <shape>
        <solid android:color="your_color" />
    </shape>
</item>

<item android:state_pressed="true">
    <shape>
        <solid android:color="your_other_color" />
    </shape>
</item>

<item>
    <shape>
        <solid android:color="your_default_color" />

    </shape>
</item>
</selector>

then set it as a background drawable to all buttons, and Android will handle the rest for you.
android:background="@drawable/btn_bg_states"

A: @OnClick({R.id.next,R.id.country_us,R.id.country_india})
public void nextClicked(View view)
{ switch(view.getId()) {
    case R.id.next:
        Intent intent = new Intent(this, TutorialScreen.class);
        intent.putExtra("country_selected", ind_sel);
        startActivity(intent);
        break;
    case R.id.country_india:
        ind_sel=true;
        setselectedBlank();
        view.setBackgroundResource(R.drawable.selected_border);
        break;

    case R.id.country_us:
        ind_sel=false;
        setselectedBlank();
        view.setBackgroundResource(R.drawable.selected_border);
        break;
}
}

private void setselectedBlank() {
    country_us.setBackgroundResource(R.drawable.border);
    country_india.setBackgroundResource(R.drawable.border);
}

you could try this just call a method to change background of all to default first then change it to selected colour after that
please note i a using ButterKnife injection library here but even if you are not using it its not an issue
Happy Coding
     ImageButton spaces = findViewById(R.id.spaceship);
            spaces.setBackgroundColor(Color.TRANSPARENT);
            spaces.setOnClickListener(view -> {

              setAllnotSelected();
                    spaces.setBackgroundColor(Color.DKGRAY);

            });
     ImageButton mask = findViewById(R.id.mask);
            mask.setBackgroundColor(Color.TRANSPARENT);
            mask.setOnClickListener(view -> {

               setAllnotSelected();
                    mask.setBackgroundColor(Color.DKGRAY);

            });

public void setAllnotSelected();
{
mask.setBackgroundColor(Color.TRANSPARENT);
spaces.setBackgroundColor(Color.TRANSPARENT);
}


text:
Q: Проблема в реализации задачи на "Коня" Дана шахматная доска размером m*n. На каждой клеточке данной доски стоит число (числа могут быть как положительными, так и отрицательными). На данной доске стоит шахматный конь (в левой верхней клетке). Помогите коню добраться до правой нижней клетки данной доски и при этом собрать наибольшую сумму чисел. Конь может ходить только четырьмя способами: 2 клетки вправо и 1 вниз (x+2, y+1); 2 клетки вправо и 1 вверх (x+2, y-1); 2 клетки вниз и 1 вправо (x+1, y+2); 2 клетки вниз и 1 влево (x-1, y+2)
У меня проблема с ходом работы программы, тесты, которые я пробовал - проходят, вроде все возможные случаи хода коня учел, но всеравно есть ошибка, проблема не в кэшировании, у меня сайт выдает именно неправильное значение ответа, а не долгое время работы программы
 #include <iostream>
#include <limits.h>
using namespace std;

int h;
int w;
int Matrix[2001][2001];
int flag = 0;

long long int F(int n, int m)
{
    if ((n - 2 == 1 and m - 1 == 1) or (n - 2 == 1 and m + 1 == 1) or (n - 1 == 1 and m - 2 == 1) or (n + 1 == 1 and m - 2 == 1))
    {
        flag = 1;
        return Matrix[1][1] + Matrix[n][m];
    }
    if (n - 2 >= 1 and m - 2 >= 1 and n + 1 <= h and m + 1 <= w)
        return max(max(F(n - 1, m - 2), F(n - 2, m - 1)), max(F(n - 2, m + 1), F(n + 1, m - 2))) + Matrix[n][m];
    if (n - 2 >= 1 and m - 2 >= 1 and n + 1 > h and m + 1 <= w)
        return max(max(F(n - 1, m - 2), F(n - 2, m - 1)), F(n - 2, m + 1)) + Matrix[n][m];
    if (n - 2 >= 1 and m - 2 >= 1 and n + 1 <= h and m + 1 > w)
        return max(max(F(n - 1, m - 2), F(n - 2, m - 1)), F(n + 1, m - 2)) + Matrix[n][m];
    if (n - 2 >= 1 and n - 1 <= h and n + 1 > h and m + 1 > w and m - 2 >= 1)
        return max(F(n - 1, m - 2), F(n - 2, m - 1)) + Matrix[n][m];
    if (n - 2 >= 1 and m - 1 >= 1 and m - 2 < 1 and m + 1 <= w)
        return max(F(n - 2, m - 1), F(n - 2, m + 1)) + Matrix[n][m];
    if (m - 2 >= 1 and n - 1 >= 1 and n + 1 <= h and n - 2 < 1)
        return max(F(n - 1, m - 2), F(n + 1, m - 2)) + Matrix[n][m];
    if (n - 2 >= 1 and m + 1 <= w and m + 2 > w and m - 1 < 1)
        return F(n - 2, m + 1) + Matrix[n][m];
    if (n - 2 >= 1 and m - 1 >= 1 and m - 2 < 1 and m + 1 > w)
        return F(n - 2, m - 1) + Matrix[n][m];
    if (m - 2 >= 1 and n - 1 >= 1 and n - 2 < 1 and n + 1 > h)
        return F(n - 1, m - 2) + Matrix[n][m];
    if (m - 2 >= 1 and n + 1 <= h and n + 2 > h and n - 1 < 1)
        return F(n + 1, m - 2) + Matrix[n][m];
    return INT_MIN;
}

int main()
{
    int n, m, i, j, res;
    cin >> n >> m;
    h = n;
    w = m;
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= m; j++)
        {
            cin >> Matrix[i][j];
        }
    }
    if (n == 1 and m == 1)
        cout << Matrix[1][1];
    else
    {
        res = F(n, m);
        if (flag == 1)
            cout << res;
        else
            cout << "-";
    }
}


text:
Q: Best way to create SQL indices? What is the best way to create an SQL index in SQL database?
CREATE INDEX idx ON sometable (col1, col2, col3);

Or
CREATE INDEX idx1 ON sometable (col1);
CREATE INDEX idx2 ON sometable (col2);
CREATE INDEX idx3 ON sometable (col3);

Which is the difference between these 2 methods? Does it depends on the SQL implementation? (SQLite, MySQL, MSSQL, ...)?
Are there any efficiency considerations when using one of the two methods?

A: CREATE INDEX idx ON sometable (col1, col2, col3);

This will create a single index on all three fields together. This is perfect, if your queries will use all three fields for their WHERE clause most of the time:
SELECT (fields) FROM Table WHERE col1 = 1 AND col2 = 2 AND col3 = 3

This composite index will also be used when you query on col1 and col2 alone:
SELECT (fields) FROM Table WHERE col1 = 1 AND col2 = 2

but it cannot be used if you query on either col2 or col3 separately, or on col2 and col3 together:
SELECT (fields) FROM Table WHERE col2 = 2 AND col3 = 3  -- will *NOT* use index
SELECT (fields) FROM Table WHERE col2 = 2               -- will *NOT* use index
SELECT (fields) FROM Table WHERE col3 = 3               -- will *NOT* use index

On the other hand, if you use:
CREATE INDEX idx1 ON sometable (col1);
CREATE INDEX idx2 ON sometable (col2);
CREATE INDEX idx3 ON sometable (col3);

then you create three separate, individual indices on each of the fields. In this case, any query that uses just one of the columns will benefit from that column's index:
SELECT (fields) FROM Table WHERE col1 = 1   -- will use index on col1
SELECT (fields) FROM Table WHERE col2 = 2   -- will use index on col2
SELECT (fields) FROM Table WHERE col3 = 3   -- will use index on col3

however, if you query by two or all three columns together in a single query:
SELECT (fields) FROM Table WHERE col1 = 1 AND col2 = 2 AND col3 = 3

then only one of the three indices created will be used, and it will most likely be less efficient than a composite index on (col1, col2, col3) would be.
So yes, there's definitely a difference in how you create those indices, but there's no single "best way" to do this indexing. It really all depends on how you query your data as to which of the two options is the "better" one in your case.

A: The first one creates a composite index on 3 columns, whereas the second one creates a simple index on each column. Check out the explanation and examples in the MSDN article.
(See the examples section first and then go and read the definitions of each type of index, otherwise I feel the article is too intimidating)


text:
Q: jahia add tomcat web context For technical reasons we need to add a web context to jahia application so we add the tomcat web context (ex : /myApp).
We encounter some issues :

*

*Urls image in slider have the context 2 time (/myApp/myApp/), so the urls are wrong, no image is appeared.

*If we make an external link in menu to point in the same domain (relative root path like /my/new/path) it adds in server side the context (/myApp) so it create a url like /myApp/my/new/pah that we do not want. (We had /../my/new/path so it works).

A: The issue comes from a external module that doing wrong relative url, not from Jahia core. It's resolved with the last version of the module.


text:
Q: SQL query to find names of student who took only 4- credits courses There are 3 tables
Students (sid:integer, sname:string, age:integer)
Courses (cid:integer, cname:integer, credits:integer)
Grades(sid:integer, cid:integer, grade:string)

i would like to get students who only take courses with 4 credits
I have tried
SELECT sname FROM Students JOIN Grades ON Student.sid = Grades.sid
                           JOIN Grades ON Course.cid = Grades.cid
WHERE credits = 4

A: You can join the tables, group by student and set the condition in the having clause:
SELECT s.sid, s.sname
FROM Students s
INNER JOIN Grades g ON g.sid = s.sid
INNER JOIN Courses c ON c.cid = g.cid
GROUP BY s.sid, s.sname
HAVING SUM(c.credits <> 4) = 0


text:
Q: Is there a way to add Map coordinates in Django just as we add Datefield I have been working on this project of address book application. I've completed the project and now I have one small task pending.
Along with the address details, can I have a field in which someone can add a coordinate field. When we click on those coordinate it should redirect to Maps page(say google maps) where the place represent the coordinates should be displayed.
Thank you in advance


text:
Q: Datagridview retains waitcursor when updated from thread I have a DataGridView control in my Windows Forms Application.
I am adding rows to the grid using a background thread. I change the form's cursor to Waitcursor when the process starts and back to Default when it ends. This works well for the form, but not for the grid. When the form's cursor is changed back to default, the grid's cursor does not change, although the cursor over the rest of the form does.
Does this have anything to do with the fact that I am updating the grid from a background thread? (The cursor is being changed from the UI thread directly).
Edit: The background process raises an event, the handler checks the InvokeRequired property of the grid and decides if it needs to "Invoke" the method again from the main thread. So, in effect the actual UI update happens from the appropriate thread. I am not sure if this means that I am "using a background thread" or not. :|

A: I've had some problems doing single thread updating of my datagrids, where the datagrid did not reset to normal cursor after i've had waitcursor to true.
What I did was right after i went
this.UseWaitCursor = false;

I added
DatagridviewFoo.Cursor = this.Cursor;

Maybe it's just the same problem for you

A: I've had this problem as well. It was difficult to track down the cause, let alone a solution.
This issue only ever happened when I had a dialog box over the DGV control and the mouse clicked on a button to close the box such that when the box closed, the mouse was over a (resizable) column border. If the cursor ended up over a cell, the problem didn't arise. If I had to guess, I'd say the grid was seeing a column resize event as soon as the dialog box closed which wasn't properly handled.
Using Cursor.Current = Cursors.Default fixed my issue (without the need to explicitly reset the control's cursor). But maybe be aware that Application.UseWaitCursor = False didn't work even with the explicit control cursor reset.

A: I had a similar problem, but neither of the posted solutions worked for me. Mine was not caused by clicking a button above a movable column separator. It just randomly happened after opening and closing a dialog box. I'm pretty sure it came down to timing because .Net/Windows has issues when it comes to setting cursors and actually having them take effect. To try to overcome that, the library we use for showing and hiding the wait cursor calls - ack! - Application.DoEvents. I set a breakpoint in OnCursorChanged and saw that the cursor was sometimes actually getting set on a latter call to Application.DoEvents (used to keep the UI responsive while waiting for the file system to release a write lock on a file). So I guess sometimes the default cursor was getting turned back on before the call to set the wait cursor had fully taken effect. Anyway, my brute-force approach is to call
Cursor = Cursors.Default;

in my override of OnCellEnter (which always happens after the grid gets refreshed following the dialog box being closed). I'm not particularly proud of this, but it seems to work.


text:
Q: RegisterInputOutput() Error on the Remote Cluster, Apache Flink Execution of the following code in local version of Apache Flink does not generate any error, but on the remote cluster generates the below error!
Any help is appreciated!
 personRecords =  env.readCsvFile("dataPath/dataset.csv")
               .lineDelimiter("\n").fieldDelimiter(",")
               .includeFields("11").types(Integer.class, String.class);

 partitionedData = personRecords.map(new cleanerMap());

Error shown as following:
java.lang.Exception: Call to registerInputOutput() of invokable failed
        at org.apache.flink.runtime.taskmanager.Task.run(Task.java:529)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: The initialization of the DataSource's outputs caused an error: Could not read the user code wrapper: org.apache.flink.quickstart.myProj$cleanerMap
        at org.apache.flink.runtime.operators.DataSourceTask.registerInputOutput(DataSourceTask.java:89)
        at org.apache.flink.runtime.taskmanager.Task.run(Task.java:526)
        ... 1 more
Caused by: org.apache.flink.runtime.operators.util.CorruptConfigurationException: Could not read the user code wrapper: org.apache.flink.quickstart.myProj$cleanerMap
        at org.apache.flink.runtime.operators.util.TaskConfig.getStubWrapper(TaskConfig.java:284)
        at org.apache.flink.runtime.operators.BatchTask.instantiateUserCode(BatchTask.java:1465)
        at org.apache.flink.runtime.operators.chaining.ChainedMapDriver.setup(ChainedMapDriver.java:39)
        at org.apache.flink.runtime.operators.chaining.ChainedDriver.setup(ChainedDriver.java:78)
        at org.apache.flink.runtime.operators.BatchTask.initOutputs(BatchTask.java:1336)
        at org.apache.flink.runtime.operators.DataSourceTask.initOutputs(DataSourceTask.java:284)
        at org.apache.flink.runtime.operators.DataSourceTask.registerInputOutput(DataSourceTask.java:86)

A: TaskConfig.getStubWrapper() throws a CorruptConfigurationException if the user code class was not found.
I would check if the cleanerMap class is contained in your program jar file.


text:
Q: Android Parse Json Response To Java ArrayList I am trying to make a GET request to my WCF service via Volley and i want to parse its response to a Java ArrayList. Here is my method
    public ArrayList<Company> getCompanies(){

        String url = AUDITTRACKINGAPP_SERVICE_URI + "GetCompanies";
        String tagJsonReq = "companiesRequest";

        final ProgressDialog pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please Wait...");
        pDialog.show();

        final ArrayList<Company> companies = new ArrayList<Company>();

        JsonObjectRequest companiesRequest = new JsonObjectRequest(  Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        Log.v(TAG, "COMPANIES RESPONSE:" + response.toString());

                        try {
                            JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");

                            for (int i = 0; i < companiesJson.length(); i++) {

                                JSONObject jObject = (JSONObject)companiesJson.get(i);

                                Company company = new Company();
                                company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                                Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                                company.setCompanyName(jObject.getString("CompanyName"));
                                Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));

                                companies.add(company);
                            }

                        } catch (JSONException e) {
                            Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
                        }

                        pDialog.hide();
                    }
                },
                new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v(TAG, "COMPANIES onErrorResponse:" + error.getMessage());
                    pDialog.hide();
                }
            });

    AppController.getInstance().addToRequestQueue(companiesRequest, tagJsonReq);

    return companies;
}

JSON RESPONSE:

 {"GetCompaniesResult":[{"CompanyId":1,"CompanyName":"CompanyName1"},{"CompanyId":2,"CompanyName":"CompanyName2"}]}

I am able to get JSON response but ArrayList<Company> returns null. I think thatonResponse is a calback method and runs in an another thread so i cant populate the list but since i am a Android newbie i dont know how to manage this issue. Any help would be appreciated.

A: You need to create json object of each element of json array
try {
                            JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");

                            for (int i = 0; i < companiesJson.length(); i++) {

                    JSONObject obj = Website.getJSONObject(i);

                                Company company = new Company();
                                company.setCompanyId(Integer.parseInt(obj.getString("CompanyId")));
                                Log.v(TAG, "COMPANIES setCompanyId:" + obj.getString("CompanyId"));
                                company.setCompanyName(obj.getString("CompanyName"));
                                Log.v(TAG, "COMPANIES setCompanyName:" + obj.getString("CompanyName"));

                                companies.add(company);
                            }

                        } catch (JSONException e) {
                            Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
                        }

A: JsonObjectRequest works asynchronous because of that the main thread continue running and a new thread is created to run JsonObjectRequest and the result is that your returns is null. Call a method in your class to send the data back and call it when you finish managing the json data, for example:
public void manageCompaniesData(ArrayList<Company>){

    //YOUR CODE HERE.

}

Your code modified:
public ArrayList<Company> getCompanies(){

String url = AUDITTRACKINGAPP_SERVICE_URI + "GetCompanies";
        String tagJsonReq = "companiesRequest";

        final ProgressDialog pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please Wait...");
        pDialog.show();

        final ArrayList<Company> companies = new ArrayList<Company>();

        JsonObjectRequest companiesRequest = new JsonObjectRequest(  Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        Log.v(TAG, "COMPANIES RESPONSE:" + response.toString());

                        try {
                            JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");

                            for (int i = 0; i < companiesJson.length(); i++) {

                                JSONObject jObject = (JSONObject)companiesJson.get(i);

                                Company company = new Company();
                                company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                                Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                                company.setCompanyName(jObject.getString("CompanyName"));
                                Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));

                                companies.add(company);
                            }

                        } catch (JSONException e) {
                            Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
                        }
                        manageCompaniesData(companies);
                        pDialog.hide();
                    }
                },
                new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v(TAG, "COMPANIES onErrorResponse:" + error.getMessage());
                    pDialog.hide();
                }
            });

    AppController.getInstance().addToRequestQueue(companiesRequest, tagJsonReq);

    }

A: JSONArray objects have a function getJSONObject(int index) so you have to use
JSONObject jObject = companiesJson.getJSONObject(i);

instead of
JSONObject jObject = (JSONObject)companiesJson.get(i);

Try this code.
for (int i = 0; i < companiesJson.length(); i++) {
  JSONObject jObject = companiesJson.getJSONObject(i);
  Company company = new Company();
  company.setCompanyId(jObject.getInt("CompanyId")));
  company.setCompanyName(jObject.getString("CompanyName"));
  companies.add(company);
 }

instead of
for (int i = 0; i < companiesJson.length(); i++) {
  JSONObject jObject = (JSONObject)companiesJson.get(i);
  Company company = new Company();
  company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
  Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
  company.setCompanyName(jObject.getString("CompanyName"));
  Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));

  companies.add(company);
 }

A: Parse you json like this inside the for loop.Also Don't declare ArrayList companies as final.
Company company = new Company();
JSONObject jObject = (JSONObject)companiesJson.optJSONObject(i);
if(jObject != null){
   company.setCompanyId(jObject.optInt("CompanyId")));
   company.setCompanyName(jObject.optString("CompanyName"));
}

A: If You wanna json values for CompanyID and CompanyName try the below snippet.
for (int i = 0; i < companiesJson.length(); i++) {
                        JSONObject jObject = companiesJson.getJSONObject(i);
                        Company company = new Company();
                        company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                        Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                        company.setCompanyName(jObject.getString("CompanyName"));
                        Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));
                        companies.add(company);

A: if you get any JSON exception in logcat, try this once.
for (int i = 0; i < companiesJson.length(); i++) {

                            JSONObject jObject = companiesJson.getJSONObject(i);
                            Company company = new Company();
                            company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
                            Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
                            company.setCompanyName(jObject.getString("CompanyName"));
                            Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));
                            companies.add(company);
 }


text:
Q: How can I define a constant variable inside a recursive function in R? I want to create functions that compute the Simple Moving Average (SMA) and the Exponential Moving Average (EMA).
My problem is in the EMA implementation. I would like to set a constant variable inside the recursive function that is equal to one of its argument.
Here is my code:
#SMA
sma <- function(P,t,n)
{
  return(sum(P[(t-n):(t-1)])/n)
}

#EMA
recursive.ema <- function(P,t,n)
{
  # Here I want to create a constant variable that keeps in memory the first
  # value of t, i.e. the value of t before the first recursion, so I can use
  # it as argument of sma function.
  # Something similar to this: tmp <- t (t given from outside the function)

  b <- 2/(n+1)
  if (t == 1)
  {
    return(b*P[1] + (1-b)*sma(P,tmp,n))
  }
  return (b*P[t] + (1-b)*recursive.ema(P,t-1,n))
}

Here P is a vector, time series of prices, t is the index of the vector, the time in my model,  and n is any positive number, corresponding to n lagged periods at time t.

A: Would this work ?
e <-new.env()
test<-TRUE
assign("test",test,e)

recursive.ema <- function(P,t,n)
{
  test <-get("test",envir=e)
  if (test) {
    assign("t",t,envir=e)
    assign("test",FALSE,envir=e)
  } else {
    t=get("t",envir=e)
  }
  b <- 2/(n+1)
  if (t == 1)
  {
    return(b*P[1] + (1-b)*sma(P,tmp,n))
  }
  return (b*P[t] + (1-b)*recursive.ema(P,t-1,n))
}


text:
Q: Spectral gap of tempered distributions Hi,
Let $\Lambda\subset\mathbb{R}$ be an infinite discrete set of finite density (for simplicity one may take the density equals 1) and $\delta_{\lambda}$
is a unit mass located at the point $\lambda\in\Lambda$. Define the
tempered distribution $\delta_{\Lambda}=\underset{\lambda\in\Lambda}{\sum}\delta_{\lambda}$.
It is known that if there exists a finite set $\Sigma$
such that for every two successive elements of $\Lambda$, $\lambda,\mu$
we have $\lambda-\mu\in\Sigma$ and $\delta_{\Lambda}$ has a spectral
gap then $\Lambda$ must be periodic, i.e. a finite union of copies
of a translated lattice.
I am trying to understand if I can drop the condition of having a
finite set of differences. In other words I am trying to construct
a set $\Lambda$ so that $\delta_{\Lambda}$ will have a spectral
gap but $\Lambda$ will have an infinite set of differences. Obviously
for periodicity of $\Lambda$ I cannot drop this condition altogether
because $\Lambda$ cannot be periodic if its set of differences is
inifinite, but constructing such a distribution will show that the two conditions are separate.
And in a more general tone, How can one get intuition regarding whether a tempered distribution of the kind $\delta_{\Lambda}$ has a spectral gap at all?


text:
Q: How can I prevent executing comman code outside if-else block? page.ts
//all imports are made correctly

       export class page{

            constructor(){}//used DI correctly.

              public someFunction(){

             let result: any;

                if(x = true){
                   try{
                     result = this.serviceClass.doSomething();
                  }
                   catch(e){
                   //do some processing.
                  }
                }
                 else{
                    try {
                      result = this.serviceClass.doAnotherThing();
                     }
                    catch(e){
                   //do some processing.
                     }
                  }

                 console.log(result); //line 1
                 service2.oneThing(); ///line 2

                 //other tasks and common functions. //line 3
           }
          }

Question1: In the above piece of code, How do I stop the execution of line 1, line 2 and line 3? When any of the try block catches the exception.
Question2: How can I use only one try-catch block for both if - else statements?That is if any exception is caught either in if or in else block only one try-catch block will do everything, and the common code does not execute i.e line 1 line 2 & line 3.

A: Answer 1: Early return when an exception is caught in try block.
Answer 2: Use if/else in try block.
public someFunction(){

  let result;

  try {
    result = x ? this.serviceClass.doSomething() : this.serviceClass.doAnotherThing();

    console.log(result); //line 1
    service2.oneThing(); ///line 2

    //other tasks and common functions. //line 3
  } catch(e) {

  }

}

A: You can put the try block arround both conditions, which will automatically jump to the catch block as soon as an error occurs.
In the following example I try to demonstrate this.

function getResult1(shouldThrow){
  if (shouldThrow) throw new Error("FAILED TO GET RESULT 1");
  return 1;
}

function getResult2(shouldThrow){
  if (shouldThrow) throw new Error("FAILED TO GET RESULT 2");
  return 2;
}

function doIt(condition, shouldThrow){
  var result;
  try {
    if (condition){
      result = getResult1(shouldThrow);
    } else {
      result = getResult2(shouldThrow);
    }

    console.log("Successfully got result", result);

  } catch (e) {
    console.error('We ran into an error', e.toString());
  }
}

for(var i = 0; i < 4; i++){
   var shouldThrow = i % 2 == 0;
   var condition   = i > 2;
   console.log(`Trying condition = ${condition} and shouldThrow = ${shouldThrow}`);
   doIt(condition, shouldThrow);
   console.log("------------------");
}


text:
Q: In Excel, how can I automatically fill value in multiple columns based on contents of another sheet? How can I  fill multiple columns in excel based on the contents of another spreadsheet? I have tried using VLOOKUP, but I'm not sure how I can automatically fill multiple columns based on another sheet.
I have a sheet which looks like this:

In another spreadsheet, I would like to find a way to automatically record

*

*whether the user name it taken through binary code of 1/0, and

*the name of the person the code is taken by.

This is the type of sheet I am trying to create:

A: In the Status column, cell B2, put:
=MIN(1, IFNA(MATCH(A2, Sheet1!B:B,0), 0))

In the Name column, cell C2, put:
=IFNA(INDEX(Sheet1!A:A, MATCH(A2, Sheet1!B:B, 0)), "")

Copy the formulas down...
If you have many more columns to fill like that, then it becomes interesting to only perform the MATCH-operation once. In that case, create a hidden column (let's say at Z) where you put in cell Z2:
=MATCH(A2, Sheet1!B:B,0)

...and then use that result of Z2 in the other columns. So, at B2:
=MIN(1, IFNA(Z2, 0))

...and at C2:
=IFNA(INDEX(Sheet1!A:A, Z2), "")


text:
Q: El apartado "if" por muchos que ponga para encadenar, no me los detecta Al seguir viendo el video donde estoy aprendiendo Python relacionado con el Condicional IF. Los if siguen sin funcionar. Expongo el código:
import random

print("Bienvenido/a, adivina un numero de entre el 0 y el 10")

numero_ganador = random.randint(0, 10) #Esto para hacer random el numero
numero_azar = int(input("¿Cual crees que es el número de la suerte?"))

if numero_azar == numero_ganador:
    print("Felicidades, lo has acetado")

if numero_ganador > 10:
    print("Te has pasado un poco, es entre 0 y 10")

else:
    print("Este era el numero a adivinar {} ".format(numero_ganador))

Bien, a partir del apartado if numero_ganador > 10: print("Te has pasado un poco, es entre 0 y 10")
No me lo detecta y en la consola al poner un numero mayor a 10 no me pone el print. El primer IF y el ELSE si lo detectan y tengo mi resultado, pero lo que haya entre medio no me lo lee en la consola

A: Te has liado con los nombres de las variables. Lo correcto es:
numero_azar = random.randint(0, 10) #Esto para hacer random el numero
numero_ganador = int(input("¿Cual crees que es el número de la suerte?"))

También en el último print.
El código con los nombres corregidos es:
import random

print("Bienvenido/a, adivina un numero de entre el 0 y el 10")

numero_azar = random.randint(0, 10) #Esto para hacer random el numero
numero_ganador = int(input("¿Cual crees que es el número de la suerte?"))

if numero_azar == numero_ganador:
    print("Felicidades, lo has acetado")

if numero_ganador > 10:
    print("Te has pasado un poco, es entre 0 y 10")
else:
    print("Este era el numero a adivinar {} ".format(numero_azar))

A: otra forma de dar solucion, se modifico un poco
import random
print("Bienvenido/a, adivina un numero de entre el 0 y el 10")
numero_ganador = random.randint(0, 10) #Esto para hacer random el numero
numero_azar = int(input("¿Cual crees que es el número de la suerte?"))
if numero_azar == numero_ganador:
print("Felicidades, lo has acetado")
elif numero_azar > numero_ganador:
print("Te has pasado un poco, es entre 0 y 10")
else:
print(f"Este era el numero a adivinar {format(numero_ganador)} ")texto en negrita


text:
Q: App crashes when I press the button on phone I'm totally new to this and it's my first app that I'm building. The problem is that when I press the button from my first activity in order to go to the second one the app crashes.
Here is the activity code:
private TextInputLayout password;
private View login;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Button login = (Button)findViewById(R.id.btn_login);
    login.setOnClickListener(new View.OnClickListener(){
        @Override
        public  void onClick(View v){
            if (password.getEditText().getText().toString().equals("alex")) {
                finish();
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
            } else {
                Toast.makeText(LoginActivity.this, "Wrong Input", Toast.LENGTH_SHORT).show();
            }
        }
    });

}

A: You should have statement like this
password =(TextInputLayout)findViewById(R.id.your_id);

As I believe it is because password is not initialised. (You will get Null pointer exception)
You can modify your on create method like this
private EditText password;
private Button login;
   @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

    password =(TextInputLayout)findViewById(R.id.password);
        login =(Button)findViewById(R.id.btn_login);
        login.setOnClickListener(new View.OnClickListener(){
            @Override
            public  void onClick(View v){
                if (password.getEditText().getText().toString().equals("alex"))
                {

                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                 finish();
                } else {
                    Toast.makeText(LoginActivity.this, "Wrong Input", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

And don't forget to have an entry in manifest.xml file for MainActivity.class


text:
Q: How I could use tail call optimisation on this combination function? My exercise, that you can see here, says that I need to
implement a recursive version of C(n, k).
That's my solution:
module LE1.Recursao.Combinacao where

combina :: Integral a => a -> a -> a
combina n k | k == 0         = 1
            | n == k         = 1
combina n k | k > 0 && n > k = (combina (n - 1) k) + (combina (n - 1) (k - 1))
combina _ _                  = 0

Now I want to create a tail-recursive version of this function, so I don't get stack overflows for large numbers and also calculate the combination quicker!
I'm new to tail call optimisation, but I did that in Elixir for the Fibonacci series:
defmodule Fibonacci do
  def run(n) when n < 0, do: :error
  def run(n), do: run n, 1, 0
  def run(0, _, result), do: result
  def run(n, next, result), do: run n - 1, next + result, next
end

I understand this Fibonacci code and I think that the combination algorithm isn't too different, but I don't know how to start.

A: The traditional implementation looks like this:
combina n k = product [n-k+1 .. n] `div` product [1 .. k]

It runs instantly for just about as big a number as you care to put in, and fairly quickly for numbers bigger than you care to put in.
> :set +s
> combina 40000 20000
<answer snipped because it's way too big to be useful>
(0.74 secs, 837,904,032 bytes)

Meanwhile for your implementation, combina 30 15 took 7s and combina 40 20 took longer than I cared to wait -- multiple minutes, at least, even compiled with optimizations rather than interpreted.
It is possible to get still more efficient than this by choosing clever orders of multiplications and divisions, but it's significantly less readable.

A: Daniel Wagner's answer (or my other answer, or similar things) is the right way in practice. But if you want to use the recurrence described in the problem set but want your function to run in a reasonable amount of time, you'll have to structure the solution rather differently. Consider what happens for some n and k not near a base case.
combina n k
  = combina (n - 1) k + combina (n - 1) (k - 1)
  =   combina (n - 2) k       + combina (n - 2) (k - 1)
    + combina (n - 2) (k - 1) + combina (n - 2) (k - 2)

See how combina (n - 2) (k - 1) is calculated twice here? This process repeats many times, leading to your algorithm taking exponential time. Ouch. How can you fix that? Well, imagine making a table of all the results of combina. Now you can walk along each row of the table to calculate the next one, avoiding the repeated work. This is really just calculating Pascal's triangle.
combina :: Int -> Int -> Integer
combina n k
  | k > n || k < 0 = 0
  | otherwise = build n !! n !! k

step :: [Integer] -> [Integer]
step xs = 1 : zipWith (+) xs (drop 1 xs) ++ [1]

build :: Int -> [[Integer]]
build n0 = go (n0 + 1) [1]
  where
    go 0 _ = []
    go n row = row : go (n - 1) (step row)

The key idea is in step, which calculates each row from the previous one.

A: Daniel Wagner writes
combina n k = product [n-k+1 .. n] `div` product [1 .. k]

This can get rather inefficient for large n and medium-size k; the multiplications get huge. How might we keep them smaller? We can write a simple recurrence:
combina :: Integer -> Integer -> Integer
combina n k
  | k > n || k < 0 = 0
  | otherwise = combina' n k'
  where
    -- C(n,k) and C(n,n-k) are the same,
    -- so we choose the cheaper one.
    k' = min k (n-k)

-- Assumes 0 <= k <= n
combina' _n 0 = 1
combina' n k
  = -- as above
  product [n-k+1 .. n] `div` product [1 .. k]
  = -- expanding a bit
  (n-k+1) * product [n-k+2 .. n] `div` (product [1 .. k-1] * k)
  = -- Rearranging, and temporarily using real division
  ((n-k+1)/k) * (product [n-(k-1)+1 .. n] / product [1 .. k-1]
  = -- Daniel's definition
  ((n-k+1)/k) * combina' n (k-1)
  = -- Rearranging again to go back to integer division
  ((n-k+1) * combina' n (k-1)) `quot` k

Putting that all together,
combina' _n 0 = 1
combina' n k = ((n-k+1) * combina' n (k-1)) `quot` k

Just one problem remains: this definition is not tail recursive. We can fix that by counting up instead of down:
combina' n k0 = go 1 1
  where
    go acc k
      | k > k0 = n `seq` acc
      | otherwise = go ((n-k+1)*acc `quot` k) (k + 1)

Don't worry about the n `seq` ; it's of very little consequence.
Note that this implementation uses O(min(k,n-k)) arithmetic operations. So if k and n-k are both very large, it will take a long time. I don't know if there's any efficient way to get exact results in that situation; I believe that binomial coefficients of that sort are usually estimated rather than calculated precisely.


text:
Q: jhipster bootswatch yo generator not installed Good morning,
i want to add bootswatch module to change theme of jhipster project as needed. Following the guide https://www.npmjs.com/package/generator-jhipster-bootswatch I installed the npm install -g generator-jhipster-bootswatch module successfully. I get an error when I run the next command yo jhipster-bootswatch
enter image description here
The output of the yo doctor command reveals no problems with this
enter image description here
Do you have any tips to resolve this message?


text:
Q: accourding to room availibility i want to show available in calander <script>
events: [{
          title: 'Available',
          start: new Date(y, m, d),
          backgroundColor: "#f56954", //red
          borderColor: "#f56954" //red
            }],
</script>

in the database table, there are some field like check-in date check out date and room_type_id according to this I want to display availability in the calendar

A: if events is an array of room, you can iterate through it:
const events = [{
          title: 'Available',
          start: new Date(y, m, d),
          backgroundColor: "#f56954", //red
          borderColor: "#f56954" //red
            }],
const availableRooms = events.filter(el => el.title === "Available")
if(availableRooms.length === 0){ // It means that no rooms are available
    const unavailableRooms = events.filter(el => el.title === "Unavailable")
    {...}
} else { // Many/all rooms are available
    {...}
}