text:
Q: How to properly import Open Source projects in Flutter? I am learning Flutter and I would like to import an Open Source project to learn some of the structure etc.
The project is: https://github.com/matthewtory/trinity-orientation-2018
I am using Android Studio, and so far I can create my own projects and run them via my phone but when I want to import this project I am  getting a lot of errors and warnings. The app is finished and also on the play store, so why doesn't it run in my IDE? Am I missing something?
Error message is:
Launching lib\main.dart on SM G960F in debug mode...
Initializing gradle...
Resolving dependencies...
* Error running Gradle:
ProcessException: Process "C:\Users\marcs\AndroidStudioProjects\trinity-orientation-2018-master\android\gradlew.bat" exited abnormally:
firebase_storage
firebase_messaging
url_launcher
camera
path_provider
cloud_firestore
shared_preferences
image_picker
firebase_core
firebase_auth

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\marcs\AndroidStudioProjects\trinity-orientation-2018-master\android\app\build.gradle' line: 16

* What went wrong:
A problem occurred evaluating project ':app'.
> versionCode not found. Define flutter.versionCode in the local.properties file.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
  Command: C:\Users\marcs\AndroidStudioProjects\trinity-orientation-2018-master\android\gradlew.bat app:properties

Finished with error: Please review your Gradle project setup in the android/ folder.

I downloaded the project and imported the folder in Android Studio. It first asked to get the dependencies which I did and immediately, I tried to run it on my phone.
Feel free to check the code on the Github project. I have not changed anything. I hope to run this project to learn about animation and navigation concepts.

A: The error message says you have to define version code. Try to add below lines to your local.properties file (under android folder)

flutter.versionName=1.0.0
flutter.versionCode=1

You may get other errors but at least this will fix the error in your question. Share other error message if you get.


text:
Q: TFS stand-alone MS Excel/Project add-ons I want to know if there is a stand-alone setup for TFS Excel/Project add-ons or not. I know I can obtain them through Team Explorer but the problem with it are :
1- It is a huge (+300Mb) setup file
2- It is a complicated process setup for people who have no any knowledge of VS and TFS. Always a developer should be there for installation
I will be so excited if there is a light stand-alone installer for TFS Excel/Project add-ons.

A: No, there isn't, but you can create an answer file for Team Explorer to install it silently with just one click.
http://msdn.microsoft.com/en-us/library/ee225237.aspx
You can place this install on a network share.
I'm not sure if you can register a new server connection from a script. I've asked the powers that be.
The powers that be have responded, you can export your own TFS server registrations (or create a .reg file from scratch) and import those on the new machine in order to pre-populate the connection window:
Martin Woodward  @martinwoodward:
@jessehouwing See HKCU:\Software\Microsoft\VisualStudio\11.0\TeamFoundation\Instances (or 10.0 for VS2010)

A: When "Team" add-in goes missing from Office:
•Go to Excel Options
•Select COM add-ins and add "TFSOfficeAdd-in.dll"  from "C:\Program Files\Microsoft Visual
 Studio 10.0\Common7\IDE\PrivateAssemblies"
•In case if its not there install Team Explorer 2010

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding the proof of $\displaystyle\lim_{n\to\infty}(\sqrt n)^\frac{1}{n}=1$ I need help understanding this:
Prove that $$\lim_{n\to\infty}(\sqrt n)^\frac{1}{n}=1$$

$$(\sqrt n)^\frac{1}{n}\geq
(\sqrt1)^\frac{1}{n}=1, \forall n\in\Bbb N$$
  By binomial theorem we get for $n\geq 2$
$$n=((\sqrt n)^\frac{1}{n})^n=[1+((\sqrt n)^\frac{1}{n}-1)]^n=\sum_{k=0}^{n}{{n}\choose{k}}1^{n-k}(\sqrt n^\frac{1}{n}-1)^k$$
  $$\geq 1+{{n}\choose {2}}(\sqrt n^\frac{1}{n}-1)^2=1+\frac{n(n-1)}{2}(\sqrt n^\frac{1}{n}-1)^2$$
  $$\Rightarrow (\sqrt n^\frac{1}{n}-1)^2\leq \frac{2}{n}$$
  $$\Rightarrow \sqrt n^\frac{1}{n}\leq 1+\frac{\sqrt 2}{\sqrt n}$$
  $1+\frac{\sqrt 2}{\sqrt n}$ approaches $1$ for $n \rightarrow \infty$ so by the sandwich theorem we get $\lim_{n\to\infty}(\sqrt n)^\frac{1}{n}=1$

I don't understand this part:
$$
\sum_{k=0}^{n}{{n}\choose{k}}1^{n-k}(\sqrt n^\frac{1}{n}-1)^k\geq 1+{{n}\choose {2}}(\sqrt n^\frac{1}{n}-1)^2.$$ Could someone explain how they got that on the RHS?

A: Since $n^{1/n}\ge 1$, then all of the terms in the binomial expansion
$$\left(1+(\sqrt[n]{n}-1)\right)^n=\sum_{k=0}^n\binom{n}{k}(\sqrt[n]{n}-1)^k$$
are non-negative.  Therefore, we have for any $m\le n$
$$\sum_{k=0}^n\binom{n}{k}(\sqrt[n]{n}-1)^k\ge \sum_{k=0}^m\binom{n}{k}(\sqrt[n]{n}-1)^k$$
Taking $m=2$ and $n\ge 2$ yields
$$\begin{align}
\sum_{k=0}^n\binom{n}{k}(\sqrt[n]{n}-1)^k&\ge \sum_{k=0}^2\binom{n}{k}(\sqrt[n]{n}-1)^k\\\\
&=1+n(\sqrt[n]{n}-1)+\frac{n(n-1)}{2}(\sqrt[n]{n}-1)^2\\\\
&\ge 1+\frac{n(n-1)}{2}(\sqrt[n]{n}-1)^2
\end{align}$$
where the last inequality is true since $n(\sqrt[n]{n}-1)\ge 0$.

A: They are truncating the binomial expansion, discarding positive terms: if
$$
r=r_0+r_1+r_2+\dots+r_n
$$
and $r_i\ge0$ for $i=0,1,\dots,n$, then $r\ge r_0+r_2$.

It can be done more easily. Set $(\sqrt{n})^{1/n}=1+a_n$, so
$$
\sqrt{n}=(1+a_n)^{n}\ge1+na_n
$$
by Bernoulli's inequality. Hence
$$
a_n\le\frac{\sqrt{n}-1}{n}=\frac{1}{\sqrt{n}}-\frac{1}{n}
$$
so
$$
(\sqrt{n})^{1/n}=1+a_n\le 1+\frac{1}{\sqrt{n}}-\frac{1}{n}
$$
and the squeeze theorem allows to conclude.

A: Set $l =\lim_{n\to\infty}n^\frac{1}{n}$
$$\lim_{n\to\infty}(\sqrt n)^\frac{1}{n}=\sqrt{\lim_{n\to\infty}n^\frac{1}{n}}=\sqrt{l}$$
For the limit of the sequence $n^\frac{1}{n}$ get the sub-sequence $(2n)^\frac{1}{2n}$
So:
$l^2=(\lim (2n)^\frac{1}{2n})^2=\lim (2n)^\frac{1}{n}=\lim 2^\frac{1}{n}. n^\frac{1}{n}=\lim 2^\frac{1}{n}.\lim n^\frac{1}{n}=l$
$l^2=l$ and as $n^\frac{1}{n}\gt1$ we have $l=1$
And $\sqrt{\lim_{n\to\infty}n^\frac{1}{n}}=\sqrt{1}=1$

A: That proof seems a little complicated; I'll do it a different way.  Let's write $(\sqrt n)^{1/n} = 1+a_n.$ We know each $a_n>0.$ For $n\ge 2,$ the binomial theorem shows
$$\sqrt n= (1+a_n)^{n} = 1^n\cdot a_n^0 + n\cdot1^{n-1}\cdot a_n^1 + [n(n-1)/2]\cdot 1^{n-2}\cdot a_n^2 + \cdots > [n(n-1)/2]a_n^2.$$
Therefore
$$\frac{\sqrt n}{n(n-1)/2} > a_n^2.$$
Since the expression on the left $\to 0,a_n^2 \to 0,$ which implies $a_n \to 0.$ It follows that $(\sqrt n)^{1/n} \to 1.$

A: A Different Approach
Because $\left(1+\frac1n\right)^{n+1}$ is decreasing, for $n\ge3$,
$$
\begin{align}
\frac{(n+1)^n}{n^{n+1}}
&=\frac1{n+1}\left(1+\frac1n\right)^{n+1}\\
&\le\frac14\cdot\frac{256}{81}\\[6pt]
&\lt1
\end{align}
$$
Thus, for $n\ge3$,
$$
(n+1)^{\frac1{n+1}}\lt n^{\frac1n}
$$
That is, $n^{\frac1n}$ is decreasing and bounded below by $1$. So $\lim\limits_{n\to\infty}n^{\frac1n}$ exists.
$$
\begin{align}
\lim_{n\to\infty}n^{\frac1n}
&=\lim_{n\to\infty}(2n)^{\frac1{2n}}\\
&=\lim_{n\to\infty}2^{\frac1{2n}}\lim_{n\to\infty}n^{\frac1{2n}}\\
\end{align}
$$
Therefore,
$$
\begin{align}
\lim_{n\to\infty}n^{\frac1{2n}}
&=\lim_{n\to\infty}2^{\frac1{2n}}\\[6pt]
&=1
\end{align}
$$

Bernoulli's Inequality
Bernoulli's Inequality says
$$
\begin{align}
\lim_{n\to\infty}\sqrt{n}^{1/n}
&=\lim_{n\to\infty}\left(1+\left(\sqrt{n}-1\right)\right)^{1/n}\\[3pt]
&\le\lim_{n\to\infty}\left(1+\tfrac1n\left(\sqrt{n}-1\right)\right)\\[6pt]
&=1
\end{align}
$$
Since $\sqrt{n}^{1/n}\ge1$, the Squeeze Theorem says
$$
\lim_{n\to\infty}\sqrt{n}^{1/n}=1
$$

A: $$\sum_{k=0}^{n}{{n}\choose{k}}1^{n-k}(\sqrt n^\frac{1}{n}-1)^k= 1+{{n}\choose {2}}(\sqrt n^\frac{1}{n}-1)^2+\left[{{n}\choose {1}}(\sqrt n^\frac{1}{n}-1)^1+\sum_{k=3}^{n}{{n}\choose{k}}1^{n-k}(\sqrt n^\frac{1}{n}-1)^k\right]$$
and see that:
$${{n}\choose {1}}(\sqrt n^\frac{1}{n}-1)^1+\sum_{k=3}^{n}{{n}\choose{k}}1^{n-k}(\sqrt n^\frac{1}{n}-1)^k \ge 0$$
because
$$\sqrt{n}^\frac{1}{n}-1 \ge0$$

A: I'd like to offer another method, using $x^n-1=(x-1)(x^{n-1}+x^{n-2}+...+x^{2}+x+1)$
$$n-1=(n^{\frac{1}{2n}})^{2n}-1=\\(n^{\frac{1}{2n}}-1)(n^{\frac{1}{2n}(2n-1)}+n^{\frac{1}{2n}(2n-2)}+...+n^{\frac{1}{2n}2}+n^{\frac{1}{2n}}+1)\geq$$
using AM-GM
$$\geq(n^{\frac{1}{2n}}-1)\left((2n-1)\sqrt[2n-1]{n^{\frac{1}{2n}(2n-1)}\cdot n^{\frac{1}{2n}(2n-2)}\cdot ...\cdot n^{\frac{1}{2n}2}\cdot n^{\frac{1}{2n}}}+1\right)=\\
(n^{\frac{1}{2n}}-1)\left((2n-1)\sqrt[2n-1]{n^{\frac{1}{2n}(2n-1+2n-2+...+1)}}+1\right)=
\\(n^{\frac{1}{2n}}-1)\left((2n-1)\sqrt[2n-1]{n^{\frac{1}{2n}\frac{(2n-1)2n}{2}}}+1\right)=\\
(n^{\frac{1}{2n}}-1)\left((2n-1)\sqrt{n}+1\right)$$
Also $\ln{x}\leq x-1,x>0$ which means $$\ln{n^{\frac{1}{2n}}}=\frac{\ln{n}}{2n}\leq n^{\frac{1}{2n}}-1$$
Altogether
$$\frac{\ln{n}}{2n}\leq n^{\frac{1}{2n}}-1\leq \frac{n-1}{(2n-1)\sqrt{n}+1}<\frac{1}{2\sqrt{n}}$$

A: Let $\lim_{n\to\infty} n^{1/2n} = L$
Taking logarithms, we get ;
$log(L) =$$\lim_{n\to\infty}$$\frac{1}{2n}$$log(n)$
Applying $LH$ Rule :
$log(L) =$$\lim_{n\to\infty}$$\frac{1}{2n}=0$
Hence, $L=e^0=1$


text:
Q: Publication bias in meta-analysis of diagnostic accuracy in R? Are there any implemented methods in R that could be used to assess publication bias in a meta-analysis of diagnostic accuracy (Egger's test, funnel plots)?
One way would be to change sensitivites and specifities to log diagnostic odds ratios (logDOR), run meta-analysis on the logDOR using common rfx-models and then e.g. use funnel() and regtest() from the metafor package. However as I understand the bivariate approach (Reitsma et al., 2005) is to be prefered. But if a run a bivariate linear model, how can I assess publication bias?
library(mada)
data(Dementia)
(fit <- reitsma(Dementia))
summary(fit)

A: There is an older paper of Deeks et al justifying the use of the diagnostic odds ratio for this purpose:
on this method:
http://www.ncbi.nlm.nih.gov/pubmed/16085191
The work of Deeks et al is not related to the bivariate model. From my limited experience I can nevertheless recommend this approach.

A: Check out the Meta-Analysis Task View


text:
Q: Get class definition from type I have a situation where I'd like to be able to pass a Type as a generic parameter.  My problem is that once I use typeof() to obtain a Type, I cannot figure out how to get this back into a form that would allow me to pass it as a generic parameter, even though the type is still a class type.
The below is purely to demonstrate my issue, I'm not actually calling typeof() on something that's already constrained as a class type:
public void Example<T>() where T : class
{
  //This works fine.
  var firstList = new List<T>();

  Type aType = typeof(T);

  //This resolves to true.
  bool thisIsTrue = aType.IsClass;

  //This does not compile?!?
  var secondList = new List<aType>();
}

Answering any of the following questions would likely solve my issue:
-- Is there a command similar to typeof(), .GetType(), etc., that would allow me to constrain the result to a class, so the compiler would accept it for a generic parameter?  Then I could avoid the issue of going from type to class altogether.
-- Is there actually a way to transform a type into a class?  I couldn't find a way to do it from either the type or an instantiated object of said type.
-- As a last resort, am I going to need to dynamically define these classes at runtime to actually get this to work?

A: You are looking for MakeGenericType method
var secondListType = typeof(List<>).MakeGenericType(aType);
var secondList = (List<T>)Activator.CreateInstance(secondListType);


text:
Q: MiniMRYarnCluster, run MR locally I'm trying to run MR jobs locally using MiniMRYarnCluster.
I'm using old mapreduce (not YARN) and mapreduce API v2
This stuff can be found here:
<dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mapreduce-client-jobclient</artifactId>
            <version>2.0.0-cdh4.1.1</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>

Here is a portion of log:
--127.0.1.1-58175-1358256748215, blockid: BP-1072059606-127.0.1.1-1358256746988:blk_6137856716359201843_1008, duration: 229871
13/01/15 17:32:34 INFO localizer.LocalizedResource: Resource hdfs://localhost:50123/apps_staging_dir/ssa/.staging/job_1358256748507_0001/job.xml transitioned from DOWNLOADING to LOCALIZED
13/01/15 17:32:34 INFO container.Container: Container container_1358256748507_0001_01_000001 transitioned from LOCALIZING to LOCALIZED
13/01/15 17:32:34 INFO container.Container: Container container_1358256748507_0001_01_000001 transitioned from LOCALIZED to RUNNING
13/01/15 17:32:34 INFO nodemanager.DefaultContainerExecutor: launchContainer: [bash, /home/ssa/devel/POIClusterMapreduceTest/ru.mrjob.poi.POIClusterMapreduceTest-localDir-nm-0_1/usercache/ssa/appcache/application_1358256748507_0001/container_1358256748507_0001_01_000001/default_container_executor.sh]
13/01/15 17:32:34 WARN nodemanager.DefaultContainerExecutor: Exit code from task is : 1
13/01/15 17:32:34 INFO nodemanager.ContainerExecutor:
13/01/15 17:32:34 WARN launcher.ContainerLaunch: Container exited with a non-zero exit code 1

And here is an exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/yarn/service/CompositeService
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.yarn.service.CompositeService
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 12 more
Could not find the main class: org.apache.hadoop.mapreduce.v2.app.MRAppMaster.  Program will exit.

I've used org.apache.hadoop.mapreduce.v2.TestMRJobs as a base for my own test. Did anyone met the problem?
Here is my code, it an abstract base class to test MR jobs locally on CI server or developer machine:
public abstract class AbstractClusterMapReduceTest {

    private static final Log LOG = LogFactory.getLog(AbstractClusterMapReduceTest.class);

    public static final String DEFAULT_LOG_CATALOG = "local-mr-logs";

    private static final int DEFAULT_NAMENODE_PORT = 50123;
    private static final int ONE_DATANODE = 1;

    private static final int DEFAULT_REDUCE_NUM_TASKS = 1;
    private static final String SLASH = "/";
    private static final String DEFAULT_MR_INPUT_DATA_FILE = "mr-input-data-file";

    private MiniMRYarnCluster mrCluster;
    private MiniDFSCluster dfsCluster;

    /** Shitty code from base Cloudera example*/
    private static Path TEST_ROOT_DIR = new Path("target",
            AbstractClusterMapReduceTest.class.getName() + "-tmpDir").makeQualified(getLocalFileSystem());
    static Path APP_JAR = new Path(TEST_ROOT_DIR, "MRAppJar.jar");

    private static FileSystem getLocalFileSystem(){
        try {
            return FileSystem.getLocal(new Configuration());
        } catch (IOException e) {
            throw new Error("Can't access local file system. MR cluster can't be started", e);
        }
    }

    /**
     * Always provide path to log catalog.
     * Default is: ${project.build.directory}/{@link AbstractClusterMapReduceTest#DEFAULT_LOG_CATALOG}
     * */
    protected String getPathToLogCatalog(){
        return getPathToOutputDirectory()+ SLASH + DEFAULT_LOG_CATALOG;
    }

    private String getPathToOutputDirectory(){
        return System.getProperty("project.build.directory");
    }

    private void checkAppJar(){
        if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
            throw new Error("MRAppJar " + MiniMRYarnCluster.APPJAR+ " not found. Not running test.");
        }else{
            LOG.info(MiniMRYarnCluster.APPJAR + " is at the right place. Can continue to setup Env...");
        }
    }

    public void setupEnv() throws IOException{
        checkAppJar();

        System.setProperty("hadoop.log.dir", getPathToLogCatalog());
        System.setProperty("javax.xml.parsers.SAXParserFactory",
                "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");

        dfsCluster = buildMiniDFSCluster();
        //dfsCluster.getFileSystem().makeQualified(createPath(getHDFSPathToInputData()));
        //dfsCluster.getFileSystem().makeQualified(createPath(getOutputPath()));

        mrCluster = new MiniMRYarnCluster(this.getClass().getName(), 1);
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", getFileSystem().getUri().toString());   // use HDFS
        //conf.set(MRJobConfig.MR_AM_STAGING_DIR, getPathToOutputDirectory()+"/tmp-mapreduce");
        conf.set(MRJobConfig.MR_AM_STAGING_DIR, "/apps_staging_dir");
        mrCluster.init(conf);
        mrCluster.start();

        //Cloudera tricks :)
        // Copy MRAppJar and make it private. TODO: FIXME. This is a hack to
        // workaround the absent public discache.
        getLocalFileSystem().copyFromLocalFile(new Path(MiniMRYarnCluster.APPJAR), APP_JAR);
        getLocalFileSystem().setPermission(APP_JAR, new FsPermission("700"));
    }

    public void tearDown() {
        if (mrCluster != null) {
            mrCluster.stop();
            mrCluster = null;
        }
        if (dfsCluster != null) {
            dfsCluster.shutdown();
            dfsCluster = null;
        }
    }

    public boolean createAndSubmitJob() throws IOException, ClassNotFoundException, InterruptedException{
        LOG.info("createAndSubmitJob: enter");
        checkAppJar();
        LOG.info("MRAppJar has been found. Can start to create Job");

        Configuration configuration = mrCluster.getConfig();
        configuration.set(MRConfig.MASTER_ADDRESS, "local");

        Job job = Job.getInstance(configuration);
        job.setJobName(this.getClass().getSimpleName()+"-job");
        job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.

        job.setJarByClass(getMRJobClass());
        job.setJobName(getMRJobClass().getSimpleName());

        job.setNumReduceTasks(getReduceNumTasks());

        job.setOutputKeyClass(getOutputKeyClass());
        job.setOutputValueClass(getOutputValueClass());

        job.setMapperClass(getMapperClass());
        job.setReducerClass(getReducerClass());

        job.setInputFormatClass(getInputFormat());
        job.setOutputFormatClass(getOutputFormat());

        FileInputFormat.setInputPaths(job, getHDFSPathToInputData());
        FileOutputFormat.setOutputPath(job, createPath(getOutputPath()));

        job.setSpeculativeExecution(false);
        job.setMaxMapAttempts(1); // speed up failures

        LOG.info("Submitting job...");
        job.submit();
        LOG.info("Job has been submitted.");

        String trackingUrl = job.getTrackingURL();
        String jobId = job.getJobID().toString();
        LOG.info("trackingUrl:" +trackingUrl);
        LOG.info("jobId:" +jobId);

       return job.waitForCompletion(true);
    }

    protected FileSystem getFileSystem() throws IOException {
        return dfsCluster.getFileSystem();
    }

    protected int getReduceNumTasks(){
        return DEFAULT_REDUCE_NUM_TASKS;
    }

    /**
     * @return InputStream instance to file you want to run with your MR job
     * */
    protected InputStream getInputStreamForInputData() {
        return this.getClass().getClassLoader().getResourceAsStream(this.getClass().getSimpleName()+"/"+getInputDatasetName());
        //return getPathToOutputDirectory()+ SLASH + DEFAULT_INPUT_CATALOG+"/mr-input-data";
    }

    protected String getHDFSPathToInputData() throws IOException{
        InputStream inputStream = getInputStreamForInputData();
        Path hdfsInputPath = new Path(DEFAULT_MR_INPUT_DATA_FILE);
        FSDataOutputStream fsDataOutputStream = getFileSystem().create(hdfsInputPath);
        copyStream(inputStream, fsDataOutputStream);
        fsDataOutputStream.close();
        inputStream.close();

        return hdfsInputPath.toString();
    }

    private void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024]; // Adjust if you want
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1)
        {
            output.write(buffer, 0, bytesRead);
        }
    }

    /**
     * Dataset should be placed in resources/ConcreteClusterMapReduceTest
     * @return a name of a file from catalog.
     * */
    protected abstract String getInputDatasetName();

    /**
     * @return path reducer output
     * default is: @{link AbstractClusterMapReduceTest#DEFAULT_OUTPUT_CATALOG}
     * */
    protected String getOutputPath(){
        return "mr-data-output";
    }

    /**
     * Creates @{link Path} using absolute path to some FS resource
     * @return new Path instance.
     * */
    protected Path createPath(String pathToFSResource){
        return new Path(pathToFSResource);
    }

    /**
     * Builds new instance of MiniDFSCluster
     * Default: @{link DEFAULT_NAMENODE_PORT}, @{link DEFAULT_NAMENODE_PORT}
     * @return MiniDFSCluster instance.
     * */
    protected MiniDFSCluster buildMiniDFSCluster() throws IOException {
        return new MiniDFSCluster.Builder(new Configuration())
                    .nameNodePort(DEFAULT_NAMENODE_PORT)
                    .numDataNodes(ONE_DATANODE)
                    .build();
    }

    protected abstract Class<? extends Configured> getMRJobClass();
    protected abstract Class<? extends Mapper> getMapperClass();
    protected abstract Class<? extends Reducer> getReducerClass();
    protected abstract Class<? extends InputFormat> getInputFormat();
    protected abstract Class<? extends OutputFormat> getOutputFormat();
    protected abstract Class<?> getOutputKeyClass();
    protected abstract Class<?> getOutputValueClass();

}

And concrete test subclass:
public class POIClusterMapreduceTest extends AbstractClusterMapReduceTest{

    private static final String INTEGRATION = "integration";

    @BeforeClass(groups = INTEGRATION)
    public void setup() throws IOException {
        super.setupEnv();
    }

    //@Test(groups = INTEGRATION)
    public void runJob() throws InterruptedException, IOException, ClassNotFoundException {
        boolean result = createAndSubmitJob();
        MatcherAssert.assertThat(result, Matchers.is(true));

        String outputResultAsString = getFileSystem().open(createPath(getOutputPath())).readUTF();
        MatcherAssert.assertThat(outputResultAsString.length(), Matchers.greaterThan(0));

    }

    @AfterClass(groups = INTEGRATION)
    public void tearDown(){
        super.tearDown();
    }

    @Override
    protected Class<Main> getMRJobClass() {
        return Main.class;
    }

    @Override
    protected Class<POIMapper> getMapperClass() {
        return POIMapper.class;
    }

    @Override
    protected  Class<Reducer> getReducerClass() {
        return Reducer.class;
    }

    @Override
    protected Class<TextInputFormat> getInputFormat() {
        return TextInputFormat.class;
    }

    @Override
    protected Class<TextOutputFormat> getOutputFormat() {
        return TextOutputFormat.class;
    }

    @Override
    protected Class<LongWritable> getOutputKeyClass() {
        return LongWritable.class;
    }

    @Override
    protected Class<XVLRDataWritable> getOutputValueClass() {
        return XVLRDataWritable.class;
    }

    @Override
    protected String getInputDatasetName() {
        return "mr-input-data";
    }
}

A: The problem was in terrible maven conflicts. Here are correct maven dependencies:
<dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>${hadoop.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.common.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>${hadoop.common.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <classifier>tests</classifier>
            <version>${hadoop.common.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-test</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
    </dependencies>

And:
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <hadoop.version>2.0.0-mr1-cdh4.1.1</hadoop.version>
    <hadoop.common.version>2.0.0-cdh4.1.1</hadoop.common.version>
</properties>

Here is the base class for testing:
public abstract class AbstractClusterMRTest {
    private static final Log LOG = LogFactory.getLog(AbstractClusterMRTest.class);

    public static final String DEFAULT_LOG_CATALOG = "local-mr-logs";
    public static final String SLASH = "/";
    public static final String MR_DATA_OUTPUT = "mr-data-output";
    public static final String DEFAULT_OUTPUT_FILE_NAME =  "part-r-00000";

    private static final int DEFAULT_REDUCE_NUM_TASKS = 1;

    private Configuration configuration;
    private FileSystem localFileSystem;
    private MiniMRCluster mrCluster;
    private JobConf mrClusterConf;

    /**
     * Always provide path to log catalog.
     * */
    protected String getPathToLogCatalog(){
        File logCatalog = new File(getPathToOutputDirectory()+ SLASH + DEFAULT_LOG_CATALOG);
        if(!logCatalog.exists()){
            logCatalog.mkdir();
        }
        LOG.info("Path to log catalog is: "+logCatalog.getAbsolutePath());
        return logCatalog.getAbsolutePath();
    }

    private String getPathToOutputDirectory(){
        return System.getProperty("project.build.directory");
    }

    public void setup() throws IOException{
        System.setProperty("hadoop.log.dir", getPathToLogCatalog());

        configuration = new Configuration(true);
        localFileSystem = FileSystem.get(configuration);
        mrCluster = new MiniMRCluster(1, localFileSystem.getUri().toString(), 1, null, null, new JobConf(configuration));
        mrClusterConf = mrCluster.createJobConf();
    }

    public void tearDown() {
        if (mrCluster != null) {
            mrCluster.shutdown();
            mrCluster = null;
        }
    }

    /**
     * Use this method to get JobBuilder configured for testing purposes.
     * @return JobBuilder instance ready for further configuration.
     * */
    public JobBuilder createTestableJobInstance() throws IOException{
        return new JobBuilder(mrClusterConf, this.getClass().getSimpleName()+"-mrjob")
                .withNumReduceTasks(DEFAULT_REDUCE_NUM_TASKS);
    }

    /**
     * Pass configured JobBuilder and wait for completion
     * @param jobBuilder is a JobBuilder ready to submit
     * @return job completion result.
     * */
    public boolean buildSubmitAndWaitForCompletion(JobBuilder jobBuilder)
                        throws InterruptedException, IOException, ClassNotFoundException {
        String pathToInputFile = getPathToInputData();
        checkThatFileExists(pathToInputFile);

        Job job = jobBuilder.build();
        FileInputFormat.setInputPaths(job, pathToInputFile);
        FileOutputFormat.setOutputPath(job, createPath(getOutputPath()));

        LOG.info("Submitting job...");
        job.submit();
        LOG.info("Job has been submitted.");

        String trackingUrl = job.getTrackingURL();
        String jobId = job.getJobID().toString();
        LOG.info("trackingUrl:" +trackingUrl);
        LOG.info("jobId:" +jobId);

        return job.waitForCompletion(true);
    }

    /**
     * By declaration input data should be stored in test/resources folder:
     * ConcreteTestClassName/in/getInputDatasetName()
     * Don't forget to override @link{AbstractClusterMRTest#getInputDatasetName()}
     * @return path to input data
     * */
    protected String getPathToInputData(){
        String pathFile = this.getClass().getSimpleName() + SLASH + "in" + SLASH+ getInputDatasetName();
        LOG.info("Path for getting URL to file:" + pathFile);
        URL urlToFile = this.getClass().getClassLoader().getResource(pathFile);

        File file = FileUtils.toFile(urlToFile);
        return file.getAbsolutePath();
    }

    /**
     * Dataset should be placed in resources/ConcreteClusterMapReduceTest
     * @return a name of a file from catalog.
     * */
    protected abstract String getInputDatasetName();

    /**
     * @return path reducer output
     * default is: @{link AbstractClusterMapReduceTestOld#DEFAULT_OUTPUT_CATALOG}
     * */
    protected String getOutputPath(){
        return getPathToOutputDirectory()+ SLASH + MR_DATA_OUTPUT;
    }

    /**
     * @return text lines from reducer output file.
     * */
    protected List<String> getLinesFromOutputFile() throws IOException{
        String pathToResult = getOutputPath()+SLASH+DEFAULT_OUTPUT_FILE_NAME;
        File resultFile = new File(pathToResult);
        return FileUtils.readLines(resultFile);
    }

    public abstract String getEtalonOutputFileName();

    protected List<String> getLinesFromEtalonOutputFile() throws IOException{
        String pathFile = this.getClass().getSimpleName() + SLASH + "out" + SLASH+ getEtalonOutputFileName();
        LOG.debug("path to etalon file: "+ pathFile);
        URL urlToFile = this.getClass().getClassLoader().getResource(pathFile);

        File file = FileUtils.toFile(urlToFile);
        return FileUtils.readLines(file);

    }

    /**
     * Creates @{link Path} using absolute path to some FS resource
     * @return new Path instance.
     * */
    protected Path createPath(String pathToFSResource){
        return new Path(pathToFSResource);
    }

    public void checkThatFileExists(String absolutePathToFile){
        if(! new File(absolutePathToFile).exists()){
            throw new Error("Path to input file is incorrect. Can't run MR job. Incorrect path is:"+absolutePathToFile);
        }
    }

}

Just extend, create your own concrete test class. Get Job from createTestableJobInstance (there is simple builder-wrapper for a Job). Configure it and call buildSubmitAndWaitForCompletion


text:
Q: Multiple ONNX models using opencv and c++ for inference I am trying to load, multiple ONNX models, whereby I can process different inputs inside the same algorithm. Let's assume that model 1 would receive as input an image and output a set of 6 values (int) related to this image. The second model would also receive an image but output a binary classification instead.
So far, I have managed to successfully run on a single model. However when I try to load the second one I got an error:
// Load first .onnx model using OpenCV's DNN module
cv::dnn::Net net = cv::dnn::readNet("model_1.onnx");
net.setPreferableBackend(cv::dnn::DNN_BACKEND_DEFAULT);
net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);

// Load second .onnx model using OpenCV's DNN module
cv::dnn::Net net_2 = cv::dnn::readNet("model_2.onnx");
net_2.setPreferableBackend(cv::dnn::DNN_BACKEND_DEFAULT);
net_2.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);

Everything runs without errors until this point. But I got errors when trying to retrieve data from the second model.
// Forward first model
 net.setInput(blob);
 net.forward(output_blobs, output_names);
// Forward second model
 net_2.setInput(blob);
 net_2.forward(output_blobs_2, output_names_2);

Any help or advice will be more than welcome.


text:
Q: ¿Que significa la diagonal invertida en corchetes [d\u]? Inicialmente tenia el problema de validar si una cadena de texto solo contenía letras u o d
Encontré un ejemplo: new RegExp("^[d|u\d|u]"+$)
Me funcionó pero no entiendo bien la expresión de diagonal invertida dentro de los corchetes.
¿Alguien me podría ayudar explicando esa expresión?

A: La diagonal invertida significa dos cosas dependiendo el contexto en el que se encuentre:

*

*Define un escape de caracter especial para poder ser usado como literal en la RegExp.

*Significado especial dependiendo de letra o letras que lleve delante.

Por ejemplo, los caracteres \ y " pueden escaparse dentro de un string usando \ esto se hace para no tener que concatenar strings ni tampoco reemplazar el tipo de comillas que encierran la cadena, un ejemplo:

console.log("\"Edgar \\ alan \\ poe\"");

De esta manera aunque usemos comillas dobles ("") para encerrar a nuestro texto podemos usarlas.
En una expresion regular es lo mismo, la diferencia es que para construir una regex no necesitamos ningun tipo de comillas ni al inicio ni al final:

console.log(/\"Edgar \\ alan \\ poe\"/g);

Ahora bien, a lo que me refiero de que en ciertos casos puede tener un significado especial es porque en los casos donde en una RegExp le procedan ciertas letras en especifico el significado de acción de la RegExp cambia, como podemos verlo aquí en este enlace:
RegExp
De hecho dentro de ese enlace podemos percatarnos que en tu expresión regular el significado de una de las partes donde se usa el símbolo \ es distinto de simplemente poder "escapar" caracteres especiales:
new RegExp("^[d|u\d|u]"+$)

Mas especificamente esta parte de aquí:
\d

Donde según la pagina anterior mencionada esto no significa que estamos escapando el caracter d, significa:

Coincide con un digito básico de 0-9 en el alfabeto latino, es
  equivalente a: [0-9]

De hecho poniendo el fragmento entero que te interesa::
u\d

Esta expresión equivale a decir:

Encuentra un valor que contenga el caracter u y seguido a el cualquier numero entre 0 y 9.

Por lo que no hay que perderse, aquello que este alfrente del caracter \, si se trata de un carácter especial simplemente será escapado, pero si se trata de un carácter con un significado especifico en la RegExp no será escapado, sino que adquirirá las acciones o el significado especial de la RegExp.
Para saber cuales caracteres o conjunto de caracteres tiene un significado especial al colocarlos al lado de \ debes mirar la tabla mencionada en la anterior pagina por si te interesa.
Puesto que mirar y explicar aquí todos y cada uno de ellos sería algo muy tedioso y largo, hay muchos significados que descubrir en las RegExp, esa pagina puede serte de ayuda en su descubrimiento.


text:
Q: Map not show in map fragment after generated signed apk (debug and release) but show when connected through data cable I generated debug api key on Windows like this :
c:\Program Files\Java\jdk1.7.0_09\bin>keytool.exe -list -v -keystore "c:\Users\MyUsername.android\debug.keystore" -alias androiddebugkey - storepass android - keypass android
after that I register SHA1 to Google Map APIs console, and I get Google Map API key.
I put everthing to androidmanifest.xml, to the point...It is already show the map on map fragment when I debug use data cable to android device. But when I generated signed apk (debug and release) the app did not show map on fragment (it is a blank map).
How to correct this issue? I mean how to show the map when generated signed apk?


text:
Q: How to update data continuously to another file I am trying to update stock market data for 120 symbols in another file in python.
file1.py
#Subscribing to stock exchange data through an api
ret=api.start_websocket(subscribe_callback=data_update)

def data_update(quote):

    print(quote)

#To pull data continuously

while True:

    pass

Examples of quote:
quote{'symbol':'1','price':100.00,'volume':43100}

or
quote={'symbol':'113','price':124.15,'volume':12429}

and so on
Please suggest me a fast way to continuously update the data to another file, say, file2


text:
Q: Hijacking a client socket I have set up a server socket (plain raw socket) listening on port A. A client now connects to this server. OS opens up a port for the client for this purpose. Say port B is allocated to this client. Now my question is, can a 3rd script connect to this port B and send data. Or in other words can I spoof a response to the client as if it was coming from the server? I tried spoofing it using scapy, but it wasnt working.
server.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", A))
s.listen(10)
ns, cli_addr = s.accept()
time.sleep(30) # so that i can trigger my 3rd script

goodclient.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", A))
print s.getsockname() # to get the local port of client - B
s.recv(1024)

badboy.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", B)) # connection refused error
s.send("hihihi")

scapybadboy.py
pack = IP(src="localhost", dst="localhost") / TCP(sport=A, dport=B) / "Hello"
send(pack) # Packet sent but not received by the client

A: Because server and client using SOCK_STREAM sockets, they both aware of TCP session(including port, IP and (SEQ_NUMBER,ACK_NUMBER)), so when session is already in process, you will have to perform TCP hikacking and IP spoofing in order to send messages in stream.
In other words, you will have to guess(or steal) ACK number of server in order to send fake messages to client using badclient.
However, if you will make somehow goodclient answer you and not a server you should run the following:
iptables -A FORWARD -j NFQUEUE --queue-num 1 , because your operating system doesn't  know about session that you just "opened" with goodclient and it will send RST packet. This command will prevent it.


text:
Q: How do I spawn many cancellable timers using Tokio? How do I use Tokio to implement a fixed number of timers that are regularly reset and canceled across threads? When a timer expires, a callback will be executed.
An API similar to that of Go's time.AfterFunc is essentially what I desire:
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.AfterFunc(time.Hour, func() {
        // happens every 2 seconds with 1 second delay
        fmt.Println("fired")
    })

    for {
        t.Reset(time.Second)
        time.Sleep(time.Second * 2)
    }
}

The only crate I've found that implements a (sufficiently) similar API is timer and it does so in a very naive fashion, by spawning 2 threads. This quickly becomes prohibitive when the timers are reset often.
The obvious answer is to use Tokio, the question is how to do this elegantly.
One option is to spawn a new green thread every time a timer is updated and cancel the previous timer using an atomic, by conditioning the execution of the callback on this atomic, such as this pseudo-Rust:
tokio::run({
    // for every timer spawn with a new "cancel" atomic
    tokio::spawn({
        Delay::new(Instant::now() + Duration::from_millis(1000))
            .map_err(|e| panic!("timer failed; err={:?}", e))
            .and_then(|_| {
                if !cancelled.load(Ordering::Acquire) {
                    println!("fired");
                }
                Ok(())
            })
    })
})

The problem is that I maintain state for timers which are already canceled, potentially for minutes. In addition, it does not seem elegant.
Besides tokio::time::Delay, tokio::time::DelayQueue also seemed applicable. In particular, the ability to reset and cancel timers by referencing them with the Key returned from "insert".
It is unclear how to use this library in a multi-threaded application, namely:

The return value represents the insertion and is used at an argument to remove and reset. Note that Key is token and is reused once value is removed from the queue either by calling poll after when is reached or by calling remove. At this point, the caller must take care to not use the returned Key again as it may reference a different item in the queue.

Which would create a race-condition between a task canceling the timer by its key and the task consuming timer events from the DelayQueue stream — resulting in a panic or canceling of an unrelated timer.

A: You can use the Select combinator from futures-rs with Tokio. It returns the result of the first completed future then ignores/stops polling the other one.
As a second future, we can use a receiver from oneshot::channel to create a signal to finish our combinator future.
use futures::sync::oneshot;
use futures::*;
use std::thread;
use std::time::{Duration, Instant};
use tokio::timer::Delay;

fn main() {
    let (interrupter, interrupt_handler) = oneshot::channel::<()>();

    //signal to cancel delayed call
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(500)); //increase this value more than 1000ms to see is delayed call is working or not.
        interrupter
            .send(())
            .expect("Not able to cancel delayed future");
    });

    let delayed = Delay::new(Instant::now() + Duration::from_millis(1000))
        .map_err(|e| panic!("timer failed; err={:?}", e))
        .and_then(|_| {
            println!("Delayed Call Executed!");

            Ok(())
        });

    tokio::run(delayed.select(interrupt_handler).then(|_| Ok(())));
}

Playground


text:
Q: Windows won't release lock on drive tray after burning a disc I have two bluray drives of the same exact model and brand installed in my computer. I occasionally like to use either of them to burn CDs or DVDs using various software (Windows Media Player 12, Zune, ImgBurn, Windows DVD Maker, etc). It will get through the burning process and complete successfully, but with either drive, it will not release the resource lock on the disc, meaning the disc continues to spin, the access light flashes continuously, and I cannot eject the drive. When I use ImgBurn to burn a disc, it will typically do a verify step after burning, which cycles the drive tray. Because the lock is not released, it will not be able to cycle the drive tray. Right now, I've just burned a CD in Windows Media Player, and it completed successfully (I can even play the CD in WMP) but I cannot eject the drive. The only reliable way I've found of getting the disc out is to reboot the machine and then when it powers back up I can eject the disc.
Why would this be happening? It's consistently doing this 100% of the time. I've updated my drivers but it didn't change anything.
This is the specific drive listing on TigerDirect: Lite-On iHBS212-08 12X Internal Blu-Ray Writer
I'm using Windows 7 Professional x64 SP1.
Has anyone run into this kind of issue before? What can I do to fix it?
EDIT
Note, I also just updated the firmware for the drives, which didn't help. Additionally, I unplugged one of them (on the off chance that the fact that there were 2 identical drives was causing conflicts somewhere) and it made no difference.
Also, I found a way to force the ability to get the drive tray open without rebooting. Through ImgBurn, I went to the Tools menu, then Drive, then clicked "Close session" and it let me open the tray again.
Also of note, if I instead tried clicking "Eject" in the Drive menu in ImgBurn, it gave me a descriptive error message, basically stating lots of technical junk and the error "Logical unit not ready - Long write in progress". I think this long write is what's keeping the drive occupied. But it doesn't appear to ever finish. So is this a driver issue then? It does happen across programs.
EDIT #2
Per Paperlantern's suggestion below, I tried using a Linux LiveCD session to burn a disc. I booted into Kubuntu and burned a small audio CD using k3b. Interestingly, it worked perfectly. It burned the CD and then ejected the disc at the end. So this apparently is not a hardware issue, but a Windows one.
EDIT #3
After some troubleshooting with the help of a couple people here, I've determined that the likely cause is a problem with how Windows is issuing commands to ATAPI devices. This Windows installation originally was installed to an IDE drive, but it was switched over to RAID without doing a reinstall. This may have put Windows in a state where it isn't properly communicating with the drives. I did a fresh install of Windows on the machine (after backing up my previous installation) and did a couple test burns and Windows operates properly, ejecting the drive at the end of the burn job. I will restore my backup image and proceed from there.

A: This sounds to me like it's a problem that Windows is having interfacing with your motherboard's chipset. Specifically, in speaking ATAPI to the CD Drive. Things I would recommend:
(NOTE: Please don't try more than one of these things at a time. It's never fun to solve something and not know exactly which step was the final piece to the puzzle. =) )
Update Motherboard Chipset
Go to the manufacturer's website for your motherboard and download the latest chipset drivers. It will require a reboot, but shouldn't require any kind of pre-Windows boot media. You should be able to update from within Windows.
Update storage controller
If your PC has a storage controller in it or a storage chipset (perhaps Matrox or Nvidia, as is the case in some consumer level PCs), update those chipsets / drivers.
Update BIOS
It's possible that part of the problem is in the BIOS's presentation of the attachment. Consider
updating to the latest BIOS from your PC manufacturer for the model in question.
Move the drive to a different SATA channel
If you have multple SATA ports, especially if you have ports that are on different controllers, move the optical drive to a new port on the motherboard.
Curiosities
I would be interesting in knowing if your BIOS is in IDE or AHCI mode. I would expect it to be in IDE mode, but it's possible that it's in AHCI.

EDIT 1
After finding out that the PC was switched from IDE to RAID/AHCI mode without a reinstall of Windows (and apparently it was something of an ordeal to get Windows to handle the change correctly) I believe that this might be the cause. Windows may be handling ATAPI communications slightly wrong now. I'm not sure yet what the solution would be. Perhaps a repair installation.

A: So this happens on any and all types of burns? To alleviate ANY issues with current driver or software being the problem, what I would do, being as frustrated as you probably are, is to load a copy of linux mint or ubuntu linux onto a spare drive in the machine. Or use the live CD in one drive and try to burn something on the other drive, to see if the problem occurs in another OS and software environment altogether. It could at least tell us if the problem is the hardware (maybe bad batch of CD ROM drives with messed up cache or something equally bizarre?), or if the issue resides with your OS or driver in some way.
If it is OS related, running a sysprep on the machine would force a redetect and reinstall of the key components involved (CDROM drivers and the ATAPI interface software), and will most likely solve this issue since a new install worked.

A: Have you tried using different burning software? I'm a big fan of ImgBurn but too have found it often doesn't release the drive. Normally if I launch MakeMKV it will allow me to eject the disc (although it sounds like you already have a workaround).
Lee


text:
Q: Why aren't read-only queries executing concurrently? I have a Django app using either sqlite or Postgres.  (I've tried both and encountered the same problem.)  Requesting a particular endpoint results in a read-only query like this that takes 1.5-3 seconds before the response.
The problem occurs when Django receives simultaneous requests to this endpoint, which is common in my application.  I expect Django to process the requests in parallel and still return a response in 3-4 seconds.  Instead, I get no response for any of the queries until 9-12 seconds.  In know that Django supports concurrent requests, so I suspect this is a database issue.
What am I missing?

A: The problem is that I was using Django's built-in development server (runserver).  The problem goes away using Gunicorn.  It doesn't matter if the database backend is Sqlite or Postgres.


text:
Q: i'm getting syntax error near the table it says not able to know what exactly needs to be done  {
            String Source = @" Data Source = (LocalDB)\MSSQLLocalDB;" + @"AttachDbFilename=c:\users\meghanaa\source\repos\datagrid\datagrid\trialdatabase.mdf;" + "Integrated Security = True";
        SqlConnection con_2 = new SqlConnection(Source);
            con_2.Open();
            for (int i = 0; i < dgv1.Rows.Count; i++)
            {
                cmd = new SqlCommand(@"INSERT INTO Table([sl],[quetions]) VALUES(@"+dgv1.Rows[i].Cells["sl"].Value+" , @"+dgv1.Rows[i].Cells["questions"].Value+",@"+ dgv1.Rows[i].Cells["op A"].Value + ")",con_2);

                cmd.ExecuteNonQuery();
                con_2.Close();
                MessageBox.Show("data saved");
            }

        }

A: The issue is due the the Table name given to your database table. In most RDBMS, this is reserved word. Ideally, you should avoid using this in naming your database objects. Refer this link for list of reserved words in SQL Server.
If you still want to use it OR cannot change it anymore, try putting it in square bracket like [Table].
Apart from the question you asked, you have another major issue in your code. Your code is susceptible to SQL Injection Attack. Please consider using parameter queries. If you are interested in using any ORM (even simpler like Dapper), that handles this issue and also promotes many best practices.


text:
Q: managing pubnub image subscriptions I am implementing a chat application with image sending feature using pubnub, I am able to publish the images.
But while subscribing i am receiving the image link instead of the actual image . I get the message as a JSON object as
'''
{"nameValuePairs":{"imageurl":"example.com"}}
''' .
How do i use it to put it into an Imageview. Here is my code
(The publish handler)
'''
var image = JSONObject() as JSONObject
image.put("imageurl","example.com")
'''
The message recieved in the subscribe handler is a json object and not the image . Why isn't pubnub catching my image from the external server.

A: So PubNub won't download and move the image for you, the PubSub messaging bus will move the URL from your publish to the subscribers of the channel.
Because of this I recommend implementing a 'type' of message that represents your image.
eg:
{
        "content": "Hi Team, anyone fancy lunch today?",
        "type": "Text",
}

An image example:
{
      "type":"image",
      "thumbnailURL":"https://cdn.image.server/thumbnail",
      "fullURL":"https://cdn.image.server/full"
}

As you know that the incoming message is a 'type' of image you can then place the URL in a factory and load that way:
URL url = new URL(pubnubMessage.fullURL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

Hope this helps!

A: It's probably easiest to use a library called Glide. This will manage the downloading and scaling of the image for you. Follow the setup instructions and then simply after receiving the image url use the example code like this:
Glide
    .with(activity or fragment, etc.)
    .load(urlFromResponse)
    .centerCrop() // If you want to crop it
    .placeholder(R.drawable.loading_spinner) // also optional
    .into(myImageView);


text:
Q: Ubuntu 18.04 .local domain dns lookup not working I'm using a Raspberry Pi 3 with Ubuntu 18.04. At my company we have a DNS server and a couple of domains with ".local".
I know technically this isn't correct and it should be ".lan" instead, because .local is reserved for multicast dns. But that's the way it is and it can't easily be changed. So on my windows machine I can ping and browse to those domain names without trouble. On my Ubuntu however I can not.
I can not use IPs because some domains are on the same machine and the IIS webserver sorts things out what goes where.
I have searched and it comes up quite often:

*

*https://smallbusiness.chron.com/resolving-local-ubuntu-38861.html

*Why do none of my local servers resolve?

*ubuntu server not resolving LAN hostnames
However changing /etc/nsswitch.conf doesn't do the trick for me.
I tried

*

*hosts: files mdns4_minimal [NOTFOUND=return] dns myhostname # default

*hosts: files dns

*hosts: files mdns4_minimal [NOTFOUND=continue] dns myhostname

*hosts: files mdns4 [NOTFOUND=return] dns myhostname

*hosts: files mdns4 [NOTFOUND=continue] dns myhostname

*hosts: files dns mdsn4_minimal myhostname

*hosts: dns

*a few others

None of which worked. I tried rebooting after a change too.
I tried to tell avahi that the domain-name=alocal in /etc/avahi/avahi-daemon.conf, didn't work after service restart, didn't work after reboot.
After this not working, I tried disabling the avahi-daemon service entirely.
sudo systemctl disable avahi-daemon

After a reboot I tried a couple of permutations in /etc/nsswitch.conf again, with no effect.
with my current settings in hosts (files dns) I get this response:
dig login.name.local # not the actual name

; <<>> Dig 9.11.3-1ubuntu1.1-Ubuntu <<>> login.name.local
;; global options: +cmd
;; Got answer:
;; WARNING .local is reserved for Multicast DNS
;; You are currently testing what happens when an mDNS query is leaked to DNS
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33538
;; flags: qr rd ra; QUERY: 1, ANSWER:0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;login.name.local. 0     IN     A

;; Query time: 2msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Thu Aug 23 10:51:50 CEST 2018
;; MSG SIZE  rcvd: 56

However when I instruct dig to query the server directly I get the correct answer:
dig @dnsIP login.name.local
; <<>> Dig 9.11.3-1ubuntu1.1-Ubuntu <<>> login.name.local
; (1 server found)
;; global options: +cmd
;; Got answer:
;; WARNING .local is reserved for Multicast DNS
;; You are currently testing what happens when an mDNS query is leaked to DNS
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57866
;; flags: qr aa rd ra; QUERY: 1, ANSWER:1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;login.name.local. 0     IN     A

;; ANSWER SECTION:
login.name.local. 3600 IN    A        serverIP

;; Query time: 2msec
;; SERVER: dnsIP#53(dnsIP)
;; WHEN: Thu Aug 23 10:51:50 CEST 2018
;; MSG SIZE  rcvd: 56

This version of Ubuntu uses netplan with the network manager.
The correct DNS IP is definitely in the list. (in fact it's the primary DNS.)
Also the dnsIp is the same as serverIP, but that shouldn't be an issue.
Ping or connecting via browser and such don't work of course. None use the dns query.
I'm at a loss at what to do. Certainly we can't switch to a different domain name.
I put the servername into /etc/hosts but that's just a temporary solution.

A: For me working way for Ubuntu 18.04 is:
Edit avahi conf:
sudo vim /etc/avahi/avahi-daemon.conf

and change .local to .alocal :
[server]
domain-name=.alocal

then, open resolved.conf:
sudo vim /etc/systemd/resolved.conf

and uncomment and edit Domains:
[Resolve]
...
Domains=yourdomain.local
...

and finally restart services:
sudo service systemd-resolved restart
sudo service avahi-daemon restart

A: The accepted answer did not resolve my issue. It was nothing to do with avahi - I did not have avahi service installed.  I have my system set to get its IP AND its DNS server settings from DHCP. However, the DHCP supplied DNS was not being checked for queries using .local
The real issue is that Ubuntu 18.04 has its resolv.conf sym-linked to a stub file that points to the localhost for name resolution.  Localhost DNS name resolution means that the system refuses to check the supplied DNS server for .local names, believing (incorrectly) that such names are invalid.  This is the default setup of /etc/resolv.conf:
ls -la /etc/resolv.conf
lrwxrwxrwx 1 root root 39 Jan 22 13:26 /etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf

content of the stub file is (comments removed):
 cat /run/systemd/resolve/stub-resolv.conf
 .. removed comments..
nameserver 127.0.0.53
    search reddog.microsoft.com

the 'real' resolve conf has the 'correct' DNS setting (from DHCP):
cat /run/systemd/resolve/resolv.conf

..removed comments..
nameserver 10.168.200.250 # This is my server that can resolve .local
nameserver 208.67.220.220 # these are optional, fallback DNS servers
nameserver 208.67.222.222
# Too many DNS servers configured, the following entries may be ignored.
nameserver 8.8.8.8
search reddog.microsoft.com

In order to make the system use your preferred DNS resolver instead of localhost, you change the symlink to point to /run/systemd/resolve/resolv.conf instead of /run/systemd/resolve/stub-resolv.conf :
sudo rm -f /etc/resolv.conf
sudo ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf

Immediately after this, resolution of .local started working. No need to reboot or restart any service.

A: I faced a very similar issue (if not exactly the same) on Linux Mint 19 (Tara). I've managed to solve it by combining 3 different pieces of information.
It seems to all be related to recent changes with systemd-resolved.
First, yes I've needed to configure /etc/nsswitch.conf as you did and would expect. As long as dns comes before mdns you should be good. I ended with simply:
hosts:          files dns myhostname

ref: https://unix.stackexchange.com/a/457172/271210
Prior to upgrading to this version of Mint, this is the only thing I needed to do. Now I also ended up making the below two other changes to get it working...

After that I've configured my search domain so systemd-resolved would work as I wanted. So I've edited the file /etc/systemd/resolved.conf, the Domains setting under the [resolve] section. In my case it ended up looking like:
[Resolve]
#DNS=
#FallbackDNS=
Domains=trilliant.local
#LLMNR=no
#MulticastDNS=no
#DNSSEC=no
#Cache=yes
#DNSStubListener=yes

ref: https://askubuntu.com/a/1031271/872881
I've also changed the avahi configuration to something else ("mdns" if I remember correctly, but it doesn't matter). It shouldn't be required however from my understanding. Just adding for completeness.

But none of it worked until I've called the following:
sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

ref: https://askubuntu.com/a/938703/872881
After calling this, everything started working perfectly and as expected!
So it's possible I didn't really need to change the /etc/systemd/resolved.conf file but I kept this change since it made sense and allows me to only type a machine's name, without the complete FQDN, for DNS resolution to work.

A: What worked for me was adding the local DNS as a nameserver to /etc/resolvconf/resolv.conf.d/head (as described here).

*

*Install the resolvconf package.
sudo apt install resolvconf

*Edit /etc/resolvconf/resolv.conf.d/head and add the following:
nameserver 8.8.4.4
nameserver 8.8.8.8

*Restart the resolvconf service.
sudo service resolvconf restart

The fix should be permanent.

A: This worked me on several Ubuntu systems:
https://github.com/lathiat/nss-mdns#etcmdnsallow
Essentially put two lines in /etc/mdns.allow:
.local.
.local

And you might need to change /etc/nsswitch.conf to use the mdns4 module instead of mdns4_minimal. Notably this necessary on a Ubuntu Server box, but not on my Kubuntu desktop.

A: For 20.04:

*

*I updating dns to use a local dns server (gnome 'wired settings' config)

*I adding local domain in: /etc/systemd/resolved.conf & Domains=domain.local

*Then restarted the service: service systemd-resolved restart
Thanks for this thread helping me get this working.

A: On Ubuntu Server 18.04/20.04 we were unable to resolve hostnames under our corpname.local domain, despite other name resolution taking place through our AD DNS server. What fixed it for me was to edit /etc/systemd/resolved.conf and add:
DNS=x.x.x.x
Domains=corpname.local

where x.x.x.x is the IP of our AD DNS server. Then run service systemd-resolved restart.
This to me seems cleaner than the various solutions posted above which involve adding symlinks to change which resolve.conf the system is using etc.

A: My situation was similar but somewhat different: We use server names like myserver on Windows but this did not work on Ubuntu 16.04 and I had to use myserver.mycompany.local. After upgrading to 18.04, I got the following behavior:
$ ping myserver.mycompany.local
ping: myserver.mycompany.local: Name or service not known

$ ping myserver
PING myserver.mycompany.local (192.168.x.y) 56(84) bytes of data.
64 bytes from myserver.mycompany.local (192.168.x.y): icmp_seq=1 ttl=62 time=3.05 ms
...

I simply had to replace myserver.mycompany.local with myserver in my applications.


text:
Q: Strange behaviour of array_keys I've got a short question that I've been wondering about for a while. There is a perfect workaround, but I'd like to know what the problem really is.
I've got an array ($lines) consisting of underlying associative arrays. I want to get the indexes of one (basically any random one) of those underlying arrays, so I use:
$headers = array_keys($lines[0]);

However, this gives me back the following error:

Warning:  array_keys() expects parameter 1 to be array, null given

But then, when I use this instead:
$line0 = $lines[0];
$headers = array_keys($line0);

Everything works exactly as I want it to. Now as far as I can see, these two should be perfectly equivalent, so I was wondering if this is a bug in PHP, or if I just fail to understand something here.
PHP version is 5.3.1
The $lines array looks like this in my test case:
Array (
    [0] => Array
        (
            [id] => 00
            [name] => John Doe
        )
    [1] => Array
        (
            [id] => 007
            [name] => James Bond
        )
)

A: I can't reproduce.
I wrote the following file:
<?php

$lines = array(
    array("A" => 1, "B" => 2, "C" => 3),
    array("A" => 1, "B" => 2, "C" => 3),
    array("A" => 1, "B" => 2, "C" => 3)
);

echo "<pre>";
var_dump(array_keys($lines[0]));
echo "</pre>";

And it outputs correctly:
array(3) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "C"
}

So I guess it's either a bug in your program or in your php version but nothing "normal".

A: Try and write out the issue in as few lines as possible to see if you can recreate, if so then you need to submit to http://bugs.php.net


text:
Q: How to scan and connect to advertising BLE devices from C++ code? I'm trying to search and connect to advertising Bluetooth Low Energy devices from C++ code.
I would like a piece of code to use laptop's wireless chip to discover and connect to BLE devices, regardless of their GATT Services.
I want in fine to use GATT properties (Services, Characteristics, Descriptors, Notification).
Programmatically
I have the BluetoothLEAdvertisementWatcher Class documentation from Windows API.
I tried to make working this example but without good results.
I also tried this example, but no success.
Manually
I figured out using Windows 10 Action Center, and use manual pairing to connect devices (because Windows con see and connect my device).
Then I could use directely the Windows.Devices.Bluetooth.GenericAttributeProfile Namespace
Is there a way to implement that automatically?

A: Hello Raphaël and welcome to stackoverflow. When you say "without good results" or "but no success", you should detail why (compilation error, runtime error...).
I used this piece of code:
Getting BLE Beacons in C++ Windows 10 Desktop Application
It compiles under Win10, so should the third link you posted (https://github.com/urish/win-ble-cpp) as it's very similar if you look at the includes here. Just note that this is not regular win32 projects: from Visual Studio you must create a new "Windows"/"Universal" C++ project, else they won't compile.
Alternatively, if you're OK with using a 3rd party library, you could simply use QtBluetooth, recent version supports windows 10. Then you can easily access BLE features from aregular win32 project.


text:
Q: How to give onPressed a method in custom button flutter i have custom button and i want to add method in my onpressed from my parameter,unfortunately i'm still stuck what type should i use in my custom button parameter, curently i hard code the onpressed method and pass a string route to navigate the problem is not all my button is made to navigate there is one button to logout, i already used void in my parameter but it's still doesn't work.
here is my custom button
FlatButton buttonMenu(String title, IconData icon, String route) {
    return new FlatButton(
      shape: new RoundedRectangleBorder(
          borderRadius: new BorderRadius.circular(25.0)),
      color: Colors.blueGrey,
      child: new Container(
        height: 50.0,
        width: 120.0,
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new Padding(
              padding: EdgeInsets.only(right: 10.0),
              child: new Icon(
                icon,
                color: Colors.white70,
                size: 30.0,
              ),
            ),
            new Text(
              title,
              style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.w300),
            ),
          ],
        ),
      ),
      onPressed: () {
      Navigator.of(context).pushNamed('/$route');
      },
    );
  }
}

and here is how i call the custom button
 buttonMenu('MVP Arc', Icons.star, 'EmployeeScreen')

and what i want is i can send method in my parameter to my onpressed so it will be like this
buttonMenu('MVP Arc', Icons.star, myMethod())

my method for navigate
void _navigate(String route){
    Navigator.of(context).pushNamed('/$route');
  }

A: The accepted answer for passing parameters no longer seems to work on newer versions of Flutter.
In case someone searches for a similar issue, the modifications below worked for me.

Modifying Raouf Rahiche's answer, the working method as of 2019. October 28 is as follows.
Update: added mising flutter version number below
Flutter version: 1.9.1+hotfix.5
Dart version: 2.5.0

Using the existing typedef:
typedef VoidNavigate = void Function(String route);

Using the type changed in a small way, you have to pass the parameter to the button separately.
FlatButton buttonMenu(
   String title,
   IconData icon,
   VoidNavigate onCustomButtonPressed,
   String route //New addition
) {
   ...
}

Calling it now:
onPressed: () { onCustomButtonPressed(route); },

Passing the function:
buttonMenu('MVP Arc', Icons.star, _navigate, 'EmployeeScreen')

A: Here is what worked for me:
Flutter Version : 2.6.0
Dart Version : 2.15.0
in my customButton function:
Widget customButton(VoidCallback onPressed)

{
....
onPressed : onPressed.call(),
}

and no other changes needed.

A: the onPressed type is VoidCallback so make your parameter like this this type.
FlatButton buttonMenu(String title, IconData icon, VoidCallback onCustomButtonPressed )

and when you call it pass a reference to it
buttonMenu('MVP Arc', Icons.star, myMethod)

and don't forget to do the same in your function body
  onPressed: onCustomButtonPressed ,

UPDATE:
if you want to pass parameters you have to declare your own Signature :

Example in your case :

typedef VoidNavigate = void  Function(String route);

and then use this new type
FlatButton buttonMenu(String title, IconData icon, VoidNavigate onCustomButtonPressed)

call it like this
onPressed: (){onCustomButtonPressed},

and you pass your function like this
buttonMenu('MVP Arc', Icons.star, _navigate('EmployeeScreen'))

or you can just do it like this as @Kirill Shashov said
buttonMenu('MVP Arc', Icons.star, () {_navigate('EmployeeScreen');})

A: the only we need to do is  add .call() to the end of the function to be void.
onPressed: ()=>onPressed   to onPressed: ()=>onPressed.call()


text:
Q: Android system stops application when launching Media Intent I am launching a media intent to take a photo. After the user took a picture and gets back to the previous activity the whole application has restarted.
As this doesn't happen all the time, I think my application goes to the background and android kills it when the device has low memory.
Is there any way to keep my application from going to the background?
Thanks!

A: I can think of two possibilities...

*

*It's not killing the activity, but the intent launches a new activity. You can stop this by  putting a tag in your manifest.xml as an attribute in the activity tag like this:
<activity
    android:name=".nameOfActivity"
    android:launchMode="singleTop" />

*Make sure that the media intent is under the activity to handle the photo, and not a main/launcher activity.

A: This is normal behavior in Android, all activities currently not visible on screen (after onStop) can be killed without notice (i.e. onDestory) if the system has low memory.
This usually happens to our app on one of our test devices which has memory issues regardless of our app.
You can usually recreate this behavior when you open the camera via the intent, and then rotate the device (portrait to landscape), this will also kill and re-create your app.
To solve this you need to extend onSaveInstanceState and use the savedInstanceState parameter in your onCreate to pass from your killed instance to your new instance some important information (like "we're in the middle of getting a pic from the camera").

A: IMO two options:

*

*Implement onSaveInstanceState/onRestoreInstanceState
or

*Make your activity a service.

A: I faced this issue and got a solution after R&D for it.
Set Target Android 4.0 and then add this line in AndroidManifest.xml of activity:
android:configChanges="screenLayout|uiMode|orientation|screenSize|smallestScreenSize"
It works for me.

A: When you start media intent use following method instead of startActivity(intent)
startActivityForResult(intent, REQUEST_CODE); //private int REQUEST_CODE = 232

When the started activity finishes, your calling activity will be started. You need to handle this using following function
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
      //Perform your task
      }
}

The activity started need to override follwoing method
@Override
    public void onBackPressed() {
        Intent intent = new Intent();
        setResult(REQUEST_CODE, intent);
        super.onBackPressed();
    }

startActivityForResult() is an special way for starting activity for a specific task and get the desired result. The called activity will send the data back.
You can use the method putExtra() & getExtra in intent to send and receive data between two activity.
This will solve your problem hopefully.
If you have doubts comment. And if possible share your code so it can be more clear.


text:
Q: Should I use "is" or "are" between two nouns (I think) in this phrase? I'm not really sure what I should use in this case, normally I can identify the difference but this time for some reason i cannot.
sentence: "In this function stringify and parse is necessary"
Is necessary
or
Are necessary

A: If you are talking about a singular operation (stringify and parse), then you would use "is".

In this function, stringify and parse is necessary.

If you are talking about two operations (stringify and parse), then you would use "are".

In this function, stringify and parse are necessary.

It is likely that you mean the second.


text:
Q: Why TypeScript gives me a duplicated identifier error without reason? Why TypeScript gives me a duplicated identifier error without reason?
That was pretty strange. That only happen when I compiled ts:

How could that possible to get a duplicated identifier error if I only have one class?
But when I deleted 'test.js' file, everything back to normal:

but that was also not possible to use ts without compile it.
What's happen?

A: You have to put the compiled JS files in a different directory.
Now you have class MyClass present in both test files.
P.S. Naming your files test.xx is not a handy case, many languages have native modules named test, and the OS often has a command test


text:
Q: How can ensure async calls in an event handler in an extension service worker run to completion? I have a service worker in my extension which listens for an action:
chrome.action.onClicked.addListener(async function(tab) {
  await performAction();
});

According to the docs, the service worker can be stopped at any moment. How can I ensure my performAction is not interrupted at some async call?


text:
Q: IntelliSense VSCode show "name must be a namespace nameC/C++(725)" on "using namespace nvcuda;" Hi everyone actually I'm programming on Cuda and I'm testing a simple tensor core example, but i have a problem with intelliSense, practically its show me errore on this commands (see image) and I dont know why, because when i compile and run programm (with tasks) its work correctly, some ideas ?
Errors:

Entire code:
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>
#include <mma.h>

using namespace nvcuda;

// The only dimensions currently supported by WMMA
const int WMMA_M = 16;
const int WMMA_N = 16;
const int WMMA_K = 16;

__global__ void wmma_example(half *a, half *b, float *c,
                             int M, int N, int K,
                             float alpha, float beta)
{

    // Leading dimensions. Packed with no transpositions.
    int lda = M;
    int ldb = K;
    int ldc = M;

    // Tile using a 2D grid
    int warpM = (blockIdx.x * blockDim.x + threadIdx.x) / warpSize;
    int warpN = (blockIdx.y * blockDim.y + threadIdx.y);

    // Declare the fragments
    wmma::fragment<wmma::matrix_a, WMMA_M, WMMA_N, WMMA_K, half, wmma::col_major> a_frag;
    wmma::fragment<wmma::matrix_b, WMMA_M, WMMA_N, WMMA_K, half, wmma::col_major> b_frag;
    wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> acc_frag;
    wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> c_frag;

    wmma::fill_fragment(acc_frag, 0.0f);

    // Loop over the K-dimension
    for (int i = 0; i < K; i += WMMA_K) {
        int aRow = warpM * WMMA_M;
        int aCol = i;
        int bRow = i;
        int bCol = warpN * WMMA_N;

        // Bounds checking
        if (aRow < M && aCol < K && bRow < K && bCol < N) {
            // Load the inputs
            wmma::load_matrix_sync(a_frag, a + aRow + aCol * lda, lda);
            wmma::load_matrix_sync(b_frag, b + bRow + bCol * ldb, ldb);

            // Perform the matrix multiplication
            wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag);
        }
    }

    // Load in current value of c, scale by beta, and add to result scaled by alpha
    int cRow = warpM * WMMA_M;
    int cCol = warpN * WMMA_N;

    if (cRow < M && cCol < N) {
        wmma::load_matrix_sync(c_frag, c + cRow + cCol * ldc, ldc, wmma::mem_col_major);

        for(int i=0; i < c_frag.num_elements; i++) {
            c_frag.x[i] = alpha * acc_frag.x[i] + beta * c_frag.x[i];
        }

                // Store the output
        wmma::store_matrix_sync(c + cRow + cCol * ldc, c_frag, ldc, wmma::mem_col_major);
    }

}

A: Set CUDA_ARCH variable in c_cpp_properties as follow:
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "__CUDA_ARCH__=750"
            ],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "linux-gcc-x64"
        }
    ],
    "version": 4
}


text:
Q: Is usefull this method Collections.unmodifiableList? Let's me explain, I have been reading (incredible) about make your collections unmodifiable, take a look encapsulate collections, it's an interesting idea, but I can't imagine a practical situation for it.
Can someone explain a practical application of it?

A: It's really useful when you return a list that's a private member of an object, as modifying the list from outside would break encapsulation
e.g. obj.getList().clear(); would clear the list inside the obj (asssuming getList() returns a private member), but if getList() returned a list that was passed into Collections.unmodifiableList then an exception would be thrown

A: It has two main advantages:

*

*While coding you can make a read-only collection class without making a subclass, you can use a generic read-only wrapper on every type of collection (re-usability)

*In the runtime you can create a read-only view of an existing collection without copying the whole collection to a read-only implementation (which is usually expensive)

The latter is often useful when you want to prevent your class users from modifying your own internal collection.
Nowadays it's also considered good design to favor composition over inheritance, which fits this pattern nicely.
Example of 1:
class myComplicatedCollection<T> implements Collection<T> {
     // Code goes here

     // O no, I still have to deal with the read-only use-case.
     // Instead of duplicating almost all of my code or using inheritance I'll use this handy-dandy wrapper
     public Collection<T> readonlyVersion() {
          return Collections.unmodifiableCollection(this);
     }
}

Example of 2:
class myClass {
     private Collection<T> theData;

     // Users need to access the data,
     // but we don't want them modifying the private data of this class
     public Collection<T> getTheData() {
         return Collections.unmodifiableCollection(theData);
     }
}

A: Use it any time you want to safely publish a list and/or enforce immutability.
For example:
// neither the reference nor the contents can change
private static final List<String> codes = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

This list can't be modified inside the class, and could be published safely:
// the caller can't change the list returned
public static List<String> getCodes() {
    return codes;
}


text:
Q: Adding entries to CKEDITOR.stylesSet that involve multiple elements I have a design for a bullet list that has two things:
a. A blue arrow image replacing the list icon
b. A very light dotted border atop and below each list item.
I'm wanting to build this into CKEditor via (CKEDITOR.stylesSet) so that the user can select this particular style of list from a dropdown and not have to write any code to do so.
I have had success to the point where I can create a list with a particular class (and now have that themed), however, am running into issues given that it seems the only way to apply both the dotted line and the blue arrow is to use multiple backgrounds via CSS3, which, SURPRISE, doesn't work in IE8 or below.
If I added some DOM pollution (I.e., surrounded the list item text in a span) I could theme that; however, it seems CKEDITOR.stylesSet only allows for setting one element per style (I.e., I can set ul as an element or li as an element, but there's no way I can use one style to set a class on the UL and surround the text of the child li elements with a span).
Or is there? I'm thinking of falling back to JavaScript for this, but I'm also open to other suggestions to accomplish what I'm doing.
Thanks!

A: There's no need to use background images for either the arrow or the dotted line. You can do both via CSS. All you need CKEditor to do is apply a class to the  (which it sounds like you already are) and then use CSS similar to this:
.styled li {
    border-top: dotted 1px black;
    border-bottom: dotted 1px black;
}
.styled
{
    list-style: square url('http://www.wcb.ny.gov/site_images/blueArrow.gif')
}

Full working example: http://jsfiddle.net/jwynveen/ZhjCK/


text:
Q: How to construct an array of pointer to structure and assign the value to the created structure I'm trying to create an array of pointer with this structure:
struct No {
    int decimal;
    char *binary;
    char *octal;
    char *hexadecimal;
};

and I have two functions to construct the array and print out the array:
void constructArray (No *Number, int size) {
    No **temp = new No *[size];

    for (int i = 0; i < size; i++)
    {
        temp[i]->decimal = rand() % 1000;
        temp[i]->binary = "0";
        temp[i]->octal = "0";
        temp[i]->hexadecimal = "0";
    }
}

void printArray (No *Number, int size) {
    cout << "Decimal\t" << "Binary\t\t\t" << "Octal\t\t" << "Hexadecimal" << endl;
    No **temp = new No *[size];

    for (int i = 0; i < size; i++) {
        cout << temp[i]->decimal << "\t"
            << temp[i]->binary << "\t\t\t"
            << temp[i]->octal << "\t\t"
            << temp[i]->hexadecimal << endl;
    }
}

then I call them inside the main function:
int main() {
    No *number;
    int size = (rand() % 9) + 1;
    constructArray(number,size);

    printArray(number,size);
}

The program was successfully compiled and run but nothing is output. What's the problem with my code? Is there something wrong with the way I initialize the array here? How can I overcome this problem? Thank you very much in advance for your help.

A: I think your intent requires adding a line where you have
for (int i = 0; i < size; i++)
{
    temp[i]->decimal = rand() % 1000;

You should have
for (int i = 0; i < size; i++)
{
    temp[i] = new No;
    temp[i]->decimal = rand() % 1000;


text:
Q: How do I delete local Docker images by repository? I have a bunch of docker images I want to get rid of and it would be convenient if I could remove them by specifying the repository name as it appears when I run docker images. For example if docker images returns:
REPOSITORY      TAG              IMAGE ID            CREATED             SIZE
ui_test         191127_manual    41a7ca9824d6        24 hours ago        1.42GB
ui              git-24fa8d1a     cdd254eff918        24 hours ago        1.44GB
ui              git-31a4b052     9b4740060a62        25 hours ago        1.45GB
ui_test         191122_manual    ba9cb04ce2d8        6 days ago          1.39GB
ui              git-68110e426    f26ef80abc25        6 days ago          1.38GB

what command would I use to remove all of the ui_test images?

A: You can pass image IDs you want to delete to docker rmi:
docker rmi $(docker images -q 'ui_test')

From the docs:

The docker images command takes an optional [REPOSITORY[:TAG]] argument that restricts the list to images that match the argument. If you specify REPOSITORYbut no TAG, the docker images command lists all images in the given repository.


text:
Q: relation model between two models: null value I would like to make a relation between two models User and Task using backbone-relational.
I would like for each Task to get the User model.
The relation between the two model is the following:
taskModel.creator_id = userModel.id

Here is my code (1) (2)
The issue is the following (3):
When I try to fetch the models of task I get for the attributes.user the null value.

(1)
// TaskModel
var Task = Backbone.RelationalModel.extend({

    relations: [
        {
            type: 'HasOne',
            key: 'user',
            relatedModel: User
        }
    ],

    urlRoot: 'url_get_tasks'
});

(2)
// UserModel
var User = Backbone.RelationalModel.extend({

    urlRoot: "url_get_users"

});

(3)
user = new User();
user.fetch();
console.log(user.attributes); // {id: 1, .....}

task = new Task();
task.fetch();
console.log(task.attributes); // {id: 12, creator_id: 1, user: null} ???

Why the task.attributes.user have the null value?

A: Your relation on Task should be something like:
   {
       type: 'HasOne',
       key: 'user',
       keySource: 'creator_id',
       relatedModel: User
   }

(You're expecting it to use creator_id for the association but never told it that.)


text:
Q: solr cache configuration for high performance queries I have configured solr caches for my index in solrcloud 4.3.0.I have also configured autoCommit policy to 1h hard commit and opensearcher false. Though i am not reopening searcher,it seems that after every 1 hour my caches gets flushed and resets.As per my understanding only closing and opening the new searcher can cause caches to be flushed.But i don't understand why this is happening ?

A: Have you tried to change mergePolicy settings? You can read about merging segments here. I guess, your rare hard commits and the size of new segments requires Solr to merge segments, in this case the searcher should be reopened anyway.


text:
Q: Ripping DVDs to 700 MB video files When downloading movies on torrent websites, usually they come as 700 MB video files and with the .avi extension.
In one single DVD I have 4~6 movies and they play very nice (with good quality) in my DVD player!
I've downloaded Handbrake and DVD43. But I don't know the settings to get those nice results. How can I do it?

A: The AVI extension has nothing to do with it's format. AVI is what's known as a container format, the codec you're probably thinking of is DivX (and the open source alternative Xvid).
Handbrake doesn't convert to AVI.
Assuming the copyright laws in your country allow for backups, you can use DVD Shrink to backup DVDs, but they will remain as VOB files (which are really of the Mpeg codec). You could then also use something like Clone DVD Mobile to convert to DivX. In Clone DVD Mobile, there are simple options to modify the quality of the output video which will also show you its size.
There are other options such as DVDX, since Clone is not freeware. I recommend looking for Xvid converters since the Divx converters are hardly free (since they require licenses and what not).
Also see: lifehacker.com/380702/five-best-dvd-ripping-tools
You are probably better off asking on forums of the site you download these files from. And don't forget to share any more info! Digitising a movie collection is a good move as discs get scratched too easily too fast.
UPDATE: I just tried AutoGK, it's more accurate than Clone DVD Mobile in output size. Plus it's free.

A: My favorite tool to rip and convert movie DVDs to AVI:

DVDx is likely the most popular DVD backup software world
  wide. Based on well known open source
  libraries, DVDx converts DVD movies in
  high qulaity (S)Video CD, DivX or
  Windows Media files.

*

*DVDx copies DVD movie to VCD, SVCD, DivX, AVI or WMV in one step.

*DVDx has been designed as a simple and intuitive program.

*DVDx produces high quality MPEG and AVI movies.

DVDx is freeware.

A: I use Eahoosoft DVD Ripper, fast speed and work fine.

Eahoosoft DVD Ripper - one of the best dvd ripper software, can rip
  DVD to MP4, H.264, AVI, MP3, WMV, WMA, FLV, MKV, MPEG-1, MPEG-2, 3GP,
  3GPP, VOB, DivX, Mov, RM, RMVB, M4A, AAC, WAV, etc. with fast DVD
  ripping speed and excellent image and sound quality.

A: The first thing to check is what's supported by your DVD player... And sadly, if your DVD player doesn't support the MP4/MKV containers, despite the fact it's the most friendly/efficient tool, handbrake is no more a good choice because AVI is no more supported...
So to encode a DVD as AVI files, I recommend:
DVD Decrypter for ripping (extracting & decrypting the dvd)
(keep DVD43 it could help DVD Decrypter on some protections)
Megui for encoding:

*

*video: MPEG-4 ASP (xvid), MPEG-4 AVC (x264)

*audio: AAC, MP2, MP3,  Vorbis, AC3

*containers: MP4, MKV, AVI, M2TS

(If they are supported by your DVD player, x264/AAC should have the best quality/size results)
And if you're not happy with the results of the "One Click/AutoEncode" buttons, start by following this guide
Note:  It's not a piece of cake to have the best video encoding. Video compression has many parameters and for optimal results they should be tweaked differently by movies characteristics and some subjectives choices...
So, if you want the long answer you should go to this site: doom9.org (and his forum)

A: I don't really see why you need any other tools - if you have the 700MB files, you do not really want to edit them down any further or you will loose quality.
What I recommend you do is either copy as many as will fit to a DVD and use it as AVI files so you will just play it on a computer, alternatively use a tool such as Sothink DVD Movie Maker or DVD Flick, you can import all the AVIs and transcode to DVD format- then create a menu which allows you to select what to play.


text:
Q: CSS: change float columns structural layout? I have three columns where one of the columns is 50% wide and the other two columns are sidebars with 25% width.
HTML

CSS
article {
    width:50%;
    float:left;
}

aside {
    width:25%;
    float:left;
}

Maintaining the HTML structure, is it possible to float them in a way to achieve a different layout - I'd like to have #s1 on the left side of the article and #s2 on the right side of the article.
Is this possible with CSS3? Here is a jsFiddle of the code above

A: There is no way to do it without changing the structure of the page - CSS is NOT mean to be used for structural purposes. It completely goes against the principles of semantic markup.
You can easily restructure the page, as in this example using HTML to change the structure. Alternatively, @sandeep seems to have a good answer.

A: Example for two column table structure with css
#content {

  -webkit-column-count: 2;
  -webkit-column-rule: 1px solid #bbb;
  -webkit-column-gap: 2em;

  -moz-column-count: 2;
  -moz-column-rule: 1px solid #bbb;
  -moz-column-gap: 2em;

  column-count: 2;
  column-rule: 1px solid #bbb;
  column-gap: 2em;

  display: block;
}

Here is a live demo.
http://playground.html5rocks.com/#columns

A: You can use display:table for this. Write like this:
article {
    background:#f0f0f0;
    width:50%;
    display:table-cell;
}

aside {
    width:25%;
    display:table-cell;
}

HTML

check this http://jsfiddle.net/UaFFP/2/

A: You wanted S1 to be on the left of the article - so,place it first

Then the article

Then,on the right - you wanted the "s2" - so,place it last

Although some changes to the Css will be good - but it works without any changes to the css.


text:
Q: Convert string to column name I'm trying to write a simple postgres function which looks more or less like that:
CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) RETURNS float AS $$
  DECLARE
    sum float;
  BEGIN
    sum = (SELECT SUM($1) FROM jobs WHERE jobs.technician_id = in_t.id);
    RETURN sum;
  END;
$$ LANGUAGE plpgsql;

And i need to use it like that:
SELECT users.*, USER_TOTALS('jobs.price', users.*) AS total_price_value FROM users;

Hovewer, that's obviously not working cause SUM() function expects to get a column name but my code passes a varchar to it, so the error says:
Function sum(character varying) does not exist

The question is - can i somehow cast a varchar variable to column name var type? I've been googling for this thing for about 2 hours now and i have no idea how can i make that happen.

A: CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) RETURNS float AS $$
DECLARE
    sum float;
BEGIN
    EXECUTE 'SELECT SUM('||column_name||') FROM jobs WHERE jobs.technician_id='||in_t INTO sum;
    RETURN sum;
END;
$$ LANGUAGE plpgsql;

A: A recommended form:
CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users)
RETURNS float AS $$
DECLARE
  sum float;
BEGIN
  EXECUTE format('SELECT SUM(%I) FROM jobs WHERE jobs.technician_id=$1', column_name)
    INTO sum
    USING in_t;
  RETURN sum;
END;
$$ LANGUAGE plpgsql;


text:
Q: BOOL method to detect if nodes have been removed from scene Im making a brick breaker type game and need to know if all the bricks have been broken in order to transition to the win screen.
The way I've been thinking of solving this is to create a BOOL method that is ran each time a brick is removed to calculate how many bricks are left. If there are no bricks left... move to the win scene.
Im struggling with the logic on how to do this.
So far I have:
-(BOOL)isGameWon{

for (SKNode* node in self.children){

    if ([node.name isEqual:brickCategoryName]){
        //some logic
    }

}
return YES;
}

didBeginContactMethod:
if (notTheBall.categoryBitMask == brickCategory) {
    [self runAction:_smashSound];
    [notTheBall.node removeFromParent];
    if ([self isGameWon]) {
        NSLog(@"YOU WIN!");
    }

}


text:
Q: Autocompletion of citation in TeXShop without BibDesk? The documentation for autocompletion of citations within TeXShop appears to be fragmented around the web.  The default suggestion is to use a service from BibDesk, but this requires BibDesk to be open.  I don't use BibDesk and I don't want to keep selecting the correct .bib file.
Is there a standard way to accomplish this without BibDesk?  I see from this decade-old discussion that there were some applescripts to accomplish this, so it's at least possible.


text:
Q: How to refractor big if-else webservice dispatcher The Problem
In my webservice I have only one dispatching function that handle every call by checking the first parameters that keep the name of the function called.
Why ?
The reason is when we update the software of our clients. We don't update obligatory the server and the client at the same time and if we generate the client from the server wsdl. The coupling is strong and the compatibility will break. Ex: if we add a function to the webservice server and update only the server exception will be thrown cause the client is not sync with the server anymore.
Exemple
Client
public class WClient {
  public WClient () {}
  public String callFunction2(){
      String[] parameters = {"function2", "blabla"};
      WServer.dispatchingFunction(parameters);
  }
}

Server
public class WServer {

  public WServer() {}

  public String[] dispatchingFunction(String[] parameters) throws Throwable {
      String functionName = paramaters[0];
      if(functionName.equals(function1)) {};
      else if(functionName.equals(function2)) {};
      ...
      else if(functionName.equals(function15)) {};
      else //ERROR
  }
}

A: Do you absolutely need to refactor this? Could you declare the web service part as deprecated, leave it as is and add new features by adding restful APIs on the server? With restful APIs you can basically always get away with adding things without worrying about the client breaking.


text:
Q: How to integrate AXIOS on ReactJS base CDN Now i'm doing build a front page use ReactJS but base CDN format not base node/npm. now i want to integrate AXIOS on it but face an issue about that. All the code that i implement error.. i will share my code
this is my index.html code
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Buynow Project</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" >

this is my app.js code
function Product() {

  axios.post('http://<domainName>.com/api/product_ec7cac9007758d89656160f668_1381')
  .then(function (response) {
    // handle success
    console.log("result response");
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log("result error");

    console.log(error);
  })
  .then(function () {
    console.log("last");

    // always executed
  });

  return (

        DISPLAY PRODUCT DETAIL
        {/* will display detail product value */}

    )

}

class App extends React.Component {
  render() {
    return(

            <Product />

    )
  }
}

from this code. there are no result for the response. evendo the console.log for
console.log("result response");
console.log("result error");
console.log("last");

not display also. so i don't know what is response when run this code.
actually i also tried another code for fetch data. i will share the code
second code
const uf = await axios.post("http://<domainName>.com/api/product_ec7cac9007758d89656160f668_1381");
const response = await fetch(uf);
const data = await response.jso(response);

console.log("second code");
console.log(data);

third code
  const fetchOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
        }
    };

    const response = await fetch('http://<domainName>.com/api/product_ec7cac9007758d89656160f668_1381', fetchOptions);
  console.log(response);

and both have same error result
Uncaught SyntaxError: http://localhost:81/website/App.js: await is a reserved word (36:13) (at babel.min.js:7:10099)
 34 |
 35 | function Product() {
> 36 |   const uf = await axios.get("http://<domainName>.com/api/product_ec7cac9007758d89656160f668_1381");
    |               ^
 37 |   const response = await fetch(uf);
 38 |   const data = await response.jso(response);
 39 |

please help. i not sure how to solve this

A: You can only use await, when async function is there.
async function Product() {
 const uf = await axios.get("http://<domainName>.com/api/product_ec7cac9007758d89656160f668_1381");

const response = await fetch(uf);
const data = await response.jso(response);

Learn more here -
https://www.w3schools.com/js/js_async.asp