text:
Q: how to periodically read contents on stdout redirected to file descriptor using dup2 I am struggling to continuously read contents of stdout which is redirected to file. please help  me to resolve issue.
My problem in detail is that i have two thread in first thread , i have to execute a c file which is continously writing output to stdout(i.e writing hello world in infinite loop) and in second thread i have to retrieve line by line output periodically from stdout and store in buffer.
For second thread implementation i created pipe and redirected stdout to the write end of this pipe and tried to continuously read content of this pipe line by line but i didnt get expeced result.
code for second thread is as below:
int redirectPipe[2];
//creation of pipe
pipe(redirectPipe);
//redirection of pipe
dup2(redirectPipe[1],STDOUT_FILENO);
//reading continuously line by line from pipe
// some code here

Can somebody please help me in coding how to continuously read line by line from this pipe?
Below is the code: please suggest me is my approach right? and how to implement entryOpThread() method so that it will read contents of stdout periodically whether should i use read() system call or getLine()or any other method to read line by line from pipe(stdout is redirected to this pipe).
In this example exec thread is executing test.c which is continuouslly printing hello world on stdout,so according to my requirement i have to read this output line by line("Hello world") continuouslly in Opthread from pipe and store it in buffer
//*************************CODE***********************************************************
#include <iostream>
#include<pthread>
#include<unistd.h>
#include<sys/wait.h>
const int MAX_LENGTH=100;
using namespace std;

//! file descriptor to duplicate the system standard input
//!
int inputPIPE[2];

//! file descriptor to duplicate the system standard output
int OutputPipe[2];

//!Thread to retrieve output
//!
pthread_t OpThread;

//!Thread to execute script
//!
pthread_t ExecThread;

//! entry point of the exec thread
void *entryExecThread(void * obj)
{
    //create a child process to launch the script
    int lPid;
    lPid=fork();
    //connect read end of the pipe to the standard input
    if(dup2(inputPIPE[0],STDIN_FILENO)==-1)
    {
        //throw exception
    }

    //connect write end of the pipe to the standard output
    if(dup2(OutputPipe[1],STDOUT_FILENO)==-1)
    {
        //throw exception
    }
    if(lPid==0)
    {

        execvp("./test",NULL);
    }

    else
    {
        int mProcessId=lPid;
        waitpid(mProcessId,NULL,0);
    }
    return NULL;

}

//! entry point of the output thread
void *entryOpThread(void * obj)
{
    //read contents of stdout periodically
   /* char *lMssg=new char[MAX_LENGTH];
    read(OutputPipe[0],lMssg,MAX_LENGTH);

    FILE *fd=fdopen(OutputPipe[0],"r");
    int lBufferLength=MAX_LENGTH;
     while(true)
        {
            getline(&lMssg,(size_t * )&lBufferLength,fd);
            // push message to the output buffer
            if (lMssg !=NULL)
            {
                pthread_mutex_lock( &mOutputBufferMutex);
                mOutputBuffer.push(lMssg);
                pthread_mutex_unlock( &mOutputBufferMutex);
            }
        }
     */

}
int main() {

    //call to pipe system call
    if(pipe(inputPIPE)==-1)
    {
        printf("ERROR IN OPENING FILE \n");
    }
    if(pipe(OutputPipe)==-1)
    {
        printf("ERROR IN OPENING FILE\n ");
    }

    //CREATE OUTPUT THREAD TO RETRIEVE OUTPUT

    if (pthread_create(&OpThread,0,entryOpThread,NULL)!=0)
    {

        //throw exception
        printf("Creation of Output thread  failed for Script with ID\n");
    }

    //Create execution thread to launch script
    pthread_t execThread;
    if (pthread_create(&ExecThread,0,entryExecThread,NULL)!=0)
    {

        //Stop output thread
        pthread_cancel(OpThread);
        //throw exception
        printf("Creation of Execution thread  failed for Script with ID\n");
    }
}
//**********************************************************************************888
test.c

#include <stdio.h>
#include "string.h"
//using namespace std;

int main() {
     int i=0;
     while(i<500)
    {
    printf("!!!Hello World!!! \n" ); // prints !!!Hello World!!!
    //extracting header and data from message
        sleep(5);
      i++;
    }
    return 0;
}
//***********************************************************************************

A: Could it be an buffering issue (http://www.pixelbeat.org/programming/stdio_buffering/)?
When stdout is connected to a terminal, its output will be line-buffered. When this is not the case, output is page-buffered.
To verify, you can try removing sleep() from your writer thread, and check for output on your consumer thread (printing a handful of bytes every 5 seconds will take a while to fill a page). From there you might consider using fflush() or setvbuf().


text:
Q: Why I'm getting Error [ERR_MODULE_NOT_FOUND]: Cannot find module when running the server I'm doing a startup server. Basically It has initial setup with express and nodemon dependencies. Unfortunately, I'm getting ERR_MODULE_NOT_FOUND when running yarn dev or npm run dev
Here is the code and file structure I have.

A: You need to add .js extension
index.js:
import { SampleExport } from "../path/file.js"

In my opinion, it is better to use .env files together with some npm package or even a json file.

A: The issue is a missing file extension. The import needs to look like this:
import { sampleExport } from "../config/env.js";
//                                         ^^^

import doesn't use the same algorithm that require used. Instead, it works according to the ECMAScript Modules specification, which requires a definite extension.
This is also explained in the node.js docs for ECMAScript modules:

A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js') must also be fully specified.
This behavior matches how import behaves in browser environments, assuming a typically configured server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing Enumerate Colors using Beamer Theme Berlin I am trying to figure out how to change the coloring of enumerations in Beamer using the Theme 'Berlin'. I was able to change the color of the Itemize environment by:
    \setbeamercolor{itemize item}{fg=TAMIU}

Also I was able to change the color of the Table of Content enumeration by:
    \setbeamercolor{section number projected}{bg=TAMIU,fg=white}

But non of these two approaches work for the enumeration:
    \setbeamercolor{enumerate item}{fg=TAMIU}
    \setbeamercolor{enumerate number projected}{bg=Tamiu,fg=white}

So how can I do this?

A: There is no enumerate number projected template. Try instead
\setbeamercolor{item projected}{fg=white,bg=TAMIU}

which will also take care of section number projected in one go.

A: You can change the color by using a copy of the definition of the enumerate item template for the square option, as given in the file beamerbaseauxtemplates.sty. A little example:
\documentclass{beamer}
\usetheme{Berlin}

\setbeamertemplate{enumerate item}
{
  \hbox{%
    \usebeamerfont*{item projected}%
    \usebeamercolor[olive!30]{item projected}% original: [bg]
    \vrule width2.25ex height1.85ex depth.4ex%
    \hskip-2.25ex%
    \hbox to2.25ex{%
      \hfil%
      \color{red!60!black}\insertenumlabel% original: [fg]
      \hfil}%
  }%
}

\begin{document}

\begin{frame}
\begin{enumerate}
  \item First.
  \item Second.
\end{enumerate}
\end{frame}

\end{document}


text:
Q: Any good ways to get useful information when the released App has no response to User Interaction? Background:
I release my App on the App Store.
Now, some users reflect the problem: when they install the App and launch it, the App was blocked at the launching page, or some other pages.
What I'm interested is that if there are some ways to detect the running function which blocks the UI thread.
If I have the iPhone which meets the problem, maybe I can use Instruments to attach to the process, and find the time-consuming unit.
But I cannot always have the real iPhone. Can I write some code in advance and when the problem occurs, I can write the Call Stack down to the log on disk?
Many thanks.

A: What you want is some way to monitor you app in (near) realtime to know not just analytics but app crashes and other problems. In this area, there are some really good services which do the job for you.

*

*NewRelic - mobile monitoring

*chartbeat

*testflight

*Crashlytics - as mentioned by @jszumski

I have tried all of them although their feature set is somewhat similar but they differ slightly. I prefer NewRelic mobile monitoring. Hope this helps...

A: If I understood correctly your application is doing some heavy weight stuff on the launch. Is is basically a bad habit. App should always bypass the launch phase before doing any large amount of work. That's why you see many apps have "Loading..." or "Please wait..." or an image with light animations etc at theire launch.
Solution:
Try watching Up and Running: Making a Great Impression with Every Launch (Session 225) from WWDC 2012. This is one of the most useful sessions I've ever seen from WWDC. Try not to mess with watchdog!
Create your own logging mechanism. Write the time frame and a refrence to each line to a txt file. then on each launch if that file exists, on application:didFinishLaunchingWithOptions: or even main grab that file and use one of the reporting solutions mentioned on other solutions and report it. If you actually have the device try using
NSLog(@"%@ happend", eventName)
and watch console for event logs.
Also I use plcrashreporter, it's free and open-source.
Hope this helps


text:
Q: NSURLConnectionDelegate methods not called using AFNetworking code I am using AFNetworking ,the code is working well but none of the delegate nethods of NSURLConnectionDelegate methods are being called after making successful connection.
I have declared in my interface file as delegate of NSURLConnection too.But nothing seems working ,is it something issue with working with background threads and main thread?
Here is my code:
NSLog(@"\n\n1 Is main thread %@", ([NSThread isMainThread] ? @"Yes" : @" NOT"));

AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];

 manager.responseSerializer.acceptableContentTypes= [NSSet setWithObject:@"text/html"];

 NSDictionary *parameters = @{
                             @"email": [Constants sharedInstance].email,

                             @"password": [Constants sharedInstance].password,

                             };

 NSLog(@"\n\nparameters:   %@",parameters);

 [manager POST:@"https://anyurl/" parameters:parameters success:^

 (AFHTTPRequestOperation *operation, id responseObject) {

   //  [operation setRunLoopModes:[NSSet setWithObject:NSDefaultRunLoopMode]];

     NSLog(@"\n\n 2 Is main thread %@", ([NSThread isMainThread] ? @"Yes" : @" NOT"));

     [self stopLoading];

     NSLog(@"\n\nconnection successful!!");

    NSLog(@"\n\nJSON: %@", responseObject);

 }

      failure:^(AFHTTPRequestOperation *operation, NSError *error) {

 NSLog(@"\n\nError: %@", error);

 [self stopLoading];

 NSLog(@"Connection could not be made");

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Network" message:@"Cannot make connection to the server" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];

 [alert show];

      }
   ];

  NSLog(@"\n\n 3 Is main thread %@", ([NSThread isMainThread] ? @"Yes" : @" NOT"));

  [self startLoading];

  NSLog(@"\n\n4 Is main thread %@", ([NSThread isMainThread] ? @"Yes" : @" NOT"));

I saw this link but not able to use that answer.

A: AFNetworking is a separate library if you use AFNetworking its success and failure block will be executed. If you want to execute NSURLConnectionDelegate methods, use NSURLConnection instead of AFNetwork


text:
Q: iframe-resizer, resizing 3 frames in different tabs I am using iFrameResizer version 3.3.3.
I have 3 iframes set into tabs of a jquery tabs object on a page.
each I frame contains its own tabbed view where the length changes considerably depending on which tab is clicked inside the iframe.
The resizing works perfectly on the a single iframe.
However, on the other 2 iframes (which are on the hidden tabs of the parent page) have their height set to zero and once iFrameResize() as run, the size will not dynamically change.
I have tested this further where I do not run iFrameResize automatically on the page.  each iframe loads with its default size.  If I select the second tab then run iFrameResize from the console, the 2nd tab iframe resizes automatically while the iframes on tabs 1 and 3 have their height set to 0.
Ideally I would like each tab to "activate" its iframe when it is selected and allow the iframe to resize automatically as each of the tabs inside the iframe are selected.  This would be regardless of anything currently selected on any of the other tabs on the parent page.
You can see the above mentioned page at http://brellatech.com.au/iframe.php
Is this possible with iFrame Resizer?
Regards
Greg J


text:
Q: Error in Python process: : index 1 is out of bounds for axis 1 with size 1 I have to work on someone else's code, who left the company, and I can't figure out what the last line of this is supposed to do ? Any idea ?
modele1 = RandomForestClassifier(n_estimators=96,
                              criterion= 'entropy',
                              random_state=2,
                              n_jobs=-1,
                              min_samples_leaf=100,
                              max_depth=20)
modele_churn_1=modele1.fit(X_train, Y_churn_1_train)
Y_score_proba_churn_1 = modele_churn_1.predict_proba(X_test)[:,1] # this line throws the following error :

Error in Python process: : index 1 is
  out of bounds for axis 1 with size 1


text:
Q: Passing variable arguments : python I want to write a code that takes file and class names, and operates over it. An example will explain it much more clearly than I possibly can:
I have a file test.py that goes as:
import pandas as pd
from preProcess import preProcess
from visualise import visualise

df=pd.read_csv('input.csv')

li1=["preProcess","visualise"]
li2=["minMax","pca"]

for i in range(len(li1)):
    x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i])
    a=x(df)
    # does some more stuff...

li1 contains name of the modules and li2 contains the name of the classes in the corresponding modules.
To make it a bit clearer, preProcess.py goes as:
class minMax():
    def __init__(df):
    # does something

and visualise.py goes as:
class pca():
    def __init__(df):
    # does something

The line x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i]) gives me the classes minMax and pca.
Now the thing is that this code works perfectly fine if __init__ takes only one argument. But, what if it requires more than 1 arguments? For eg., pca could have been:
class pca():
    def __init__(df,metaData):
    # does something

What should I do in such a case? Any help would be appreciated.
If the question is not clear, please drop a comment. I would provide a more detailed explanation then. Thanks...

A: perhaps you should utilize the spread operator. maybe this snippet helps:
class X:
  def __init__(self, a, b):
    self.a = a
    self.b = b

args = [2, 'hellow']
x = X(*args)

EDIT: this is just an outline of the general approach. for a more comprehensive overview of how this approach is applicable to this specific problem, please check the discussion on this answer.


text:
Q: How to instantiate subclass from within a superclass What's wrong with the following code and how do I fix it? My objective is to work with a superclass in my main method. This superclass object is supposed to itself create (in its internal state) instances of its subclass.
The purpose of this is because the subclass only needs the state of the superclass to work with, and because all operations the subclass needs to do are only important as far as the superclass is concerned.
public class Test {
    public static void main(String[] args) {
        Test2 testSuperclass = new Test2("success #1");
    }
}

class Test2 {
    public Test2(String printComment) {
        System.out.println(printComment);
        Test3 testSubclass = new Test3("success #2");
    }
}

class Test3 extends Test2 {
    public Test3(String printComment2) {
        System.out.println(printComment2);
    }
}

The Test3 constructor is generating the error Implicit super constructor Test2() is undefined. Must explicitly invoke another constructor.

A: The first thing a constructor has to do is call a constructor for the superclass.
Often, you don't see that, because the Java compiler automatically inserts a call to the non-arguments constructor (super()) if you don't specify another one. But in your case, there is no non-argument constructor in Test2 (because you created another one that needs a String).
public Test3(String printComment2) {
    super(printComment2);
    System.out.println(printComment2);
}

A: Adding to Thilo's answer, when you don't explicitly define a super(a call to the parent's constructor) an implicit call is made as simply "super()". So you are essentially allowing a call to Test2's constructor but without passing a string resulting in an undefined error.

A: You can either do one of the following :

*

*If you just want to make your code work without any additional printing or creating objects, create a no-arg constructor :
class Test2 {
    public Test2(){
    }
    public Test2(String printComment) {
        System.out.println(printComment);
        Test3 testSubclass = new Test3("success #2");
    }
}

class Test3 extends Test2 {
    public Test3(String printComment2) {
        System.out.println(printComment2);
    }
}

*Or the other way was as Thio mentioned :
public Test3(String printComment2) {
  super(printComment2);
  System.out.println(printComment2);
}


text:
Q: Querying a list to a manytomany field in django returning more results than expected I wrote the following filter based off the answer provided here: Django filter queryset __in for *every* item in list
Distinct_Alert.objects.filter(entities__in=relevant_entities, alert_type=alert_type).annotate(num_entities=Count('entities')).filter(
        num_entities=len(relevant_entities))

The issue that I'm running into is that it seems to be filtering inappropriately, there are times where it's matching sublists, I was using get to get the distinct alert, but I noticed that some of them error out because they return multiple matches, and here's the culprit.
[2016-07-27 18:02:23,473: WARNING/Worker-4] [<Entity: DOGE>, <Entity: 8.8.8.8>]
[2016-07-27 18:02:23,474: WARNING/Worker-4] [<Entity: potato>, <Entity: DOGE>, <Entity: 8.8.8.8>]
[2016-07-27 18:02:23,475: WARNING/Worker-4] [<Entity: desktop_potato>, <Entity: DOGE>, <Entity: 8.8.8.8>]

My entities list should contain only
[<Entity: DOGE>, <Entity: 8.8.8.8>]

but it's somehow matching on the other two. Any help would be appreciated
The temporary hack that I came up with is this:
for alert in distinct_alert_query.all():
            if alert.entities.all().count() == len(relevant_entities) and all([entity in relevant_entities for entity in alert.entities.all()]):
                distinct_alert = alert
                break

where distinct_alert_query refers to the really long query mentioned above. The issue with this is that if the query's matching on Distinct_Alerts with a set of entities larger than relevant_entities it will break :(
models:
class Distinct_Alert(models.Model):
    #alert_type = models.ForeignKey(Alert_Type, on_delete=models.CASCADE) for the sake of this problem and the filter, this isn't really needed.
    entities = models.ManyToManyField(to='Entity', through='Entity_To_Alert_Map')

class Entity(models.Model):
    label = models.CharField(max_length=700, blank=False)
    #entity_type = models.ForeignKey(Entity_Type_Label) not necessary for this problem
    related_entities = models.ManyToManyField('self')

class Entity_To_Alert_Map(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)
    distinct_alert = models.ForeignKey(Distinct_Alert, on_delete=models.CASCADE)
    entity_alert_relationship_label = models.ForeignKey(Entity_Alert_Relationship_Label, on_delete=models.CASCADE)

    class Meta:
        unique_together = ('entity', 'distinct_alert', 'entity_alert_relationship_label')

A: Try this:
from django.db.models import IntegerField, Case, When, F

Distinct_Alert.objects.filter(
    alert_type=alert_type
).annotate(
    num_entities=Count('entities'),
    num_relevant_entities=Count(
        Case(When(entities__in=relevant_entities, then=1),
             default=None,
             output_field=IntegerField()),
    ),
).filter(
    num_entities=F('num_relevant_entities'),
    num_relevant_entities=len(relevant_entities),
)

Your query:
Distinct_Alert.objects.filter(
    entities__in=relevant_entities,
    alert_type=alert_type
).annotate(
    num_entities=Count('entities')
).filter(
    num_entities=len(relevant_entities)
)

Order of annotate() and filter() matters.


text:
Q: Magento 2.4: Change price filter text and range programmatically I want to change the price filter text and range on the layered navigation from:

To:
Something like this:
Under  $30.00
$30.00 - $60.00
$60.00 - $90.00
$90.00 - $120.00
$120.00 and Above
How can it be done programmatically?


text:
Q: NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong? I have an application that I'm trying to wrap into a jar for easier deployment.  The application compiles and runs fine (in a Windows cmd window) when run as a set of classes reachable from the CLASSPATH.  But when I jar up my classes and try to run it with java 1.6 in the same cmd window, I start getting exceptions:
C:\dev\myapp\src\common\datagen>C:/apps/jdk1.6.0_07/bin/java.exe -classpath C:\myapp\libs\commons -logging-1.1.jar -server -jar DataGen.jar
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at com.example.myapp.fomc.common.datagen.DataGenerationTest.<clinit>(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    ... 1 more

The funny thing is, the offending LogFactory seems to be in commons-logging-1.1.jar, which is in the class path specified.  The jar file (yep, it's really there):
C:\dev\myapp\src\common\datagen>dir C:\myapp\libs\commons-logging-1.1.jar
 Volume in drive C is Local Disk
 Volume Serial Number is ECCD-A6A7

 Directory of C:\myapp\libs

12/11/2007  11:46 AM            52,915 commons-logging-1.1.jar
           1 File(s)         52,915 bytes
           0 Dir(s)  10,956,947,456 bytes free

The contents of the commons-logging-1.1.jar file:
C:\dev\myapp\src\common\datagen>jar -tf C:\myapp\libs\commons-logging-1.1.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/apache/
org/apache/commons/
org/apache/commons/logging/
org/apache/commons/logging/impl/
META-INF/LICENSE.txt
META-INF/NOTICE.txt
org/apache/commons/logging/Log.class
org/apache/commons/logging/LogConfigurationException.class
org/apache/commons/logging/LogFactory$1.class
org/apache/commons/logging/LogFactory$2.class
org/apache/commons/logging/LogFactory$3.class
org/apache/commons/logging/LogFactory$4.class
org/apache/commons/logging/LogFactory$5.class
org/apache/commons/logging/LogFactory.class
... (more classes in commons-logging-1.1 ...)

Yep, commons-logging has the LogFactory class.  And finally, the contents of my jar's manifest:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 10.0-b23 (Sun Microsystems Inc.)
Main-Class: com.example.myapp.fomc.common.datagen.DataGenerationTest
Class-Path: commons-logging-1.1.jar commons-lang.jar antlr.jar toplink
 .jar GroboTestingJUnit-1.2.1-core.jar junit.jar

This has stumped me, and any coworkers I've bugged for more than a day now.  Just to cull the answers, for now at least, third party solutions to this are probably out due to licensing restrictions and company policies (e.g.: tools for creating exe's or packaging up jars).  The ultimate goal is to create a jar that can be copied from my development Windows box to a Linux server (with any dependent jars) and used to populate a database (so classpaths may wind up being different between development and deployment environments).  Any clues to this mystery would be greatly appreciated!

A: The -jar option is mutually exclusive of -classpath. See an old description here

-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A quick and dirty hack is to append your classpath to the bootstrap classpath:

-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.

However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.

A: You can omit the -jar option and start the jar file like this:
java -cp MyJar.jar;C:\externalJars\* mainpackage.MyMainClass

A: if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.
I'd prefer to use OneJar for this issue.

A: i had the same problem with my jar
the solution

*

*Create the MANIFEST.MF file:

Manifest-Version: 1.0
Sealed: true
Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar
Main-Class: com.MainClass

*Right click on project, Select Export.

select export all outpout folders for checked project

*select using existing manifest from workspace and select the MANIFEST.MF file

This worked for me :)

A: This is the problem that is occurring,
if the JAR file was loaded from "C:\java\apps\appli.jar", and your manifest file has the  Class-Path: reference "lib/other.jar", the class loader will look in "C:\java\apps\lib\" for "other.jar".  It won't look at the JAR file entry "lib/other.jar".
Solution:-

*

*Right click on project, Select Export.

*Select Java Folder and in it select Runnable JAR File instead of JAR file.

*Select the proper options and in the Library Handling section select the 3rd option i.e. (Copy  required libraries into a sub-folder next to the generated JAR).

[ EDIT = 3rd option generates a folder in addition to the jar, 2nd option ("Package required libraries into generated JAR") can also be used as you have the jar. ]

*Click finish and your JAR is created at the specified position along with a folder that contains the JARS mentioned in the manifest file.

*open the terminal,give the proper path to your jar and run it using this command  java -jar abc.jar
Now what will happen is the class loader will look in the correct folder for the referenced JARS  since now they are present in the same folder that contains your app JAR..There is no "java.lang.NoClassDefFoundError" exception thrown now.
This worked for me... Hope it works for you too!!!

A: I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. "required_lib/sun/pop3.jar required_lib/sun/smtp.jar ". Even if it is the last in the list.


text:
Q: What's wrong with my MySQL query? (using BETWEEN) I'm trying to select businesses from my database who fall within a 10mi radius of the user. Testing shows that the problem lies in my query (though no MySQL error is thrown). The variables $lat and $lng are imported from Javascript and they, too, are fine. I suspect the issue is something to do with my use of BETWEEN, as this is the first time I've used it. Any ideas?
$r = 20; // in miles
$lat_min = $lat - ($r / 69);
$lat_max = $lat + ($r / 69);
$lng_min = $lng - $r / abs(cos(deg2rad($lat)) * 69);
$lng_max = $lng + $r / abs(cos(deg2rad($lat)) * 69);

$query = "SELECT name FROM businesses WHERE $lat BETWEEN $lat_min AND $lat_max $lng BETWEEN $lng_min AND $lng_max ORDER BY Rand() LIMIT 6";

A: The query should be:
  SELECT name FROM businesses
  WHERE THE_ACTUAL_NAME_OF_THE_COLUMN BETWEEN $lat_min AND $lat_max
  AND THE_NAME_OF_THE_NEXT_COLUMN BETWEEN $lng_min AND $lng_max
  ORDER BY Rand() LIMIT 6

Somehow $lat does not look like a column name in the table. Also you were missing an AND.

A: Looks like you have you're missing and AND e.g.
SELECT
   name
FROM
   businesses
WHERE
  $lat BETWEEN $lat_min AND $lat_max
  AND $lng BETWEEN $lng_min AND $lng_max
ORDER BY Rand() LIMIT 6

A: $query = "SELECT name FROM businesses WHERE $lat BETWEEN $lat_min AND $lat_max AND $lng BETWEEN $lng_min AND $lng_max ORDER BY Rand() LIMIT 6";

A: Like, the other answers, and to be sure, place ( ).
$query = 'SELECT name
FROM businesses
WHERE
('.$lat.' BETWEEN "'.$lat_min.'" AND "'.$lat_max.'")
AND ('.$lng.' BETWEEN "'.$lng_min.'" AND "'.$lng_max.'")
ORDER BY Rand() LIMIT 6";

A: Assuming $lat and $lng resolve to actual column names, I think you're just missing an "AND". Sometimes, just formatting the SQL statement can reveal the issue.
SELECT name
  FROM businesses
  WHERE $lat BETWEEN $lat_min AND $lat_max
    **AND** $lng BETWEEN $lng_min AND $lng_max
ORDER BY Rand() LIMIT 6;

A: I think you need an AND in the WHERE clause...
WHERE ($lat BETWEEN $lat_min AND $lat_max) AND ($lng BETWEEN $lng_min AND $lng_max)


text:
Q: Почему не добавляется class к элементу? Есть данный код:

Blog

About

Log in

и стили для него(sass, компилирую в css), которые по идее должны добавляться через js:
.menu-for-mobile-opened
  position: absolute
  display: block
  width: 100%
  background-color: rgba(185, 174, 128, 1)
  text-align: center
  li
      display: block

сам js:
var cubeList = document.getElementById("cube-list");

var cube = document.getElementById("cube");
cube.addEventListener("click", function(){
  //alert(this.style.display)
  cube.style.display = (cube.style.display == 'none') ? 'block' : 'none';
  //if (this.style.display == 'none')
      //cubeList.classList.remove('menu-for-mobile-opened');
  //else
      cubeList.classList.add("menu-for-mobile-opened");
});

в итоге класс добавляется, но элемент(список ul) никак не меняется. в чем проблема?

A: Если cube это например кнопка для изменения стилей, то все работает

var cubeList = document.getElementById("cube-list");

var cube = document.getElementById("cube");
cube.addEventListener("click", function(){
  cube.style.display = (cube.style.display == 'none') ? 'block' : 'none';
  cubeList.classList.add("menu-for-mobile-opened");
});
.menu-for-mobile-opened {
  position: absolute;
  display: block;
  width: 100%;
  background-color: rgba(185, 174, 128, 1);
  text-align: center;
  }
 .menu-for-mobile-opened li {
      display: block
      }
 <button id="cube">cube</button>

Blog

About

Log in

A: В общем, проблема в том, что если при создании страницы класс не использовался, то при компиляции sass он не будет добавлен в css файл.


text:
Q: Wireless disabled: HardBlock I'm experiencing the Wireless HardBlock problem. I posted this question when I was using Ubuntu 11.10 on askubuntu and no hope!
Here are some solved problems which I tried, but they didn't work for me: (1,2,3)
I'm using now Fedora 17 alongside Xubuntu where I have no problem with my wireless card. Can anyone give me hope to solve it?

A: Slide the little switch on the side of the laptop to "ON"...
or, if you don't have an off/on switch for your wireless, look for a Fn key, and a little picture on the number keys of the keyboard.  One of those likely has a little wireless tower....
Hold down Fn, then press the key with the wireless tower picture on it.
Check your wireless.  If it's still not working, try this again, maybe you toggled it twice or something.


text:
Q: Get CSS element value by JS and Jquery I insert css in 3 ways

*

*Inline style (p1)

*Internal style sheet (p2)

*External style sheet (p3)
I want to get value of css in each by Javascript && Jquery . Please show me how .
I cant get the value of p2 , p3 in same way as p1 . What's wrong ?
Many thanks !

window.onload = abc();

function abc(){
 var p1 = document.getElementById('p1').style.height;
 document.getElementById('p1').innerHTML = p1;
 var p2 = document.getElementById('p2').style.width;
 document.getElementById('p2').innerHTML = p2;
 var p3 = document.getElementById('p3').style.height;
 document.getElementById('p3').innerHTML = p3;
}
#p3{
 width: 200px;
 height: 200px ;
 background-color: aqua ;
}
<!DOCTYPE html>

<title>CSS Element output</title>

CSS output element property

check p1

check p2

check p3

**
strong text
**

A: When you use dot notation, you are asking for an attribute.  Only the first element has a style attribute, so this is why only your first attempt works.

A: You can get value of style attributes using window.getComputedStyle(); and getPropertyValue();
Please see the sample code below for getting value of height for your element p2:
var element = document.getElementById('p2'),
    style = window.getComputedStyle(element),
    res = style.getPropertyValue('height');

alert(res);


text:
Q: Angularjs:ng-click in directive is not working I am trying to implement a simple pagination with directives in angularjs
Controller
//load the result server
$scope.getData  = function(page) {
        $http.post('/search?page='+page,searchParams).then(function (response) {

            if(response.data.status){
                $scope.arts        = response.data.result;
                $scope.currentPage = response.data.currentPage;
                $scope.pageCount   = response.data.pageCount;
            }else{
                $scope.arts = [];
            }
        },function (err) {
            $scope.arts = [];
            console.log(err);
        });
    }

When the HTTP call is finished i am using a directive is to print the pagination links.
HTML

  <pagination pagecount="pageCount" currentpage="currentPage"></pagination>

Directive
This directive just build pagination links and returns to
app.directive('pagination',function () {
    //custom directive for build pagination
    return {
        restrict: 'E',
        scope: {
            pagecount: '=',
            currentpage: '='
        },
        link:function (scope,elem,attr) {
            var element = angular.element(document.getElementsByClassName('paginate'));
            var str ='';
            var i = 1;
            if (scope.currentpage > 5) {
                i = +scope.currentpage - 4;
            }

            for (i; i<=scope.pagecount; i++) {

                if (scope.currentpage == i) {
                    str+='
'+i+'
'
                }else{
                    str+='
'+i+'
'
                }
                if (i == (+scope.currentpage + 4)) {
                    break;
                }
            }
            element.prepend(str);

        }
    };
})

But the problem is ng-click="getData()" in the anchor is not worked why its not getting worked.
the difference is getData() is defined in controller

A: I think href="" might be redirecting or refreshing your page, which is why ng-click is not getting triggered.
Try it as below.
href="#"

or
href="javascript:void(0)"

A: You need to pass that function to directive for access that function from directive.
Html

  <pagination pagecount="pageCount" get-data="getData()" currentpage="currentPage"></pagination>

Directive
This directive just build pagination links and returns to
app.directive('pagination',function () {
//custom directive for build pagination
return {
    restrict: 'E',
    scope: {
        pagecount: '=',
        currentpage: '=',
        getData: '&'    /**This is how you can access function of controller**/
    },
    link:function (scope,elem,attr) {
        var element = angular.element(document.getElementsByClassName('paginate'));
        var str ='';
        var i = 1;
        if (scope.currentpage > 5) {
            i = +scope.currentpage - 4;
        }

        for (i; i<=scope.pagecount; i++) {

            if (scope.currentpage == i) {
                str+='
'+i+'
'
            }else{
                str+='
'+i+'
'
            }
            if (i == (+scope.currentpage + 4)) {
                break;
            }
        }
        element.prepend(str);

    }
};
})


text:
Q: How to apply top offset for status bar in iOS7 for UITabBarController children only My app is a UITabBarController based app with 3 children vc.  The status bar is overlapping with my viewcontrollers.  I have tried everything I have found in SO:

*

*I tried adding this to my AppDelegate:
//Offset downwards to make room for status bar
self.window.bounds = CGRectMake(0, -20, self.window.frame.size.width, self.window.frame.size.height);
It worked because it moved the entire UITabBarController down by 20.  But this resulted in the tabs being cut off at the bottom by -20.
So Im thinking i just want to apply the effect to the UIViewControllers in each tab since there is not much to cut off at the bottom.

*So I tried adding similar code to the viewDidLoad and calling setNeedsDisplay afterwards:
self.view.bounds = CGRectMake(0, -20, self.view.frame.size.width, self.view.frame.size.height);
But this has no effect at all, still get overlapping.

*I tried adding this to viewDidLoad
self.edgesForExtendedLayout = UIRectEdgeNone;
and I also unchecked the Extend Edges Under Top Bars but it still runs into the status bar.  Also tried:
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
 {
    self.edgesForExtendedLayout = UIRectEdgeNone;
 }

but no cigar.

*I dont have the deltas because im using AL.

*I dont want to HIDE my status bar because it displays open/close times so the user would find it handy to be able to see the time.
Im thinking shifting the view down a bit in each viewcontroller that needs it is the best option, but why didnt my code work for #2?

(btw:not sure why code format isnt working and the numbering is off, even when i try to edit it, it seems to be working fine in the edit view but not in the pre-view or live-view)

A: for iOS 7 and xcode 5 to avoid overlapping
use in
viewDidLoad method
self.edgesForExtendedLayout = UIRectEdgeNone;
self.automaticallyAdjustsScrollViewInsets = NO;

A: Well, I have the same problem as you.
I fixed it with many moves.
I use ruby motion:
@window.bounds = CGRectMake(0, -20, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height - 20)
@window.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)
....
tabBarController.view.bounds = CGRectMake(0, 20, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height - 20)

Let me know how it's going at your end.
update:
attach the screenshot:


text:
Q: Finite expectation - Difference between these two statements? Main Question: Let $\{X_n, n=0,1,2...\}$ be a stochastic process. How are following two statements different?
\begin{align}
E[|X_n|]<\infty \text{ for all } n
\end{align}
and
\begin{align}
\text{ for some } M<\infty, E[|X_n|]\leq M\text{ for all } n
\end{align}
A bit more background and my idea: If $X_n$ is a Martingale, we know the first statement holds. However, Martingale Convergence Theorem requires second statement in addition to $X_n$ being a Martingale. Therefore, it seems like two statements are not equivalent but I cannot see the difference.
In the first statement, we do not force an finite upper bound that holds for every $n$. Then, for every $n$ there is an $M_n<\infty$ such that $E[|X_n|]\leq M_n$ and for every $M_n$, there is a $m\neq n$ such that $E[|X_m|]> M_n$. So, for every $n$, there is a finite bound but there is not a single finite value that is true for all $n$. I am not sure if my interpretation is correct. Like I said, I cannot see the difference between two statements and that's the explanation I came up with but I am not convinced.
If someone can help me to understand this, I would be grateful. Thanks.

A: The distinction exists even without any randomness.  Let $x_n = n$.  Then
$|x_n| < \infty$ for all $n$, but there is no $M < \infty$ such that
$|x_n| \le M$ for all $n$.


text:
Q: Uploadify: start uploading manually I need to have an ability to start uploading each file in the queue manually, but it doesn't work for me.
That's what I'm trying to do:
$('#fileinput').uploadify({
    uploader: 'uploader.php',
    swf: 'uploadify.swf',
    auto: false,
    onSelect: function (file) {
        $('form').append('
Start uploading '+file.name+' ('+file.id+')');
    }
});
function startUpload(fileId) {
    $('#fileinput').uploadify('upload', fileId);
}

One file is being uploaded well, but while it's being uploaded, other links don't work.
And only after the first file is uploaded, I can start uploading next file.
Debug message is: StartUpload(): Upload already in progress. Not starting another upload.
Is there any way to be able to start uploading while another file is being uploaded?


text:
Q: Map a key to run formatter in Vim I have this in my .vimrc
set formatprg=astyle

I can press gggqG to format the whole file just fine,.
Now I'd like to map a hotkey to do this, eg <F10>, but gggqG is not a command I type in Vim command line, so I don't know how to map this to a key. Thanks for the help.

A: You can use map:
map <F10> gggqG


text:
Q: How to set Ripple effect on a LinearLayout programmatically? I want to set the background android.R.attr.selectableItemBackground to a LinearLayout. When using XML there are no problems (it works)
<LinearLayout
    android:id="@+id/llMiner"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true" >

... but I have to do this in java code, so I've tried this
llMiner.setClickable(true);
llMiner.setBackgroundResource(android.R.attr.selectableItemBackground);

... and it doesn't work, infact I get a NotFoundException on this second line.
So after I've tried this variant thinking that the resource is a Color.
llMiner.setClickable(true);
llMiner.setBackgroundColor(android.R.attr.selectableItemBackground);

This one doesn't launch exception, but... doesn't work (there are no changing of background when pressing, but the state change in pressed as it have to do)... any suggestion?

A: You can use this way.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // If we're running on Honeycomb or newer, then we can use the Theme's
    // selectableItemBackground to ensure that the View has a pressed state
    TypedValue outValue = new TypedValue();
    this.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
    textView.setBackgroundResource(outValue.resourceId);
}

A: Use this helpful extenstion
fun Context.makeCircleRippleDrawable(
    @ColorInt rippleColor: Int = ContextCompat.getColor(this, R.color.black_alpha_25),
    @ColorInt backgroundColor: Int = ContextCompat.getColor(this, android.R.color.transparent),
    @ColorInt disabledColor: Int = backgroundColor,
    elevation: Float = 0F
): Drawable {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        val content: GradientDrawable?
        val mask: GradientDrawable?

        if (backgroundColor == Color.TRANSPARENT) {
            content = null
            mask = GradientDrawable()
            mask.setColor(rippleColor)
            mask.shape = GradientDrawable.OVAL
        } else {
            content = GradientDrawable().also {
                it.shape = GradientDrawable.OVAL
                it.color = ColorStateList(
                    arrayOf(
                        intArrayOf(android.R.attr.state_activated),
                        intArrayOf(android.R.attr.state_enabled),
                        intArrayOf(-android.R.attr.state_enabled)
                    ),
                    intArrayOf(
                        backgroundColor,
                        backgroundColor,
                        disabledColor
                    )
                )
            }
            mask = null
        }

        RippleDrawable(
            ColorStateList(
                arrayOf(
                    intArrayOf(android.R.attr.state_pressed),
                    intArrayOf(android.R.attr.state_focused),
                    intArrayOf(android.R.attr.state_activated)
                ),
                intArrayOf(
                    rippleColor,
                    rippleColor,
                    rippleColor
                )
            ),
            content,
            mask
        )
    } else {

        val shapePressed = GradientDrawable()
        shapePressed.shape = GradientDrawable.OVAL
        shapePressed.setColor(rippleColor)

        val shapeDefault = GradientDrawable().also {
            it.shape = GradientDrawable.OVAL
            it.color = ColorStateList(
                arrayOf(
                    intArrayOf(android.R.attr.state_activated),
                    intArrayOf(android.R.attr.state_enabled),
                    intArrayOf(-android.R.attr.state_enabled)
                ),
                intArrayOf(
                    backgroundColor,
                    backgroundColor,
                    disabledColor
                )
            )
        }

        val stateListDrawable = StateListDrawable()
        stateListDrawable.addState(
            intArrayOf(
                android.R.attr.state_pressed,
                android.R.attr.state_enabled
            ), shapePressed
        )
        stateListDrawable.addState(intArrayOf(), shapeDefault)
        stateListDrawable
    }
}


text:
Q: XSLT: How to change an attribute value during ? I have an XML document, and I want to change the values for one of the attributes.
First I copied everything from input to output using:
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

And now I want to change the value of the attribute "type" in any element named "property".

A: This problem has a classical solution: Using and overriding the identity template is one of the most fundamental and powerful XSLT design patterns:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:param name="pNewType" select="'myNewType'"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="property/@type">
        <xsl:attribute name="type">
            <xsl:value-of select="$pNewType"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

When applied on this XML document:
<t>
  <property>value1</property>
  <property type="old">value2</property>
</t>

the wanted result is produced:
<t>
  <property>value1</property>
  <property type="myNewType">value2</property>
</t>

A: You need a template that will match your target attribute, and nothing else.
<xsl:template match='XPath/@myAttr'>
  <xsl:attribute name='myAttr'>This is the value</xsl:attribute>
</xsl:template>

This is in addition to the "copy all" you already have (and is actually always present by default in XSLT). Having a more specific match it will be used in preference.

A: Tested on a simple example, works fine:
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="@type[parent::property]">
  <xsl:attribute name="type">
    <xsl:value-of select="'your value here'"/>
  </xsl:attribute>
</xsl:template>

Edited to include Tomalak's suggestion.

A: I had a similar case where I wanted to delete one attribute from a simple node, and couldn't figure out what axis would let me read the attribute name.  In the end, all I had to do was use
@*[name(.)!='AttributeNameToDelete']

A: I also came across same issue and i solved it as follows:
<!-- identity transform -->
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<!-- copy property element while only changing its type attribute -->
<xsl:template match="property">
  <xsl:copy>
    <xsl:attribute name="type">
      <xsl:value-of select="'your value here'"/>
    </xsl:attribute>
    <xsl:apply-templates select="@*[not(local-name()='type')]|node()"/>
  </xsl:copy>
</xsl:template>

A: The top two answers will not work if there is a xmlns definition in the root element:
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <property type="old"/>
</html>

All of the solutions will not work for the above xml.
The possible solution is like:
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:template match="node()[local-name()='property']/@*[local-name()='type']">
      <xsl:attribute name="{name()}" namespace="{namespace-uri()}">
                some new value here
          </xsl:attribute>
  </xsl:template>

  <xsl:template match="@*|node()|comment()|processing-instruction()|text()">
      <xsl:copy>
          <xsl:apply-templates select="@*|node()|comment()|processing-instruction()|text()"/>
      </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

A: For the following XML:
<?xml version="1.0" encoding="utf-8"?>
<root>
    <property type="foo"/>
    <node id="1"/>
    <property type="bar">
        <sub-property/>
    </property>
</root>

I was able to get it to work with the following XSLT:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="//property">
        <xsl:copy>
            <xsl:attribute name="type">
                <xsl:value-of select="@type"/>
                <xsl:text>-added</xsl:text>
            </xsl:attribute>
            <xsl:copy-of select="child::*"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

A: If your source XML document has its own namespace, you need to declare the namespace in your stylesheet, assign it a prefix, and use that prefix when referring to the elements of the source XML - for example:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xhtml="http://www.w3.org/1999/xhtml">

<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes" />

<!-- identity transform -->
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<!-- exception-->
<xsl:template match="xhtml:property/@type">
    <xsl:attribute name="type">
        <xsl:text>some new value</xsl:text>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

Or, if you prefer:
...
<!-- exception-->
<xsl:template match="@type[parent::xhtml:property]">
  <xsl:attribute name="type">
        <xsl:text>some new value</xsl:text>
  </xsl:attribute>
</xsl:template>
...

ADDENDUM:
In the highly unlikely case where the XML namespace is not known beforehand, you could do:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes" />

<!-- identity transform -->
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<!-- exception -->
<xsl:template match="*[local-name()='property']/@type">
    <xsl:attribute name="type">
        <xsl:text>some new value</xsl:text>
    </xsl:attribute>
</xsl:template>

Of course, it's very difficult to imagine a scenario where you would know in advance that the source XML document contains an element named "property", with an attribute named "type" that needs replacing - but still not know the namespace of the document. I have added this mainly to show how your own solution could be streamlined.


text:
Q: AS3 - Friction(?) causing Movie Clip to jump, temporarily alter path (playable SWF included) Im making a game in FlashBuilder where the player controls a movieclip (_character) around the stage with the arrows or WASD. On the stage there are squares/boxes with collision detection and a 50 pixel border around.
While testing Ive noticed that if I hold a direction key, then switch to another AND the MovieClip is travelling past a gap in the boxes, the movieclip will jump a few pixels in the previous pressed direction, then back down again quickly.
It's a split second flicker but creates a distracting jumpy, stutter effect. This happens with multiple key presses, but not if I press a button, release it, then press the other direction button.
The yellow crosses on the image below show some of the areas where this happens.

The larger the Friction number in my code, the more noticeable it is. But if I lower the friction too much (0.8ish) The Movie Clip moves too slowly around the stage and the game is unplayable.
I currently have the friction at 0.88 which lessens the jump, but it is still noticeable. Does anyone know why this is happening and/or how I could stop it? (while keeping the fluid movement of the movieclip of course.)
This SWF shows friction at 0.94 so the effect is very noticeable, especially in the top right corner. (Move character around stage with arrows or WASD.)
0.94 Friction SWF
This SWF has friction at 0.88, less noticeable, but it still happens!
0.88 Friction SWF
This problem doesn't happen if I'm going UP to DOWN or LEFT to RIGHT, traveling past gaps. It only happens when two diagonal linked direction buttons are pressed, traveling past a gap.
If I travel UP then LEFT the MovieClip will jump upwards. If I travel DOWN, then LEFT and go across a gap the movieclip will jump a few pixels downwards, like the character is squatting(?)

Current Code
Rookies game/Application class is used as a level switcher to put levelOne onto the stage.
package
{
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.events.Event;
    [SWF(width="650", height="450", backgroundColor="#FFFFFF", frameRate="60")]

    public class RookiesGame extends Sprite
    {
        private var _levelOne:LevelOne;
        //public static var gameMute:Boolean = false;

        public function RookiesGame()
        {
            _levelOne = new LevelOne(stage);

            stage.addChild(_levelOne);
            stage.addEventListener("levelOneComplete",levelTwoSwitchHandler);
        }
        private function levelTwoSwitchHandler(event:Event):void
        {
        }
    }
}

Level One contains most of the code, and majority of the work.
package
{
    //import statements

    public class LevelOne extends Sprite
    {
        //Declare the variables to hold the game objects
        private var _character:Character = new Character();
        private var _background:Background = new Background();

        private var _box1:Box = new Box();
        //Other box vars

        //A variable to store the reference to the stage from the application class
        private var _stage:Object;
        //Control System
        private var _bUp:Boolean = false;
        private var _bDown:Boolean = false;
        private var _bLeft:Boolean = false;
        private var _bRight:Boolean = false;

        public function LevelOne(stage:Object)
        {
            _stage = stage;
            this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
        }
        private function addedToStageHandler(event:Event):void
        {
            startGame();
            this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
        }
        private function startGame():void
        {
            addGameObjectToLevel(_background, 0, 0);
            addGameObjectToLevel(_box1, 300, 200);
            //Other boxes added to Level

            //Add character
            this.addChild(_character);
            _character.x = 300;
            _character.y = 50;
            _character.gotoAndStop(1);

            playGame();
        }
        private function playGame():void
        {   //EVENT LISTENERS////////////////////////
            _stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            _stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
            this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
        }
        private function enterFrameHandler(event:Event):void
        {
            _character.accelerationX = 0;
            _character.accelerationY = 0;
            _character.friction = 0.94;

            var _updown:Boolean=Boolean(!(_bUp==_bDown));
            var _leftright:Boolean=Boolean(!(_bLeft==_bRight));

            if (!_updown && !_leftright)
            {   // not moving anywhere
                _character.gotoAndStop(1);
                _character.accelerationX = 0;
                _character.accelerationY = 0;
                _character.friction = 0.94;

                _character.vy=0;
                _character.vx=0;
            }
            else
            {
                if (_bUp)
                {
                    _character.accelerationY = -0.5;
                    _character.gotoAndStop(2);
                }
                else if (_bDown)
                {
                    _character.accelerationY = 0.5;
                    _character.gotoAndStop(3);
                }
                if (_bLeft)
                {
                    _character.accelerationX = -0.5;
                    _character.gotoAndStop(4);
                }
                else if (_bRight)
                {
                    _character.accelerationX = 0.5;
                    _character.gotoAndStop(5);
                }
            }
            //Apply friction
            _character.vx *= _character.friction;
            _character.vy *= _character.friction;
            //Apply acceleration
            _character.vx += _character.accelerationX;
            _character.vy += _character.accelerationY;
            //Limit the speed
            if (_character.vx > _character.speedLimit)
            {
                _character.vx = _character.speedLimit;
            }
            if (_character.vx < -_character.speedLimit)
            {
                _character.vx = -_character.speedLimit;
            }
            if (_character.vy > _character.speedLimit)
            {
                _character.vy = _character.speedLimit;
            }
            if (_character.vy < -_character.speedLimit)
            {
                _character.vy = -_character.speedLimit;
            }
            //Force the velocity to zero after it falls below 0.1
            if (Math.abs(_character.vx) < 0.1)
            {
                _character.vx = 0;
            }
            if (Math.abs(_character.vy) < 0.1)
            {
                _character.vy = 0;
            }
            //Move the character
            _character.x += _character.vx;
            _character.y += _character.vy;
            checkStageBoundaries(_character);

            //Box Collisions
            Collision.block(_character,_box1);
            //All other box collisions

        }
        private function checkStageBoundaries(gameObject:MovieClip):void
        {
            if (gameObject.x < 50)
            {
                gameObject.x = 50;
            }
            if (gameObject.y < 50)
            {
                gameObject.y = 50;
            }
            if (gameObject.x + gameObject.width > _stage.stageWidth - 50)
            {
                gameObject.x = _stage.stageWidth - gameObject.width - 50;
            }
            if (gameObject.y + gameObject.height > _stage.stageHeight - 50)
            {
                gameObject.y = _stage.stageHeight - gameObject.height - 50;
            }
        }

        public function replay():void
        {
            _stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            _stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
            this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
            startGame();
        }
        private function keyDownHandler(event:KeyboardEvent):void
        {
            if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
            {
                _bLeft=true;
            }
            else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
            {
                _bRight=true;
            }
            else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
            {
                _bUp=true;
            }
            else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
            {
                _bDown=true;
            }
            if (event.keyCode == Keyboard.ENTER)
            {
                replay();
            }
        }
        private function keyUpHandler(event:KeyboardEvent):void
        {
            if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT
                || event.keyCode == 65 || event.keyCode == 68)
            {
                _bLeft=false;
                _bRight=false;
            }
            else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP
                || event.keyCode == 87 || event.keyCode == 83 )
            {
                _bUp=false;
                _bDown=false;
            }
        }
        private function addGameObjectToLevel(gameObject:Sprite, xPos:int, yPos:int):void
        {
            this.addChild(gameObject);
            gameObject.x = xPos;
            gameObject.y = yPos;
        }
    }
}

_character is an instance of the Character Class.
The SWF has five key frames, each with an animation inside, which plays when the four direction buttons are pressed, plus the red stationary animation when nothing is being pressed.
package
{
    import flash.display.MovieClip;
    import flash.display.DisplayObject

        [Embed(source="../swfs/characterResource.swf", symbol="Character")]
        public class Character extends MovieClip
        {
            //Public properties
            public var vx:Number = 0;
            public var vy:Number = 0;
            public var accelerationX:Number = 0;
            public var accelerationY:Number = 0;
            public var speedLimit:Number = 4;
            public var friction:Number = 0.94;

            public function Character()
            {
            }
        }
}

The Box and Background classes are the same, they just embed the png and add the sprites. Note that the grid background is a single image. The game is not tile based..
And finally the Collision Class. When _character collides with a box, it calls the Collision.block function.
package
{
    import flash.display.Sprite;

    public class Collision
    {
        static public var collisionSide:String = "";

        public function Collision()
        {
        }
        static public function block(r1:Sprite, r2:Sprite):void
        {
            //Calculate the distance vector
            var vx:Number
                = (r1.x + (r1.width / 2))
                - (r2.x + (r2.width / 2));

            var vy:Number
                = (r1.y + (r1.height / 2))
                - (r2.y + (r2.height / 2));

            //Check whether vx
            //is less than the combined half widths
            if(Math.abs(vx) < r1.width / 2 + r2.width / 2)
            {
                //A collision might be occurring! Check
                //whether vy is less than the combined half heights
                if(Math.abs(vy) < r1.height / 2 + r2.height / 2)
                {
                    //A collision has ocurred! This is good!

                    //Find out the size of the overlap on both the X and Y axes
                    var overlap_X:Number
                    = r1.width / 2
                        + r2.width / 2
                        - Math.abs(vx);

                    var overlap_Y:Number
                    = r1.height / 2
                        + r2.height / 2
                        - Math.abs(vy);

                    //The collision has occurred on the axis with the
                    //*smallest* amount of overlap. Let's figure out which
                    //axis that is

                    if(overlap_X >=  overlap_Y)
                    {
                        //The collision is happening on the X axis
                        //But on which side? _v0's vy can tell us
                        if(vy > 0)
                        {
                            collisionSide = "Top";

                            //Move the rectangle out of the collision
                            r1.y = r1.y + overlap_Y;
                        }
                        else
                        {
                            collisionSide = "Bottom";

                            //Move the rectangle out of the collision
                            r1.y = r1.y - overlap_Y;
                        }
                    }
                    else
                    {
                        //The collision is happening on the Y axis
                        //But on which side? _v0's vx can tell us
                        if(vx > 0)
                        {
                            collisionSide = "Left";

                            //Move the rectangle out of the collision
                            r1.x = r1.x + overlap_X;
                        }
                        else
                        {
                            collisionSide = "Right";

                            //Move the rectangle out of the collision
                            r1.x = r1.x - overlap_X;
                        }
                    }
                }
                else
                {
                    //No collision
                    collisionSide = "No collision";
                }
            }
            else
            {
                //No collision
                collisionSide = "No collision";
            }
        }
    }
}

Any help would be much appreciated. I'm a beginner so its always possible the problem is something simple I've missed.
Im also asking a question about the unwanted bobbing of the animations. If any of that info helps you, or you're smart enough to know the solution to that too, the question is HERE

A: have you tried this?
    if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
                {
                    _bLeft=true;

                    _bRight=false;
                    _bUp=false;
                    _bDown=false;
                }
                else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
                {
                    _bRight=true;

                    _bLeft=false;
                    _bUp=false;
                    _bDown=false;
                }
                else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
                {
                    _bUp=true;

                    _bRight=false;
                    _bLeft=false;
                    _bDown=false;
                }
                else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
                {
                    _bDown=true;

                    _bRight=false;
                    _bLeft=false;
                    _bUp=false;
                }


text:
Q: Maximize a figure on creation I'm using the below setting to maximize a Matlab Figure:
set(gcf,'units','normalized','outerposition',[0 0 1 1])

Although it is maximized, but it is still not fully maximized like the maximize icon in the label (below)  is not on.

And this makes me loose parts of the figure when exporting it. So I'm wondering how I can fully maximize it as if I manually pressed the maximize button of the figure.

A: You can use some undocumented features to achieve what you want:
drawnow
jFig = get(handle(gcf), 'JavaFrame');
jFig.setMaximized(true);

The drawnow is not obvious, but essential as mentioned by Yair Altman in one of his comments how to avoid Java erros:

Another possible reason is due to EDT effects. The easiest solution is
  to place a call to drawnow; pause(0.1); before you access the
  JavaFrame functionality (setMaximized or any other Java function).

Tested with Matlab R2015a on Windows 8.1.


text:
Q: Custom console output channels I'm working on a problem right now, where I have to read, filter and process console outputs. To parse it correctly is nearly impossible so my question was if it's possible to work with custom output channels. At the moment I only have Console.Error and Console.Out available. But this is not enough to separate them efficiently.
Example console output:
Info text over many lines. It can be everything written in plain text.
Now important messages are coming I have to filter out.

Important Message for C1! It can be everything in plain text.
Important Message for C1! It can be everything in plain text.
Important Message for C1! It can be everything in plain text.

Info text over many lines. It can be everything written in plain text.
Now important messages are coming I have to filter out.

Important Message for C2! It can be everything in plain text.
Important Message for C2! It can be everything in plain text.
Important Message for C2! It can be everything in plain text.

Now I want to write the output of C1 like this: Console.C1.WriteLine("Message 1")
And for C2: Console.C2.WriteLine("Message 2")
The only difference in the console you can see is the color. Maybe i can go on this? If so, it will be good to.
Thank you for your help :D

A: You could write the output to files instead of console, so you would have multiple output channels.


text:
Q: Mobile Featured Image Bug I have a weird issue on my site that's only affecting mobile. If you scroll down past the black "What's Hot" section, you'll see the standard posts with featured images. Now, if you refresh the page, the standard posts after the "What's Hot" section are missing the featured images. Nothing shows up in the apache or wordpress logs, and if you browse in a private session, then the featured images appear. This leads me to believe it's a caching issue, but I don't know how to proceed from there.
Another side note, I really noticed this when I swapped over to HTTPS, and I'm serving mixed content (images over http, everything else over https for performance). Here are my rewrite rules from my .htaccess (I just ripped them from a tutorial):
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I have verified that this is affecting Android 6.0.1 on a handful of devices, as well as some variations of iPhone. At this point, I really don't know how to proceed.

A: The images there you load is always to big for teh view screen, as example this image - https://meta-game.org/wp-content/uploads/2016/12/league_of_legends_world_championship_2015.0.0.jpg, 1600 x 900 pixel. As alternate for the mobile view is this image defined - https://i2.wp.com/meta-game.org/wp-content/uploads/bfi_thumb/dummy-transparent-n019axwscfu441qfxjqwpodrdle9kgsyvjjtwpvhgo.png?zoom=2&resize=288%2C162, but this is a transparent dummy.
You should use for this usage a thumbnail with smaller size to load fast. Change your theme source to load a thumbnail of each image. Maybe you have function inside the functions.php of your theme, a settings options or much other chances for this definition. TO analyze this use an Webinspector inside a browser on a Desktop, like in Chrome - screenshot below.

*

*Also the hint. The question is to localized and without code is not really possible to solve the topic. Maybe you should ask the developer, the support team of this team to solve this solid.

A:
The images not being loaded are prefixed with the domain https://i2.wp.com
This is the CDN used when you activate the PHOTON module in the Jetpack Plugin.
If you deactivate the PHOTON module or deactivate the Jetpack Plugin, you should be rid of the issue.

A: I've accessed your website and it seems there's no issues with your post featured images, this leads me to think you might have solved it or it was just a caching issue as you've mentioned.

WordPress HTTPS
Forcing All Pages to HTTPS
For ensuring everything else is loaded over https, make sure you change the site and home urls under Settings >> General in WordPress Admin. Make it read https://meta-game.org - and then Save changes.

Additionally, If you're looking for a simple way to secure WordPress logins (the wp-login.php script) or the entire wp-admin area, you could set one the constant bellow in wp-config.php:
define('FORCE_SSL_ADMIN', true);

Inspecting the mixed content sources
Regarding the mixed content being loaded from both the http and https protocols, I'd suggest you to inspect your theme's templates or even a plugin and search for anything hard-coded with http and then fix it.
When developers are aware of this, it shouldn't be a problem, but some times a few themes come with the httpprotocol hard-coded within its templates, that's a bad practice I know, but we've got to fix it somehow.
A pretty simple method for inspecting is to load the page via HTTPS, and then right-click anywhere on the page and click "View Page Source", "View Source", or "Source", depending on your browser.
Then use the "Find" command, Edit -> Find or (Ctrl+F or Cmd+F) and search for:
src="http:
(with double-quote)
src='http:
(with single-quote)
Long story short, you're manually looking for images, scripts, iframes, and all other assets served via HTTP instead of HTTPS.
Make note of each item sourced via HTTP and you'll get an idea where to find the problem.

Thoughts on fixing the mixed content
Using Relative URLs
This is the simplest fix. If an asset (image, script, etc.) is hard-coded into a plugin or theme, change it from http://example.com/assets/logo.png to //example.com/assets/logo.png.
Typically, this is most useful when including assets from other servers, like Google scripts, API scripts, or iframes.
Before doing this, however, you need to make sure the HTTPS version is available. If loading an asset from a site that doesn't have HTTPS enabled, it's probably best to remove the reference entirely (i.e. comment out or delete) or to save the asset to your own server and change the source to load via your site instead.

Using Proper WordPress Coding Standards
A nice approach is to use the WP function is_ssl() to conditionally load assets in templates depending of the protocol that is being used by the website, e.g:
$protocol = is_ssl() ? 'https:' : 'http:';
Enqueueing an external content with the above method:
Instead of manually setting the protocol...
wp_enqueue_script('bootstrapjs', 'https://cdn.jsdelivr.net/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js', 'false', null, TRUE);
Let's do it dynamically
wp_enqueue_script('bootstrapjs', $protocol.'//cdn.jsdelivr.net/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js', 'false', null, TRUE);
Assuring your website does not serve mixed content, provides your visitors with a pleasant browsing experience, the described methods here should help you to keep your site on track while using ssl.


text:
Q: Number of integers up to r that are coprime to n Let $n$, $r$ be integers such that $n\geq 2$ and $2 \leq r \leq n$. Recall that the Euler's totient function $\varphi(n)$ is equal to the number of integers $<n$ that are coprime to $n$. Now I want to generalize this quantity and define $\psi(n,r)$ as the number of integers $<r$ that are coprime to $n$. Note that by definition $\psi(n,n)=\varphi(n)$. I am interested in obtaining a good lower bound on $\psi(n,r)$ in general for all $r$, as well as in the special case when $r \approx \varphi(n)/2$. In the latter case, $r = r(n)$ is just a function of $n$, so it would be interesting to determine the rate of growth of the function $\psi(n,r(n))$ as $n$ approaches infinity.
In the very special case when $n=p^k$ is a prime power, it is easy to prove that
$$
\psi(p^k,r) = r - \lfloor r/p\rfloor.
$$
But how do we expand this result to $n$ with several distinct prime factors?
In general, what do we know about the distribution of integers coprime to $n$ on the interval $[1,n-1]$ when $n$ is large and has many prime factors? Has this question been studied at all? I'd be thankful for any references.


text:
Q: How to find all dependent (dependency walker) packages before installing a .deb file? When installing Ubuntu Core 13.10 according to the instructions at wiki.ubuntu.com/Core/InstallationExample, step 5 says that Ubuntu 12.04 "Precise Pangolin" development kernel requires the 'wireless-crda' package. This wiki suggest to have a look at packages.ubuntu.com. However the precise/linux-image-3.8.0-37-generic page  doesn't even mention the 'wireless-crda' package at all.
After reading the Ask Ubuntu articles for 'download +kernel +packages +deb', '"depends on" +kernel +packages', 'wireless-crda' and "How to automatically fetch missing dependencies when installing software from .deb?" I still don't know how to figure out all dependent packages.
Update#1
The answers from How can I check dependency list for a deb package
1. apt-cache showpkg linux-image-3.11.0-18-generic
doesn't output a 'wireless-crda' dependency:
Reverse Depends:
  linux-image-3.11.0-18-generic:i386,linux-image-3.11.0-18-generic
  linux-signed-image-3.11.0-18-generic,linux-image-3.11.0-18-generic 3.11.0-18.32
  linux-image-virtual,linux-image-3.11.0-18-generic
  linux-image-generic,linux-image-3.11.0-18-generic
  linux-image-extra-3.11.0-18-generic,linux-image-3.11.0-18-generic
Dependencies:
3.11.0-18.32 - initramfs-tools (2 0.36ubuntu6) module-init-tools (2 3.3-pre11-4ubuntu3) dpkg (2 1.10.24) fdutils (0 (null)) linux-doc-3.11.0 (16 (null)) linux-source-3.11.0 (0 (null)) linux-tools (0 (null)) linux-headers-3.11.0-18-generic (0 (null)) grub-pc (16 (null)) grub-efi-amd64 (16 (null)) grub-efi-ia32 (16 (null)) grub (16 (null)) lilo (2 19.1) hotplug (3 0.0.20040105-1) hotplug:i386 (3 0.0.20040105-1) linux-image-3.11.0-18-generic:i386 (0 (null))
Provides:
3.11.0-18.32 - redhat-cluster-modules linux-image-3.0 linux-image kvm-api-4 ivtv-modules fuse-module
Reverse Provides:

2. dpkg -I linux-image-3.11.0-18-generic_3.11.0-18.32_amd64.deb
also doesn't output a 'wireless-crda' dependency:
Depends: initramfs-tools (>= 0.36ubuntu6), module-init-tools (>= 3.3-pre11-4ubuntu3)
 Recommends: grub-pc | grub-efi-amd64 | grub-efi-ia32 | grub | lilo (>= 19.1)
 Suggests: fdutils, linux-doc-3.11.0 | linux-source-3.11.0, linux-tools, linux-headers-3.11.0-18-generic
 Conflicts: hotplug (<< 0.0.20040105-1)
 Provides: fuse-module, ivtv-modules, kvm-api-4, linux-image, linux-image-3.0, redhat-cluster-modules

When installing the kernel through apt-get install linux-{headers,image}-generic there is a depending 'wireless-crda' package.
Question:
How to find out - before actually installing the Ubuntu kernel .deb file - all dependent packages that need to be installed?

A: You can have a look packages.ubuntu.com. The apt-get install linux-{headers,image}-generic command installs two packages:

*

*linux-headers-generic

*linux-image-generic
1. linux-headers-generic
depends on linux-headers-3.11.0-18-generic, which depends on:

*

*libc6, which depends on libgcc1

*linux-headers-3.11.0-18, which depends on coreutils
2. linux-image-generic
depends on:

*

*linux-firmware

*linux-image-3.11.0-18-generic

*linux-image-extra-3.11.0-18-generic
2.2. linux-image-3.11.0-18-generic
depends on:

*

*dpkg

*initramfs-tools

*module-init-tools
2.3. linux-image-extra-3.11.0-18-generic
depends on:

*

*crda or wireless-crda

*linux-image-3.11.0-18-generic
And there you have found how the kernel .deb file is depending upon wireless-crda.

A: With apt-cache showpkg pkg-name1 or dpkg -I pkg-name1_version.deb you can get the list of the dependencies for the pkg-name1. But one of the dependency package to pkg-name1 say pkg-name2 may depend on some other package pkg-name3 and so on.
So you'll need to not only know the pkg-name1's dependencies but also for their dependencies' dependencies ... ... and then you can download the packages (that are not already installed in your system.)


text:
Q: A string read from standard input has extra whitespace when printed I came across this anomalous behavior during printing:
use std::io;

fn main() {
    let mut number = String::new();
    io::stdin()
        .read_line(&mut number)
        .expect("Failed to read line");

    let mut number_len = number.len();
    number.truncate(number_len - 1); // removing trailing \n
    number_len = number.len();

    println!("Number entered is {} with length {}", number, number_len);

    for i in 0..(number_len - 1) {
        println!("Char at {} is {}", i, &number[i..i + 1]);
    }
}

Output
4200                                       <- my input
 with length 5 is 4200                     <- Oddly printed output
Char at 0 is 4
Char at 1 is 2
Char at 2 is 0
Char at 3 is 0

Why is this happening?
Additionally, the length of number is wrong... it should be 4 whereas it is printing 5 even after the truncating.


text:
Q: Does spring hava method to get field by @Value string literial? @Value("${properties.name:Tom}")
String name;
@Value("${properties.email}")
String email;

I want to get Filed by the annotation's value.
getField("properties.name")  returns the String field name,not the value "tom".
Does spring hava method like this?

A: It is possible using reflection, because Value has RetentionPolicy RUNTIME
Field field = Stream.of(YourClass.class.getFields())
    .filter(field -> field.isAnnotationPresent(Value.class))
    .filter(field -> field.getAnnotation(Value.class).value().contains("properties.name")) // or compare to whole expression, or use startsWith, or regex... Also think about NPE check
    .findFirst()
    .orElse( /* HANDLE FIELD NOT PRESENT */);


text:
Q: Matrix multiplication performance improvement I have got some unclear questions for the following matrix multiplication algorithm.

1) Why does the inner for-loop (line 6) do not use a "parallel for" construct?
2) Can we further improve the performance of the inner loop computation (lines 6-7) by some form of parallelism?


text:
Q: Adding 4 byte values causes Overflow Exception The following code raises a System.OverflowException
    Dim b1 As Byte = 13
    Dim b2 As Byte = 26
    Dim b3 As Byte = 125
    Dim b4 As Byte = 225

    Dim i As Integer = (b1 + b2 + b3 + b4) \ 2

Why does this happen?

A: The value(s) doesn't get converted into an Integer until you assign it to the variable. This means that up until, and including, the \ 2 part everything is still of type Byte.
To make this work you've got to convert at least the first variable into an Integer, so that additional numbers can be added to it and go beyond 255.
Dim i As Integer = (CType(b1, Integer) + b2 + b3 + b4) \ 2

Online test: https://dotnetfiddle.net/Lxmx2S

Be aware that since this respects the order of mathematical operations, you must convert all the instances of too small types that are calculated before the others. For instance if you changed your operation to this:
Dim i As Integer = (CType(b1, Integer) + b2 * b3 + b4) \ 2

It would also throw an error because b2 * b3 is calculated before b1 + b2, and thus you would have to change it to:
Dim i As Integer = (CType(b1, Integer) + CType(b2, Integer) * b3 + b4) \ 2


text:
Q: Enable fine grained on keycloak with docker I have set up keycloak using docker, my problem is that I need to do some modifications on the clients that need the fine grained to be enabled. I have read the documentation and i know I should use the parameter -Dkeycloak.profile=preview or -Dkeycloak.profile.feature.admin_fine_grained_authz=enabled. My problem is that I tried to use that on my docker execution command, but with no luck
docker run --rm \
  --name keycloak \
  -p 80:8080 \
  -e KEYCLOAK_USER=admin \
  -e KEYCLOAK_PASSWORD=[adminPass] \
  -e PROXY_ADDRESS_FORWARDING=true \
  -e DB_VENDOR=MYSQL \
  -e DB_ADDR=[SQL_Server] \
  -e DB_DATABASE=keycloak \
  -e DB_USER=[DBUSER] \
  -e DB_PASSWORD=[DB_PASS] \
  -e JDBC_PARAMS=useSSL=false \
  -e -Dkeycloak.profile.feature.admin_fine_grained_authz=enabled \
  jboss/keycloak

any help?

A: It is documented in the Docker image readme https://hub.docker.com/r/jboss/keycloak

Additional server startup options (extension of JAVA_OPTS) can be configured using the JAVA_OPTS_APPEND environment variable.

So in your case:
-e JAVA_OPTS_APPEND="-Dkeycloak.profile=preview"

A: Guess you might need to pass the environment variables to the JVM when starting the Wildfly containing the Keycloak WAR. There is a runner shell script that starts when launching the container. You need to add your environment variables to that call.


text: Q: How do I check if all the 5 mins Candle Close is above VWAP since 9:15AM? Tradingview Say, latest 5 mins candle closes below VWAP then I wanted to check if all the 5mins candle before latest candle since 9:15 closed above VWAP in pine script. Trading view


text:
Q: Evaluation Metrics for Binary Classification in Spark: AUC and PR curve I was trying to calculate Precision, Recall by Threshold for LogisticRegressionwithLBFGS using BinaryclassificationMetrics.
I got all those. I was trying to figure out if I could get a graphical output of PR and AUC curve.
Pasting my Codes below:
import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS
import org.apache.spark.mllib.evaluation.{BinaryClassificationMetrics, MulticlassMetrics}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object log_reg_eval_metric {

  def main(args: Array[String]): Unit = {

    System.setProperty("hadoop.home.dir", "c:\\winutil\\")

    val sc = new SparkContext(new SparkConf().setAppName("SparkTest").setMaster("local[*]"))

    val sqlContext = new org.apache.spark.sql.SQLContext(sc);

    val data: RDD[String] = sc.textFile("C:/Users/user/Documents/spark-1.5.1-bin-hadoop2.4/data/mllib/credit_approval_2_attr.csv")

    val parsedData = data.map { line =>
      val parts = line.split(',').map(_.toDouble)
      LabeledPoint(parts(0), Vectors.dense(parts.tail))
    }

    //Splitting the data
    val splits: Array[RDD[LabeledPoint]] = parsedData.randomSplit(Array(0.7, 0.3), seed = 11L)
    val training: RDD[LabeledPoint] = splits(0).cache()
    val test: RDD[LabeledPoint] = splits(1)

    // Run training algorithm to build the model
    val model = new LogisticRegressionWithLBFGS()
      .setNumClasses(2)
      .run(training)
    // Clear the prediction threshold so the model will return probabilities
    model.clearThreshold

    // Compute raw scores on the test set
    val predictionAndLabels = test.map { case LabeledPoint(label, features) =>
      val prediction = model.predict(features)
      (prediction, label)
    }

    // Instantiate metrics object
    val metrics = new BinaryClassificationMetrics(predictionAndLabels)

    // Precision by threshold
    val precision = metrics.precisionByThreshold
    precision.foreach { case (t, p) =>
      println(s"Threshold: $t, Precision: $p")
    }

    // Precision-Recall Curve
    val PRC = metrics.pr

    print(PRC)

  }
}

output from print(PRC):
UnionRDD[39] at union at BinaryClassificationMetrics.scala:108

I am not sure what is an union RDD and how to use it. Is there any other way to get the graphical output. Doing my research on it. Any suggestion would be great.

A: You can use BinaryLogisticRegressionTrainingSummary from spark.ml package.It provides PR and ROC values out of box as dataframes.
You can input these values to any rendering utility to see the specific curves.(Any multiline plot with x and y values will display the curves.)


text:
Q: easy IDE to get autocomplete and syntax highlighting? What is a very simple to hack up IDE to get automplete/intellisense for my own language and syntax highlighting? The output will be for .NET and maybe in C++

A: Scite or Notepad++ would probably be the best options for doing it yourself.

A: try Geany

A: http://www.e-texteditor.com/ making new language bundles for e (and Textmate, which e is based on and the bundles are compatible with both) is fairly simple and extremely well documented.

A: I'm not clear about the "my own language" and "output will be .Net and maybe in C++".  The own language part there are many editors like UltraEdit and the like.  When you add .Net it make me think you want to use Visual Studio Shell to make your own IDE.
That said, some editors do give you "F5" build experience by calling into the command line build engine.
Hope this helps.


text:
Q: Is there a way of making the notion of "stronger theorem" precise? Mathematicians frequently speak of a theorem being stronger than another. But on its face, this does not make sense, since all theorems in a formal system imply each other, hence are equivalent. Is there some paper or text where this notion is made precise, where there is defined a preorder on theorems that is stronger than equivalence but weaker than strict identity? I would like a link to such a paper.

A: "All theorems in a formal system imply each other".
Not so.
Suppose $T \vdash_S A$ and $T \vdash_S B$ where $T$ is some theory whose deductive apparatus is $S$ [e.g. first-order logic], and $\vdash_S$ is syntactic entailment in $S$. Nothing whatsoever follows about whether $A \vdash_S B$ or $B \vdash_S A$. So the claim doesn't apply to theoremhood and implication understood in terms syntactic entailment.
Suppose $T \vDash_L A$ and $T \vDash_L B$ where $T$ is some theory in language $L$, and $\vDash_L$ is the notion of semantical entailment appropriate to the language $L$. Nothing whatsoever follows about whether $A \vDash_L B$ or $B \vDash_L A$. So the claim doesn't apply to theorem hood and implication understood in terms of semantic entailment either.
(Perhaps you think "implies"  in the sense relevant to talk about one theorem implying more than another is well captured by material implication, i.e. the truth-functional conditional. Well, it isn't. And anyway even if $T \supset A$ and $T \supset B$, nothing as yet follows about whether $A \supset B$ or $B \supset A$ either.)

A: Yes, there is a way of making this notion precise.  Namely, for two theorems $A$ and $B$ of a theory $T$, one can fix a subtheory $T_0$ of $T$ and ask whether or not $T_0 \cup \{A\} \vdash B$.  The idea is that the "base theory" $T_0$ has only some basic axioms that we take for granted (and which axioms we wish to take for granted can depend on the context.)
For example, both the Boolean Prime Ideal Theorem and the Hahn–Banach Theorem are provable in $\mathsf{ZFC}$; however, it is often said that
the Hahn–Banach Theorem is weaker than the Boolean Prime Ideal Theorem because it can be proved from the $\mathsf{ZF}$ axioms plus the Boolean Prime Ideal Theorem, whereas the Boolean Prime Ideal Theorem cannot be proved from the $\mathsf{ZF}$ axioms plus the Hahn–Banach Theorem.
Naturally, the meaning of "weaker than" depends on the base theory (here it is $\mathsf{ZF}$.)
Besides consequences of $\mathsf{AC}$, another context in which this notion has been studied extensively is subsystems of second order arithmetic — see the book by Stephen G. Simpson by this name.  Here the theory $T$ is second-order arithmetic (instead of $\mathsf{ZFC}$) and the base theory $T_0$ is a weak subtheory called $\mathsf{RCA}_0$.


text:
Q: New members can't find logout button From time to time we receive questions about logout button on ru SO:

*

*Как выйти с учетной записи в Stackoverflow?

*Как выйти с аккаунта на сайте.

*Где кнопка Выход?

*Подскажите, как выйти из аккаунта на сайте stackoverflow?
New members can't find it.
Usually this button is located on the bottom side of the menu. GitHub, Facebook, etc...

On SE sites location of this button is not, hm, obvious.
If you don't want to move it, you can, at least, make it bold:
font-weight: bold;
text-decoration: underline;

Even with this small change the button will be more evident.

A: There is a tour in the StackExchange Network sites, which introduces users to the basics of each community and how to contribute.
Maybe, there should be a user interface tour too.
The location of the StackExchange speech bubble is the upper right corner, which is where usually options are located. This can also be seen in the screenshots from GitHub and Facebook.However, people are used to click on profile pictures to get these options, including logout.
The hover card (tooltip) of the speech bubble states that it is a list of all 174 StackExchange sites, which makes it lesser obvious.
But it is common knowledge, that the logout option is usually located somewhere in a menu in the upper right corner, so it could be guessed.

TL;DR:
I believe that icons would make a larger visibility difference than bold text.


text:
Q: can't reopen featherlight div after closing it I've started using FeatherLight and have a small problem:
I have a simple div. Here is its code:

....

Basically i can open the lightbox and it is shown perfectly and everything is ok - UNTIL i manually force a close of the lightbox popup via Javascript.
After closing it once? - when i try to reload it again, i get an empty lightbox (maybe the close operation erased the div's content).
For the close command i use:
$.featherlight.close();

and for the opening command (opening of the featherlight lightbox) i use the following command:
$.featherlight($('#AddNewItemToMenu'), { 'persist' : true });

Any ideas why that happens?.
Maybe there is another methood of hiding instead of closing? (something that won't vanish my div?).
Thank you!.
Updated:
I've attached an example file. Uploaded to some temp site. here is the link: https://ufile.io/wxipg
When opening index.html => click on the "Open Featherlight" and then close the popup and then click on the "Open Featherlight" again, and you'll see empty div.

A: You should either use featherlight's binding (e.g. $('#open-fl').featherlight(...)), or else use the result of $.featherlight to re-open it, e.g.:
var fl = $.featherlight(...); // Opens dialog a first time
fl.close(); // Closing it via JS
fl.open(); // Opening again


text:
Q: Unity Asset Bundles Rebuilding with Old Data I have a mobile project which displays various AR experiences to the user via a mobile application. This application is made in Unity.
Alongside this Unity project we have a second project that stores asset bundles exclusively. Each AR experience is a prefab marked with a unique asset bundle name. These bundles are stored online and downloaded into the main mobile application when relevant. We're having issues with having these bundles correctly update, when changing things on the prefab such as scale or rotation they aren't reflected in the rebuilt asset bundle.
Here's a look at the process we're using for rebuilding assets, It's only a simple script.
[MenuItem("Spiff/Build AssetBundles")]
static void BuildAllAssetBundles()
{
    // BuildPlatformBundles(BuildTarget.iOS);
    BuildPlatformBundles(BuildTarget.Android);
}

static void BuildPlatformBundles(BuildTarget platform)
{
    // We convert the passed platform enum to a string.
    string platformFolder = platform.ToString();
    string assetBundleDirectory = "Assets/AssetBundles/" + platformFolder;

    // Build our bundles out to the relevent platform specific folder.
    if (!AssetDatabase.IsValidFolder(assetBundleDirectory))
    {
        AssetDatabase.CreateFolder("Assets/AssetBundles/", platformFolder);
    }
    BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, platform);
}

Currently we use 'BuildAssetBundleOptions.None' We've also tried the ForceRebuild flag but this has no effect. Am I correct in assuming that Unity has some sort of internal cache it keeps for assets bundles? If so can we clear this somehow so I can ensure 100% that the bundle I am building is going to be the most up to date based on the prefab tagged with it?

A: Loaded Assetbundles are indeed cached, and will remain so until AssetBundle.Unload() has been called to free up all memory accociated with the asset.
After the asset has been unloaded a newer version of the assetbundle can be downnloaded and instantiated with the new values (Assuming the file downloaded has all the updated information), else it will load the data from cache if available.
On a side note: It seems like you're still using the old assetbundle pipeline. Unity has a plugin tool that makes the assetbundle workflow considerably easier called the assetbundle browser found here. It comes with a way easier UI for building bundles and inspecting bundles, open source and a very customisable pipeline. It may be worth checking out.

A: Like remy_rm mentioned, do give the Unity Asset Bundle Browser tool a try. It gives more control over what assets are in the bundle.
Your problem can be solved if you ensure two things:
1- When you make changes to a prefab and create a new bundle, is it indeed created with the said changes? (again using the tool would make checking this easier)
2- The bundles you are downloading in the main application are the new ones and not the old cached ones. In Unity Webgl for instance, you need to clear the browser cache to be 100% sure that the application downloads the new asset bundles and doesn't use the old ones in browser cache.