text:
Q: Yarn MapReduce Job Issue - AM Container launch error in Hadoop 2.3.0 I have setup a 2 node cluster of Hadoop 2.3.0. Its working fine and I can successfully run distributedshell-2.2.0.jar example. But when I try to run any mapreduce job I get error. I have setup MapRed.xml and other configs for running MapReduce job according to (http://www.alexjf.net/blog/distributed-systems/hadoop-yarn-installation-definitive-guide) but I am getting following error :
14/03/22 20:31:17 INFO mapreduce.Job: Job job_1395502230567_0001 failed with state FAILED due to: Application application_1395502230567_0001 failed 2 times due to AM Container for appattempt_1395502230567_0001_000002 exited
with  exitCode: 1 due to: Exception from container-launch: org.apache.hadoop.util.Shell$ExitCodeException:
    org.apache.hadoop.util.Shell$ExitCodeException:
        at org.apache.hadoop.util.Shell.runCommand(Shell.java:505)
        at org.apache.hadoop.util.Shell.run(Shell.java:418)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:650)
        at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:195)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:283)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:79)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:744)

    Container exited with a non-zero exit code 1
    .Failing this attempt.. Failing the application.
    14/03/22 20:31:17 INFO mapreduce.Job: Counters: 0
    Job ended: Sat Mar 22 20:31:17 PKT 2014
    The job took 6 seconds.

And if look at stderr (log of job) there is only one line
"Could not find or load main class 614"
Now I have googled it and usually this issues comes when you have different JAVA versions or in yarn-site.xml classpath is not properly set , my yarn-site.xml has this
  <property>
    <name>yarn.application.classpath</name>
    <value>/opt/yarn/hadoop-2.3.0/etc/hadoop,/opt/yarn/hadoop-2.3.0/*,/opt/yarn/hadoop-2.3.0/lib/*,/opt/yarn/hadoop-2.3.0/*,/opt/yarn/hadoop-2.3.0/lib/*,/opt/yarn/hadoop-2.3.0/*,/opt/yarn/hadoop-2.3.0/lib/*,/opt/yarn/hadoop-2.3.0/*,/opt/yarn/hadoop-2.3.0/lib/*</value>
  </property>

So any other ideas what could be the issue here ?
I am running my mapreduce job like this:
$HADOOP_PREFIX/bin/hadoop jar $HADOOP_PREFIX/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.2.0.jar randomwriter out

A: I encountered the same problem when trying to install Hortonworks HDP 2.1 manually.  I managed to capture the container launcher script which contained the following:
#!/bin/bash

export NM_HTTP_PORT="8042"
export LOCAL_DIRS="/data/1/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001,/data/2/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001,/data/3/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001,/data/4/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001"
export JAVA_HOME="/usr/java/latest"
export NM_AUX_SERVICE_mapreduce_shuffle="AAA0+gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
export CLASSPATH="$PWD:$HADOOP_CONF_DIR:$HADOOP_COMMON_HOME/share/hadoop/common/*:$HADOOP_COMMON_HOME/share/hadoop/common/lib/*:$HADOOP_HDFS_HOME/share/hadoop/hdfs/*:$HADOOP_HDFS_HOME/share/hadoop/hdfs/lib/*:$HADOOP_YARN_HOME/share/hadoop/yarn/*:$HADOOP_YARN_HOME/share/hadoop/yarn/lib/*:$HADOOP_MAPRED_HOME/share/hadoop/mapreduce/*:$HADOOP_MAPRED_HOME/share/hadoop/mapreduce/lib/*:job.jar/job.jar:job.jar/classes/:job.jar/lib/*:$PWD/*"
export HADOOP_TOKEN_FILE_LOCATION="/data/2/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001/container_1406927878786_0001_01_000001/container_tokens"
export NM_HOST="test02.admin.hypertable.com"
export APPLICATION_WEB_PROXY_BASE="/proxy/application_1406927878786_0001"
export JVM_PID="$$"
export USER="doug"
export HADOOP_HDFS_HOME="/usr/lib/hadoop-hdfs"
export PWD="/data/2/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001/container_1406927878786_0001_01_000001"
export CONTAINER_ID="container_1406927878786_0001_01_000001"
export HOME="/home/"
export NM_PORT="62404"
export LOGNAME="doug"
export APP_SUBMIT_TIME_ENV="1406928095871"
export MAX_APP_ATTEMPTS="2"
export HADOOP_CONF_DIR="/etc/hadoop/conf"
export MALLOC_ARENA_MAX="4"
export LOG_DIRS="/data/1/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001,/data/2/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001,/data/3/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001,/data/4/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001"
ln -sf "/data/1/hadoop/yarn/local/usercache/doug/filecache/10/libthrift-0.9.2.jar" "libthrift-0.9.2.jar"
ln -sf "/data/4/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001/filecache/13/job.xml" "job.xml"
mkdir -p jobSubmitDir
ln -sf "/data/3/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001/filecache/12/job.split" "jobSubmitDir/job.split"
mkdir -p jobSubmitDir
ln -sf "/data/2/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001/filecache/11/job.splitmetainfo" "jobSubmitDir/job.splitmetainfo"
ln -sf "/data/1/hadoop/yarn/local/usercache/doug/appcache/application_1406927878786_0001/filecache/10/job.jar" "job.jar"
ln -sf "/data/2/hadoop/yarn/local/usercache/doug/filecache/11/hypertable-0.9.8.0-apache2.jar" "hypertable-0.9.8.0-apache2.jar"
exec /bin/bash -c "$JAVA_HOME/bin/java -Dlog4j.configuration=container-log4j.properties -Dyarn.app.container.log.dir=/data/4/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001 -Dyarn.app.container.log.filesize=0 -Dhadoop.root.logger=INFO,CLA  -Xmx1024m org.apache.hadoop.mapreduce.v2.app.MRAppMaster 1>/data/4/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001/stdout 2>/data/4/hadoop/yarn/logs/application_1406927878786_0001/container_1406927878786_0001_01_000001/stderr "

The line that sets CLASSPATH was the culprit.  To resolve the problem I had to set the variables HADOOP_COMMON_HOME, HADOOP_HDFS_HOME, HADOOP_YARN_HOME, and HADOOP_MAPRED_HOME in hadoop-env.sh to point to the appropriate directories under /usr/lib.  In each of those directories I also had to setup the share/hadoop/... subdirectory hierarchy where the jars could be found.

A: I solved this question with the following:
Because in my hadoop/etc/hadoop[hadoop-2.7.3 configuration catalog]:About mapred-site.xml:
<configuration>
 <property>
  <name>mapreduce.framework.name</name>
  <value>yarn</value>
 </property>
 <property>
   <name>mapreduce.jobhistory.address</name>
   <value>zhangjunj:10020</value>
 </property>
 <property>
    <name>mapreduce.jobhistory.webapp.address</name>
    <value>zhangjunj:19888</value>
 </property>
</configuration>

In this file. The 'zhangjunj' must be your master's machine name, but I had written 'hadoop' in the beginning.

A: I fixed the issue, it was due to incorrect paths. By giving full dir path to mapred , hdfs , yarn & common solves the problem.
Thanks,
Tony

A: Please check the property.
Ensure all required jars are present.

**yarn.application.classpath**
    /etc/hadoop/conf,/usr/lib/hadoop/,/usr/lib/hadoop/lib/,/usr/lib/hadoop-hdfs/,/usr/lib/hadoop-hdfs/lib/,/usr/lib/hadoop-yarn/,/usr/lib/hadoop-yarn/lib/,/usr/lib/hadoop-mapreduce/,/usr/lib/hadoop-mapreduce/lib/

A: Please check the logs first (they will be in user directory under logs directory of Hadoop).
Also check the permissions of all directories you mentioned in yarn, hdfs, core-site  XML files. Because this error is caused by wrong permission issues in most cases.

A: Maybe you can run HistoryServer with following code under $HADOOP_HOME/bin,
./mr-jobhistory-daemon.sh start historyserver

And then you can control logs of Hadoop Error from this url, (History Log)
http://<Resource Manager Host name adress>:8088/cluster

And Most probably You get Class Not Found Exception

A: I also encountered this issue on Ambari 2.0 + HDP2.3 + HUE3.9
my fix experiece is:
1. make sure spark client exist on all hadoop yarn node
2. export SPARK_HOME on all yarn node (spark client), and hue host

A: The permissions should be 6050 owner:root group hadoop
---Sr-s--- 1 root hadoop /usr/lib/hadoop-yarn/bin/container-executor

A: Check Swap size in your system: free -m
If there is Swap: 0 0 0 allocate Swap memory following these instructions

A: In my case the problem was due to insufficient memory. I inserted the below into yarn-site-xml as adino suggested in his comment above:
<property> <name>yarn.nodemanager.delete.debug-delay-sec</name> <value>600</value> </property>

After that I could see an error in the stderr log file. I don't remember the exact wording (logfile got deleted after a while). It was along the lines of "out of memory error"
I edited my virtual machine to add another swap partition of the size 3 Gigabytes (probably total overkill). I did this with Gparted.
Afterwards I had to register the new swap partition by typing
mkswap /dev/sda6 (/dev/sda6 is the partition name)
swapon /dev/sda6

I found the uid of the new swap partition by typing "blkid" and copying the uid.
I registered the swap into the file fstab:
sudo vi /etc/fstab

I added a new line for the new swap partition. I copied the whole line from the previous swap partition and just changed the UID.
UUID=2d29cddd-e721-4a7b-95c0-7ce52734d8a3 none  swap    sw      0       0

After this, the error disappeared. I'm sure there's more elegant ways to solve this, but this worked for me. I'm pretty new to dealing with Linux.

A: You will need to delay log removal by setting yarn.nodemanager.delete.debug-delay-sec to 600.
This will allow you to browse the stderr, stdout and syslog in /hadoop/yarn/log in the relevant container directory.
Most likely, you will find the error in syslog. And, most likely, it will be a ClassNotFoundException for class tez.history.logging.service.class=org.apache.tez.dag.history.logging.ats.ATSV15HistoryLoggingService.
If that is the case, then refer to the following ticket:
https://issues.apache.org/jira/browse/AMBARI-15041


text:
Q: Flutter Custom paint stack object over object Is it possible to achieve or stack paint object over another like this. I tried many resources for custom painter but was not able to stack the text in center of the circle and applying gradient behind circle. Help appreciated.

A: You don't need Custom paint to achieve this. You can create the layout using stack like the following
Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      colors: [
                        Colors.orangeAccent.withOpacity(0.4),
                        Colors.transparent
                      ],
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      stops: [0.4, 1])),
              width: 100,
              height: 200,
            ),
            Container(
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.deepPurple,
                  border: Border.all(color: Colors.white, width: 3)),
              width: 100,
              height: 100,
              child: Center(
                  child: Text(
                "80",
                style: TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.w900,
                    color: Colors.white),
              )),
            ),
          ],
        )

A: You can use Kaushik's answer, it's simpler and straight forward. However, if you have to use CustomPaint, here's how I would do it:
@override
void paint(Canvas canvas, Size size) {
  // top left point of shader rectangle
  var pointA = Offset(size.width * 0.2, 0);
  // define rectangle
  var rect = pointA & Size(size.width * 0.6, size.height);

  // Define a paint with shader
  final Paint shaderPaint = Paint()
    ..color = Colors.yellow
    ..style = PaintingStyle.fill
    ..strokeWidth = 1
    ..shader = const LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [
          Colors.deepPurple,
          Colors.yellow,
        ]).createShader(rect);
  // draw rectangle
  canvas.drawRect(rect, shaderPaint);

  // paint for circle
  final Paint circlePaintFill = Paint()
    ..color = Colors.deepPurple
    ..style = PaintingStyle.fill;
  final Paint circlePaintStroke = Paint()
    ..color = Colors.white
    ..style = PaintingStyle.stroke
    ..strokeWidth = 5;

  // draw circle
  canvas.drawCircle(Offset(size.width * 0.5, size.height * 0.3),
      size.width * 0.3, circlePaintFill);
  canvas.drawCircle(Offset(size.width * 0.5, size.height * 0.3),
      size.width * 0.3, circlePaintStroke);

  //draw text
  const textStyle = TextStyle(
      color: Colors.white, fontSize: 60, fontWeight: FontWeight.bold);
  const textSpan = TextSpan(
    text: '80',
    style: textStyle,
  );
  final textPainter = TextPainter(
    text: textSpan,
    textDirection: TextDirection.ltr,
  );
  textPainter.layout(
    minWidth: 0,
    maxWidth: size.width,
  );
  // position of text
  final xCenter = (size.width - textPainter.width) / 2;
  final yCenter = (size.height * 0.6 - textPainter.height) / 2;
  final offset = Offset(xCenter, yCenter);
  textPainter.paint(canvas, offset);
}

You'll have to adjust the size value inside custom painter based on the size you define outside the custom painter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculator creation jquery I have created calculator in php.  Now i want calculator code in jquery with same functions same formula what are all the php.i need to write jquery calculator.I am new in jquery. i dont know its possible or not.anybody please help me
My php code:
<?php

/*
 * Template Name: Calculator-iFrame
 */

get_header();?>

        <?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
if (isset($_POST['valuec'])) $valuec = $_POST['valuec'];
if (isset($_POST['valued'])) $valued = $_POST['valued'];
if (isset($_POST['valuee'])) $valuee = $_POST['valuee'];
if (isset($_POST['valuef'])) $valuef = $_POST['valuef'];
$answera = (($valueb / $valuea) + ($valued / $valuec) + ($valuef / $valuee)) / 3;

echo <<<_END
<form method='post' action='http://whatsmyrealrate.com/solutionreach'>

Whats your effective rate?

Month 1

Total Sales, Including Amex	<input type='text' name='valuea' value="$valuea"/>

Total Fees, less any terminal or rental fees	<input type='text' name='valueb' value="$valueb"/>

Month 2

Total Sales, Including Amex	<input type='text' name='valuec' value="$valuec"/>

Total Fees, less any terminal or rental fees	<input type='text' name='valued' value="$valued"/>

Month 3

Total Sales, Including Amex	<input type='text' name='valuee' value="$valuee"/>

Total Fees, less any terminal or rental fees	<input type='text' name='valuef' value="$valuef"/>

<input type='submit' value='Calculate'/>

_END;
?>

<?php

if ($answera > .0238): {
    echo "Your Effective Rate:

";
    echo  round($answera*100,2);
    }
elseif ($answer == 0): {
    echo "Your Effective Rate:

";
    echo  "0.00%";
    }

else: {
    echo "Oops, something has gone terribly wrong!

Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis.";
    echo gravity_form( 1, false, false, false, '', false );
}

endif
?>

</form>

<?php  ?>

A: Apart from your specific example using rates: here's a general description that just shows how to make a square-root calculator. You can extend it to meet your needs. In general, you'll need to follow these steps:

*

*Include jquery.js in some HTML page that renders your calculator

*Have <input type="text" id="mynum"/> fields in your HTML where users input values (or use type="number" etc.). Make sure you use id="...." as the field ID, you'll re-use it later.

*Have a placeholder to show results, e.g.
Calculation result will appear here.
. Again, id="...." is used to identify this element so that you can put in values using Javascript.

*Have some buttons to do calculations, e.g. <input type="button" value="SQRT" onclick="sqrt_stuff();"/>
Next comes the calculation part. The hypothetical above function sqrt_stuff() would then use JQuery to pick up values and paste results; for example:
function sqrt_stuff() {
    // Get user input from field with id "mynum"
    var nr = $('#mynum');
    // Calculate root
    var root = Math.sqrt(nr);
    // Show in div with id "result"
    $('#result').html('The answer is: ' + root);
}


text:
Q: auto-scroll to same place before leaving the page? Is there a way to automatically scroll to the same place in the page that was before leaving it?
for example - the client is in the middle of the page -> then goes to google -> and when he entered the page again the page will be scrolled to the previous position.
I found this HTML5 local storage but I don't know if it usable in this case of leaving the page completely...

A: That is what you need yes. LocalStorage keeps the keys that you store in the user's computer, so even if the browser is closed the keyis there when you open the site again.
You can find more info on 'How to use it' here


text:
Q: Python 3: module in same directory as script: "ImportError: No module named" I'm trying to import a module (venues) from an IPython shell. The venues module is correctly imported but it then tries itself to import a module named makesoup and fails to do so.
I'm located in the ~ directory and am trying to import the venues.py file located in the subdirectory processors. The makesoup.pyfile is also located in the processors subdirectory, which means any Python script near it should be able to find it, right?
In [1]: import processors.venues
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-765135ed9288> in <module>()
----> 1 import processors.venues

~/processors/venues.py in <module>()
      7 """
      8
----> 9 import makesoup
     10 import re
     11

ImportError: No module named 'makesoup'

I have added an empty __init__.py in both the ~ and processors directories, unsuccessfully.
Note: the makesoup module is correctly imported when I'm located in processors but I know this is not the only way it should work.

A:
The makesoup.py file is also located in the processors subdirectory, which means any Python script near it should be able to find it, right?

No.  This feature was changed in Python 3 and that syntax no longer works.
Change the import makesoup to this:
from . import makesoup

Or to this:
from processors import makesoup

Both of these will make it impossible to run python processors/venues.py directly, though you can still do python -m processors.venues from your home directory.

A: Sometimes, this does not work:
from . import xxx

Maybe someone will tell you to add init.py under the directory. It won't work for some special cases as well.
The most useful way would be to check the sys.path first with:
import sys
print(sys.path)

Then you can find where you should import from.
There is an another way as well:
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname("__file__"), '..')))

or use insert function instead:
sys.path.insert(0, xxx)

These two ways are suitable for small project. I will recommend you choose the first one if your project is complex and huge.


text:
Q: How to make a card "inactive" but showed with a sign that says something like "work in progress" upon it? In CSS probably the question is not well formulated, I will try to clarify what I meant. I'm making a website which contains several cards that clicking on them some contents shows on new pages. I would like to see the website online soon but some contents are not already done so I would like to show the cards in order to create curiosity but the cards have to appear "inactive" with opacity and with a kind of sign upon them that intends I'm working on them and soon they will be finished. A kind of "man at work sign" upon them. In particular, the cards behind the sign have to appear opacity and the sign on them have to appear normal with no opacity. Sorry if I was verbose. I hope you all understood the problem. Thank you so much in advance

A: maybe you want to share some code? In general that doesn't sound too hard. :)
Without additional information, that's the maximum I was able to understand:

A: It appears from your question you want to have a non-opaque child element appear within a semi-opaque parent element. But you have run into the difficulty that all children of a semi-opaque (e.g. opacity=.5) inherit the (lack of) opacity.
If so, the question has an answer at Make a child element opaque in a div that is not opaque


text:
Q: How to write console output to a user named file My issue is simple. And I am sure the solution is simple too. But my attempts have failed. I looked on every question on here that relates to this but it does not contain the solution I am looking for. I am using a ReadGameFile() method and a WriteToGameFile() method that is in my class VideoGameManager. I have a class that contains a method that outputs data in the following way :
this class is called VideoGameManager
which has a method that is called public void printSearchCriteria(String nameInput,String consoleInput);
name (tab space) platform
name "         " platform
name "         " platform
....etc.
then in a main class I have a new instance of VideoGameManaer
VideoGameManager vG = new VideoGameManager();
I then call the method that outputs the data with the following parameters
in which the user inputs
nameInput = keyboard.next();
consoleInput = keyboard.next();
vG.printSearchCriteria(String nameInput, String consoleInput);
This results in the data being printed in the way which was stated above.
I now need to find a way to take that output. and store it in new file in which the user will name.
System.out.println("Enter the file name to print out.");
String fileNamePrintToFile = keyboard.next();
//Some way that takes the data from the output of printSearchCriteria and stores it in a new file from the user input -fileNamePrintToFile.
VideoGameManager File
public class VideoGameManager {
Scanner keyboard = new Scanner(System.in);
//array list
private ArrayList<VideoGame> games;
//tab
private static final String delim = "\t";

//constructor
public VideoGameManager(){
    games = new ArrayList<VideoGame>();
}

public void ReadGameFile(String fileName)
{
    //This reconstructs a new instance of the VideGame array list.
    //This is done to clear the array list
    games = new ArrayList<VideoGame>();
    try
    {
        //Create a new file Scanner
        Scanner fileScanner = new Scanner(new File(fileName));
        //Reads each line in the file one-by-one
        while(fileScanner.hasNextLine())
        {
            //Stores the next line of code
            String nextLine = fileScanner.nextLine();
            //That line is then split using the delimiter (\t)
            String[] splitStrings = nextLine.split(delim);
            //If the newly created array is not 2 items in length then
            //that line is not correctly formatted and should be ignored.
            if(splitStrings.length != 2)
                continue;
            String gameName = splitStrings[0];//The first element is the game name
            String console = splitStrings[1];//Next is the console
            VideoGame newVideoGame = new VideoGame(gameName,console);
            games.add(newVideoGame);//Added to the array list
        }
        fileScanner.close();
    }
    catch(Exception e)
    {
        System.out.println(" File does not exist ");
    }

}
public void WriteToGameFile(String fileName, boolean append)
{
    if(games == null)//if the file name is null then return
        return;
    try
    {
        //Creates the new instance of a print writer
        PrintWriter fileWriter = new PrintWriter(new FileOutputStream(fileName,append));
        for(VideoGame aVideoGame : games)
        {
            //Prints to the file
            fileWriter.println(aVideoGame.getName()+delim+
                                aVideoGame.getConsole());
        }
        fileWriter.close();
    }
    catch(Exception e)
    {
        System.out.println("Error");
    }
}
//returns an array list of video games based on a search criterion (name and console)
public void PrintSearchCriteria(String nameInput, String consoleInput)
{

    for(VideoGame aVideoGame : games)
    {
        if(aVideoGame.getName().contains(nameInput) == true && aVideoGame.getConsole().contains(consoleInput) == true)
        {
            VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
            System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());

        }
        else if(aVideoGame.getName().contains(nameInput) == true && consoleInput.equalsIgnoreCase("*"))
        {
            VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
            System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());

        }
        else if(nameInput.equalsIgnoreCase("*") && aVideoGame.getConsole().contains(consoleInput) == true)
        {
            VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
            System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());

        }

    }
}

public void PrintCurrentResults(String fileName)
{
    for(VideoGame aVideoGame : games)
    {
        System.out.println(aVideoGame.getName()+delim+
                                aVideoGame.getConsole());
    }
}

}
Main Class
public class VideoGameFrontEnd {

public static void main(String[] args) {
    //create and connect scanner object to keyboard
    Scanner keyboard = new Scanner(System.in);
    VideoGameManager vG = new VideoGameManager();
    System.out.println("Welcome to the video game database!");
    boolean quit = false;
    try{
    while(quit == false)
    {

    System.out.println("Enter 1 to load the video game database");
    System.out.println("Enter 2 to search the database");
    System.out.println("Enter 3 to print current results");
    System.out.println("Enter 4 to print current results to file");
    System.out.println("Enter 0 to quit");
    int input = keyboard.nextInt();

    switch(input){
    case 0: input = 0;
        System.out.println("Good Bye");
        quit = true;
        break;

    case 1: input = 1;
        System.out.println("Enter the file Name");
        String fileName = keyboard.next();
        vG.ReadGameFile(fileName);
        break;
    case 2: input = 2;
        System.out.println("Enter the name of the game or '*' for all names");
        String nameInput = keyboard.next();
        System.out.println("Enter the name of the console or '*' for all consoles");
        String consoleInput = keyboard.next();
        vG.PrintSearchCriteria(nameInput,consoleInput);

        break;
    case 3: input = 3;
        //print current results
        break;
    case 4: input = 4;

        System.out.println("Enter the file name to print out.");
        String fileNamePrintToFile = keyboard.next();
        System.out.println("Append to file ? True or False");
        String appendToFile = keyboard.next();
        if(appendToFile.equalsIgnoreCase("true"))
        {
            vG.WriteToGameFile(fileNamePrintToFile, true);
        }
        else if(appendToFile.equalsIgnoreCase("false"))
        {
            vG.WriteToGameFile(fileNamePrintToFile, false);
        }
        else
        {
            System.out.println("Incorrect Response, auto shutdown");
            System.exit(0);
        }
    default:
        break;

        }

    }
}
catch(Exception e)
{
    System.out.println("error");
    System.exit(0);
}

}
}

A: I suggest logging framework like log4j,slf4j and so on. Or java standard logging utils.
If you want to know, how to save all the outputs send by System.out.print or println, here is one of the way, how you can achieve.
public static void main(String[] args) throws FileNotFoundException {
        PrintStream ps = new PrintStream("mylog.log");
        System.setOut(ps);
        System.out.println(String.format("%s: %s", new Date(),"Application Started"));
        System.out.println(String.format("%s: %s", new Date(),"Application Terminated"));
    }

And the output will be some thing like this,


text:
Q: Gmaps4Rails - auto-adjusting map to bounds not respecting hidden markers Using Gmaps4Rails, I've got some markers that I can show/hide based on an attribute. That works fine. However, I'm trying to get the map to auto-adjust to the current set of markers with Gmaps.map.adjustMapToBounds() called after I set the currently visible markers.
Whenever I filter items, the entire map shows, as if it were displaying all of the markers, even though it actually displays just the filtered ones. I think it is because it considers hidden markers when setting the bounds, but I could be wrong!
Here is my filtering code:
$("select").change(->
    currentFilters = $('select').val()
    hideAllMarkers()
    visibleMarkers()
    Gmaps.map.adjustMapToBounds()
  )

  visibleMarkers = ->
    filtered = Gmaps.map.markers
    filtered = _.filter(filtered, (marker) ->
      _.include(currentFilters, marker.market)
    )

    _.each filtered, (marker) ->
      Gmaps.map.showMarker marker

  hideAllMarkers = ->
    _.each Gmaps.map.markers, (marker) ->
      Gmaps.map.hideMarker marker

And here are the options I'm initializing the map with:
@gmap_options = {"map_options" => {
  "auto_zoom" => true,
  "auto_adjust" => true,
  "mapTypeControl" => true,
  "detect_location" => true,
  "center_on_user" => true},
  "markers" => {"data" => @map}
}


text:
Q: Error: unknown type name y struct Error: unknown type name y struct

El error está en la linea siguiente: void busqueda(Persona arreglo[], int, char, int, int){, en ¨Persona", y no se me ocurre cómo arreglarlo
#include<stdlib.h>
#include<stdio.h>

struct Persona {
    char nombre[30];
    int edad;
    float est;
    char sexo;
} Persona_n[10];
void darNumElem(int *);
void busqueda(Persona arreglo[], int, char, int, int){
    printf("\n Nombre  Edad");
    for(int i=1; i<=n; i++){
        if(arreglo[i].edad==e){
            for(int j=0; arreglo[i].nombre[j]!='\0'; j++){
                if(arreglo[i].nombre[j]==l && j==p){
                    printf("\n %s, %d", arreglo[i].nombre, arreglo[i].edad);
                }
            }
        }
    }
}

int main(){
    int n, i, p, e;
    char l;
    darNumElem(&n);
    for(i=0; i<n; i++){
        fflush(stdin);
        printf("\n Ingresa cadena \n");
        gets(Persona_n[i].nombre);
        printf("\n Ingresa edad \n");
        scanf("%d", &Persona_n[i].edad);
        printf("\n Ingresa estatura \n");
        scanf("%f", &Persona_n[i].est);
        fflush(stdin);
        printf("\n Ingresa sexo \n");
        Persona_n[i].sexo=getchar();
        fflush(stdin);
    }
    printf("\n ¿Que letra del nombre tiene la persona que desea encontrar? \n");
    scanf("%c", &l);
    printf("\n ¿En que posicion debe estar la letra? \n");
    scanf("%d", &p);
    printf("\n ¿Que edad debe tener la persona \n");
    scanf("%d", &e);
    busqueda(Persona_n, n, l, p, e);
}
void darNumElem(int * n){
        printf("Numero de elementos \n");
        scanf("%d", n);
    }

El programa debe guardar los datos en un arreglo de estructuras e imprimir solo el nombre y edad de los datos que cumplan las condiciones; pero para comparar el arreglo nombre con la letra en la posición introducida por el usuario, debo recorrer el arreglo nombre dentro del arreglo Persona_n, ¿Las condiciones de los if son correctas?
void busqueda(Persona arreglo[], int, char, int, int){
    printf("\n Nombre  Edad");
    for(int i=1; i<=n; i++){
        if(arreglo[i].edad==e){
            for(int j=0; arreglo[i].nombre[j]!='\0'; j++){
                if(arreglo[i].nombre[j]==l && j==p){
                    printf("\n %s, %d", arreglo[i].nombre, arreglo[i].edad);
                }
            }
        }
    }
}

Esta es la información del compilador:
11    15  C:\A [Error] unknown type name 'Persona'
De antemano muchas gracias

A: Sólo necesitas dos cambios en tu código para que sea válida (no necesariamente correcto, pero válido):
En la declaración de la función
void busqueda(Persona arreglo[], int, char, int, int){

Persona no es un tipo de datos. Los tipos de datos se crean usando typedef. Lo que tú tienes es una struct Persona.
Cuando defines una función tienes que ponerle nombre a los parámetros; si no, ¿cómo los accesas?
La declaración correcta es asi:
void busqueda(struct Persona arreglo[], int n, char l, int e, int p) {

Nota: use los nombres que aparecen sin declarar dentro de la función. Revisa que correspondan.
En cambio, en
void darNumElem(int *);

no pones nombres porque no estas definiendo la función; simplemente dices que existe y que recibe tales parámetros. La definición está en otra parte.
No usar gets
Por razones de seguridad (buffer overflow), en lugar de gets usa fgets. Donde dice:
gets(Persona_n[i].nombre);

usa
fgets(Persona_n[i].nombre, 30, stdin);

La función fgets está definida así:
char *fgets(char *str, int n, FILE *stream)

*

*str: un puntero donde dejaras lo leido.

*n: l tamaño disponible (en bytes).

*stream: desde donde lees.

La función lee un máximo de n-1 caracteres y le agrega un 0 al final para convertirlo en una cadena valida.


text:
Q: Typescript definition for values function which always return array of argument export type Primitive =
  | null
  | undefined
  | string
  | number
  | boolean
  | symbol
  | bigint;

function values<T extends any[]>(value: T): T;
function values<T extends Primitive>(value: T): [T] {
  return Array.isArray(value) ? value : [value];
}

I want to build a function to always return array.
my attempt so far for the values function, but it's not working. Does anyone have a better idea or suggestion? thanks in advance.
Playground

A: You should have to add more overloadings:
export type Primitive =
  | null
  | undefined
  | string
  | number
  | boolean
  | symbol
  | bigint;

function values<T extends Primitive>(value: T): [T];
function values<T>(value: Array<T>): Array<T>;
function values<T extends Primitive>(value: T): [T] | Array<T> {
  if (Array.isArray(value)) {
    const x = value
    return value
  } else {
    return [value]
  }
}

const x = values(1) // [1]
const y = values('hello') // ['hello']
const z = values([1,2,3]) // number[]


text:
Q: How do we use distinct in left join of mysql I am using PHP and MySQL for my application.
I have a table "Enquiries" with PK enquiry_id and a table "Enquiry_comments" with FK enquiry_id. There will be multiple comments for each enquiry. In my join how do I show the last comment only against each enquiry?

SELECT * FROM enquiries AS e LEFT JOIN enquiry_comments AS ec
  ON ec.enquiry_id = e.enquiry_id WHERE e.status = 'Active'
  ORDER BY e.enquiry_id DESC LIMIT 10

The above query gives me duplicate records so I want to use group by or distinct on enquiry_id and order by enquiry_comment_id DESC for enquiry_comments and show only the recent comment with the listing.
The Table Structure:
Table Enquiries
enquiry_id  enquiry_about enquiry_date
1           PHP           2017-09-20
2           MySQL         2017-08-21

Table Enquiry_comments
enquiry_comment_id enquiry_id enquiry_comment enquiry_comment_date
1                     1       PHP is Easy     2017-08-03
2                     1       PHP is Ver 7    2017-09-17
3                     2       MySQK is RDBS   2017-09-13

From the above example data I want to get the latest one comment with each enquiry so PHP should get one comment with enquiry_comment_id 2 which is latest and MySQL get the enquiry_comment_id 3
The Listing Data I want
1   PHP    PHP is Ver 7    2017-09-17
2   MySQL  MySQK is RDBS   2017-09-13

A: Try this query:
SELECT
    t1.enquiry_id,
    t1.enquiry_about,
    (SELECT t2.enquiry_comment FROM Enquiry_comments t2
     WHERE t2.enquiry_id = t1.enquiry_id
     ORDER BY t2.enquiry_comment_date DESC LIMIT 1) AS enquiry_comment,
    (SELECT MAX(t2.enquiry_comment_date) FROM Enquiry_comments t2
     WHERE t2.enquiry_id = t1.enquiry_id) AS enquiry_comment_date
FROM Enquiries t1
ORDER BY t1.enquiry_id;

For each record in the Enquiries table, this query does a subquery on Enquiry_comments and selects the latest comment for each parent enquiry.  To find the latest record it uses an ORDER BY with LIMIT trick.  To also find the corresponding latest comment date, we can just use a simple subquery with the MAX() function.
Output:

Demo here:
Rextester


text:
Q: Fetch value of a specific key from nested dictionary in pandas with python I am iterating through the rows in pandas dataframe printing out nested dictionaries from the specific column. My nested dictionary looks like this:
{'dek': "
Don't forget to buy a card
",
 'links': {'edit': {'dev': '//patty-menshealth.feature.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
   'prod': '//patty-menshealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
   'stage': '//patty-menshealth.stage.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c'},
  'frontend': {'dev': '//menshealth.feature.net/trending-news/a19521193/fathers-day-weekend-plans/',
   'prod': '//www.menshealth.com/trending-news/a19521193/fathers-day-weekend-plans/',
   'stage': '//menshealth.stage.net/trending-news/a19521193/fathers-day-weekend-plans/'}},
 'header': {'title_color': 1, 'title_layout': 1},
 'sponsor': {'program_type': 1, 'tracking_urls': []},
 'social_dek': "
Don't forget to buy a card
",
 'auto_social': 0,
 'index_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
 'short_title': "Treat Your Dad Right This Father's Day",
 'social_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
 'editors_notes': '
nid: 2801076
created_date: 2017-06-16 13:00:01
compass_feed_date: 2017-06-21 14:01:58
contract_id: 40
',
 'seo_meta_title': "Treat Your Dad Right This Father's Day\u200b | Men's Health",
 'social_share_url': '/trending-news/a19521193/fathers-day-weekend-plans/',
 'seo_related_links': {},
 'editor_attribution': 'by',
 'hide_from_homepage': 1,
 'syndication_rights': 3,
 'seo_meta_description': "\u200bFrom gifts to food ideas, we've got your Father's Day covered. Just don't forget to buy him a card."}

I use the code below:
def recursive_items(dictionary):
    for key, value in dictionary.iteritems():
        if type(value) is dict:
            yield from recursive_items(value)
        else:
            yield (key, value)

for key, value in recursive_items(merged_df["metadata_y"]):
    print(key, value)

How do I grab the value of a specific key? I tried to include the index of the key I am looking to fetch with print(key[5], value it gave me an error: TypeError: 'int' object is not subscriptable.
How can I grab the value?

A: Apologies about not directly addressing the original question, but maybe it's worth "flattening" the nested column using json_normalize.
For example, if your example data is named dictionary:
from pandas.io.json import json_normalize

# Flatten the nested dict, resulting in a DataFrame with 1 row and 23 columns
this_df = json_normalize(dictionary)

# Inspect the resulting columns. Is this structure useful?
this_df.columns
Index(['dek', 'social_dek', 'auto_social', 'index_title', 'short_title',
       'social_title', 'editors_notes', 'seo_meta_title', 'social_share_url',
       'editor_attribution', 'hide_from_homepage', 'syndication_rights',
       'seo_meta_description', 'links.edit.dev', 'links.edit.prod',
       'links.edit.stage', 'links.frontend.dev', 'links.frontend.prod',
       'links.frontend.stage', 'header.title_color', 'header.title_layout',
       'sponsor.program_type', 'sponsor.tracking_urls'],
      dtype='object')

A: data={'dek': "
Don't forget to buy a card
",
'links': {'edit': {'dev': '//patty-menshealth.feature.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
'prod': '//patty-menshealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c',
'stage': '//patty-menshealth.stage.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c'},
'frontend': {'dev': '//menshealth.feature.net/trending-news/a19521193/fathers-day-weekend-plans/',
'prod': '//www.menshealth.com/trending-news/a19521193/fathers-day-weekend-plans/',
'stage': '//menshealth.stage.net/trending-news/a19521193/fathers-day-weekend-plans/'}},
'header': {'title_color': 1, 'title_layout': 1},
'sponsor': {'program_type': 1, 'tracking_urls': []},
'social_dek': "
Don't forget to buy a card
",
'auto_social': 0,
'index_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
'short_title': "Treat Your Dad Right This Father's Day",
'social_title': "\u200bWeekend Guide: Treat Your Dad Right This Father's Day",
'editors_notes': '
nid: 2801076
created_date: 2017-06-16 13:00:01
compass_feed_date: 2017-06-21 14:01:58
contract_id: 40
',
'seo_meta_title': "Treat Your Dad Right This Father's Day\u200b | Men's Health",
'social_share_url': '/trending-news/a19521193/fathers-day-weekend-plans/',
'seo_related_links': {},
'editor_attribution': 'by',
'hide_from_homepage': 1,
'syndication_rights': 3,
'seo_meta_description': "\u200bFrom gifts to food ideas, we've got your Father's Day covered. Just don't forget to buy him a card."}

def findValByKey(key:str, data:dict, level=0):
    for i in data.keys():
        print("{} {}".format(level*'-', i))
        if i==key:
            print('---found---')
            return data[key]
        elif isinstance(data[i], dict):
            res = findValByKey(key, data[i], level+1)
            if res:
                return res

print(findValByKey('title_color', data))


text:
Q: Eclipse won't read images from drawable I was working on some project and everything was fine, but yesterday i replaced some images in drawable folder and the old pictures are still there and won't replace and i get and error "Image cannot be resolved or is not a field"  (i was doing that before and everything worked fine). I reinstalled android development kit and downloaded everything again and nothing.
Please help, thanks
http://i.stack.imgur.com/laedA.png

A: Refresh your project or rename the new file and set it

A: Make sure you haven't old images in other drawable folders (hdpi, mdpi etc). If you have delete it, clean and build project.

A: *

*Scenario 1:: You have deleted images in drawable-folder but same named images are present in drawable-hdpi,ldpi,mdpi folders

*Scenario 2:: Delete the old images and then add the new ones

*Scenario 3:: Check the naming conventions for the images, make sure all are lower case and you don't use integers

*Scenario 4:: Use a different image with different name and reference

{EDIT-1}:: On Quote:: I have errors "Image cannot be resolved or is not a filled"
This is caused because you have deleted the image and there is no image and still you are referencing it in your project

{EDIT-2}::
instead of
import android.R
Changing it to following for ex::
import com.example.app.R

*

*Try deleting the R.Java and clean the eclipse and then again run the
project

{EDIT-3}
Scenario 3 ..... I explained clearly you cannot use integers for imagename..... instead of for example c3pipe13 name it as c_three_pipe_thirteen ......... do the same for all the images ...... that is what causing the error
Hope this helps, let me know if you need any information

A: Maybe drag the pictures onto the drawable-folder in your eclipse-projecttree. Then select copy files.


text:
Q: Replace some of the values in pandas dataframe I have a pandas dataframe like this:
     df
                  Case   Type   Base
        Year
        2000      HI      PC1   0
        2001      HI      PC1   0
        2003      HI      PC1   2.0
        2004      HI      PC1   0
        2005      HI      PC2   0
        2006      HI      PC2   0
        2007      HI      PC2   2.0
        2008      HI      PC2   0
        2009      LO      PC1   0
        2010      LO      PC1   0
        2011      LO      PC1   2.0
        2012      LO      PC1   0
        2013      LO      PC2   0
        2014      LO      PC2   0
        2015      LO      PC2   2
        2016      LO      PC2   0

I want to replace some of the zero values not all of them in column ['Base'] with value 1, so the final df looks like this:
          df
                    Case   Type   Base
         Year
         2000      HI      PC1   1
         2001      HI      PC1   1
         2003      HI      PC1   2.0
         2004      HI      PC1   0
         2005      HI      PC2   1
         2006      HI      PC2   1
         2007      HI      PC2   2.0
         2008      HI      PC2   0
         2009      LO      PC1   1
         2010      LO      PC1   1
         2011      LO      PC1   2.0
         2012      LO      PC1   0
         2013      LO      PC2   1
         2014      LO      PC2   1
         2015      LO      PC2   2.0
         2016      LO      PC2   0

I used the code below:
         df.groubpy(['Case','Type'].apply(lambda x: x.[0:3,3].replace({0:1})

But I realize I only get the results between 2000 and 2001, not between 2000,2016.
Thank you for your help.

A: mask and bfill
zeroes = df.Base.eq(0)
shiftd = zeroes.astype(int).shift().bfill()
df.assign(Base=df.Base.mask(zeroes).fillna(shiftd))

     Case Type  Base
Year
2000   HI  PC1   1.0
2001   HI  PC1   1.0
2003   HI  PC1   2.0
2004   HI  PC1   0.0
2005   HI  PC2   1.0
2006   HI  PC2   1.0
2007   HI  PC2   2.0
2008   HI  PC2   0.0
2009   LO  PC1   1.0
2010   LO  PC1   1.0
2011   LO  PC1   2.0
2012   LO  PC1   0.0
2013   LO  PC2   1.0
2014   LO  PC2   1.0
2015   LO  PC2   2.0
2016   LO  PC2   0.0


text:
Q: Is there any way to attach VisualVM to java lambda function runned by AWS SAM local There is a way to run lambda function locally using:
sam local start_lambda [OPTIONS]

The function is written in Java. I want to investigate memory allocation.
Therefore I need to attach VisualVM to java process running within docker container started by SAM CLI.
There is a way to expose JMX for java running within docker: How do I attach VisualVM to a simple Java process running in a Docker container
The question is how to pass the above configuration when running SAM local?


text:
Q: Blender OpenGL animation rendering without open GUI (display) from command line I'd like to render animation with opengl.
I have a script for render and this working with open blender GUI.
I want to run this script (with render.opengl function) from linux command line without X.
I tried some way without success :(

A: Short answer: Can't be done.
Long answer: For OpenGL to be usable you need a so called render context. OpenGL itself can not create render contexts, that's the job of the display graphics system (X11, EGL/Wayland, etc.).
Mesa's software rasterizer is accompanied with an offscreen render context manager, however using that one must be prorammed specifically, works only with Mesa and Blender doesn't support it!
When launched in windowless mode, Blender doesn't even bother to create a render context.

A: You can use
export DISPLAY=:0
blender -b your_file.blend -a

Not exactly what you asked, but  it will do the trick to if you want to render in a remote machine.
Basically it is going to create the render context in the remote machine, nevertheless the render command itself won't open a GUI


text:
Q: how to extract database xml data in soapui My data is saved in SQL Server 2014 in xml format, and in SOAPUI JDBC request it is coming in this format
<Results>
<ResultSet fetchSize="128">
<Row rowNumber="1">
  <ConfigurationXML><![CDATA[<ROOT><Device>[{"Name":"AL","Profile":{"ID":1,"Height":240},"Index":-1}]</Device></ROOT>]]></ConfigurationXML>
</Row>
</ResultSet>
</Results>

I want to compare this data with my REST Json Response, But how can I fetch data from this CDATA

A: The sample jdbc response provided by is little complex. Needs to be retried in multiple phases based on the nature of the data.

*

*Response xml has CDATA

*CDATA again has Xml

*That xml has json
Please find the below groovy script to retried final json and retrieving its properties as shown below.
Script is done with appropriate comments in line.
import com.eviware.soapui.support.XmlHolder
import groovy.json.*
//Sample response
def response = '''<Results>
<ResultSet fetchSize="128">
<Row rowNumber="1">
  <ConfigurationXML><![CDATA[<ROOT><Device>[{"Name":"AL","Profile":{"ID":1,"Height":240},"Index":-1}]</Device></ROOT>]]></ConfigurationXML>
</Row>
</ResultSet>
</Results>'''
//Create the xml holder object for the jdbc response
def holder = new XmlHolder(response)
//Get ConfigurationXML Node value using Xpath from holder object, which will retrive CDATA
def configurationXmlCdata =  holder.getNodeValue('//*:ConfigurationXML')
log.info "Configruation Xml Cdata: ${configurationXmlCdata}"
//There is again xml inside CDATA, so create xml holder object to retried json string
def cdataHolder = new XmlHolder(configurationXmlCdata)
def jsonString = cdataHolder.getNodeValue('//ROOT/Device')
log.info "Device Json data: ${jsonString}"
//Create Json slurper object if you need to access json
def jsonData = new JsonSlurper().parseText(jsonString)
log.info jsonData.Name
log.info jsonData.Index
log.info jsonData.Profile.ID

A: I tried to convert XML to string then replace characters and finally cast the replaced character expression back to XML
declare @xml xml = '
<Results>
<ResultSet fetchSize="128">
<Row rowNumber="1">
  <CONFIGURATIONXML><ROOT></Device>[{"Name":"AL","Profile":{"ID":1,"Height":240},"Index":-1}]</ROOT></CONFIGURATIONXML>
</Row>
</ResultSet>
</Results>
'

select replace(replace( CAST(@xml as nvarchar(max)),'<','<'),'>','>')
    -- CAST( replace(replace( CAST(@xml as nvarchar(max)),'<','<'),'>','>') as xml)

But it fails because of the DEVICE tag
It should be in

A: Reading the value properly will de-code the characters implicitly.
But: Your inner XML is not valid!:
DECLARE @xml XML=
'<Results>
  <ResultSet fetchSize="128">
    <Row rowNumber="1">
      <CONFIGURATIONXML><ROOT></Device>[{"Name":"AL","Profile":{"ID":1,"Height":240},"Index":-1}]</ROOT></CONFIGURATIONXML>
    </Row>
  </ResultSet>
</Results>';
SELECT @xml

SELECT @xml.value('(/Results/ResultSet/Row/CONFIGURATIONXML)[1]','nvarchar(max)')

Leads to:
<ROOT></Device>[{"Name":"AL","Profile":{"ID":1,"Height":240},"Index":-1}]</ROOT>

As you can see, the </DEVICE> is a closing tag, but there's no opening tag for this...
Don't know how this is created... If this is always the same, you could repair this like this:
SELECT CAST(REPLACE(@xml.value('(/Results/ResultSet/Row/CONFIGURATIONXML)[1]','nvarchar(max)'),'</Device>','') AS XML).value('/ROOT[1]','varchar(max)')

The result
[{"Name":"AL","Profile":{"ID":1,"Height":240},"Index":-1}]


text:
Q: Sluggish UI/video performance on NVIDIA GeForce 8600 GS and very high CPU usage I am a newbie in Linux and installed Ubuntu in my really old laptop Dell Vostro 1500. Everything seems to be working fine except the graphics driver. Initially, I didn't understand that Linux is using the default driver as all colours were looking good however the UI looks very slow and sluggish. Moving window or any new popup comes up so late.
System configuration:

*

*Intel Centrino 1.7GHz dual-core

*3 GB RAM

*320 GB HDD

*NVIDIA GeForce 8600 GS

*Ubuntu 13.10

Firstly I tried to install with the latest Ubuntu provided NVIDIA driver, but it didn't work and caused x-server to crash. I used sudo apt-get install nvidia-latest. Also tried installing the recommended driver from Device Manager, that didn't work either. I ended up with 640x480 resolution.
After lots of Googling, I came up with unofficial NVIDIA drivers from x-swat which seems to fix my resolution and a loaded NVIDIA driver. I used the command below
sudo add-apt-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install nvidia-current
sudo nvidia-xconfig

I have also checked if NVIDIA is loaded using
lsmod | egrep "nvidia"

which resulted
nvidia              10304704  44

I have also checked the driver version from NVIDIA X Server Settings from start menu which resulted 304.117
I have also black-listed the following in /etc/modprobe.d/blacklist.conf
blacklist intel_agp
blacklist nouveau
blacklist lbm-nouveau

I have also tried to tweak NVIDIA settings with these following commands:
nvidia-settings -a InitialPixmapPlacement=2 -a GlyphCache=1

and also added:
Option "PixmapCacheSize" "300000"
Option "OnDemandVBlankInterrupts" "True"

to my xorg.conf Device section.
Still, everything is slow, resizing/moving windows, scrolling, and also deserves mentioning video playback is extremely choppy.
It would be lovely to have a response from Linux gurus :)


text:
Q: Out of Memory during MessagePack Decoding I'm running into out of memory issues when I attempt to decode MessagePack files using the msgpack-lite library in the browser. When run, the browser tab crashes (Chrome shows an 'Awww Snap!' error page). If I run the app with the developer tools open and set some breakpoints, it stops occasionally with a warning of a potential out of memory error. I can then continue execution and the decoding completes successfully. This leads me to believe the garbage collector needs time to run.
I'm wondering if there are any known issues around types of files or ways of interacting with the msgpack-lite library that affect this? Does the organization of file contents affect memory requirements?
In the application I'm using Angular/RXJS and calling msgpack.decode(new Uint8Array()):
this.http.get(url, {responseType: 'arraybuffer'})
      .map((response: ArrayBuffer) => BaseService.msgpack.decode(new Uint8Array(response)))

One of the files I'm having problems with is available here: https://file.io/SYxHDb
Any help with this is greatly appreciated!


text:
Q: Changing exisiting standard property to DependencyProperty Is that possible to change for example MediaElement.Position property to DependencyProperty by inheriting MediaElement class and then creating DependencyProperty in a new class from inherited class?
How to do it? AFAIK DependencyProperty stops normal behaviour of default accessor, how to reconnect things to not break up after change?
I want to update Slider.Value through Binding thus I need MediaElement.Position as DependencyProperty. I know I can do it with DispatcherTimer but I think it's not professional solution.

A: You can create either a custom control (a XAML-less control that inherits from MediaElement) or a UserControl with a MediaElement somewhere in its visual tree.
In either case, create your DependencyProperty, and use the PropertyChangedCallBack (in FrameworkPropertyMetadata) to respond to changes made, and use events to listen the other way.
In either case, you are creating a new control to use instead of the MediaElement. The advantage of a User Control is that you only expose the properties needed. The disadvantage being naturally that you have to expose them all. The custom control will also expose the Position property even though you don't want to use it.


text:
Q: how to write an if else statement in Spark for a variable which sometimes does not exist in the database? I am new to Spark and I have some troubles with using if else statement for the variable that is sometimes exist, sometimes more. I am trying to write a code line where there is a condition, if the "context_type" exists, then show me in the final Pipeline rdd, if not just show 0.
I have tried this one for the mapping function of the media_play, context_type is the one which is not always present in the database, it is an optional parameter:
def media_play_map_func(x):
    ```
        Extract elements needed from media_play event

        Params:
            x(dict): Event dictionary
        Return:
            (dict): Dictionary with values required for each event
    ```
    context_type=0 if context_type is None else str(x.get("event").get("context").get("type"))

  -- I have also tried the code below, but it did not work
    **context_type**=str(x.get("event").get("context").get("type"))
 if context_type is not None else 0

    return {

        'user_id': str(x.get('user_id')),
        'session_start_timestamp': x.get('session_start_timestamp'),
        'collect_timestamp': x.get('collect_timestamp'),
        'context_type':context_type

    }

And this is the error which appears when I try to show data:
print(data.take(10))

UnboundLocalError: local variable 'context_type' referenced before assignment

I have also tried:
 context_type= 0 if not str(x.get("event").get("context").get("type")) else  str(x.get("event").get("context").get("type"))

AttributeError: 'NoneType' object has no attribute 'get'

The Question: how to write an if else statement for a variable which sometimes does not exist in the database to avoid this error?


text:
Q: OLS vs. Regression with ARMA errors I'm working with a time series of macroeconomic data (independent variables) and bank loss rates (dependent variable) to show how bank losses vary based on the state of the economy.
To estimate the relationship between the dependent and independent varaibles, I am considering two regression techniques: standard OLS and Regression with ARMA errors as outlined in this extremely helpful article https://robjhyndman.com/hyndsight/arimax/.
When comparing the coefficients and residuals calculated by the two methodologies, I am struggling to interpret which is preferable. I'll walk you through my thought process with the hope that others can better intuit which is the preferable model.
OLS Model
When I estimate the model using OLS, I get a decently fit model (63% Adj R-squared) with all coefficients showing some degree of significance:
> summary(varLM)

Call:
lm(formula = DepVar ~ modelFactors)

Coefficients:
                                   Estimate Std. Error t value  Pr(>|t|)
(Intercept)                       -0.260879   0.061043  -4.274  4.73e-05 ***
NAT.5_Year_Treasury_Yield          0.012234   0.005059   2.418   0.01759 *
NAT.House_Price_Index_Growth      -0.002837   0.001129  -2.514   0.01371 *
REG.Real_Disposable_Income_Growth -0.011284   0.003674  -3.072   0.00281 **
REG.Unemployment_Rate              0.060506   0.006767   8.942  4.18e-14 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.08086 on 91 degrees of freedom
Multiple R-squared:  0.6491,    Adjusted R-squared:  0.6337

The model residuals pass stationarity tests, so I feel fairly confident that my model isn't misspecified. Below are my residuals plotted over time as well as the ADF test on the OLS residuals.

> adf.test(varLM$residuals)

Augmented Dickey-Fuller Test

data:  varLM$residuals
Dickey-Fuller = -3.9243, Lag order = 4, p-value = 0.01605
alternative hypothesis: stationary

Now where my models got dinged is that the residuals show autocorrelation. Below is the Durbin-Watson test for this model:
Durbin-Watson test

data:  varLM
DW = 1.0976, p-value = 1.709e-07
alternative hypothesis: true autocorrelation is greater than 0

A model validator could not get over that 1) my models had autocorrelation and 2) that I didn't use an arima structure. In fact they told me that the above model was basically garbage. On the autocorrelation point, I thought I could get around it using Newey-West Standard errors as I've read that serial correlation only affects the model's standard errors...
Regression with ARMA Errors
Based on this feedback, I investigated using a regression with ARMA errors to resolve the serial correlation issue in my models. I used the auto.arima function in R to fit an ARIMA model on my residuals:
> auto.arima(DepVar, xreg = modelFactors)
Series: DepVar
ARIMA(1,0,0) with non-zero mean

Coefficients:
     ar1  intercept  NAT.5_Year_Treasury_Yield  NAT.House_Price_Index_Growth
  0.4674    -0.2429                     0.0075                       -0.0029
  0.0985     0.0894                     0.0080                        0.0017
        REG.Real_Disposable_Income_Growth  REG.Unemployment_Rate
                             -0.0078                 0.0586
 s.e.                         0.0051                 0.0101

sigma^2 estimated as 0.005294:  log likelihood=118.34
AIC=-222.67   AICc=-221.4   BIC=-204.72

Comparing the coefficients on this model with the coefficients on the OLS model, I see little change. The obvious difference is now we are modeling the errors using an AR(1) process. The difference can be seen in the residuals which now look like true white noise.

Conclusion
Am I wrong to say that the OLS model is fine, despite the serial correlation of the residuals? My preference is to stick to a simpler model structure (OLS) because I'd prefer to avoid a more complex model if possible. The other issue with the ARMA model is that I"m building multiple - what I've shown here is a subset. And when use the auto.arima function, I'm getting a different mix of AR() and MA() terms for each model.
I guess in general, is there a good rule of them of when OLS is appropriate for times series and when an ARIMA model is preferrable?

A:
Am I wrong to say that the OLS model is fine?

I'd say no, you're not wrong, but it does depend on what you mean by "fine." An economist introduced me to the book "A Guide to Econometrics" by Peter Kennedy, which is a really nice book for telling you what happens when classical assumptions are violated but you use the classical technique anyways. Usually the sky does not fall, but you do lose something.
In the case of regression with autocorrelated errors, Section 7.4 states:
"With positive first-order autocorrelated errors this implies that several succeeding error terms are likely also to be positive, and once the error term becomes negative it is likely to remain negative for a while...In repeated samples these estimates will average out, since we are as likely to start with a negative error as with a positive one, leaving the OLS estimator unbiased, but the high variation in these estimates will cause the variance of [the OLS estimator] to be greater than it would have been had the errors been distributed randomly."
Additionally, it goes on to mention that the variance of beta_OLS is also underestimated, which of course will mess up your test statistics. But you still have unbiasedness!

A: Simple regression using OLS, or any modeling technique, is primarily used to predict the relationship among population parameters, using sample data. When you want to use OLS on the sample data, and extrapolate your relationship to the population data, there are certain assumptions which are required. For. eg: the errors are independent, variance of errors is constant, etc. Unless these assumptions are satisfied, your results from sample data cannot be used for making inference on the relationship between population parameters.
The fact that the errors in OLS are autocorrelated indicate that your model, which you built using the sample data, cannot be used to comment on the relationship between population parameters.
If you have used all the entire data in your population for your model, your R-square may be high - indicating some sort of linear relationship. But, even then model cannot be used for forecasting accurately for the future - meaning that one cannot be sure of the validity of coefficients of the regression output on unseen future data.

A: You are perfectly fine to use the OLS Method.  I would just recommend utilizing robust p-values to show that your variables are still significant and running Bruesch-Pagan, Durbin-Watson and ADF tests against your results to further show the model is solid.  No one model is ever better than another, it all depends upon the context of the utilization of the model.  The approach I have shared is current and common practice across the financial industry.


text:
Q: Laravel 5.2 - use attach method with array values I am creating a blog with posts in Laravel 5.2. Every post is going to have multiple tags. I created a relationship between posts and tags. When the post is created, I am trying to attach multiple tags to it.
Controller function
public function store(Request $request)
{
        $attributes = [
            'author_id' => Auth::user()->id,
            'title' => $request->input('title'),
            'text' => $request->input('text'),
        ];

        $post = Post::create($attributes);

        // Get the tag ids from the the tags table in the database
        $tagsList = $request->input('tags');
        $tags = explode(",", $tagsList);

        $tagIds = array();
        foreach($tags as $tag) {
          $tagIds[] = Tag::select('id')->where('name', $tag)->limit('5')->get();
        }

        dd($tagIds); // Output below

        $post->tags()->attach($tagIds); // not working
}

dd($tagIds) output
array:2 [▼
  0 => Collection {#316 ▼
    #items: array:1 [▼
      0 => Tag {#317 ▼
        #fillable: array:2 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:1 [▼
          "id" => 32
        ]
        #original: array:1 [▶]
        #relations: []
        #hidden: []
        #visible: []
        #appends: []
        #guarded: array:1 [▶]
        #dates: []
        #dateFormat: null
        #casts: []
        #touches: []
        #observables: []
        #with: []
        #morphClass: null
        +exists: true
        +wasRecentlyCreated: false
      }
    ]
  }
  1 => Collection {#318 ▼
    #items: array:1 [▼
      0 => Tag {#319 ▼
        #fillable: array:2 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:1 [▼
          "id" => 36
        ]
        #original: array:1 [▶]
        #relations: []
        #hidden: []
        #visible: []
        #appends: []
        #guarded: array:1 [▶]
        #dates: []
        #dateFormat: null
        #casts: []
        #touches: []
        #observables: []
        #with: []
        #morphClass: null
        +exists: true
        +wasRecentlyCreated: false
      }
    ]
  }
]

The returned array contains correct ids of the tags. I just do not know how to get them into a format, so that they can be passed to the attach method.
I would be very thankful for any kind of help!

A: For convenience, attach and detach also accept arrays of IDs as input:
        $tagIds = array();
        foreach($tags as $tag) {
          $tagIds[] = Tag::select('id')->where('name', $tag)->first()->id;
        }

        dd($tagIds); // Output below
        /*
       Array
       (
           [0] => 1
           [1] => 3
           [2] => 5
        )
        */

        $post->tags()->attach($tagIds);

A: You can just use pluck to get the array of ids from collection, no need to loop to get the ids of tags.
example:
$tags = Tag::pluck('id');
$post->tags()->attach($tags);
Please also refer to the documentation
https://laravel.com/docs/9.x/collections#method-pluck


text:
Q: Minimization of Norm Function Let $C$ be a symmetric and idempotent $m\times m$ real matrix. Let $z=\left[z_1 \cdots z_m\right]^T$ such that $z_i\in\{0,1\}$ for each $i=1,\ldots,m$ and $b\in\mathbb{R}^{m\times 1}$. We wish to find,
$\operatorname{argmin}_z \|(\displaystyle\frac{Czz^TC}{z^TCz}-C)b\|^2$
where $\|\cdot\|$ denotes the Euclidean norm. A few observations:

*

*The right hand side $C$ term may be factored out.

*$z^TCz=\|Cz\|^2$ since $\|Cz\|^2=(Cz)^T(Cz)=z^TC^TCz=z^TCCz=z^TCz$ using the fact that $C$ is symmetric and idempotent.

*The $(i,j)$ entry of $zz^T$ is $z_iz_j$ and is symmetric.

*$z_i^k=z_i$ since $z_i\in\{0,1\}$


text:
Q: Loop over hosts in serial with group in ansible There are hosts inventory like this:
[cluster]
10.1.1.1 rack=1
10.1.1.2 rack=1
10.1.1.3 rack=1
10.1.1.4 rack=2
10.1.1.5 rack=2
.
.
10.1.1.150 rack=50

I want to restart each group of hosts that have same rack number in serial. that mean in first restart 3 server with rack number 1 and after these 3 server reachable restart next 3 server and continue.
is there any why to do this with ansible?


text:
Q: How to create a StackedBarChart with specific intervals, empty space and reoccurring Row Keys in JFreeChart? I want to create a StackedBarChart that represents Elements within a certain length. The Endresult should look something like this:

I have the data for each row (Row 1 -> A from 0,5 - 3 and B from 4,5 to 7 for example).
After playing around for a while and not finding a direct way to do this, as a workaround i tried to use a CategoryDataset with a StackedBarRenderer and "convert" my Data to the Format and just paint the empty the same as the Background.
This already is a problem, since it then tries to add both "empty" entries and just display it as one in the middle. I then simply made each "empty" entry unique and it worked fine that way. The Problem comes with the next "A" entry in Row "3" where it somehow switches the order i put the data into the dataset and displays "A" before "B" (i'm guessing to line it up with the A in the first row).
Current result of below Code.. as you can see, it's pretty close, but i guess actually very, very far away:

I don't really know what else to try right now. I have a feeling i missed something and there is a very easy way to achieve this - is there any way to do this with JFreeChart or should i use a different library?
Dataset:
private CategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        //testdata
        dataset.addValue((Number) 0.5, "empty", 1);
        dataset.addValue((Number) 2.5, "A", 1);
        dataset.addValue((Number) 1.5, "empty2", 1);
        dataset.addValue((Number) 2.5, "B", 1);

        dataset.addValue((Number) 1.5, "empty3", 2);
        dataset.addValue((Number) 2.5, "C", 2);
        dataset.addValue((Number) 2, "empty4", 2);
        dataset.addValue((Number) 3, "D", 2);

        dataset.addValue((Number) 1, "empty5", 3);
        dataset.addValue((Number) 2.5, "B", 3);
        dataset.addValue((Number) 1.5, "empty6", 3);
        dataset.addValue((Number) 3, "A", 3);
        return dataset;
}

Chart:
        plot = new CategoryPlot();
        plot.setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT);
        plot.setOrientation(PlotOrientation.HORIZONTAL);

        CategoryDataset dataset = createDataset();

        CategoryAxis catAxis = new CategoryAxis();
        NumberAxis numAxis = new NumberAxis();
        numAxis.setVerticalTickLabels(true);

        StackedBarRenderer rend = new StackedBarRenderer();

        for (int i = 0; i < dataset.getRowCount(); i++) {
            String currKey = (String) dataset.getRowKey(i);
            if (currKey.startsWith("empty")) {
                rend.setSeriesPaint(i, INVISIBLE);
                rend.setSeriesItemLabelFont(i, new Font("Verdana", Font.BOLD, 0));
            }
        }

        rend.setShadowVisible(false);
        rend.setBarPainter(new StandardBarPainter());
        rend.setMaximumBarWidth(HEIGHT);

        rend.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{0}", NumberFormat.getInstance()));
        rend.setBaseItemLabelsVisible(true);

        plot.setDataset(dataset);
        plot.setDomainAxis(catAxis);
        plot.setRangeAxis(numAxis);
        plot.setDomainGridlinesVisible(false);
        plot.setRangeGridlinesVisible(false);
        plot.setRenderer(rend);
        plot.setBackgroundPaint(INVISIBLE);

        JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        chart.getLegend().setVisible(false);


text:
Q: en C++ las cadenas std::string son de longitud dinámica o fija Estoy aprendiendo C++ desde hace dos semanas y tengo una duda sobre las cadenas de texto encontradas en el encabezado <  string  > , la pregunta es si estas cadenas son de longitud fija o pueden crecer concatenándoles contenido.
#include <iostream>
#include <string>

void imprimir(std::string cdn){
    std::cout << cdn << "\n";
}

int main(int argc, char *argv[]) {

    std::string parrafo[5];

    parrafo[0]="Esta es la primera linea de un parrafo";
    parrafo[1]="EL gallo canta por la mañana";
    parrafo[2]="Hola mundo";
    parrafo[3]="frase que no tiene sentido";
    parrafo[4]="Esta es la ultima linea de un parrafo"

    imprimir(parrafo[0]);
    imprimir(parrafo[1]);
    imprimir(parrafo[2]);
    imprimir(parrafo[3]);

    return 0;
}

Mi interés es crear un arreglo 1D de tipo string para representar líneas de un documento en forma de un párrafo, pero tiene líneas de diferentes longitudes y lo que quiero saber es si esto dará un problema mas adelante.
Como he leído que los arrays almacenan datos de tamaño constante como por ejemplo un array de números flotantes solo puede almacenar valores de una misma longitud de bits y por eso me sale la duda sobre los strings de longitudes variadas.
Realmente si pueden explicarme como funcionan los strings por dentro agradeceria mucho.
#include <iostream>

int main(int argc, char *argv[]) {

    std::string cadena ="Hola mundo";
    cadena = "otro texto";

    return 0;
}

En el código de arriba declaré una cadena y luego le cambio el valor, el valor anterior se perdió o quedó en la memoria perdido, se sobrescribió en el mismo lugar de memoria o qué pasó realmente.

A:
la pregunta es si estas cadenas son de longitud fija o pueden crecer concatenándoles contenido

Pueden crecer concatenándoles contenido. Por eso disponen de las siguientes funciones:

*

*insert: Inserta caracteres.

*push_back: Añade un carácter al final.

*append: Añade una cadena al final.

*operator +=: Añade caracteres o una cadena al final.

Este programa:
std::string perro = "Perro";

std::cout << perro << '\n';

perro.insert(1, 1, 'u');
std::cout << perro << '\n';

perro.push_back('s');
std::cout << perro << '\n';

perro.append(" a la parrilla");
std::cout << perro << '\n';

perro += " que ricos!";
std::cout << perro << '\n';

Genera la siguiente salida:

Perro
Puerro
Puerros
Puerros a la parrilla
Puerros a la parrilla que ricos!

Como he leído que los arrays almacenan datos de tamaño constante como por ejemplo un array de números flotantes solo puede almacenar valores de una misma longitud de bits

Tienes un lío de conceptos muy grande:

*

*Array es el nombre de un concepto Y el nombre de un contenedor de datos.

*

*Se conoce como formación (o arreglo, o en inglés array) una colección de datos del mismo tipo cuya cantidad de datos es fija y cuyos datos se almacenan en memoria de manera anexa.

*El contenedor std::array es un contenedor diseñado para ayudar a manejar formaciones.

*Confundes el tamaño del contenedor con el tamaño de los datos. Un contenedor de datos sólo almacena datos del mismo tipo, por ello los datos serán todos del mismo tamaño. La cantidad de datos que almacena el contenedor puede ser fija o variable dependiendo del tipo de contenedor.


text:
Q: This application is available to over 0 devices My apk is active
I just published my application and when I go to the Play Store web page, it states my application isn't compatible with any of my devices : Sharelist

So I check the Play publish page and I got "This application is available to over 0 devices"

I'm not doing anything fancy on my Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.plumillonforge.android.sharelist"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<supports-screens
    android:smallScreens="true"
    android:normalScreens="true"
    android:largeScreens="true"
    android:anyDensity="true"/>

<application
    android:icon="@drawable/launcher"
    android:label="@string/app_name"
    android:theme="@style/SharelistTheme">

    <activity
        android:name=".PagerActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="file" />
            <data android:mimeType="*/*" />
            <data android:pathPattern=".*\\.shl" />
            <data android:pathPattern=".*\\..*\\.shl" />
            <data android:pathPattern=".*\\..*\\..*\\.shl" />
            <data android:pathPattern=".*\\..*\\..*\\..*\\.shl" />
            <data android:host="*" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>

    <activity
        android:name=".ListActivity"
        android:label="@string/title_activity_apps_list" />

    <activity
        android:name=".fragment.FilePickerActivity"
        android:label="@string/choose_shl_file" />

    <activity android:name="com.google.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>

A: Hey add the following code to Manifest file and give a try. It should work.
<uses-feature android:name="android.hardware.touchscreen"  android:required="false" />

and try to remove the Copy Protection in the Play Store Publish page also.
Just give a try.

A: I found out the problem
It was the Google Admob jar file include which was causing this weird behavior : I created a folder in my src/, add the jar and include it in my build path
It seems the build was oki but the Play Store got confused
So I delete the jar and build path, then created a libs/ folder in my project root then add it to the build path and it works now :)
You musn't add you jar file in the src/ folder (or any children folder) and add it to your build path


text:
Q: How to prove that $y$ is a minimiser for a certain functional $J$? The problem
Consider the functional $$J(y)=\int_a^b (y')^2 \, \mathrm{d}x$$ where $y \in D = C^{1,\mathrm{pw}}[a,b] \cap \{ y(a)=A,y(b)=B \}$ (the usual domain in the calculus of variations). We are told this functional is known as the "Dirichlet integral".
Solving the Euler-Lagrange equation relating to this function and considering the boundary conditions, one obtains the function $$y_0(x)=\frac{B-A}{b-a}x+\frac{bA-aB}{b-a}$$ as the only possible minimiser for $J$ on $D$.
As an assignment, I have to prove that $y_0$ is indeed a minimiser, by showing that $J(\tilde{y}) \geq J(y_0)$ for all $\tilde{y} \in D$.
How far I got
Plugging $y_0$ into $J$, we get:
$$J(y_0)=\frac{(B-A)^2}{b-a}$$
So we need to show that $$J(\tilde{y})=\int_a^b (\tilde{y}')^2 \, \mathrm{d}x \geq \frac{(B-A)^2}{b-a}$$ for all $\tilde{y} \in D$.
We are advised to use integration by parts somehow. Applying this on $J(\tilde{y})$ yields:
\begin{align}
  J(\tilde{y})
  & = \int_a^b (\tilde{y}')^2 \, \mathrm{d}x\\
  & = \left . (\tilde{y} \tilde{y}') \right |_a^b - \int_a^b \tilde{y} \tilde{y}'' \, \mathrm{d}x\\
  & = B \tilde{y}'(b) - A \tilde{y}'(a) - \int_a^b \tilde{y} \tilde{y}'' \, \mathrm{d}x\\
\end{align}
This is as far as I got, though. I just don't see how to get anywhere from here. It would be great if someone could provide a hint so that I can finish the proof myself, though a full-fledged answer would be appreciated as well. Thanks in advance!

A: Hint: Write $\bar y=y_0+h$, expand the integrand and apply integration by parts only to the summand that contains derivatives of $y$ and $h$. For the boundary terms, take into account that $h$ satisfies the boundary conditions $h(a)=h(b)=0$.


text:
Q: How to call method inside Rails Method I am struggling to call a method in my User Model. I have a long method similar to this:
def find_content
  def find_x
  # call api
  end
  def find_y
  #call api
  end
  content = {"x": find_x, "y": find_y}
  return content
end

I then try to call it like this in my model:
class User < ApplicationRecord
  def User.news
    # get result of find_content
    content = find_content
    # I also tried doing User.find_content when the function was inside the model
    ## the function then passes the content variable to my UserMailer which sends emails to my users with the content
  end

I have tried placing my find_content in the User Model with def  self.find_content and without the self part.
I was wondering where is the best place to put a function that can be used like this in the model.

A: If I where are you I would create a Service class or a lib class, and I would call it.
Don't define your methods inside methods. Try something like this
class MyFancyService
  def find_content
    {"x": find_x, "y": find_y}
  end

  private
  def find_x
    #code
  end

  def find_y
    #code
  end
end

And inside your model
#remember to require your libs/services class in somewhere (maybe application.rb)
class User < ApplicationRecord
  def news
     MyFancyService.new.find_content
  end
end

Do not abuse of Class method (def self.bla) you should have more instance methods.

A: The reason you are having this issue is that finding content is not really a User concern and should be broken out into a separate class as Horacio mentions, but I don't think the User class needs to know anything about finding content.  It is possible that you need some User info to properly find content however.
I would suggest something like this (assuming you need something from a User object to call your api)
class User
  def user_stuff_needed_by_api
  end
end

class NewsAPI
    def initialize(user_stuff)
        # set stuff needed based on the user
    end
    def find_x
        # call api
        "x"
    end
    def find_y
        # call api
        "y"
    end
    def find_content
        {"x": find_x, "y": find_y}
    end
end

Then in your controller you have the user object, so get what you need from it, create an instance of the api and make your call
user_stuff = @user.user_stuff_needed_by_api
news_api = NewsAPI.new(user_stuff)
content = news_api.find_content

If you really want to make calls to the api inside your a User instance which I don't think you should, I would recommend passing in an instance of the api via a setter and then delegate find_content to that instance.  So something like this.
class User
  def set_news_api(api)
    @news_api = api
  end
  def find_content
     @news_api.find_content
  end
end

Lastly if you really want to put all this in the User class something like this should work, but again is not recommended.
class User
  def self.find_x
    "xx"
    # call api
    end
  def self.find_y
    "yy"
    #call api
  end
  def find_content
    {"x": self.class.find_x, "y": self.class.find_y}
  end
  def self.other_find_content
    {"other_x": find_x, "other_y": find_y}
  end
  def user_stuff_needed_by_api
  end
end

puts User.new.find_content
puts User.other_find_content


text:
Q: Is the AudioContext not working on mobile? (iPhone tested) I read an article introducing HTML5 Web Audio API.
It's very interesting with my desktop Chrome.
However, is this not working for mobile?

A: The article seems to be about three years old. And back then the autoplay policy of browsers wasn't really affecting the usage of the Web Audio API. That has changed. Now it is required to have a user gesture (typically a click event) to start an AudioContext.
The first example of the referenced article would than look like this:
const $playButton = document.getElementById('play-button');

$playButton.addEventListener('click', () => {
    const context = new AudioContext();
    const oscillator = context.createOscillator();

    oscillator.type = 'sine';
    oscillator.connect(context.destination);
    oscillator.start();
};

This does assume that you have a button with the id play-button somewhere in your HTML.
<button id="play-button">play</button>


text:
Q: ggplot2: How to show a datapoint in a circular 360 degree bar plot with an angle of 0 degree? I got a circular 360 degree bar plot in which I manually need to specify the angle of each bar (numeric x-axis).
In general the plotting works fine besides for a datapoint having an angle of 0 resp. 360 degree.
This row is removed and not plotted, not even with a bar width of 1.
Why is that and how can a bar with a center value of 0 and a bar width of e.g. 20 be drawn (from -10 resp. 350 degree to 10 degree)?
Thanks!
MWE:
library(tidyverse)

# dummy data
data <- data.frame(
  variable = c(0, 90, 180, 270),
  value = c(50, 100, 150, 200))

# plot
ggplot(data, aes(x = variable, y = value, fill = factor(variable))) +
  geom_col(width = 20)  + # Even with a widh of 1 the first datapoint is removed from the plot.
  scale_x_continuous(breaks = seq(from=0, to=359, by=10),  limits=c(0, 360)) +
  coord_polar(start = 0)

A: I can't see an easy general solution to plotting bars that straddle the wrap-around point of polar co-ordinates, but it's easy to shift the limits and start point to get the desired effect:
ggplot(data, aes(x = variable, y = value, fill = factor(variable))) +
  geom_col(width = 20)  +
  scale_x_continuous(breaks = seq(0, 359, by = 10), limits = c(-10, 350)) +
  coord_polar(start = -pi/18, clip = "off")

Obviously this would now cause problems if you try to plot bars between 350 and 359 degrees rather than between 0 and 9 degrees, but assuming you don't want any bars overlapping I'm guessing this isn't a problem.


text:
Q: SQL Converting Vertical Column to Horizontal and Counting Values I really need your help and it seems from an SQL standpoint that I can't seem to quite think like an SQL programmer with trying to obtain the following result set.
Consider the following table below (which is a snapshot from my MS Access MDB file:
+-----------------+-----------------+-----------------+-----------------+
|  Date Received  |  Request Type   |      Branch     |     Division    |
+-----------------+-----------------+-----------------+-----------------+
|   2016-05-10    | Status Report   |      Alpha      |       AAA       |
|   2016-05-11    | Business Case   |      Bravo      |       BB        |
|   2016-05-12    | Business Plan   |      Charlie    |       C         |
|   2016-05-13    | Project Charter |      Alpha      |       A         |
|   2016-05-14    | Status Report   |      Alpha      |       AAA       |
|   2016-05-15    | Business Plan   |      Charlie    |       CC        |
|   2016-05-16    | Financial Report|      Alpha      |       AAAA      |
|   2016-05-17    | Financial Report|      Alpha      |       AA        |
|   2016-05-18    | Status Report   |      Bravo      |       BBB       |
|   2016-05-19    | Financial Report|      Alpha      |       AAA       |
|   2016-05-20    | Financial Report|      Bravo      |       B         |
+-----------------+-----------------+-----------------+-----------------+

I need your help to basically capture the metrics (occurrence/count of each request type and then sort it by Division), resulting in the new result set below:
+-----------------+-----------------+-----------------+-----------------+
|    Division     |  Status Report  |  Business Case  |  Business Plan  |
+-----------------+-----------------+-----------------+-----------------+
|   A             |        1        |         0       |        0        |
|   AA            |        1        |         0       |        0        |
|   AAA           |        1        |         0       |        0        |
|   B             |        0        |         1       |        0        |
|   BB            |        0        |         1       |        0        |
|   BBB           |        0        |         1       |        0        |
|   C             |        1        |         0       |        1        |
|   CC            |        1        |         0       |        1        |
|   CCC           |        1        |         0       |        1        |
+-----------------+-----------------+-----------------+-----------------+

A: Edit: count the request types for a branch:
DECLARE @count int;
DECLARE @count0 int;
DECLARE @count1 int;

set @count = (select Count(Request Type) from TABLENAME where Request Type = 'Status Report', Division = 'AAA')

set @count0 = (select Count(Request Type) from TABLENAME where Request Type = 'Business Case', Division = 'AAA')

set @count1 = (select Count(Request Type) from TABLENAME where Request Type = 'Business Plan', Division = 'AAA')

Edit: use this to order
order by COLUMNXXX ASC


text:
Q: Submit the form after submit ( Ruby on Rails ) I am a newbie on Ruby on Rails
I have a regular form in a "new" page.
I hope when the user fulfilled the form and submit this form.
The page can popup a bootstrap modal and display the full content the user just typed in the form.(like a confirm page)
How can I do this?

I found this
http://archive.railsforum.com/viewtopic.php?id=11255
seems it can help me solve my problem
but can I change <div id="preview"> to a bootstrap modal(or other popup)?

A: You can use JavaScript to show the modal based on an onclick or onsubmit event
<%= submit_tag, :onclick => "launchConfirmPage();" %>

where launchConfirmPage() is some JS function that shows the modal filled with info. Then in that modal, have the actual submit button for the form. I'm not entirely sure of the specifics of how a submit_tag works, but you can also try using an anchor tag or button_tag to achieve the same thing if that doesn't work.


text:
Q: Laravel Framework 5.7.27 custom method return blank page I have this issue of getting a blank page in Laravel and I don't know where I go wrong.
Here is my code sample: view maintenance/index.blade.php
<form method="post" action="{{route('maintenance.update_request')}}" enctype="multipart/form-data">
     <input type="hidden" name="_method" value="put">
     {{ csrf_field() }}
     .....

and in  Controller MaintenanceController.php I create custom method update_request
public function update_request(Request $request) {
    dd($request);
}

then web.php (route)
Route::post('maintenance/update_request', 'MaintenanceController@update_request')->name('maintenance.update_request');
Route::resource('maintenance', 'MaintenanceController');

but when i click submit button i get blank page ....public/maintenance/update_request

A: Your route method should be put because you are submitting your form on put request.
Route::put('maintenance/update_request', 'MaintenanceController@update_request')->name('maintenance.update_request');

OR

Route::put('maintenance/update_request', ['as'=>'maintenance.update_request','uses'=>'MaintenanceController@update_request']);


text:
Q: JSoup acts differently on Android than on PC? I have been porting a PC Application I made to Android. I have the code up and running perfectly, but JSoup seems to be getting the wrong data for some reason. I did a direct copy and paste from the working PC Application, which works just fine. Here is a piece of the code I am using in both PC and Android
        String AllGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG";
        String HomeGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG&split=Home";
        String AwayGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG&split=Road";
        String DivisionGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG&split=Division";

        Document AllGames = Jsoup.connect(AllGamesURL).get();
        Document HomeGames = Jsoup.connect(HomeGamesURL).get();
        Document AwayGames = Jsoup.connect(AwayGamesURL).get();
        Document DivisionGames = Jsoup.connect(DivisionGamesURL).get();

        Elements AllGamesTeams = AllGames.select("table.data-table1 tr.tbdy1");
        Elements HomeGamesTeams = HomeGames.select("table.data-table1 tr.tbdy1");
        Elements AwayGamesTeams = AwayGames.select("table.data-table1 tr.tbdy1");
        Elements DivisionGamesTeams = DivisionGames.select("table.data-table1 tr.tbdy1");

        for (Element teamName : AllGamesTeams) {
            if(teamName.select("td[align] > a[href]").text().trim().equals("")) {
                team = teamName.select("td[align]").text().trim();
            } else {
                team = teamName.select("td[align] > a[href]").text().trim();
            }
            if(team.equals(currentSelectedTeam)) {
                //Division = teamName.select("td:eq(2)").text().trim();
                wins = Integer.parseInt(teamName.select("td:eq(3)").text().trim());
                losses = Integer.parseInt(teamName.select("td:eq(4)").text().trim());
                ties = Integer.parseInt(teamName.select("td:eq(5)").text().trim());
                gamesPlayed = wins + losses + ties;
                pointsFor = Integer.parseInt(teamName.select("td:eq(7)").text().trim());
                pointsAgainst = Integer.parseInt(teamName.select("td:eq(8)").text().trim());
                break;
            }
        }

On the PC Version, it gets the wins, losses, etc just fine, but on Android, it is getting the wrong data. Any ideas?

A: Pass in a specific userAgent when you connect to request the desktop version of the site instead of the mobile version, for example:
Document AllGames = Jsoup.connect(AllGamesURL)
    .userAgent("Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36")
    .get();

To confirm, I also tried the same thing but passed in an Android userAgent instead and it retrieved different content (which is what will be happening on Android by default).
You can use the code I provided, or see a list of user agents here: http://www.useragentstring.com/pages/useragentstring.php


text:
Q: Final animation state is discarded at end of animation I'm trying to animate an element at the :leave transition and I'm a bit baffled by its behaviour.
trigger('inOut', [
      transition(':enter', [
        style({'max-height': '0'}),
        animate(250, style({'max-height': '150px'}))
      ], { params: { maxHeight: '150px'}}),

So I would expect my element being animated to have a max-height of 15px set at the final frame of the animation... and left there! I can see the max-height being animated but then at the end its removed and the element scales to whatever height fits its content. Struggling to imagine how this is useful, am I doing something wrong?
Update - Resolved it with this
trigger('inOut', [
      state('void', style({'max-height': '0'})),
      state('*', style({'max-height': '{{maxHeight}}'}), { params: { maxHeight: '0px'}}),
      transition(':enter', animate(300)),
      transition(':leave', animate(250))
    ]),

A: A way to solve this is to use a state for the end of the animation and (@animation.done) to trigger this state.
Here is a StackBlitz example.
app.component.html
<div [@routeAnimations]="state" (@routeAnimations.done)="onDone($event)" class="animate-div">
</div>

app.component.ts
import { trigger, style, state, animate, transition } from '@angular/animations';

@Component({
  animations: [
    trigger('routeAnimations', [
      state('done', style({
        maxHeight: '150px'
      })),
      transition(':enter', [
        style({ 'max-height': '0' }),
        animate(1000, style({ 'max-height': '150px' }))
      ], { params: { maxHeight: '150px' } })
    ])
  ]
})
export class AppComponent {
  state = '';
  onDone(event) {
    this.state = 'done';
  }
}