text:
Q: Index match max/min scores (Java) I am working through a coding assignment and am close to completion save for my final print statement which needs to match names w/ scores for max and min.
I have been able to get appropriate values in two sentences using two if statements, but I am a bit stumped on how to get my indexing correct to align names to scores w/ max and min.
I am not able to use classes or additional / different methods other than arrays and indexing.
    //Create method StudentMax
private static int StudentMax(int[] Scores) {
    int ScoreMax = Scores[0];
    for (int i = 0; i < Scores.length; i++){
        if (Scores[i] > ScoreMax){
            ScoreMax = Scores[i];
        }
    }
    return ScoreMax;
}

//Create method StudentMin
private static int StudentMin(int[] Scores) {
    int ScoreMin = Scores[0];
    for (int i = 0; i < Scores.length; i++){
        if (Scores[i] < ScoreMin) {
            ScoreMin = Scores[i];
        }
    }
    return ScoreMin;
}

public static void main(String[] args) {

    //Call Scanner
    Scanner scan = new Scanner(System.in);

    //User Welcome
    System.out.println("Welcome to the student score sorter.");
    System.out.println("\nThis program will accept a number of student names and score values, then find the highest and lowest score.");
    System.out.println("\nThen will return the names and max/min scores.");

    //User Prompt Enter number of students
    System.out.println("\nHow many students would you like to enter: ");
    int StudentCount = scan.nextInt();

    //Create arrays: Scores, StudentFirst, StudentLast
    int [] Scores = new int[StudentCount];
    String [] StudentFirst = new String [StudentCount];
    String [] StudentLast = new String [StudentCount];

    for (int i = 0; i < Scores.length; i++) {
        System.out.println("\nStudent " + (i+1)+":");
        System.out.println("\nEnter Student's name:");
        StudentFirst[i] = scan.next();
        StudentLast[i] = scan.next();
        System.out.println("\nEnter Student's score (0-100):");
        Scores[i] = scan.nextInt();
    }

    int max = StudentMax(Scores);
    int min = StudentMin(Scores);

    for (int i = 0; i < Scores.length; i++) {
        System.out.println("\n"+StudentFirst[i] + " " + StudentLast[i] +":      " + Scores[i]);
    }

    for (int i = 0; i < Scores.length; i++)  {
        if (Scores [i] == max) {
            System.out.println("\n"+ StudentFirst[i] +" "+ StudentLast[i] + " has the highest score => " +max+ " and " + StudentFirst[i]+" " + StudentLast[i]+ " has the lowest => " +min);
        }
    }

    //This is the sentence format that I need to make work, but I am struggling to understand how to align the index for names and scores.
    //System.out.println("\n"+StudentFirst[i] +" "+ StudentLast[i]+ " has the highest score => " +max+ " and " +StudentFirst[i] +" "+ StudentLast [i]+ " has the lowest score => " +min);

    //Scan Close
    scan.close();
    //Close Program
}

}

A: Pass back the index not the value
private static int StudentMin(int[] Scores) {
    int ScoreMin = Scores[0];
    int index = 0;
    for (int i = 0; i < Scores.length; i++){
        if (Scores[i] < ScoreMin) {
            ScoreMin = Scores[i];
            index = i;
        }
    }
    return index;
}

Then you can use it later
int index = StudentMax(Scores);

System.out.println("\n"+ StudentFirst[index] +" "+ StudentLast[index] + " has the highest score => " +Scored[index]);

Note Please pay attention to Java naming conventions


text:
Q: Azure DevOps: work item type rules triggered by Board Column I would like to do changes to my work items automatically when working in Kanban board. For example, if I drag work item type to other column (changing Board Column field value) - I want to place a tag saying it's current Board Column value.
This is currently not available in Rules settings for work item types.
Where is the best place to put ADO Boards enhancement requests?

A: Your requirement can be achieved by alternative. Generally, when you drag work item type to other column, the state filed is changed too. So you can create a tag filed and add rules to set tag value when state changed. Check the following steps:

*

*Create a tag field:

*Create rules for each state changed. For example:

By the way, if you have new ideas, you could submit suggestions at website below:
https://developercommunity.visualstudio.com/content/idea/post.html?space=21

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to limit number of characters typed in a textbox in MFC? I have 2 questions...my 1st question is how do I limit the number of character typed in a textbox in MFC..say if I want the user to type only 4 characters..the text box should take only 4 character.And my 2nd question is when it exceeds the character limit it should jump to the next textbox/tab control.I tried using the following code..but it seem to not work in my case...Please help me if you know any alternatives...
CEdit::SetLimitText(4);

A: handle the EN_CHANGE message (OnEnChange). In that handler, find the number of chars the textbox has. If it's more than 4, remove the last ones. If it's four, use NextDlgCtrl() to tab to the next control or use SetFocus() to set the focus to a specific control.


text:
Q: Unable to automate clicking of button in Mobile app I am having trouble in simulating a click on a simple button (id = btn_sign_in) in a mobile app. I have tried a lot of combination using By.xpath, By.CLassname etc. but I keep getting error which is shown below.
First, here is my code.
public class Firstflow {
    static DesiredCapabilities dc = new DesiredCapabilities();
    @SuppressWarnings("rawtypes")
    static AndroidDriver driver;
    static AppiumDriver <MobileElement> driver_App;
    @SuppressWarnings("rawtypes")
    public static void main(String[] args) throws MalformedURLException, InterruptedException{
        dc.setCapability("deviceName", "emulator-5444");
        dc.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.mol.molwallet.uat");
        //dc.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.mol.molwallet.module.start.UserGuidance.UserGuidanceActivity");
        //dc.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.mol.molwallet.module.login.SignPageActivity");
        System.out.println(dc);
        dc.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.mol.molwallet.module.start.SplashActivity");
        dc.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "60");
        dc.setCapability("noReset", "true");
        driver_App = new AndroidDriver<MobileElement>(new URL("http://localhost:4723/wd/hub"), dc);
        driver_App.setLogLevel(Level.INFO);
        Thread.sleep(5000);
        String gps = driver_App.getPageSource();
        System.out.println(gps);
        //driver.findElement(By.xpath("//div/child::*[normalize-space()='SKIP']")).click();
        //driver.findElement(By.xpath("//android.widget.TextView[@text='SKIP']")).click();
        Thread.sleep(1000);
        //driver.findElement(By.xpath("//*[@text='LOG IN']")).click();
        //driver.findElement(By.xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.LinearLayout/android.widget.Button[2]")).click();
        driver_App.findElement(By.id("btn_sign_in")).click();
        driver_App.findElement(By.xpath("//*[@text='Region']")).click();
        driver_App.findElement(By.xpath("//*[@text='Malaysia']")).click();
        driver_App.findElement(By.xpath("//*[@id='etAccount']")).sendKeys("123456");
        driver_App.findElement(By.xpath("//*[@text='NEXT']")).click();
    }
}

The error message is as below:
INFO: Executed: [f0d477cf-ac78-426a-b2a8-9e08a3443e86, findElement {using=id, value=btn_sign_in}]
Exception in thread "main" org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=1, ELEMENT=1}
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'RZB-MY-041', ip: '192.168.60.194', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_211'
Driver info: driver.version: AndroidDriver
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:370)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:413)
    at io.appium.java_client.DefaultGenericMobileDriver.findElementById(DefaultGenericMobileDriver.java:70)
    at io.appium.java_client.AppiumDriver.findElementById(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElementById(AndroidDriver.java:1)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
    at Firstflow.main(Firstflow.java:45)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to org.openqa.selenium.WebElement
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
    ... 13 more

I see two errors here:
a) Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=1, ELEMENT=1}
b) java.util.HashMap cannot be cast to org.openqa.selenium.WebElement
    at org.openqa.selenium.remote.RemoteWebDriver.findElement
I am using Appium Server's element inspector to get the element's detail. Attached is the screenshot of the inpector's result.

I have try plenty findElement's syntax, and even change AndroidDriver to AppiumDriver, to no avail. I really hope it's nothing to do with any upgrading or downgrading of libraries. By the way, I am using Eclipse to write the automation test, so I do not have dependencies in Build.gradle or Maven. I just hope to have advice on what syntax should I use to click on the element. Thanks.

A: *

*It looks like you're trying to access the elements which are in the WebView and in order to be able to access the WebView content you need to explicitly configure it for debugging

*Using Thread.sleep() is a some form of a performance anti-pattern, consider using WebDriverWait instead, check out How to use Selenium to test web applications using AJAX technology, the concept is the same for Appium tests

*I believe you should also add the next line to your driver initialization routine:
dc.setCapability("automationName", "uiautomator2");

as UIAutomator2 is the automation name you should be using if you're automating Android 5 or higher


text:
Q: Exit all called KornShell (ksh) scripts How can a KornShell (ksh) script exit/kill all the processes started from another ksh script?
If scriptA.ksh calls scriptB.ksh then the following code works good enough, but is there a better solution for this?:
scriptA.ksh:
#call scriptBSnippet
scriptBSnippet.ksh ${a}

scriptB.ksh:
#if error: exit this script (scriptB) and calling script (scriptA)#
kill ${PPID}
exit 1

To add complexity what if scriptA calls scriptB which calls scriptC, then how to exit out of all three scripts if there is an error in scriptC?
scriptA.ksh:
#call scriptBSnippet
scriptBSnippet.ksh ${a}

scriptB.ksh:
#if error: exit this script (scriptB) and calling script (scriptA)#
kill ${PPID}
exit 1

scriptC.ksh:
#if error: exit this script (scriptC) and calling scripts (scriptA, scriptB)#
#kill ${PPID}
#exit 1

Thanks in advance.

A: Killing all processes started by the same script is a bit of a brute force method.
It would be best to have some method of communication between the processes that would allow them to gracefully shutdown.
However, if all processes are in the same process group, you can send a signal to the entire process group:
kill -${Signal:?} -${Pgid:?}

Note that two arguments are required in this case.  A single argument starting with - is always interpreted as a signal.
Run some tests to see which processes get included in the process group.
parent.sh:
Shell=ksh
($Shell -c :) || exit

$Shell child1.sh & pid1=$!

$Shell child2.sh & pid2=$!

$Shell child3.sh & pid3=$!

ps -o pid,sid,pgid,tty,cmd $PPID $$ $pid1 $pid2 $pid3
exit

child.sh:
sleep 50

If you run parent.sh from a terminal - it will become the process leader.
granny.sh:
Shell=ksh
($Shell -c :) || exit

$Shell parent.sh &

wait
exit

If you run parent.sh from another script granny.sh, then that will be the process group leader, and will be included when you use the kill -SIG -PGID method.
See also this answer to:
What are "session leaders" in ps? for some background on sessions and process groups.


text:
Q: NodeJS process disconnects on SSH session logout I am doing SSH on the server, which is Ubuntu 14.04 server. I tried various things to keep the Node server running. But as soon as I type exit and disconnect the server from my Ubuntu Desktop the Node server is also disconnected.
Though it is running on the server. When I SSH into the server I can access it.
I have tried these :
nohup node server.js &

nohup node server.js > /dev/null 2> error.log < /dev/null &

sudo nohup supervisor server.js &

forever start server.js

Also I tried using tmux and screen. Its the same problem with all of these. As soon as I disconnect the SSH the node server is not available. But when I just login to the server, it is available again.
What am I missing?

A:
Though it is running on the server

seems to contradict

As soon I disconnect the ssh, it terminates

Are you doing anything special with your ssh session? ( like forwarding server port to a client ) How do you check if server is running?
Possible reasons:
1) You test using server's localhost when on server and server IP from client: check you are binding your server to "0.0.0.0" address and not 127.0.0.1
2) You have some kind of port forwarding and connect to server vi client localhost:forvarded_port -> ssh -> server localhost:remote forward side port. - Checj you are listening on 0.0.0.0, that server IP is not blocked by firewall and try to access it via direct ip/port


text:
Q: How to Send Email using office 365 exchange online in C#? I have seen many examples related to sending mails via office 365 SMTP but cant find any help for
office 365 exchange online using c#.
It would be great some one can help me in this with an example so that I can understand the difference between these two.

A: http://msdn.microsoft.com/en-us/library/office/dn567668(v=exchg.150).aspx
This helped me, it has got proper reference for all the queries you might have.


text:
Q: How to do power save on a ARM-based Embedded Linux system? I plan to develop a nice little application that will run on an arm-based embedded Linux platform; however, since that platform will be battery-powered, I'm searching for relevant information on how to handle power save.
It is kind of important to get decent battery time.
I think the Linux kernel implemented some support for this, but I can't find any documentation on this subject.

*

*Any input on how to design my program and the system is welcome.

*Any input on how the Linux kernel tries to solves this type of problem is also welcome.
Other questions:

*

*How much does the program in user space need to do?

*And do you need to modify the kernel?

*What kernel system calls or APIs are good to know about?

Update:
It seems like the folks involved with the "Free Electrons" site have produced some nice presentations on this subject.

*

*http://free-electrons.com/services/power-management/

*http://free-electrons.com/docs/power

*http://free-electrons.com/docs/optimizations
But maybe someone else has even more information on this subject?

Update:
It seems like Adam Shiemke's idea to go look at the MeeGo project may be the best tip so far.
It may be the best battery powered Embedded Linux project out there at this moment.
And Nokia is usually kind of good at this type of thing.

Update:
One has to be careful about Android since it has a "modified" Linux kernel in the bottom, and some of the things the folks at Google have done do not use baseline/normal Linux kernels. I think that some of their power management ideas could be troublesome to reuse for other projects.

A: You can do quite a bit of power-saving without requiring any special support from the OS, assuming you are writing (or at least have the source code for) your application and drivers.
Your drivers need to be able to disable their associated devices and bring them back up without requiring a restart or introducing system instability.  If your devices are connected to a PCI/PCIe bus, research which power states they support (D0 - D3) and what your driver needs to do to transition between these low-power modes.  If you are selecting hardware devices to use, look for devices that adhere to the PCI Power Management Specification or have similar functionality (such as a sleep mode and a "wake up" interrupt signal).
When your device boots up, every device that has the ability to detect whether it is connected to anything needs to do so.  If any ports or buses detect that they are not being used, power them down or put them to sleep.  A port running at full power but sitting unused can waste more power than you might think it would.  Depending on your particular hardware and use case, it might also be useful to have a background app that monitors device usage, identifies unused/idle resources, and acts appropriately (like a "screen saver" for your hardware).
Your application software should make sure to detect whether hardware devices are powered up before attempting to use them.  If you need to access a device that might be placed in a low-power mode, your application needs to be able to handle a potentially lengthy delay in waiting for the device to wake up and respond.  Your applications should also be considerate of a device's need to sleep.  If you need to send a series of commands to a hardware device, try to buffer them up and send them out all at once instead of spacing them out and requiring multiple wakeup->send->sleep cycles.
Don't be afraid to under-clock your system components slightly.  Besides saving power, this can help them run cooler (which requires less power for cooling).  I have seen some designs that use a CPU that is more powerful than necessary by a decent margin, which is then under-clocked by as much as 40% (bringing the performance down to the original level but at a fraction of the power cost).  Also, don't be afraid to spend power to save power.  That is, don't be afraid to use CPU time monitoring hardware devices for opportunities to disable/hibernate them (even if it will cause your CPU to use a bit more power).  Most of the time, this tradeoff results in a net power savings.

A: One of the most important things to think of as a power aware application developer is to avoid unnecessary timers. If possible use interrupt driven solutions instead of polled solutions. If a timer must be used then use as long poll interval as is possible.
For example if something special should be done at a certain room temperature it is unnecessary to check the temperature every 100 ms since temperature in a room changes slowly. A more reasonable polling interval is could be 60 s.
This affects the power consumption in several ways. In Linux the CPUIDLE subsystem takes the CPU (SOC) to as deep power saving state as possible depending on when it predicts the next wakeup to occur. Having a lot of timers in a system will fragment the sleep making it impossible to go to the deeper sleep states for longer periods. A typical deep sleep state for CPUIDLE turns the CPU off but keeps the RAM in self refresh. When a timer triggers the CPU will boot and serve the timer of the application.

A: I haven't actually done this, but I have experience with the two apart (Linux and embedded power management). There are two main Linux distributions that come to mind when thinking about power management, Android and MeeGo. MeeGo uses (as far as I can tell) an unmodified 2.6 kernel with some extras hanging on. I wasn't able to find a lot on exactly what their power management strategy is, although I suspect more will be coming out about it in the near future as the product approaches maturity.
There is much more information available on Android, however. They run a fairly heavily modified 2.6 kernel. You can see a good bit on the different strategies implemented in http://elinux.org/Android_Power_Management (as well as kernel drama). Some other links:
https://groups.google.com/group/android-kernel/browse_thread/thread/ee356c298276ad00/472613d15af746ea?lnk=raot&pli=1
http://www.ok-labs.com/blog/entry/context-switching-in-context/
I'm sure that you can find more links of this nature. Since both projects are open source, you can grab the kernel code, and probably get further information from people who actually know what they are talking about in forms and groups.
At the driver level, you need to make sure that your drivers can properly handle suspend and shut devices off that are not in use. Most devices aimed at the mobile market offer very fine-grained support to turn individual components off, and to tweak clock settings (remember, power is proportional to clock^2).
Hope this helps.

A: It's not actually your topic, but it might come in handy to log your progress: i was looking for testing / measuring my embedded linux system. chris desjardins from this forum recommended me this:
I have successfully used bootchart in the past:
http://elinux.org/Bootchart
Here is a list of other things that may also help:
http://elinux.org/Boot_Time


text:
Q: matlab libsvm multiclass one against all classification I am new to classification and trying to do multiclass classification using libsvm. I have song features and want to classify then in 3 classes. Code works but the output (pred) give only one label for all test data. for example pred = [2;2;2;2];
Any change I do has not effect on output. I am not getting where I am going wrong. Can anyone help me out pls. Below is the code
load 113gender

s=cellstr(types);
[~,~,labels] = unique(s);
data = allfeature;
numInst = size(data,1);
numLabels = max(labels);
numTest = size(alltest,1);

trainData = data;
trainLabel = labels;
testData = alltest;
%testLabel = ones(22,1);
%testLabel = [1;1;1;1;1;1;2;2;2;2;2;2;2;2;3;3;3;3;3;3;3;3];
testLabel = [3;3;3;3;3;3;2;2;2;2;2;2;2;2;1;1;1;1;1;1;1;1];

%# train one-against-all models
model = cell(numLabels,1);
for k=1:numLabels
    model{k} = svmtrain(double(trainLabel==k), trainData, '-c 1 -g 0.2 -b 1');
end

%# get probability estimates of test instances using each model
prob = zeros(numTest,numLabels);
for k=1:numLabels
    [~,~,p] = svmpredict(double(testLabel==k), testData, model{k}, '-b 1');
    prob(:,k) = p(:,model{k}.Label==1);    %# probability of class==k
end

%# predict the class with the highest probability
[~,pred] = max(prob,[],2);
acc = sum(pred == testLabel) ./ numel(testLabel)
C = confusionmat(testLabel, pred)


text:
Q: Django inheritance and parent object related name I'm upgrading a project from django 1.8 to 1.10 and it looks like django has improved the check of eventual name collision between foreign keys and model inheritance.
This is obviously a good thing, but the projet I need to upgrade is a big one and it would be a hell to rename a model.
Let me explain the problem : I have a base class called Parent and many children which are linked together, like so :
class Parent(models.Model):
    title = models.CharField(max_length=10)

class ChildA(Parent):
    description = models.TextField()

class ChildB(Parent):
    description = models.TextField()
    childa = models.ForeignKey(ChildA)

The clash here is that a childb object has 2 "childa" attributes :

*

*The "childa" ForeignKey

*The instance inherited by the ChildA model (because childb has also the parent attributes).

The 2 obvious solutions here are :

*

*Rename the ForeignKey ChildB.childa to ChildB.somethingelse

*Rename the ChildA model to something else.

Both solutions costs a lot and will probably introduce new bugs.
So I wondered : Is it possible to rename the reverse related name of the inherited object ?
For example :
p = Parent.objects.get(pk=1)
print p.childa_child  # Hit the ChildA instance

I have no idea if I'm clear enough but I'll keep this question up to date.
==== EDIT ====
To be more concise, if I have 2 models class Parent(models.Model) and class Child(Parent), a dynamic attribute parent.child is created.
Is it possible to edit this attribute name without touching the class name ?

A: Multi-table inheritance creates an implicit OneToOneField field between the base model and the subclass.
Django allows you to modify this relationship by explicitly setting the one to one field.
class Parent(models.Model):
    title = models.CharField(max_length=10)

class ChildA(Parent):
    parent = models.OneToOneField(to=Parent, parent_link=True)
    description = models.TextField()

class ChildB(Parent):
    parent = models.OneToOneField(to=Parent, parent_link=True)
    description = models.TextField()
    childa = models.ForeignKey(ChildA)

The important bit here is the parent_link=True argument which tells Django to use this field declaration for managing the multi-table inheritance with these two models.
So you can now set related_name='+' to prevent Django from creating a reverse relationship or you can set related_name to a more unique name:
class ChildA(Parent):
    parent = models.OneToOneField(to=Parent, parent_link=True, related_name='child_a_here')
    description = models.TextField()

class ChildB(Parent):
    parent = models.OneToOneField(to=Parent, parent_link=True, related_name='child_b_here')
    description = models.TextField()
    childa = models.ForeignKey(ChildA)

A: I'm a little confused as to how ChildB has to two ChildA links, it looks like you left out some relationship fields from the models perhaps? Regardless, what I think you are looking for is the related_name parameter.
So with:
class ChildB(Parent):
    description = models.TextField()
    childa = models.ForeignKey(ChildA, related_name='b_children')

You could do a query like so:
a = ChildA.objects.get(id=1)
print(a.b_children)

You may also be interested in abstract models.


text:
Q: use variable for style on ionic i would like to know if it is possible to use variable, declared in my ts file for styling my ionic components.
I know i can do it by declaring the variables as globals, but as they are not fixed, i have to declare then in my ts file.
Example:
i have this code, witch is working:
  <ion-col style=" height: 170px; background: rgb(226, 45, 144)" > {{room.name}}</ion-col>

But i want something like:
<ion-col style=" height: room.height; background: room.bckg_color" > {{room.name}}</ion-col>

Thanks for your help.

A: I don't have an account for Ionic Academy, can you share the answer ?
Otherwise, this would be my answer,
this is called "inline style", and it can be defined with something like:
<ion-col [style.height.%]="room.height" [style.backgroundColor]="room.bckg_color" >
   {{room.name}}
</ion-col>

Or Ionic 1
<ion-col [ngStyle]="{height: room.height, backgroundColor: room.bckg_color}">
   {{room.name}}
</ion-col>


text:
Q: importerror when I use pathos I try to use pathos for multiprocessing,but when I start the
process, I get the ImportError:no module named pp,please help me.
I download pathos from github, install by python setup.py, python version 2.7.8,

A: I'm the pathos author.  pathos has a few dependencies, and if you are installing pathos by hand (as you are doing now), you have to get all of the dependencies for it fully work.
The easiest thing to do is to use pip, and pip install pathos.
Or, you can first install setuptools, and then repeat what you already have done (install by hand), and setuptools will grab and install the dependencies for you.
Or if you do want to do everything the hard way… then you need to install dill, pox, ppft, and multiprocess.  Install them before installing pathos.
It's typically much much easier if you have setuptools installed.


text:
Q: HTTP 2.0 Over the Wire (Raw) Are there any tools to see what is coming through the wire (Raw request and response) for HTTP 2.0?
I used Fiddler and saw only HTTP 1.1 data.
I enabled HTTP 2.0 / SPDY in Chrome and visited https://http2.akamai.com to see the request and response.

A: Wireshark has support for HTTP/2.0 (https://wiki.wireshark.org/HTTP2)
You can also simply check the frames using the built-in Chrome packet monitor.
Open a tab to chrome://net-internals, select 'SPDY' (or 'HTTP/2' in most recent versions) in the top left menu and click 'View live SPDY sessions' or 'View live HTTP/2 sessions'.
Whenever another tab is using a new SPDY or HTTP/2 connection, you'll be able to inspect the stream details from this tab.


text:
Q: Stop CSS transition from moving text I have a series of items that when hovered change the border and box-shadow properties. However, during the transition both the text on the page and inside the container move to accommodate the transition. I'm struggling to find a way to stop this from occurring:

            Question 1?

CSS:
.faq-container {
    width: 100%;
    padding: 15px;
    border: 1px solid #dedede;
}

.faq-container:hover {
    border: 4px solid #0052e7;
    transition: 0.2s ease all;
    cursor: pointer;
}

.faq-container>div a {
    text-decoration: none;
    font-size: 24px;
    font-weight: bold;
    color: #000;
}

.faq-icon {
    float: right;
    font-size: 28px;
    font-weight: bold;
    color: #aaa;
}

A: You're adding to the border so that means everything has to shift to accommodate the added pixels in the border.
Option #1
Transition the border-color property from transparent to a color. Instead of transitioning the border width.
Option #2
Absolutely position the element getting a border so its removed from the DOM flow and can't "move" when you add to the size by changing the border.
Option #3
Create another element BEHIND the text container with the border color and then scale that element on hover so it looks like the border expands but its really the thing behind your content scaling so nothing moves.


text:
Q: How does the type deduction work for string literals in C++? In C++ if I have a generic function:
template <typename T>
void func(T& s)
{
    std::cout << "in generic\n";
    std::cout << typeid(s).name();
}

T will get deduced to typeid(s).name().
But how come if I do:
func("test");

That generic function works, but this one doesn't:
void func(const char*& s)
{
    std::cout << "in overloaded\n";
    std::cout << typeid(s).name();
}

I know that it'll work if I change const char*& to const char* or const char* const&in the overloaded function's signature, and that if I want to pass an argument to the overloaded function it must be non-temporary. I just don't understand what happened to T&, isn't it supposed to turn into const char*& after the deduction?

A: String literals are arrays of const characters. So in the case of the template function called like this:
func("test");

T is deduced as char const[5]. And s is a reference to the string literal, and its type is char const (&)[5]. That is, a reference to an array of 5 const char.

A: The type of "test" is const char[5]. When calling a function template and using an argument to deduce a parameter of reference type, the array-to-pointer conversion does not happen. So the generic function deduces T to be const char[5] - you can see that the output for "test" and for a const char* differs:
template<typename T>
void func(T& s){

    std::cout << "in generic\n";
    std::cout << typeid(s).name() << '\n';
}

int main()
{
    func("test");
    const char *c = "test";
    func(c);
}

GCC output:
in generic
A5_c
in generic
PKc

On the other hand, in the non-generic function, you want a reference to a non-const pointer to const char. However, as the type of "test" is const char[5], it has to undergo the array-to-pointer conversion, which means that the resulting const char* is a temporary (an rvalue). As such, it cannot bind to a reference to non-const.


text:
Q: Large tag counts off by a factor of 10 on Android App For tags with >= 10,000 questions, the tag counts are misrepresented on my StackExchange Android app.
Specifically, they are reduced by a factor of 10.
Here is a screenshot of the highest tag counts on Stackoverflow (website)

And here are the same tags on the Android app:

You can see how javascript, for example, has 945,345 questions, but the app displays this as 94.5k.
A related phenomenon: the tags seem to be sorted correctly, it is just that the displayed numbers are wrong; see the following screenshot where numbers "drop" from 1k to 9,950.

This is on a Nexus 5 running Android 5.1.1 and Stack Exchange Android App version 1.0.73

A: As of v1.0.82 (beta), it has been fixed. The app now shows the tag count properly.


text:
Q: What's the term for re-implementing an old API in terms of a newer API The reason for doing it is to solve the case when a newer API is no longer backwards compatible with an older API.
To explain, just say that there is an old API v1.0. The maker of this API decides it is broken and works on a new API v1.1 that intentionally breaks compatibility with the old API v1.0. Now, any programs written against the old API cannot be recompiled as-is with the new API.
Then lets say there is a large app written against the old API and the developer doesn't have access to the source code. A solution would be to re-implement a "custom" old API v1.0 in terms of the new API v1.1 calls. So the "custom" v1.0 API is actually keeping the same interface/methods as the v1.0 API but inside its implementation it is actually making calls to the new API v1.1 methods.
So the large app can be then compiled and linked against the "custom" v1.0 API and the new v1.1 API without any major source code changes.
Is there a term for this practice?
There's a recent example of this happening in Jamie Zawinski's port of XScreenSaver to the iPhone - he re-implemented the OpenGL 1.3 API in terms of the OpenGL ES 1.1 API. In this case, OpenGL 1.3 represents the "old" API and OpenGL ES 1.1 represents the "new" API.

A: If I understand you right, you'd be implementing the adapter pattern to isolate the API calls from the rest of your application. So when the time came to switch from v1.0 to v1.1, you'd just modify your API wrapper implementation to make different calls and the rest of your application wouldn't know or care.
So your application structure would look something like this:
.----------.       .-------------.       .----------.
| Your App | ----> | API Wrapper | ----> | API v1.0 |
'----------'       '-------------'       '----------'
                              |
                              |          .----------.
                              `--------> | API v1.1 |
                                         '----------'

A: Thanks to Anna Lear and Yannis Rizos for their answer, i.e. that the API 1.0 has effectively become an adaptor for API 1.1.
I just wanted to put forward a more specific answer. In my case the API 1.0 has retained the same public interface, so the application doesn't need to change. The only thing that has changed is the internal implementation of the API 1.0 itself - it now has a dependency on the new API 1.1. So instead of "porting the application" to use API 1.1, we're "porting the API".


text:
Q: Get the types of the keys in a dictionary Is there a "clean" way to take the type of the keys of a dictionary in python3?
For example, I want to decide if one of this dictionaries has keys of type str:
d1 = { 1:'one', 2:'two', 5:'five' }
d2 = { '1':'one', '2':'two', '5':'five' }

There is several ways to achieve this, for example, using some as:
isinstance(list(d2.keys())[0], type('str'))

But this is quite annoying because d2.keys() is not indexable, so you need to convert it into a list just to extract the value of one element of the list and check the type.
So has python3 something as get_key_type(d2)?
If not, is there a better (cleaner) way to ask if the key of a dictionary is of type str?

A: If you want to find out if your dictionary has only string keys you could simply use:
>>> set(map(type, d1)) == {str}
False

>>> set(map(type, d2)) == {str}
True

The set(map(type, ...)) creates a set that contains the different types of your dictionary keys:
>>> set(map(type, d2))
{str}
>>> set(map(type, d1))
{int}

And {str} is a literal that creates a set containing the type str. The equality check works for sets and gives True if the sets contain exactly the same items and False otherwise.

A: If i understood your question right, the cleanest way i know to get types of all keys in a dict is :
types1 = [type(k) for k in d1.keys()]
types2 = [type(k) for k in d2.keys()]

or if you want to have all the unique types you can use:
types1 = set(type(k) for k in d1.keys())
types2 = set(type(k) for k in d2.keys())

like that you'll know if there is a single or multiple types. (Thanks @Duncan)
this returns lists with types of keys found in respective dicts:
o/p:
[<class 'int'>, <class 'int'>, <class 'int'>]
[<class 'str'>, <class 'str'>, <class 'str'>]

However, if you're asking about the type of d2.keys() it's:
<class 'dict_keys'>

Hope this was somehow helpful.

A: d1.keys() returns <class 'dict_keys'> type objects which is iterable but you can not index it like lists
>>> d1 = { 1:'one', 2:'two', 5:'five' }
>>> d1.keys
<built-in method keys of dict object at 0x7f59bc897288>
>>> d1.keys()
dict_keys([1, 2, 5])
>>> type(d1.keys())
<class 'dict_keys'>
>>> [i for i in d1.keys()]
[1, 2, 5]
>>> [i for i in d1.keys() if isinstance(i, int)]
[1, 2, 5]

Also just repeating what you said
>>> d1.keys()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object does not support indexing

Also Check this out


text:
Q: When I use VS2010, I got an error creating a c++ project An error occurred while creating or opening the C++ browsing database file r:/t1/t1.sdf. IntelliSense and browsing information will not be available for C++ projects.
Ensure that Microsoft SQL Server Compact 3.5 is installed and that no other applications are accessing the file. If this problem persists, delete the file and reopen the solution.
In a blog, the writer said that it's caused by the RAMDISK or FlashDisk, if use the harddisk, the problem will be solved.
But i don't make, someone can help me?

A: No amount of installing SQL Server Compact, repairing VS, etc. fixed this for me. Finally I saw something about a Network drive or RAM disk being unsuitable.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/3a15f89c-074e-413c-ac6b-f8fceb64b7b1/how-do-i-enable-intellisense-to-work-on-a-ramdisk?forum=visualstudiogeneral
I assume that the database uses low level access to the file system that is incompatible with RAM disk or network drives, etc. The following setting moved the sdf file to a location that does not interfere with whatever direct access the database demands. After a VS restart the problem vanished.
tl;dr
TOOLS / Options / Text Editor / C++ / Advanced / Always use fallback location = True

A: As WhiteRabbit pointed out, download the "SSCERuntime-ENU.exe" from:
For VS2010:
http://www.microsoft.com/en-us/download/confirmation.aspx?id=5783
For versions after VS2010:
http://www.microsoft.com/download/details.aspx?id=17876
Click download, then choose the suitable version for your device (32-bit = x86, 64-bit = x64), then download and install it.


text:
Q: consider evaluate all third if second true i'm to tired to think :)
is in java any simple solution to this ?
A B | =         XOR -> NO
--------        AND -> NO
0 1 | 0         OR -> NO
0 0 | 0
1 1 | 0
1 0 | 1

this came from
             condition 1       if condition 2    take condition 3
            evaluated to       evaluated to         to consider
               true               true

 return         a        &&       if(b)      &&              c

                                  else  only a

 // i can make it like this
return (a && b) ? a && b && c : a;
// then simplifying
return b ? a && c : a;

but if a is statement i need make solution/compute & substitute on right side
or maybe there's a simpler way to write this condition?
Does a && !b work? – bradimus
Maybe it's me -- but what are you asking? – Hovercraft Full Of Eels
example to consider:
public boolean isRequestInQue(Request<User> requestToCheck,
                              boolean checkCallerAlive) {
    int id = requestToCheck.getId();
    Request<User> requestInQue = _stateCallerRequestList.get(id);
    return requestInQue != null
               ? checkCallerAlive
               ? requestToCheck.equals(requestInQue)
               && requestInQue.isCallerAlive()
               : requestToCheck.equals(requestInQue)
               : false;
}

Ternary operator can be difficult to follow, especially if you are asking for help with the logic. Can you give an example using if statements? – dave
if(requestInQue!=null)
   if(checkCallerAlive)
      if(requestToCheck.equals(requestInQue))
         if(requestInQue.isCallerAlive())
            return true;
   else if(requestToCheck.equals(requestInQue)
           return true;
return false;

finaly based on dave answer
true && (!false || true) = true
true && (!true || true) = true
true && (!true || false) = false
true && (!false || false) = true

public boolean checkWithCifB(boolean a, boolean b, boolean c) {
    return a && (!b || c);
}

A: I think this should work:
return requestInQue != null && requestToCheck.equals(requestInQue) &&
       (!checkCallerActive || requestInQue.isCallerAlive());


text:
Q: Missing "des" Tcl package When i am trying to execute the following tcl code i got this
can't find package des
while executing
"package require des"
(file "encdec.tcl" line 1)
Tcl code
package require des

set key "12345678";  # Must be 8 bytes long
set msg "abcde"

##### ENCRYPTION
set encryptedMsg [DES::des -dir encrypt -key $key $msg]
# $encryptedMsg is a bunch of bytes; you'll want to send this around...

##### DECRYPTION
set decryptedMsg [DES::des -dir decrypt -key $key $encryptedMsg]
puts "I got '$decryptedMsg'"

how to get that package ?

A: This package is a part of "the standard Tcl library", tcllib.
If you're using a "batteries included" Tcl distribution, like ActiveTcl, you should use its means to get this package; for instance, with ActiveTcl, the command to install tcllib would be
teacup install tcllib

(you should run it in your Windows console prompt).
If you're using Tcl installed from a package of your operating system, tcllib is typically available in the form of a package as well.  For instance, on a Debian (or its derivative) the command to install tcllib would be
apt-get install tcllib

Next time please tell us about your platform up front, without forcing anyone here to guess.


text:
Q: Cannot find declaration to go to in PHP Storm on ubuntu Does someone have had this trouble on ubuntu - php storm doesn't see the declaration on classes somehow. On Windows system all works well.

A: Please try to enable Laravel plugin:
Settings (Preferences) | Other Settings | Laravel Plugin | Enable Plugin for this Project

Or here:
Languages & Frameworks | Php | Laravel| Enable Plugin for this Project

As said on https://confluence.jetbrains.com/display/PhpStorm/Laravel+Development+using+PhpStorm

A: Nothing worked for me, here is how i solved it :
Just restore Settings
File > Manage IDE Settings > Restore Default Settings

Uninstalling your IDE won't help, restoring settigns is the best way to solve the problem

A: *

*Nothing works for me like invalidate cache etc etc...

*Then I follow the following steps:

*First close the project from PhpStorm

*I was on mac, going to project by the finder.

*Enable hidden files and folders by pressing Shift + CMD + . (dot).  - Now i delete .editorconfig file.

*Delete .idea folder

*Now I open the project in Phpstorm.

*then everything was fine.

A: My problem was that my whole vendor folder had somehow gotten ignored.
To check and fix, navigate to "File > Settings > Project Settings > Directories" and make sure that "vendor" is not excluded.
Sources:
http://fuelphp.com/forums/discussion/3943/how-to-setup-code-completion-in-phpstorm

A: I had to delete the .PhpStorm20* folder in my home directory, starting with a completely new config. Maybe it's better this way after two years of dragging the same config along, across several versions of PhpStorm.

A: I had this also and it was due to my URL.
I had:
templateUrl:'/features/UI/partials/labelledSelect.html'

And needed to make it:
templateUrl:'features/UI/partials/labelledSelect.html'

So I could control-click on it (in WebStorm actually though they seem to be extremely similar).

A: I got "cannot find declaration..." in my file routes/web.php
Route::get('/', function () {
    return view('welcome');
});

But after adding use Illuminate\Routing\Route;
it's fine.

A: In my case PHP Storm didn't see declarations of standard php functions: fopen(), fwrite etc. These steps helped to fix this issue:

*

*Download code of the official phpstorm-stubs repo to your PC as zip archive.

*Unpack it to some folder.

*Open Settings > Languages and frameworks > PHP. Select PHP Runtime tab. At the bottom of the window you'll see Default stubs path option. Set it to the location where you have unpacked archive.


text:
Q: What's the difference between is_page() and is_paged() in wordpress? I can't seem to understand is_paged() but I have used is_page() before. If possible please provide an sample page. :-)

A: Have you had a look at the function reference?

*

*is_paged()

This Conditional Tag checks if page being displayed is "paged". This is a boolean function, meaning it returns either TRUE or FALSE.
Note: This refers to an archive or the main page being split up over several pages, this does not refer to a Post or Page whose content has been divided into pages using the  QuickTag.

That means you get to know whether the current page is divided into several "subpages".

*is_page()

This Conditional Tag checks if Pages are being displayed. This is a boolean function, meaning it returns either TRUE or FALSE.

A: The $paged global variable contains the page number of a listing of posts.
The $page global variable contains the page number of a single post that is paged.

A: is_paged():

*

*this function does not take any argument, it is just returns true or false. Following example will make you clearly understand the theme.

*For example you have a blog. You have total 170 posts in your blog.
When someone visits your blog's main page(it is also called index
page), he/she sees 12 posts like this site ExcelDemy.com. To
see other posts in your blog, people will click "older posts" or page number
whatever you have set in the bottom portion of your index page. After
one click on "Older Posts", you will be transferred to second page of
the blog, see this link: and observe the URL Second Page of the
blog.

*When you are in index page exceldemy.com, is_paged() function returns
"False" as this page is not paged; When you are in second page 2,
is_paged() function returns "True" as you're in a paged page.


text:
Q: Ordered products report exclude orders with status closed the default Magento2 report from ordered products excludes orders with status canceled. I also want to exclude status closed.
/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php

in line 60 shows
  $connection->quoteInto("{$orderTableAliasName}.state <> ?", \Magento\Sales\Model\Order::STATE_CANCELED),

How can I add STATE_CLOSED here? I tried a bit but no success.

A: your condition should be in your case
$connection->quoteInto(
    "{$orderTableAliasName}.state NOT IN (?)",
    [
        \Magento\Sales\Model\Order::STATE_CANCELED,
        \Magento\Sales\Model\Order::STATE_CLOSED
    ]
)


text:
Q: Display Listview inside another Listview's EmptyDataTemplate Is there any way to display listview as another listview's empty data template. I just put it like following. But it wont display the listview or it's emptydata text. only displaying 'empty data first listview' text
<asp:ListView ID="searchResults" runat="server" ItemPlaceholderID="placeholder">
    <EmptyDataTemplate>
        empty data first listview
        <asp:ListView ID="suggestions" runat="server" ItemPlaceholderID="placeholder" DataSource="<%#Model.SearchSuggestions %>">
            <EmptyDataTemplate>
                empty data second listview</EmptyDataTemplate>
            <LayoutTemplate>
                <span class="suggestionList">
                    <asp:PlaceHolder ID="placeholder" runat="server"></asp:PlaceHolder>
                </span>
            </LayoutTemplate>
            <ItemTemplate>
                <%# Container.DataItem %>
            </ItemTemplate>
            <ItemSeparatorTemplate>
                ,</ItemSeparatorTemplate>
        </asp:ListView>
    </EmptyDataTemplate>
    <LayoutTemplate>
       *************
    </LayoutTemplate>
</asp:ListView>

A: I copy and pasted your code and was able to get it to work by manually databinding it in the codebehind. The only modification I made to your aspx code was to remove the reference to the model, to simplify setting it up on my end. I have included my ugly/overly simple test code below.
protected void Page_Load(object sender, EventArgs e)
{
    searchResults.DataBind();
    searchResults.Controls[0].DataBind();
}


text:
Q: How to use optional return values in postgresql functions I know that a table can be return from a postgresql function as below,
CREATE OR REPLACE FUNCTION public.tmp()
 RETURNS table(num int, name text)
 LANGUAGE plpgsql
AS $function$
DECLARE rslt record;
begin
for rslt in select * from t1 loop num:=rslt.num; name:=rslt.name; return next; end loop;
return ; end;$function$;

But I need to return 2 different tables as optional, that is any one at a execution based on the condition.
For Example: I have 2 table structures.
table(num int, name text)
table(num int, name text, value text)

I need any one of these table structure to return.
How this can be done?

A: You can probably also create two different data types of columns you need and pass into record type. Then you return
Create  type  datatype as (column type, column type );


text:
Q: Parse all strings of specific length? I've exported my email archive of 10 years which is very large.
I want to parse all the text for any string that is 64 characters long in search of a bitcoin private key.
How can I parse strings of a certain length in characters?

A: If you mean to search for a 256-bit number in hexadecimal form (64 chars from the range 0-9 and A-F -- one of the formats in which a bitcoin private key could appear), this should do:
egrep -aro '\<[A-F0-9]{64}\>' files and dirs ...

Add the -i option or also include the a-f range if some of the keys are in lowercase.
For the general problem of finding runs of characters from the same class having a specified length, you would better use pcre regexps, which could be used with GNU grep with the -P option. For instance, to find runs of uppercase letters from any charset, of min length of 2 and max length of 4, and which are delimited by chars which are not uppercase letters:
echo ÁRVÍZtűrő tükörFÚRÓgép |
   LC_CTYPE=en_US.UTF-8 grep -Po '(?<!\p{Lu})\p{Lu}{2,4}(?!\p{Lu})'
FÚRÓ

Replace \p{Lu} with \p{Ll} for lowercase letters, \S for non-spaces, etc. See here and here for the full list.
(?<!...) and (?!...) are negative lookbehind and lookahead zero-width assertions; e.g. (?<!<)\w(?!>) will match a "word" character when not bracketed by < and >. The \< zero-width assertion from vi could be implemented by (?<!\w)(?=\w).

A: If you want to find all words of length 64 from /path/to/file, you can use
tr -c '[:alnum:]' '\n' < /path/to/file | grep '^.\{64\}$'

This replaces all non-alphanumeric characters by newlines, so each word is on its own line. Then it filters this result to include only the words of length 64.

A: If you have GNU grep (default on Linux), you can do:
grep -Po '(^|\s)\S{64}(\s|$)' file

The -P enables Perl Compatible Regular Expressions, which give us \b (word-boundaries) \S (non-whitespace) and {N} (find exactly N characters), and the -o means "print only the matching part of the line. Then, we look for stretches of non-whitespace that are exactly 64 characters long that are either at the beginning of the line (^) or after whitespace ('s) and which end either at the end of the line ($) or with another whitespace character.
Note that the result will include any whitespace characters at the beginning and end of the string, so if you want to parse this further, you might want to use this instead:
grep -Po '(^|\s)\K\S{64}(?=\s|$)'

That will look for a whitespace character or the beginning of the string (\s|^), then discard it \K and then look for 64 non-whitespace characters followed by (the (?=foo) is called a "lookahead" and will not be included in the match) either a whitespace character, or the end of the line.

A: It seems that grep is the correct tool to "search" for an string. What is left to do is to define such string with a regex. The first issue is to define the limits of a word. It is not as simple as "an space", as a book, a lamp use , as word delimiter, in the same concept, many other characters, or even the start or end of a line could act as word delimiter. There are some word delimiters in GNU grep:

*

*\< word start.

*\> word end.

*\b word boundary.

All of them assume that a word is a sequence of [a-zA-Z0-9_] characters. If that is ok for you, this regex could work:
 grep -o '\<.\{64\}\>' file

If you could use extended regex, the \ could be reduced:
 grep -oE '\<.{64}\>' file

That selects from a "word start" (\<), 64 ({64}) characters (.), to a "word end" (\>) and prints only the matching (-o) parts.
However, the dot (.) will match any character, that may be too much.
If you want to be more strict on the selection (hex digits), use:
 grep -oE '\<[0-9a-fA-F]{64}\>' file

Which will allow hex digits in lowercase or uppercase. But if you really want to be strict, as some non-ASCII characters might be included, use:
 LC_ALL=C grep -oE '\<[0-9a-fA-F]{64}\>' file

Some implementations of grep (as grep -P) do not have a "start of word" or "end of word" (as \< and \>) but have "word boundary" (as \b):
grep -oP '\b[0-9a-fA-F]{64}\b' file

There are some languages that accept the POSIX word boundaries [[:<:]] and [[:>:]], but not perl, and only from PCRE 8.34.
And there are a lot more flavors of "word boundaries".


text:
Q: Interacting with objects in SteamVR I'm trying to get Interaction setup in my scene for a colour memory puzzle game in Unity.
I've managed to get the scene changing when the player interacts with a button on a Canvas, so I'm trying to somehow replicate that through a puzzle.
The player can trigger the colour randomizer to display random colours (out of 4), then the player will need to 'press' the buttons on the panel in the correct order to proceed.
So far, I have a canvas overlapping the buttons so the player can interact with them. Each button has a box collider over the button element, so when the mouse is clicked or the trigger button is pressed on the Oculus controller, it should register a button press. But as soon as the hand comes into contact with the 'collider box' the following NullReferenceException Shows;
NullReferenceException: Object reference not set to an instance of an object.
Valve.VR.SteamVR_Action_Boolean_Source.UpdateValue()

I'm trying to figure out a way to reference each 'box' in code to that it knows its that specific colour being pressed. The code is there to accept keyboard input, just having trouble with the VR element.


text:
Q: Unexplained change of date in Windows 10 In my environment we are using Windows 10 Pro version for analytical applications. Sometimes unexplainedly time and date was going to back date.
We have changed the cmos battery, but after half a week of the analysis the date and time got changed again.
This type of issue may lead to data integrity issues.
Any suggestion on this is appreciated.

A: It may be, that Windows 10 updates the time and does not know where it is. It may then apply a different time zone.
I would turn off automatic date changes in the settings first and then see if this is the issue.
There is software that synchronizes the time with an atomic clock. This would probably be better if you rely on the time and have an internet connection available.


text:
Q: Smtp connection checking in ios Can anyone know how to check smtp connection in objective c,without using any third party libraries like skpsmtp or mailcore.
Please help.

A: I would suggest to open a TCP socket to your remote SMTP server, port 25.
If the connection opens and returns 220 code, it means that the server is available and reachable.
This would be similar to the telnet command
sst:~ sst$ telnet relay.skynet.be 25
Trying 195.238.5.128...
Connected to relay.skynet.be (195.238.5.128).
Escape character is '^]'.
220 relay.skynet.be ESMTP
quit
221 relay.skynet.be
Connection closed by foreign host.

Doing so with Cocoa requires some coding although.  This is documented in Cocoa Stream Developer Guide at http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/Streams/Streams.html#//apple_ref/doc/uid/10000188-SW1
Or you always have the choice to fall back to good old C code, like explained here :
How to Create a TCP socket connect using C to a predefined port


text:
Q: How to change the Row Number behavior in my T-SQL Query? I am using SQL Server 2014 and I have the following T-SQL query running against a table (tbl1).
Extract of tbl1:
emp_code     Name     Address   Company
---------------------------------------
100          Peter    London     ABC
125          Allan    Cambridge  DCE
125          Allan    Cambridge  DCE
115          John     Suffolk    ABC
115          John     Suffolk    XYZ
154          Mary     Highlands  ABC
154          Mary     Bristol    ABC
124          Mary     Chester    ABC

My T-SQL query stands as follows:
SELECT
    [ID],
    [Name],
    [Address],
    [Company],
    ROW_NUMBER() OVER (PARTITION BY [emp_code] ORDER BY [Address]) AS RowNumber
FROM
    [tbl1]

Output from above query:
emp_code         Name     Address   Company    RowNumber
--------------------------------------------------------
    100          Peter    London     ABC          1
    125          Allan    Cambridge  DCE          1
    125          Allan    Cambridge  DCE          2
    115          John     Suffolk    ABC          1
    115          John     Suffolk    XYZ          2
    154          Mary     Highlands  ABC          1
    154          Mary     Bristol    ABC          2
    154          Mary     Chester    ABC          3

Output I'm after:
emp_code         Name     Address   Company    RowNumber
---------------------------------------------------------
    100          Peter    London     ABC          1
    125          Allan    Cambridge  DCE          1
    125          Allan    Cambridge  DCE          1
    115          John     Suffolk    ABC          1
    115          John     Suffolk    XYZ          1
    154          Mary     Highlands  ABC          1
    154          Mary     Bristol    ABC          2
    154          Mary     Chester    ABC          3

I want my RowNumber (or change the column name if need be) to change based on the [Address] column for each [emp_code]. If the employee has the SAME address, it should have the same value (that is, 1). Else, it should give the values as in the case of employee "Mary" (above output).
I am assuming the Row_Number() function is not the right one to be used for what I'm after.
Any help would be appreciated.

A: I think you want DENSE_RANK here rather than ROW_NUMBER():
SELECT [ID], [Name], [Address], [Company],
       DENSE_RANK() OVER (PARTITION BY [emp_code]
                          ORDER BY [Address]) AS DenseRank
FROM [tbl1];

Demo


text:
Q: Popen.communicate is stuck until process spawned by sub-process terminates I have the below three scripts, and when I run main.py file, it spawns child.py which again executes the subchild.py and terminates quicly, subchild.py however keeps executing for a lot of time.
The problem with this is, main.py is blocked at p.communicate() till subchild.py terminates. If I open task manager and kill the running subchild.py main.py immediately returns the output of child.py
So my questions are as below

*

*main.py is supposed to wait only till child.py terminates, why is it waiting for subchild.py to terminate ?

*How do I make the p.communicate() not wait till subchild.py completes its execution ?

    # main.py file

    if __name__ == '__main__':
        import subprocess
        p = subprocess.Popen(
            ["python", "child.py"],
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        out, _ = p.communicate()
        print(out)

    # child.py file

    if __name__ == '__main__':
        import subprocess
        print("Child running")
        p = subprocess.Popen(["python", "subchild.py"])
        print("Child pid - ", p.pid)
        exit(1)

    # subchild.py file

    if __name__ == '__main__':
        import time
        time.sleep(10000)

Note: I'm trying this on Windows 7 Enterprise. I'm using python3.6.6
Update after comment:
On the main.py I need child.py's pid, stdout, stderr and process object so that I can kill child.py from main.py at any later point if I want to. This code is a small snippet is part of some API which I am building where the user would want the control to kill the process if he wishes to. subprocesses.call or subprocesses.run would not let me get control over the process object. I also won't have control over what child.py command I will receive as input for main.py, So I need to somehow not wait for the subchild.py and exit immediately with child.py's output as soon as it completes.

A: Your communicate call doesn't just wait for the child to complete. It first tries to read the entire contents of the child's stdout and stderr.
Even when the child has completed, the parent can't stop reading, because the grandchild inherits the child's stdin, stdout, and stderr. The parent needs to wait for the grandchild to complete, or at least for the grandchild to close its stdout and stderr, before the parent can be sure it's done reading.

A: Right now, child.py will always wait for subchild.py to finish. If you don't need to wait, you can try subprocess.call() as an alternative in the child.py code. Replace the Popen() logic with the call() logic instead.
p = subprocess.call(["python", "subchild.py"])

Here is a reference: https://docs.python.org/2/library/subprocess.html#subprocess.call

An alternative is to keep the code as it is an actually change to using .call() in the main.py file.
import subprocess
p = subprocess.call(
    ["python", "child.py"],
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE,
    stderr=subprocess.PIPE
)

You mentioned you can't use .call() because you'll need to kill it, however this is not the case. Making this change should allow you to:

*

*return main.py and child.py quickly,

*it will print the ID of the subchild process from child.py and

*subchild.py will continue running

A: Finally I found the solution to this myself, this seems to be an open issue with python. Would be glad to see this fixed.
https://bugs.python.org/issue26731


text:
Q: Candidate Keys / Reduction I have a relation
R = (S, T, U, V, W, X, Y, Z) which has the FD's
TW -> Y
TW -> Z
Y -> X
Y -> S
V -> U
X -> T
I'm trying to find the candidate key for R but because of the relationship
TW -> Y -> X -> T
I can't figure out what it is. I know it has to have 'V' and 'W' in it but I don't know if I should also have 'X' or 'T'.

A: You say that W is dead sure inside any candidate key.
Therefore,
TW -> Y -> X -> T

becomes
T -> Y -> X -> T

So, which one do you choose, X or T?
And why not Y ?

A: The candidate key of this relation R is TWV and XWV both because they cannot be derived from one another. so this relation has two candidate keys and it is possible for aa relation to have more than two candidate keys.


text:
Q: Serve only .js files from an Express static directory? I'm looking to find out if it's possible to serve only one type of file (filtered by extension) out of an Express.js static directory.
For example, let's say I have the following Static directory:
Static
    FileOne.js
    FileTwo.less
    FileThree.html
    FileFour.js

And say I want to make only files with a .js extension available to any given request, and all other requests would get a 500 response (or something like that).
How would I go about achieving this? Does Express have a baked-in filter that I haven't been able to find, or do I need to use regular expressions?

A: I use
app.get(/static\/.*js$/, function(r, s){

or
app.get('*', function(r, s){
  if(r.url.match(/.*js$/)) // then serve
})

A: Doesn't appear to me that you can configure the "static" middleware in this way. In the "serve-static" module, which is the replacement for "static" for Express 4.0 (currently in RC stage), there are some options, but not filtering.
If you want just to serve *.js files, you can create a route yourself. Create an app.get('/static/*') that responds with the file content and proper mime type, if the requested file is .js.
An alternative is to fork the "static" module, or better the new "serve-static", so it fits your needs.
For example, you could create a new library copying the contents of this file, and after the line
var originalUrl = url.parse(req.originalUrl);

You may add something like
if(originalUrl.slice(-3) != '.js') return next();

This should ignore (calling the next middleware) all requests for static files that aren't ending in ".js".
(untested, but it's inspired by the code above)
With the code above, create a new library (e.g. save it in "lib/my-static.js") and include it:
app.use(require('lib/my-static'))


text:
Q: Unix time stamp conversion in Azure synapse analytics I am using the below script to do refining the data in silver layer:
 # Read from existing internal table
 dfAsset =(spark.read.option(Constants.SERVER,"xyz.sql.azuresynapse.net")
.synapsesql("abc.Salesforce.Asset")
.select("Id","ContactId","CreatedDate","CreatedById","LastModifiedDate")
.filter(col("productCode").contains("11061164")).limit(10))
 dfAsset.show()

 For particular column CreatedDate the data is appearing in the Unix format.Please refer
 the below :

CreateDate
1652108980000
1632313243000
1632312269000
1632312410000

I need to convert the data into YYYY-MM-DD. In the above script

Please advise how it can be done.

Regards
RK

A: This is my sample Dataframe saved in the variable dfAsset.
#+-----------+
#|   date1   |
#+-----------+
#|16521089   |
#|16323132   |
#|16323122   |
#|16323124   |
#+-----------+

Using below code you can convert the data into YYYY-MM-DD.
from pyspark.sql.types import TimestampType
from pyspark.sql.functions import col,to_date
df = dfAsset.withColumn('date',to_date(col('date1').cast(TimestampType())))
df.show()

Output:


text:
Q: When exactly is a destructor or terminate on a thread called I am using C++11 std::thread. My confusion is based on the following:
terminate() on a thread is called if neither join() nor detach() is called on it.
That means when a thread returns:
a. it checks whether a join() or detach() on it is called, if not, then terminate() is called(produces a coredump),
b. if join() is called the destructor of the thread would be called by main(or calling thread)
c. if a detach() was called while the thread was executing, the thread won't return to main for cleanup, instead this thread itself will be responsible for calling its own destructor
Question: If the above points were true then i dont understand at which exact point is the decision made wehter to terminate a thread or not based on whether a join() or detach() is called or not?
void function_1()
{
        return;
}
int main()
{
        std::thread t1(function_1);
        std::cout<<"\nFirst Sleep for 5 seconds:\n";
        sleep(5);

        cout<<"\n2nd Sleep for 5 seconds:\n";
        sleep(5);

        if(t1.joinable())
        {
                cout<<"\nGonna join()\n";
                t1.detach();
        }
        cout<<"Exiting from main ...\n";

}
Since the thread would finish its execution before 5th second, i assumed the thread should be terminated as there is no join()/detach() till this point. But there's no terminate() called. Instead a thread is detached succesfully.
However if i dont detach then terminate is called after 2 sleep after "Exiting from main....", right before return 0;
Does that mean that the thread is not cleaned up(its destructor not called), until main thread(or called thread) returns?
Is that the reason why one should detach() so that the cleanup of the thread doesn't have to wait till main(or caller thread) returns?

A: Looks like you are confusing two things: the std::thread object, and the thread of execution that that object manages.
The call to std::terminate is triggered by the destructor of the std::thread object if it is joinable. This is not directly related to whether or not the thread of execution managed by the std::thread object has finished executing.
In your code, the destructor of t1 is what would trigger std::terminate. t1 is an ordinary C++ object, a local variable of main here. It gets destructed when its scope ends - end of main here. So you must have made t1 non-joinable before main returns, either by calling join or detach on t1. Whether function_1 has finished running on its thread of execution or not is not relevant.


text:
Q: How to add CORS to firebase - Access-Control-Allow-Origin Setting up a firestore functions.https.onRequest, calling this on my frontend errors  No 'Access-Control-Allow-Origin' header is present on the requested resource.
Tried a lot of other answers but could not get it to work. how do I set cors up properly for google cloud functions?
I tried most of the answers on stackoverflow the past 3 hours.

*

*Adding the cors header to the bucket via gsutil (from this answer https://stackoverflow.com/a/37765371/7151828), ? Don't know if that is something else, though...

*Read How does Access-Control-Allow-Origin header work?

*I tried to do it like this function sample: https://github.com/firebase/functions-samples/blob/master/quickstarts/time-server/functions/index.js
This is my attempt using cors middleware
const functions = require('firebase-functions');
const cors = require('cors')({
  origin: true
});

const admin = require('firebase-admin');

admin.initializeApp();

exports.exampleFunction = functions.https.onRequest(async (req, res) => {

  return cors(req, res, () => {

    // Forbidding PUT requests.
    if (req.method === 'PUT') {
      return res.status(403).send('Forbidden!');
    }

    //respond to CORS preflight requests
    if (req.method == 'OPTIONS') {
      res.status(204).send('');
      return null
    }

   // code ...
   res.sendStatus(200);
}

I dont know what I am doing wrong.
What am I doing wrong here?

A: Use URL Rewrites to allow the function to be served under your domain
Okay, the proper solution to this is to rewrite the function to use the domain name and therefore we do not even need cors.
under the hosting section in firebase.json add the following to the beginning of the "rewrites": section.
  {
    "source": "/api/functionName/**",
    "function": "functionName"
  },

And I called the request via:
// send data to cloudfunction
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://example.com/api/functionName/?param1="+ this.param1, true);
xhr.send();

This allows to get the param in the cloud function via req.query.param1

A: You mentioned getting this error in the front end - have you disabled CORS in chrome to allow for the requests to go through?
link: https://alfilatov.com/posts/run-chrome-without-cors/


text:
Q: What would you call a person who keeps on boasting about himself and is jealous of others' achievements? I have come through some words like schadenfreude and envy, but am still looking for a better word or a phrase, or a group of words that will do the trick.
Actually I'm trying to explain the nature of a character in a story; for that purpose I need a sentence which describes the character.

A: A person who boasts of his achievements is a braggart; someone envious of the station of others is an envier.
Schadenfreude means taking joy in the pain of others, which is different from braggadocio or jealousy.

A: "A strutting, covetous man."
"X held forth on her successes to anyone who would listen, but routinely slighted and impugned the accomplishments of others." (This sentence does not directly say jealousy but the implication is there and can be described further as you develop the character.)


text:
Q: Bash - Find ID Pairs on One File Listed in Another File I have a large file "F1" with listed id-pairs:
id1 = digits, id2 = characters
id1 id2
id1 id2
...
The goal is to extract the lines containing the id-pairs from a second file "F2", formatted as follows:
id1 TYHYU 61728497 rtyheyia id2 8372819203948
id1 UJLJF 57383930 utkjruak id2 5683903048377
...
Thought about processing it with almighty "grep" but I'm facing a few obstacles.
Each Id1 and Id2 from F1 repeats a few times in F2, rendering obsolete grep -Fwf F1.txt F2.txt > F3.txt. In other words, ID1+ID2 represents a full identifier.
And although executing grep -w "$id1.*$id2" db.txt would solve it, I'm not sure how to get there (probably running an awkward while read -r loop to process each line from F1 as a variable-set before running grep??).

A: You're almost there. The read loop should work fine for this situation, so something like this:
while read -r line; do
    id1=$(echo "$line" | cut -d ' ' -f 1)
    id2=$(echo "$line" | cut -d ' ' -f 2)
    grep -w "${id1}.*${id2}" "$F2"
done < "$F1"

But this could also potentially return false positives if the IDs you're grepping for are present anywhere in other fields of the data. If you can guarantee the ID fields in F2 always appear in columns 1 and 5, I'd recommend checking the field position too. This can be done pretty quickly with awk in place of the grep line:
awk -v id1="$id1" -v id2="$id2" '$1 == id1 && $5 == id2 {print $0}' "$F2"

This roughly says, "For every line in F2, if column 1 is id1 and column 5 is id2, print the whole line".
Disclaimer, I did not test this.

A: The solution by @John Moon is worthy, and I've upvoted it.  But I note that you describe your files as 'large'.  The awk-based solution requires one full pass through your large file f1, which has N lines.  It then requires N full passes through your large (?) file f2.
I'm not an awk expert.  Someone who was could likely make one pass through the f1 file to gather IDs, and then make one pass through the f2 file to print the matches.
Here's a rather klunky solution in grep which does it almost as quickly as an optimal awk solution.
First, convert the f1.txt file (N lines long) into a file of regexp's, also N lines long:
$ while read id1 id2; do
   printf '^%s[[:blank:]]+' "$id1"
   printf '[^[:blank:]]+[[:blank:]]+'
   printf '[^[:blank:]]+[[:blank:]]+'
   printf '[^[:blank:]]+[[:blank:]]+'
   printf '%s[[:blank:]]\n' "$id2"
done < f1.txt > regexp.txt

That ugly printf sequence creates a regexp that forces a string match at the beginning of the line (to match column 1), then arbitrary whitespace; then 3 repetitions of (non-blank)(blank) string pairs (to ignore columns 2, 3 and 4); then matches another string in column 5, followed by a blank.
So in one pass through the N lines of f1.txt, we've created a list of N regexps that will match lines in f2.txt that contain the same ID pairs.  That list is stored in regexp.txt.
The matching lines can now be found in one pass through f2.txt using the command:
$ egrep -f regexp.txt f2.txt

So all told, the script would be:
$ while read id1 id2; do
   printf '^%s[[:blank:]]+' "$id1"
   printf '[^[:blank:]]+[[:blank:]]+'
   printf '[^[:blank:]]+[[:blank:]]+'
   printf '[^[:blank:]]+[[:blank:]]+'
   printf '%s[[:blank:]]\n' "$id2"
done < f1.txt > regexp.txt
$ egrep -f regexp.txt f2.txt

Sample data:
f1.txt:
id1 id2
id1 id2
id3 id4
id3 id5
id4 id5
id4 id6

f2.txt:
id1 TYHYU 61728497 rtyheyia id2 8372819203948
id1 UJLJF 57383930 utkjruak id2 5683903048377
id1 UJLJF 57383930 utkjruak id2 5683903048377
id3 THREE 4444444 adfhdd id4 182i3746
id2 NOPE 4444444 adfhdd id4 182i3746
id3 TREEE 555555 affff id5 8435987345
id4 FOUR  555055 asdfl id5 3728462
id4 FORE  6666666 dfiuyd id6 845687234

Intermediate file regexp.txt (created by the script):
^id1[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+id2[[:blank:]]
^id1[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+id2[[:blank:]]
^id3[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+id4[[:blank:]]
^id3[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+id5[[:blank:]]
^id4[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+id5[[:blank:]]
^id4[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+id6[[:blank:]]

Resulting egrep output:
$ egrep -f regexp.txt f2.txt
id1 TYHYU 61728497 rtyheyia id2 8372819203948
id1 UJLJF 57383930 utkjruak id2 5683903048377
id1 UJLJF 57383930 utkjruak id2 5683903048377
id3 THREE 4444444 adfhdd id4 182i3746
id3 TREEE 555555 affff id5 8435987345
id4 FOUR  555055 asdfl id5 3728462
id4 FORE  6666666 dfiuyd id6 845687234

Again a pure awk solution would likely be faster and more elegant.  Also, the approach I've outlined may cause grep to run out of memory if the number of patterns in regexp.txt is too large.  But I just thought I'd throw this out there as a somewhat speed-optimised grep-based solution.


text:
Q: In the Starship's Mage series, where did the plotline with the Extravagant Voyage happen? In book 13 of the Starship's Mage series, "Nemesis of Mars," there is a large timeskip and what feels like a recap of past events. One of these events is the capture of a facility by Roslyn Chambers that saved hundreds of thousands of workers; this was covered in book 12. There was also a subsequent fleet battle at Mackenzie by Admiral Medici; I think this was new but also it seemed straightforward.
But another incident mentioned was Mage-Queen Kiera Alexander's royal tour on Extravagant Voyage, and how that turned out. Too the best of my knowledge, nothing about this had been written before, but it felt too important - and too full of details - to just be a recap. An I missing something here?

A: It's currently only covered by the references within Nemesis of Mars, but Glynn Stewart appears to be planning to fill in the gap, going by the 'upcoming books' section of the latest novel:

In Fall 2023, Kiera Alexander embarks on a solo adventure! In
Mage-Queen's Thief: A Starship's Mage Novella, read the story of a
kidnapping attempt gone wrong, set before the events of Nemesis of
Mars.


text:
Q: How to do jqgrid inline editing with arrow keys i am doing inline editing on jqgrid. The editing is working perfectly. After editing, the user presses enter key, and it is saved. But now i want the user to use arrow keys (up and down keys to navigate through the rows and left and right keys to navigate through the cells) in navigating through the rows and when a row loses focus, the row is saved. is this possible?

A: Have you tried using the bindKeys method? From the jqGrid docs:

bindKeys
Parameters:
{
  onEnter: null,
  onSpace: null,
  onLeftKey: null, onRightKey: null,
  scrollingRows : true
}

Description:
When called the method make it so that it is possible to select a row with Up and Down keys - i.e we scroll the grid data with keys. It is possible to invoke additional events when the row is selected and a key like enter, space, left or right are pressed. To these events a selected id of the row is passed as parameter.


text:
Q: Como alternar entre true e false o checked de um input? Tenho este código e gostaria de alternar entre true e false o atributo checked do input. Estranhamente está pegando o id do label porque o web designer sobrepôs o label ao input.
(function($){
    $("label").click(
        function(){
            var idcheck = $(this).attr("for");
            $("input[id="+idcheck+"]").attr("checked", "checked");
        }
    );
})(jQuery);

A: Sugiro remover de todo o atributo checked.
(function ($) {
    $("label").click(function () {
        var idcheck = $(this).attr("for");
        $("input[id=" + idcheck + "]").removeAttr('checked'); // <--
    });
})(jQuery);

Ou outra alternativa, semelhante (dar valor false):
(function ($) {
    $("label").click(function () {
        var idcheck = $(this).attr("for");
        $("input[id=" + idcheck + "]").prop("checked", "false"); // <--
    });
})(jQuery);

A: use $("input[id="+idcheck+"]").prop('checked', false);

A: Tente isso:
Teste: <input type="checkbox" id="ck" checked/>

$(document).ready(function(){

   $("#ck").attr('checked', false);

});

A: Se o webdesigner não fez "trabalho extra" não era para você ter problema e nem ser necessário script para setar o check. Mas caso realmente seja mais fácil adaptar o script do que ter que revisar o código...
Não use attr. Pois atributos não funcionam legal com "propriedades vivas" invés disso use prop() como sugeriu o nosso amigo Sergio e wriel.
$("label").click(function () {
     var idcheck = $(this).attr("for");
     $("input[id=" + idcheck + "]").prop("checked", "false"); // <--
});

Caso utilize o attr, depois de alterar o status algumas vezes vai parar de funcionar. Já tive este problema e já te adianto, para lhe evitar dor de cabeça. O prop, sempre vai trazer o status atual, já o attr pode se perder na memória, e não refletir o atual momento.
Aqui tem mais detalhes

A: Você pode usar esse mesmo código apenas com algumas alterações na hora que você muda o "checked".
(function($){
    $("label").click(
        function(){
            var idcheck = $(this).attr("for");

            var checkedStatus = $("input[id="+idcheck+"]").attr("checked"); // Aqui eu pego o valor atual do checked no input
            $("input[id="+idcheck+"]").attr("checked", !checkedStatus); // e atribuo um novo valor invertendo o valor antigo
        }
    );
})(jQuery);

Nesse caso ele sempre vai inverter o valor do checked do input:

*

*Se o checked do input for true ele vai setar o novo valor como false.

*Se o checked do input for false ele vai setar o novo valor como true.

A: Eu usaria o seguinte código:
/* Não precisa de JavaScript! */

Ou seja, nenhum código! Se o seu label já tem o atributo for apontando para o input, não é necessário usar JS. O comportamento padrão do clique no label é justamente inverter o estado do checkbox. Exemplo JSFiddle
O código que você postou parece ter sido criado para tentar impedir que o checkbox seja desmarcado (todo clique termina com ele checked).

A: Tente da seguinte forma:
$( "input[type='checkbox']:odd" ).attr( "checked", "true" );

A: Depois de apanhar um pouco consegui resolver de uma maneira bacana: usando a negação.
document.getElementById("Checkbox").checked = !document.getElementById("contatoCheckbox").checked;


text:
Q: Select rails 3 assets based on environment In a Rails 3 application, I would like to be able to use unminified javascript and css files in my development environment for debugging and such, and minified versions in production.
I can think of a few hacky solutions, but ideally I'd like javascript_include_tag and friends to automatically select the right asset file.
Ideas?

A: Add your js normally using
javascript_include_tag

In your development.rb set:
config.assets.compress = false

and in production.rb use:
config.assets.compress = true


text:
Q: Partitioning a linked list around a integer value I'm trying to write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x need to be after the elements less than x. However, the partition element x can appear anywhere in the "right partition".
Input 3->5->8->5->10->2->1 [partition =5]
Output 3->1->2->10->5->5->8
The Node class is defined as below.
class Node{
    Node next = null;
    int data;
    public Node(int d){
        data =d;
    }
    public Node() {
        // TODO Auto-generated constructor stub
    }
    void appendToTail(int d){
        Node end = new Node(d);
        Node n = this;
        while(n.next!=null){
            n = n.next;
        }
        n.next = end;
    }

Below is a half working code that I came up with.
static void Partition(Node n,int numb){
    Node tail = n;
    while(tail.next != null){
        tail = tail.next;
    }

Node current = n;

Node tailCurrent = tail;
Node prev = null;
while(current!= tailCurrent){
    if(current.data<numb){

        prev = current;
        System.out.println(prev.data);
    }
    else{
        prev.next = current.next;
        tail.next = current;
        tail = current;

    }
    current =current.next;
}

tail.next = null;

}

It works fine for the cases where the head node has an integer less than the partitioning number, however the error occurs when the head node has an integer greater than or equal to partitioning number. I believe this is because in the else statement in my code, prev.next throws a null pointer exception because it never goes through the if case to have a non-null value. Can anyone suggest a way to fix this? Thank you.

A: When there is no previous node to update, you can simply do nothing.
So change this:
prev.next = current.next;

to this:
if (prev != null) {
    prev.next = current.next;
}

There is another problem: the root of the list may change during partitioning, and there is no way for the calling code to get access to the new root. It can be fixed by making the Partition method keep track of where the current root is and return it in the end.
static Node Partition(Node n, int numb) {
    Node tail = n;
    while(tail.next != null) {
        tail = tail.next;
    }
    Node current = n;
    Node root = n;
    Node tailCurrent = tail;
    Node prev = null;
    while(current != tailCurrent) {
        if(current.data < numb) {
            prev = current;
        } else {
            if (prev != null) {
                prev.next = current.next;
            }
            if (root == current) {
                root = current.next;
            }
            tail.next = current;
            tail = current;
        }
        current = current.next;
    }
    tail.next = null;
    return root;
}


text:
Q: WebView showing application forced close with a null pointer exception on ProgressDialog Getting a null pointer exception on progress dialog's show() function when tried to open a locally hosted website having windows authentication. Details given in "EDIT" section:
My webView class is as follows:
Web.java
public class Web extends Activity {
private WebView webView;
 final Activity activity = this;
    public Uri imageUri;
    ProgressDialog progressDialog;
    private static final int FILECHOOSER_RESULTCODE   = 2888;
    private ValueCallback<Uri> mUploadMessage;
    private Uri mCapturedImageURI = null;
 public static final int REQUEST_SELECT_FILE = 100;
    public ValueCallback<Uri[]> uploadMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_PROGRESS);
    setContentView(R.layout.activity_web);

    webView = (WebView) findViewById(R.id.webView1);
    webView.setWebViewClient(new MyWebViewClient());

    String url = "http://192.168.*.*";
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
    webView.getSettings().setRenderPriority(RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setLoadWithOverviewMode(true);

    //webView.getSettings().setUseWideViewPort(true);

    //Other webview settings
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setPluginState(PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setSupportZoom(true);
    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    webView.setDownloadListener(new DownloadListener()
      {
       public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength)
       {
        //for downloading directly through download manager
           final String filename= URLUtil.guessFileName(url, contentDisposition, mimetype);
        Request request = new Request(Uri.parse(url));
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);
       }
      });
}

private class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);

        return false;

    }

    public void onLoadResource (WebView view, String url) {

        // if url contains string androidexample
        // Then show progress  Dialog

             if(progressDialog==null)
             {
            // in standard case YourActivity.this
            progressDialog = new ProgressDialog(Web.this);
            progressDialog.setMessage("Loading...");
           }
        progressDialog.show();}

    // Called when all page resources loaded
    public void onPageFinished(WebView view, String url) {

        try{
            // Close progressDialog
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }
}

public class MyWebChromeClient extends WebChromeClient {

public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){

    // Update message
    mUploadMessage = uploadMsg;

    try{

        // Create AndroidExampleFolder at sdcard

        File imageStorageDir = new File(
                               Environment.getExternalStoragePublicDirectory(
                               Environment.DIRECTORY_PICTURES)
                               , "r2Reviews");

        if (!imageStorageDir.exists()) {
            // Create AndroidExampleFolder at sdcard
            imageStorageDir.mkdirs();
        }

        // Create camera captured image file path and name
        File file = new File(
                        imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg");

        mCapturedImageURI = Uri.fromFile(file);

        // Camera capture image intent
        final Intent captureIntent = new Intent(
                                      android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);

        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");

        // Create file chooser intent
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");

        // Set camera intent to file chooser
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                               , new Parcelable[] { captureIntent });

        // On select image call onActivityResult method of activity
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

      }
     catch(Exception e){
         Toast.makeText(getBaseContext(), "Exception:"+e,
                    Toast.LENGTH_LONG).show();
     }

}

// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
    openFileChooser(uploadMsg, "");
}

//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
                           String acceptType,
                           String capture) {

    openFileChooser(uploadMsg, acceptType);
}

// The webPage has 2 filechoosers and will send a
// console message informing what action to perform,
// taking a photo or updating the file

public boolean onConsoleMessage(ConsoleMessage cm) {

    onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
    return true;
}

public void onConsoleMessage(String message, int lineNumber, String sourceID) {
    //Log.d("androidruntime", "Show console messages, Used for debugging: " + message);

}}

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        Intent i = new Intent(this, MainActivity.class);
                        startActivity(i);
                        finish();
                    }
                    return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
 @SuppressLint("NewApi")
    protected void onActivityResult(int requestCode, int resultCode, Intent data){

             if(requestCode==FILECHOOSER_RESULTCODE)
             {

                    if (null == this.mUploadMessage) {
                        return;

                    }

                   Uri result=null;

                   try{
                        if (resultCode != RESULT_OK) {

                            result = null;

                        } else {

                            // retrieve from the private variable if the intent is null
                            result = data == null ? mCapturedImageURI : data.getData();
                        }
                    }
                    catch(Exception e)
                    {
                        Toast.makeText(getApplicationContext(), "activity :"+e,
                         Toast.LENGTH_LONG).show();
                    }

                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;

             }

            }}

EDIT:
Tried to access a locally hosted website which is as:"http://192.168.*.**" which included windows authentication by adding a few lines of code:
public void onReceivedHttpAuthRequest(WebView view,
        HttpAuthHandler handler, String host, String realm) {
    handler.proceed("DOMAIN\\username", "password");
}

But unfortunately I got a forced close error because of null pointer exception described as: "attempting to invoke a virtual method on progressDialog.show();"
Any clues as to how I can resolve this..??
Thanks all.

A: Blocking full view is not a preferred way now a days. if you display progress dialog and don't allow to close on back press or touch on outside. user will get blocked by dark overhaul and loader so i think you should use below way to display loader.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

   <RelativeLayout
        android:id="@+id/layout_loader"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        tools:visibility="visible"
        android:gravity="center_horizontal">

        <android.support.v4.widget.ContentLoadingProgressBar
            android:id="@+id/address_looking_up"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="visible"/>

    </RelativeLayout>

</LinearLayout>

And Java file
wvLoad.setWebViewClient(new WebViewClient() {
        //If you will not use this method url links are open in new browser not in webview
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        //Show loader on url load
        public void onLoadResource (WebView view, String url) {

        }
        public void onPageFinished(WebView view, String url) {
            try{
                loader_layout.setVisibility(View.GONE);
                wvLoad.setVisibility(View.VISIBLE);
            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            loader_layout.setVisibility(View.VISIBLE);
            wvLoad.setVisibility(View.GONE);

        }
    });

    // Javascript enabled on webview
    wvLoad.getSettings().setJavaScriptEnabled(true);

    //Load url in webview
    wvLoad.loadUrl(url);

A: Your progress view is global so initialize only one time and than just show it or dismiss it:
if(progressDialog == null){
progressDialog = new ProgressDialog(Web.this);
progressDialog.setMessage("Loading...");
}

What you are doing right now is your show() method is also in if condition that is why it is showing only at start time.