text:
Q: Spring Boot error I am newbie to SpringBoot, I need to integrate Vaadin with Spring Boot. When I run the Boot main class I am getting error. My Boot class is as follows.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

I got the following error.
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]at java.util.concurrent.FutureTask.report(Unknown Source) ~[na:1.8.0_111]
at java.util.concurrent.FutureTask.get(Unknown Source) ~[na:1.8.0_111]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:344) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:99) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:84) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:554) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:179) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:164) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536) [spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at com.example.Application.main(Application.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_111]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_111]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.3.RELEASE.jar:1.5.3.RELEASE]Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[na:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[na:1.8.0_111]
at java.lang.Thread.run(Unknown Source) ~[na:1.8.0_111]Caused by: org.apache.catalina.LifecycleException: A child container failed during startat org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:947) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.14.jar:8.5.14]
... 6 common frames omitted.

Here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>PersonExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>PersonExample</name>

<prerequisites>
    <maven>3</maven>
</prerequisites>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<properties>
    <vaadin.version>8.0.0</vaadin.version>
    <vaadin.plugin.version>8.0.0</vaadin.plugin.version>
    <jetty.plugin.version>9.3.9.v20160517</jetty.plugin.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!-- If there are no local customisations, this can also be "fetch" or "cdn" -->
    <vaadin.widgetset.mode>local</vaadin.widgetset.mode>
</properties>

<repositories>
    <repository>
        <id>vaadin-addons</id>
        <url>http://maven.vaadin.com/vaadin-addons</url>
    </repository>
</repositories>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-bom</artifactId>
            <version>${vaadin.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.vaadin.spring.extensions</groupId>
            <artifactId>vaadin-spring-ext-boot</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.vaadin.spring.addons</groupId>
            <artifactId>vaadin-spring-addon-eventbus</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.vaadin</groupId>
            <artifactId>viritin</artifactId>
            <version>2.0.beta1</version>
        </dependency>
        <dependency>
            <groupId>org.vaadin.teemu</groupId>
            <artifactId>switch</artifactId>
            <version>3.0.0</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-server</artifactId>
    </dependency>
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-push</artifactId>
    </dependency>
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-client-compiled</artifactId>
    </dependency>
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-themes</artifactId>
    </dependency>
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
    </dependency>

    <!-- vaadin4spring https://github.com/peholmst/vaadin4spring
         contains lots of handy helpers for serious Spring + Vaadin
         applications. This example uses event bus to decouple the editor
         form from the MainUI class.
    -->
    <dependency>
        <groupId>org.vaadin.spring.extensions</groupId>
        <artifactId>vaadin-spring-ext-boot</artifactId>
    </dependency>
    <dependency>
        <groupId>org.vaadin.spring.addons</groupId>
        <artifactId>vaadin-spring-addon-eventbus</artifactId>
    </dependency>
    <dependency>
        <groupId>org.vaadin</groupId>
        <artifactId>viritin</artifactId>
    </dependency>
    <!-- Using Vaadin add-ons with client side extensions is easy, switch
    as an example in this project, see also vaadin-maven-plugin
    configuration.
    -->
    <dependency>
        <groupId>org.vaadin.teemu</groupId>
        <artifactId>switch</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
         <artifactId>tomcat-embed-el</artifactId>
        <scope>provided</scope>
    </dependency>
    </dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
                <!-- Exclude an unnecessary file generated by the GWT compiler. -->
                <packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-maven-plugin</artifactId>
            <version>${vaadin.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>update-theme</goal>
                        <goal>update-widgetset</goal>
                        <goal>compile</goal>
                        <!-- Comment out compile-theme goal to use on-the-fly theme compilation -->
                        <goal>compile-theme</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-clean-plugin</artifactId>
            <version>3.0.0</version>
            <!-- Clean up also any pre-compiled themes -->
            <configuration>
                <filesets>
                    <fileset>
                        <directory>src/main/webapp/VAADIN/themes</directory>
                        <includes>
                            <include>**/styles.css</include>
                            <include>**/styles.scss.cache</include>
                        </includes>
                    </fileset>
                </filesets>
            </configuration>
        </plugin>

        <!-- The Jetty plugin allows us to easily test the development build by
            running jetty:run on the command line. -->
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>${jetty.plugin.version}</version>
            <configuration>
                <scanIntervalSeconds>2</scanIntervalSeconds>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <!-- Vaadin pre-release repositories -->
        <id>vaadin-prerelease</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>

        <repositories>
            <repository>
                <id>vaadin-prereleases</id>
                <url>http://maven.vaadin.com/vaadin-prereleases</url>
            </repository>
            <repository>
                <id>vaadin-snapshots</id>
                <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>vaadin-prereleases</id>
                <url>http://maven.vaadin.com/vaadin-prereleases</url>
            </pluginRepository>
            <pluginRepository>
                <id>vaadin-snapshots</id>
                <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </pluginRepository>
        </pluginRepositories>
    </profile>
</profiles>
</project>

I added all dependencies required. I have no idea about why I am getting this error. Please help me out.

A: You must add this dependency in your code. it will solve your problem.
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>


text:
Q: Adding to Grid Selection for grid.php file I asked a similar question but I did not provide sufficient details and I got no answers so I will try again.
The main task is to add fields to the CSV file that is exported under the magento admin sales->invoices.  I found the main file to edit:
app/code/core/Mage/Adminhtml/Block/Sales/Invoice/Grid.php

This has the options to addColumn's like so:
    $this->addColumn('increment_id', array(
        'header'    => Mage::helper('sales')->__('Invoice #'),
        'index'     => 'increment_id',
        'type'      => 'text',
    ));

Now when I try to add new Column's I change the index to the appropriate database field, lets say 'tax amount' for example.  The only problem is that this new value is not in my Magento collection, so it simply populates an empty column in the table.
I am quite new to Magento so I don't fully understand how the Magento collection works or how I can access it for the scope of grid.php.  Could someone please give me some direction in how to add to the collection?
I'm really stuck and would appreciate the help.

A: You basically need to edit the resource model to include the fields you want to include. You can edit the resource in code, I'm not sure what version your using but in the Grid.php file you'll see the _prepareCollection find the code that looks like,
$collection = Mage::getResourceModel('sales/order_invoice_collection')
->addAttributeToSelect('order_id')
->addAttributeToSelect('increment_id')
->addAttributeToSelect('created_at')
->addAttributeToSelect('state')
->addAttributeToSelect('grand_total') ...and so on!

add the line
->addAttributeToSelect('tax_amount')

to that list and the you should be able to use
$this->addColumn('tax_amount', array(
    'header'    => Mage::helper('sales')->__('Tax'),
    'index'     => 'tax_amount',
    'type'      => 'number',
));

This is as untest as I am away from my dev machine and dont have Mage to hand, but this should work or at very least point you in the right direction.
Edit:
Failing that you could try replacing your whole _prepareCollection
protected function _prepareCollection()
{

$collection = Mage::getResourceModel('sales/order_invoice_collection')
->addAttributeToSelect('order_id')
->addAttributeToSelect('increment_id')
->addAttributeToSelect('created_at')
->addAttributeToSelect('state')
->addAttributeToSelect('grand_total')
->addAttributeToSelect('tax_amount')
->addAttributeToSelect('order_currency_code')
->joinAttribute('billing_firstname', 'order_address/firstname', 'billing_address_id', null, 'left')
->joinAttribute('billing_lastname', 'order_address/lastname', 'billing_address_id', null, 'left')
->joinAttribute('order_increment_id', 'order/increment_id', 'order_id', null, 'left')
->joinAttribute('order_created_at', 'order/created_at', 'order_id', null, 'left');

$this->setCollection($collection);
return parent::_prepareCollection();
}

Again this is untested, from memory this is the _prepareCollection from the 1.3 range of magento so its a little old, but quite sure it should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bundle Scala-sbt module and UI together I have a multi module project with SBT. The project structure is as below:
MyApp
    |--MyApp-api
    |--MyApp-ui

MyApp-api -> contains the scala module
MyApp-ui  -> contains the ui module (html/js/css etc)
I am using SBT for build. I am able to assemble MyApp-api module using sbt-assembly. UI module communicate with the api though REST calls. I want to bundle both api and ui modules together and then deploy in some server. How can I package both UI and API together using SBT(something like building a war file)? I do not want to put all the UI contents into resource folder of API. The reason is that I might need to deploy UI and API separately in the near future.
Any help would be really appreciated.


text:
Q: Pandas exponentially weighted covariance implementation for online version Pandas has a function compute rolling covariance over time. e.g. if I have df
          Column2   Column2

2017-10-23       NaN       NaN
2017-10-24 -0.147631  0.161791
2017-10-25  0.044194 -0.466305
2017-10-26 -0.069876  0.127095
2017-10-27  0.142261  0.807302
2017-10-30 -0.178176 -0.319247
2017-10-31  0.108544  0.094446

then to get the exponentially weighted covariance
df.ewm(span=5).cov()

Does anyone know the actual implementation of the underlying exponentially weighted covariance? I'm trying to code up my own online version (e.g. cache the state and just use the most recent data to update the covariance matrix)


text:
Q: On the syntax of \newcommand I have the following very basic question.
Say that I want to create a shortcut with \newcommand, call it \newcommand{\Bla}{BLA^{bla}}. Now, if I call it in the text with an additional ^{...}, e.g., I write \Bla^{...} to get the output BLA^{bla...}, there is an error.
I see why there is the error, but I still have the following question: how can be this error be avoided by keep on having the shortcut?
PS: Any help or edit is most welcome, since I can hardly find how to give to my problem an actual name (as the title and the tags clearly shows),

A: With \NewDocumentCommand you can use so called embellishments. These are optional arguments started by a specific token, like so:
\documentclass[]{article}

%\usepackage{xparse} % no longer needed with newer LaTeX versions
\NewDocumentCommand \bla { E{^}{{}} }{Bla^{bla#1}}

\begin{document}
$\bla$ and $\bla^{2}$.
\end{document}

The syntax of the E type argument is a bit weird on first look: E{<list of tokens>}{<list of defaults>}. That's why I use E{^}{{}} (^ will be the token, and the default belonging to ^ will be empty). Using two embellishments, you'd do something like E{^_}{{}{abc}}, that would create two arguments, one started by ^ defaulting to an empty value, and one started by _ defaulting to abc.

A: Your task can be solved classically using TeX primitives:
\def\Bla{\futurelet\next\Blax}
\def\Blax{\ifx^\next\afterfi{\Blay}\else\afterfi{\Blay^{}}\fi}
\def\Blay^#1{BLA^{bla#1}}
\def\afterfi#1#2\fi{\fi#1}

%test:
$\Bla, \Bla^2$

The \Bla macro uses supporting macros \Blax and \Blay. The second one defines the main behavior of the macro, i.e. BLA is printed following by ^{bla} or ^{bla<text>}. We suppose that \Bla is used in math. mode.
The \futurelet\next\Blax saves the next token to \next and runs \Blax. The \Blax runs \Blay if \next is ^ and it runs \Blay^{} in other cases.
% suppose \Bla z:
\next is z
\Blay^{} expands to BLA^{bla} followed by z
% suppose \Bla^z:
\next is ^
\Blay^{z} expands to BLA^{blaz}.


text:
Q: API POST error: MongoDB & Ionic App What I'm Trying to do: Connect my mongolab db to my ionic app. (I'd use Firebase but Firebase doesn't have text search, which I need).
I followed the example at (https://scotch.io/tutorials/creating-a-single-page-todo-app-with-node-and-angular) for some guidance.
However, I'm getting the error:

Failed to load resource: the server responded with a status of 404
  (Not Found) http://localhost:8100/api/todos

Structure of my files:
-Project
+-www
+---js
------app.js
------server.js
------cordova.js
+-----controllers
+---css
+---img
+---lib
+---templates

I know that I'm probably missing something fundamental. I don't understand how my server.js is even loaded by ionic?
Here's a snippet (just the relevant parts) of my server.js
// set up ========================
var express  = require('express');
var app      = express();                               // create our app w/ express
var mongoose = require('mongoose');                     // mongoose for mongodb
var morgan = require('morgan');             // log requests to the console (express4)
var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var uriUtil = require('mongodb-uri');

// configuration =================

var mongodbUri = 'mongodb://<myusername>:<mypass>@ds036648.mongolab.com:36648/<mydb>';
var mongooseUri = uriUtil.formatMongoose(mongodbUri);
mongoose.connect(mongooseUri);     // connect to mongoDB database on modulus.io

// listen (start app with node server.js) ======================================
app.listen(8100);
console.log("App listening on port 8100");

// define model =================
var Todo = mongoose.model('Todo', {
    text : String
});

// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {

    // create a todo, information comes from AJAX request from Angular
    Todo.create({
        text : req.body.text,
        done : false
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });

});

the html i'm using:

                <form>

                        <input type="text" class="form-control input-lg text-center" placeholder="I want to buy a puppy that will love me forever" ng-model="formData.text">

                    <button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
                </form>

my controller:
angular.module('starter')
.controller('todosController', function($scope,$http) {

    $scope.formData = {};
    // when submitting the add form, send the text to the node API
    $scope.createTodo = function() {
        $http.post('/api/todos', $scope.formData)
            .success(function(data) {
                $scope.formData = {}; // clear the form so our user is ready to enter another
                $scope.todos = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

A: It looks like your issue is here:
$http.post('/api/todos', $scope.formData)

It should point to a server: so it needs to be something like this:
$http.post('https://localhost:8100/api/todos', $scope.formData)

A: Firstly you need to run the node server on a port other than 8100 as ionic uses 8100 port. Write
app.listen(3000);

instead of
app.listen(8100);

Now for the api request use this
$http.post('http://localhost:3000/api/todos', $scope.formData)

But this time you will get an error

no 'access-control-allow-origin' header is present on the requested resource.

This is because the browser is blocking it as it usually allows a request in the same origin for security reasons.So solution is to open chrome by disabling the security by using the following command in the run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security


text:
Q: C++ setter/getter in one function? I've been doing a C++ course and one of the homeworks asks to implement an image class which has private member's rows_, cols_, data_. Where data is a vector of length rows X cols. They ask to implement a method whereby you can access the value of data_ given a row and column which is fine. However they also want to be able to assign a value to that position, as below:
int val = image.at(row, col);
Image.at(row, col) = 255;

I'm seems strange to me, if I returned a reference to the entry in data_ would the above functionality work? I feel you shouldn't allow Image.at(row,col) =255; as this breaks the encapsulation of data_?

A: It's quite reasonable to return a reference to some internal data this way.
If you're super concerned, you could always return a wrapper object that only allows that single pixel to be operated on, but that's probably overkill.
What's not overkill however, is providing a const-correct function.  This is important if you have a const image object and want to read pixels from it.
So, you might have something like this:
class Image
{
public:
    Image()
        : mWidth(0)
        , mHeight(0)
    {}

    Image(int width, int height, const Pixel& color = {})
        : mWidth(width)
        , mHeight(height)
        , mBuffer(width * height, color)
    {}

    Pixel& at(int row, int col)
    {
        return mBuffer.at(row * mWidth + col);
    }

    const Pixel& at(int row, int col) const
    {
        return mBuffer.at(row * mWidth + col);
    }

private:
    int mWidth, mHeight;
    std::vector<Pixel> mBuffer;
};

Note that I've used Pixel here to show the more generic form of returning const-reference.  Of course, if you're just using integers, there's no need for the const version to return a reference at all -- it could just return int, while the non-const function would still return int&.

A: Yes declare the method to return reference.
int & at(int row, int col) {return data[row * width + col];}

Assigning new value to the output will then rewrite the data in memory allocated somewhere inside the data member as that is where the reference is pointing to.

A: This is analogue to eg. std::vector at
Based on that this is how most standard containers and iterators work, I would say that it is fine. Remember const correctness though and provide const accessor as well.


text:
Q: Let card content take the available height if necessary I have a page that contains a card.
The card should take the automatic height which depends on its content, except when the content exceeds the height of the screen it is necessary to display a bare scroll.
In this case the title and the content will be scrollable but not the footer. the footer must always be displayed at the bottom of the page in fixed mode (when the content is large).

.card {
  width: 80%;
  border: solid 2px #eee;
  margin-left: 30px;
}

  Hello

<menu>

</menu>

Title

      Integer ullamcorper mi nec pellentesque ultricies. Sed vel efficitur augue. Cras fringilla non nisl convallis blandit. Nunc libero odio, tincidunt vitae sodales eu, pellentesque sed leo. Donec tempus erat sed leo vestibulum, eu fringilla ante dignissim.
      Fusce viverra interdum diam id lacinia. Nam tincidunt euismod quam, at pretium lorem mattis non. Nulla facilisi. Mauris sem massa, porttitor id nisl eu, placerat tincidunt turpis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis
      ultricies turpis eu mi facilisis, in venenatis lectus iaculis. In vitae augue nec neque pellentesque suscipit eget a est. Aenean dolor ex, vehicula sed bibendum eu, semper in sapien. In eget ante eu nulla scelerisque pharetra vitae tristique lacus.
      Aliquam erat volutpat. Nunc at condimentum velit. Maecenas tempor efficitur lacus, eget bibendum quam dapibus ac. Cras hendrerit metus ac velit mollis, sed dignissim justo aliquet. Fusce eleifend pharetra lectus eget sodales. Quisque ac lacus mollis,
      sollicitudin ligula elementum, porttitor ex. Nulla facilisi. Donec ultricies iaculis dignissim. Pellentesque eu neque quis sapien porta ultricies. Quisque rhoncus pulvinar fringilla.

    <button>
      Apply
      </button>

Demo
What's the most elegant way to do it? Preferably in full CSS/Sass.

A: You need to add a max-height to .card and make the .card-footer a sticky element to follow the card when being scrollable in small screens.
http://jsfiddle.net/2d0Labwf

.card {
  width: 80%;
  border: solid 2px #eee;
  margin-left: 30px;
  position: relative;
  max-height: 80vh;
  overflow-y: auto;
}

.card-footer {
  position: sticky;
  bottom: 0;
  height: 50px;
  background-color: white;
}

Title

      Integer ullamcorper mi nec pellentesque ultricies. Sed vel efficitur augue. Cras fringilla non nisl convallis blandit. Nunc libero odio, tincidunt vitae sodales eu, pellentesque sed leo. Donec tempus erat sed leo vestibulum, eu fringilla ante dignissim. Fusce viverra interdum diam id lacinia. Nam tincidunt euismod quam, at pretium lorem mattis non. Nulla facilisi. Mauris sem massa, porttitor id nisl eu, placerat tincidunt turpis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis ultricies turpis eu mi facilisis, in venenatis lectus iaculis. In vitae augue nec neque pellentesque suscipit eget a est. Aenean dolor ex, vehicula sed bibendum eu, semper in sapien. In eget ante eu nulla scelerisque pharetra vitae tristique lacus.
Aliquam erat volutpat. Nunc at condimentum velit. Maecenas tempor efficitur lacus, eget bibendum quam dapibus ac. Cras hendrerit metus ac velit mollis, sed dignissim justo aliquet. Fusce eleifend pharetra lectus eget sodales. Quisque ac lacus mollis, sollicitudin ligula elementum, porttitor ex. Nulla facilisi. Donec ultricies iaculis dignissim. Pellentesque eu neque quis sapien porta ultricies. Quisque rhoncus pulvinar fringilla.

      <button>
      Apply
      </button>

A: You can set a max-height on the card content equal to the viewport height minus the height of the card header and footer by using calc. Then set the overflow to scroll.
This will ensure the card isn't taller than the viewport, the card footer always displays at the bottom, and the rest of the card content is scrollable.

.card {
  width: 80%;
  border: solid 2px #eee;
  margin-left: 30px;
}
.card-content {
  max-height: calc(100vh - 71px);
  overflow: scroll;
}
body { margin: 0; }

  Hello

<menu>

</menu>

Title

      Integer ullamcorper mi nec pellentesque ultricies. Sed vel efficitur augue. Cras fringilla non nisl convallis blandit. Nunc libero odio, tincidunt vitae sodales eu, pellentesque sed leo. Donec tempus erat sed leo vestibulum, eu fringilla ante dignissim.
      Fusce viverra interdum diam id lacinia. Nam tincidunt euismod quam, at pretium lorem mattis non. Nulla facilisi. Mauris sem massa, porttitor id nisl eu, placerat tincidunt turpis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis
      ultricies turpis eu mi facilisis, in venenatis lectus iaculis. In vitae augue nec neque pellentesque suscipit eget a est. Aenean dolor ex, vehicula sed bibendum eu, semper in sapien. In eget ante eu nulla scelerisque pharetra vitae tristique lacus.
      Aliquam erat volutpat. Nunc at condimentum velit. Maecenas tempor efficitur lacus, eget bibendum quam dapibus ac. Cras hendrerit metus ac velit mollis, sed dignissim justo aliquet. Fusce eleifend pharetra lectus eget sodales. Quisque ac lacus mollis,
      sollicitudin ligula elementum, porttitor ex. Nulla facilisi. Donec ultricies iaculis dignissim. Pellentesque eu neque quis sapien porta ultricies. Quisque rhoncus pulvinar fringilla.

    <button>
      Apply
      </button>


text:
Q: Apply a Hover Effect to Headings Using CSS I'm trying to achieve a fade on hover effect to the headings using CSS3 with no success. I'm not sure what I did wrong as I am pretty sure that I followed the W3 Schools tutorial.
Could you help me with fixing the code so I can get the fade on hover effect for my headings? The class that I'm trying to apply the hover effect is the .lesson-title, h1.
Meaning it would apply to those headings with names such as "Identify Your Business Opportunity" "Test Your Concept or Product", etc., etc.
They are also links so you could also apply the hover effect to them as another option.
Here is the code:

    For First-Time Business Owners

        Lesson plans: 8

         One hour webinar over a duration of 8 weeks.

01

Identify Your Business Opportunity

Choosing what kind of business to start with can be a challenging task when confronted with many ideas and opportunities. It's important to determine where your passions lie and to understand what it takes to start the business. You have to consider your skills and resources. The industry you are entering may be dying or a fast-growing and emerging business.

02

Test Your Concept or Product

Concept testing is the process of evaluating likely customer response to a product idea prior to its introduction into the market. Seen through a jobs-to-be-done lens, the goal of concept testing is to validate that a product concept is better than the competing solutions at helping customers to get a job done.

03

Name Your Business

Naming your business is important. The right business name will help you distinguish you from a sea of bland competitors, hence provide your customers with a reason to remember and use your company.

04

Build a Business Plan

For any start-ups, a business plan is an important tool and it also allows you to gain a better understanding of your industry structure, competitive landscape and the capital requirements of starting the small business. The plan lays out a vision of growth and the steps needed to get there.

      <button class="collapsible">More lessons</button>

05

Find Start-Up Money

To start a business, you must invest in the business. The journey of finding start-up funds will be different for each individual. Some businesses require small amount or large amount of money to start.  Finding the money you need may come from a source you would have never thought of.

06

Choose a Business Structure

Deciding on the structure of your business is not a decision to be taken lightly. Whether you have the LLC, a sole proprietorship or form a corporation; your choice will have an impact on your business liability and taxes.

07

Get Your Business Licenses and Permits

Depending on your chosen business structure, may need to register your business with the state authorities. Setting up your small business may require an employer identification number (EIN) which is also used by state taxing authorities to identify businesses. Additional paperwork can entail sales tax licenses and zoning permits.

08

Get Business Insurance

As a new small business owner, you have the responsibility to manage the risks associated with your business. Don't put your new startup at risk without getting the proper small business insurance to protect your company in the event of a disaster or litigation.

It will need to stay in HTML format as I will be copying/pasting this into a drag-and-drop website editor. Sorry for the messy code.
Thanks! If you need any more details, reply to me.

A: I think you've gotten your tag wrong:
.lesson-title h1:hover{
    opacity: 0.2;
    transition: 0.3s;
    -webkit-transition: 170ms ease-in-out;
    -moz-transition: 170ms ease-in-out;
    -ms-transition: 170ms ease-in-out;
    -o-transition: 170ms ease-in-out;
    transition: 170ms ease-in-out;
    transition-duration: 170ms;
    transition-timing-function: ease-in-out;
    transition-delay: 0s;
  }

should be
h1.lesson-title:hover{
    opacity: 0.2;
    transition: 0.3s;
    -webkit-transition: 170ms ease-in-out;
    -moz-transition: 170ms ease-in-out;
    -ms-transition: 170ms ease-in-out;
    -o-transition: 170ms ease-in-out;
    transition: 170ms ease-in-out;
    transition-duration: 170ms;
    transition-timing-function: ease-in-out;
    transition-delay: 0s;
  }

The original selector means on hover for h1 which are a child of .lesson-title.
Whereas what you wanted to say was on hover for h1 which have the class .lesson-title.
Hope that helps!

A: Super simple: remove your class="lesson-title" from the
 tag (and .lesson-title h1:hover CSS) altogether. Then it works (see below).

h1:hover{
        opacity: 0.2;
        transition: 0.3s;
        -webkit-transition: 170ms ease-in-out;
        -moz-transition: 170ms ease-in-out;
        -ms-transition: 170ms ease-in-out;
        -o-transition: 170ms ease-in-out;
        transition: 170ms ease-in-out;
        transition-duration: 170ms;
        transition-timing-function: ease-in-out;
        transition-delay: 0s;
      }

02

Test Your Concept or Product

Concept testing is the process of evaluating likely customer response to a product idea prior to its introduction into the market. Seen through a jobs-to-be-done lens, the goal of concept testing is to validate that a product concept is better than the competing solutions at helping customers to get a job done.


text:
Q: KendoUI Grid custom groupable object I am trying to make a grid groupable on columns field but the columns are object.
{
  Gestionnaire :
     { id: 4, nom:'nomgestionnaire'},
     {..},
      ..
}

I have success for sortable:
columns: [
     field: "Gestionnaire"
     title: "Gestionnaire"
     sortable:
         compare: (a,b) =>
               @compareColumnFields(a.Gestionnaire.Nom, b.Gestionnaire.Nom)
]

with @compareColumnFields function is :
if a is b
    return 0
else if a > b
    return 1
else
    return -1

and for groupable?
groupable : ...

A: I think you're wanting to allow the user to actively group columns.
In that case, all you need is:
groupable: true
in the main structure of the grid.
For example:
$('#grid').kendoGrid({
    columns: [
        {
            fields: "Guestionaire",
            title: "Guestionaire",
            sortable:
                compare: (a,b) =>
                    @compareColumnFields(a.Guestionaire.Nom, b.Guestionaire.Nom)
         },
         {...placeholder for other columns...}
    ],
    groupable: true
});

Kendo has a sample of this at http://dojo.telerik.com/ejehe
Ignore the SelectRow and Expand/Collapse stuff and that ought to be the same as what you're trying to accomplish.

A: For those in the same situation as me , I completely change solution. Instead of making me a function that returns true and false , it giving it the object in full, I just give the string .
For my example I give directly a.Gestionnaire.Nom and b.Gestionnaire.Nom, and THEN you can call :
groupable: true

In fact it was obvious.


text:
Q: How do I get a reference to one of my HTML meta tags? I have a meta tag like so in my ASP.NET MVC View:
<meta name = "currentRequestAbsoluteUri"
 content="@Url.Content(HttpContext.Current.Request.Url.AbsoluteUri)" />

Using JavaScript or jQuery, how do I read the value of this meta tag?
I can do it using JavaScript but it is long-winding:
var element =
document.getElementByName('currentRequestAbsoluteUri');

// And then how do I get its content property
// like this?
// var content = element["content"]

Wait, I am not even sure if HTML DOM API has that function to get something by its name.
I can also use jQuery but jQuery uses sizzle, the CSS selector engine and I don't know how to get an element like meta because it has neither an id nor a CSS class.

A: You can use css attribute selectors. Read more here.
You can use the css attribute selectors in JS using querySelector. Read more here.
var meta  = document.querySelector("meta[name='currentRequestAbsoluteUri']");
var value = meta.content;

A: You can use document.getElementsByTagName(). It returns an array-like HTMLCollection that contains all meta tags in the DOM. You can then iterate through it to get your reference to meta tags. Each item
var metaTags = document.getElementsByTagName('meta');
var metaTagsArray = Array.prototype.slice.call(metaTags);

metaTagsArray.forEach(function(metaTag){
  var metaTagName = metaTag.name;
  var metaTagContent = metaTag.content;
});

You can optionally turn it into an array using slice to have access to native array methods, like forEach.


text:
Q: Using variable for error code in MySQL with SQLSTATE I'm trying to manage my own errors in MySQL using a procedure and an error message table named "error_messages".
How can I manage to select a specific error message in that table?
I would like to do something like this.
DELIMITER $$

CREATE PROCEDURE throw_error_test (divisor INT)
BEGIN
  SET @errorCode = '45123';
  IF divisor = 0 THEN
    SIGNAL SQLSTATE @errorCode
    SET MESSAGE_TEXT = SELECT message
                       FROM error_messages
                       WHERE id = @errorCode;
  END IF;
END;

Thanks for helping

A: As documented under SIGNAL Syntax:

The condition_value in a SIGNAL statement indicates the error value to be returned. It can be an SQLSTATE value (a 5-character string literal) or a condition_name that refers to a named condition previously defined with DECLARE ... CONDITION (see Section 13.6.7.1, "DECLARE ... CONDITION Syntax").
[ deletia ]
Valid simple_value_specification designators can be specified using stored procedure or function parameters, stored program local variables declared with DECLARE, user-defined variables, system variables, or literals.

Therefore, for the MESSAGE_TEXT you could use a user variable—but my preference would be for stored program local variables; however can't specify the SQLSTATE with a variable:
CREATE PROCEDURE throw_error_test (divisor INT)
BEGIN
  DECLARE _messageText VARCHAR(128);

  IF divisor = 0 THEN
    SELECT message
    INTO   _messageText
    FROM   error_messages
    WHERE  id = '45123';

    SIGNAL SQLSTATE '45123' SET MESSAGE_TEXT = _messageText
  END IF;

END

For the avoidance of doubt, the underscore _ prefixes are purely a convention that I adopt to avoid ambiguity—they are not a necessary part of a local variable name.


text:
Q: C Search duplicates in 2D array and working with indexes I am a kind of newbie in C so pardon me if i got something very wrong.
There is a problem i cant solve myself.
15 5
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
0 1 0 1 0
0 0 1 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
1 0 0 0 1
0 0 1 0 0
0 0 0 1 0

This is one of the input files i got called "ex1.be"
The first 2 number represents the 2D array's column and row, the rest is the data inside it.
My tasks first part is to "manage a robot" which gathers the numbers "1". If there is no "1" in the first row, the robot starts at the top left corner "[0][0]" otherwise at the position of the "1" which is [0][2] in this case. The robot can move only one "index" after each row so if the robot starts at [0][2] then in the next row it can be [1][1], [1][3] or can stay at [1][2]. The robot have to gather as many "1" as it can, but here comes the final part of the task that i need to count how much "1" will the robot miss either way.
For example at the 7th row there is 2 number "1" and it can only collect one of them.
Where i stuck currently at, is that i cant combine the program parts. My guess is that i have to know how much "1"s are in each row, for that i have to make 3 else-if statement for each case (zero "1", one piece of "1" and more piece of "1"). And a "for" cycle to  get the indexes of the "1"s. This two, i cant combine.There is my program so far:
#include <stdio.h>
#include <string.h>

int main()
{
    int rocket;  // the end return value
    int sum = 0;   // sum of each row
    int x;
    int i, j;
    int row, col;       //row, column
    FILE* ex1 = fopen("ex1.be", "r");
    fscanf(ex1, "%d %d", &row, &col);    //Row Column Initialization
    int matrix[row][col];   //Mátrix declaration

    for (int i = 0; i < row; i++)     //Matrix
    {
        for (int j = 0; j < col; j++)
        {
            fscanf(ex1, "%d", &matrix[i][j]);
        }
    }

    for (i = 0; i < row; i++) {  //mátrix draw
        for (j = 0; j < col; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    for (row = 0; row < i; row++) {
        sum = 0;
        for (col = 0; col < j; col++)
        {
            sum = sum + matrix[row][col];
        }
        if (sum < 1) {
            printf("zero rocket\n");
        }
        else if (sum == 1) {     //this part doesnt work as i would like it...
            if (matrix[i][j] == 1) {
                x = j + 1;
                printf("%d\n", x);
                x = 0;

            }
        }
        else if (sum > 1) {
            printf("more than one rocket\n");
        }
    }

    sleep(10000);
    return rocket;
}

There is many useless printf i know, those are for self-cheks. After this my guess is that i only need to do a few addition, subtraction and i could get the final number for the missing "1"s (rockets in my program because the task is covered in a fantasy scenario. Catching asteroids, and knowing how many rockets i need for the missed asteroids).

A: for (row = 0; row < i; row++)
{
    matrix[i][j]
    ...
}

This is not a proper loop. First, you are loosing the value of row and col. i and j remain constant, you don't go over the matrix elements. You have already worked it out for printing the elements, you just need to repeat that loop.
sum value has to be initialized each time. I don't what you intend to do with x, but the code should be more like this:
for (int i = 0; i < row; i++)
{
    sum = 0;
    for (int j = 0; j < col; j++)
        sum = sum + matrix[i][j];
    if (sum == 0)
        printf("zero rocket\n");
    else if (sum == 1)
    {
        for (int j = 0; j < col; j++)
        {
            if (matrix[i][j] == 1)
            {
                printf("%d\n", j + 1);
            }
        }
    }
    else if (sum > 1)
    {
        printf("more than one rocket\n");
    }
}


text:
Q: Where should I put background processes in rails? I'm building a Rails project that has a cron-type job that I'm managing with Rufus Scheduler. I have two questions about how to set this up appropriately in Rails:

*

*Where's the best place to put the job's code?

*Where should I place the Rufus code to schedule the job? How should I kick it off?

A: To control the scheduler I would create a config/initializers/task_scheduler.rb:
task_scheduler = Rufus::Scheduler.start_new

task_scheduler.every("1m") do
   Something.to_do! # Do something every minute!
end

Now for the Something.to_do code, that sort of depends on what it does. Perhaps it is a data model and it should go in the app/models directory, but if it is something more generic you might want to place it in lib/. If you wind up with a number of scheduled tasks you might want to create a app/scheduled_tasks directory, but that might be overkill for just one file.


text:
Q: WaitForExitAsync with a timeout So I noticed that there's a method called WaitForExit that accepts and int as argument (milliseconds) so if the process isn't able to exit itself, I just killed it after some seconds.
Something like this.
if (!CMD.WaitForExit(3000))
    CMD.Kill();

The thing is that meanwhile I'd like to save the output, so I noticed that there's an async method WaitForExitAsync but this one doesn't accept these milliseconds.
// Wait for exit async...
// Meanwhile save the output till it kills itself.

while (CMD.StandardOutput.ReadLine() != null)
    standard_output = StandardOutput.ReadLine();

Any idea how to do this? Thanks!

A: You need to use CancellationTokenSource. It has a ctor which accepts a TimeSpan
var timeoutSignal = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
   await CMD.WaitForExitAsync(timeoutSignal.Token);
} catch (OperationCanceledException)
{
   CMD.Kill();
}

When the CTS signals then the awaited operation will throw an OperationCanceledException. So you need to wrap your await call into a try-catch to handle cancelled operation properly.

UPDATE #1: Capture STDOUT with async wait of exit
Naive approach
First let me share with you the naive version of the code
Console.WriteLine("Launch ping with fifteen retries");
var terminal = Process.Start(new ProcessStartInfo("/sbin/ping")
{
    RedirectStandardOutput = true,
    Arguments = "-c 15 stackoverflow.com",
    UseShellExecute = false,
});

_ = Task.Run(() =>
{
    string line = null;
    while ((line = terminal.StandardOutput.ReadLine()) != null)
        Console.WriteLine(line);
});

var timeoutSignal = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
    await terminal.WaitForExitAsync(timeoutSignal.Token);
    Console.WriteLine("Ping has been Finished");
}
catch (OperationCanceledException)
{
    terminal.Kill();
    Console.WriteLine("Ping has been Terminated");
}

*

*I'm using .NET on a Macintosh machine so, I don't have ping.exe rather than I can run /sbin/ping command

*I ping stackoverflow fifteen times to make sure the command runs more than 3 seconds

*I've moved the StandardOutput reading to a separate thread (Task.Run)

*

*Without that, the cancellation signal will not have any effect

*The rest of the code same as above + debug logging

Suggested approach
The Process class does expose a capability to read data asynchronously from the StandardOutput without the need to do extra tricks
Console.WriteLine("Launch ping with fifteen retries");
var terminal = new Process()
{
    StartInfo = new ProcessStartInfo("/sbin/ping")
    {
        RedirectStandardOutput = true,
        Arguments = "-c 15 stackoverflow.com",
        UseShellExecute = false,
    }
};

terminal.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
terminal.Start();
terminal.BeginOutputReadLine();

var timeoutSignal = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
    await terminal.WaitForExitAsync(timeoutSignal.Token);
    Console.WriteLine("Ping has been Finished");
}
catch (OperationCanceledException)
{
    terminal.Kill();
    Console.WriteLine("Ping has been Terminated");
}

Let me highlight only the differences

*

*Rather than starting the process right away, first we create a Process and specify its StartInfo property

*Then we subscribe to the OutputDataReceived event

*

*Its EventArgs' Data property contains the newly available information

*After the subscription we can call the Start method

*And finally we need to call the BeginOutputReadLine method to tell the Process fire the above event handler whenever new data is available on the standard output

A: The new .NET 6 comes with WaitAsync method that allows asynchronously waiting for a task with a timeout.
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromMilliseconds(1000));

if (!process.HasExited)
{
    //timeout!
}

A: It have a argument takes millisecond
WaitForExitAsync(process, timeout);


text:
Q: Laravel questions about using One to One relationship between 2 tables I have 2 tables which is district and address. Suppose these 2 tables have relations between each other. address table holds district foreign key. The problem is that it returns null in views. How do I display/output the district name? I followed the instruction exactly based on Laravel documentation.
DISTRICT TABLE

District Model
public function address()
{
    return $this->hasOne('App\Address');
}

ADDRESS TABLE

Address Model
public function district()
{
    return $this->belongsTo('App\District', 'district');
}

View
$getAddress = App\Address::all();

foreach($getAddress as $add)
{
   Address name: {{ $add->address_name }}
   District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}

A: Instead you should get all value in one stroke by using with
$getAddress = App\Address::with('district')->all();

And get value as
{{ $add->district->district_name }}

A: you should try this:
<php $getAddress = App\Address::with('district')->get(); ?>

@foreach($getAddress as $add)

   Address name: {{ $add->address_name }}

   @foreach($add->district as $districrt)
    District name : {{ $districrt->district_name }}
  @endforeach

@endforeach


text:
Q: Subversive: Change SVN commit message retroactively? Actually I need to modify SVN commit message. A lot of related staff exists how to do it (e.g. Change SVN commit message retroactively?).
My question is, could I do it from Eclipse's subversive plugin?

A: As gouessej commented, for quick reference, the process for me was:

*

*Team > Show History

*Right click on an element in the list and select Set Commit Properties

A: It is not easy to find, but possible. This recipe is working for Eclipse Indigo (3.6) and Subversive 0.7.9I20110321-1700. Do the following steps:

*

*Open for an item where you want to change a log message the history: Team > Show History. This opens a new view named History.

*In that view, you see the log messages of the selected item. Select one of the messages and choose from the context menu Show revision properties.

*Select svn:log and then from the context menu Edit.... This opens a new dialog where you can change the log message (if allowed on the server).

The best answer I found at Stackoverflow to the base question was this one that states clearly that it is not the default behavior of a Subversion server to allow that, so normally, it won't be possible without the help of an administrator.


text:
Q: Error when importing a SQL file using phpMyAdmin I am not proficient in MySQL and phpMyAdmin and got this error when trying to import my SQL file to a new installation of WAMP. I was developing a joomla website on my local pc and after completion, decided to launch it online with Rochen web hosting. When importing this into my Cpanel, it gave me the error below.
Error
Static analysis:

*

*errors were found during analysis.
A closing bracket was expected. (near ")" at position 276)
SQL query:

*

*Database: kwadi.

Table structure for table iq2rf_assets:
CREATE TABLE `iq2rf_assets`
(
  `id` int(10) UNSIGNED NOT NULL COMMENT 'Primary Key',
   `parent_id` int(11) NOT NULL DEFAULT '0'COMMENT
)

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near ')' at line 14

I tried to resolve with their support but their advice was for me to upgrade my WAMP Server on my local pc to the one that has MariaDB in it and try extract. Now after installing the new WAMP server i am faced with the same issue when trying to import my back up db using phpmyadmin.
It is giving me the same error. I do not know what to do.
Need assistance.

A: CREATE TABLE iq2rf_assets ( id int(10) UNSIGNED NOT NULL COMMENT 'Primary Key', parent_id int(11) NOT NULL DEFAULT '0')

You do not have a comment on the second field (parent_id), yet you are using the keyword "COMMENT" only to be closing the query after that. Remove it and you're good to go

A: The assets table has more fields than the 2 fields shown in your post.
This is the reason for the failed import, check your export.


text:
Q: Proving limit of sin(1/x)cos(1/x) doesn't exist as x goes to 0 Just a quick question, this may or may not be a duplicate by the way. I've seen the proof of the trig functions not existing separately but I couldn't seem to find them multiplied together like in this problem. My question is could I just separate the two functions, prove that both limits do not exist and say the overall limit doesn't exist or is that the completely wrong way of approaching the problem?
EDIT: Here's my attempt with the use of $\frac{sin(\frac{2}{x})}{2}$ hint.
Proof:
Note that $\sin(\frac{1}{x})\cos(\frac{1}{x})$ =  $\frac{\sin(\frac{2}{x})}{2}$. Let f(x) =  $\frac{\sin(\frac{2}{x})}{2}$.
$\sin \theta = 1$ when $\theta = \frac{4k+1 \pi}{2}$ for $k \in \mathbb{Z}$
$\sin \theta = -1$ when $\theta = \frac{4k+1 \pi}{2}$ for $k \in \mathbb{Z}$
so $\sin(2/x_n) = 1$ when $x_n = \frac{4}{(4n+1)\pi}$ which equals $0$ when $n$ goes to infinity and $f(x_n) = 1$ for all $n$
$\sin(2/y_n) = 1$ when $y_n = \frac{4}{(4n-1)\pi}$ which equals $0$ when $n$ goes to infinity and $f(y_n) = -1$ for all $n$
It then follows that:
$\sin(2/x_n)/2 \implies f(x_n) = 1/2$
$\sin(2/y_n)/2 \implies f(y_n) = -1/2$
Since $\{x_n\}$ goes to zero $x_n \neq 0$ and $\{y_n\}$ goes to zero $y_n \neq 0$ but
$\{f(x_n)\} \rightarrow 1/2 \neq -1/2 \leftarrow\{f(y_n)\}$
$\lim_{x \to 0} f(x)$ does not exist by the sequential criterion.
Is this totally off?

A: You could use the identity $ \sin(2/x)/2 = \sin(1/x)\cos(1/x) $ and then quote the result for $ \sin(1/x)$. As for separating the two functions and proving it that way, the answer is no. For example $ f(x) = 1 $ for $ x > 0 $ and $ f(x) = 0 $ for $ x \leq 0 $ and $ g(x) = 1 $ for $ x \leq 0 $ and $ g(x) = 0 $ for $ x > 0 $. Then neither of the limits exist as $ x\to 0 $ but the product $ f(x)g(x) = 0 $ does exist.


text:
Q: How to enable/disable macro expansion in XCode? Some of the machines in our office when compiling projects in XCode will flag build errors because they are doing macro expansion and finding legitimate errors.  Other machines don't do the expansion and don't catch these errors.  There must be an option to enable/disable this somewhere in XCode.  I cannot find it, is anyone familiar with this?

A: This was my fault and it was because of a preprocessor def. In one case the macro will expand to a typed constant whereas the other case which I use most of the time the macro expanded out to a function call with the constant as a string parameter. So in one case I get int myConstant which the compiler will flag if there is a problem. In the other case it would be myFunc("myConstant") which would not flag a compiler error.


text:
Q: Get Smiley and text into string from edittext In chat application i use emoji i am set it in edittext but while fetching it return an obj
EditText txt = (EditText)findViewById(R.id.edit_text);
ImageGetter imageGetter = new ImageGetter() {
    public Drawable getDrawable(String source) {
    try
    {
        Drawable d = getResources().getDrawable(value);
        int size = txt.getHeight();
        d.setBounds(0, 0, size, size);
        return d;
    }
    catch(Exception e)
    {
        return null;
    }
    }
};

Spanned cs1 = Html.fromHtml("<img src='"+d+"'   />", imageGetter, null);
txt.getText().insert(txt.getSelectionStart(), cs1);

this is how i set emoji in edittext. now issue comes while fetching text+emoji
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(txt.getText().toString());

here i got text but not emoji it return obj


text:
Q: Making a simple javascript Image gallery I'm trying to make a very simple Image gallery. Most of the design is already complete (used JQuery)...but now I'm trying to think out the logic it takes to get the images to change. For this part I was thinking I would just use javaScript instead of Jquery just to keep it simple. I'm not too familiar with the javaScript syntax but this is my attempt to get started. Is this a feasible way to create an image gallery? I know making the images the background isn't a great idea, but for testing purposes I don't feel like cropping images -- so setting the image as the background trims the images to fit.
I was also trying to think about how to set the ImageCnt to zero initially... Can an onload function be used to set the ImageCnt to 0 when the page loads? Can a var be passed into next()? If so, I could pass the current ImageCnt from the onClick to the function.
PS. I've omitted a lot of code to keep it simple to read, but I can provide more if it's necessary.
Thanks! here's my code:
Javascript

html

A: Most importantly, you need to build the background property by concatenating ("+" operator) its different parts, as shown below ; otherwise it won't be replaced by the values from your array if you make it a static string.
Also use the global scope to declare and initialize your image array and counter :

Finally, return false from onclick otherwise you'll reload the page :

A: This is the best example of a simple inline non-jQuery image gallery that I've found, obtained from http://extremestudio.ro/:
<!DOCTYPE html PUBLIC>

    <title>
      Simple and Effective Photo Gallery with HTML and JavaScript
    </title>

Simple and Effective Photo Gallery with HTML and JavaScript

The only javascript is embedded in the  tags, but could easily be moved to script tags for more flexibility.


text:
Q: Is there a program to shorten this? I'm new to python, started doing it in quarantine just for fun. I was working on some Python code the other day, and decided to create an image with the turtle program. I'm seeing a lot of repetition here, so I was wondering if there was a way I could shorten it. Here's the code:
import turtle
wn = turtle.Screen()
House = turtle.Turtle()

House.forward(150)
House.left(90)
House.forward(110)
House.left(45)
House.forward(110)
House.left(90)
House.forward(110)
House.left(45)
House.forward(110)

wn.mainloop()

Thanks!

A: For this explicit example, you can try this:
House.forward(150)
for iter in range(2):
    for left_pos in [90,45]:
        House.left(left_pos)
        House.forward(110)
wn.mainloop()

A: You can do something like:
left_vals = [90, 45, 90, 45]
House.forward(150)
for v in left_vals:
  House.left(v)
  House.forward(110)

You can always use a for loop to reduce code repetition. If there is a pattern, you can use a function instead of putting values in the list. Here for example it seems like you call 90 and 45 in order. So you can do this:
House.forward(150)
for i in range(4):
  House.left(45 * (2 - i%2))
  House.forward(110)

A: import turtle

wn = turtle.Screen()
house = turtle.Turtle()

# function table for the turtle (fill up with other functions)
draw = {
    'F': house.forward,
    'L': house.left,
}

# direction, value
instructions = (
    ('F', 150),
    ('L', 90),
    ('F', 110),
    ('L', 45),
    ('F', 110),
    ('L', 90),
    ('F', 110),
    ('L', 45),
    ('F', 110),
)

for dir, val in instructions:
    draw[dir](val)  # call each function from the dict with the value

wn.mainloop()

A: First, let's correct the initial forward() distance to match the roof size.  Then the program breaks down to four repetitions of the same left() and forward() motion with an alternating angle:
from turtle import Screen, Turtle

turtle = Turtle()
turtle.forward(110 * 2 ** 0.5)

angle = 90

for _ in range(4):
    turtle.left(angle)
    turtle.forward(110)

    angle = 135 - angle

screen = Screen()
screen.mainloop()

A: Here's something:
import turtle
wn = turtle.Screen()
House = turtle.Turtle()

for n in [(150,90),(110,45),(110,90),(110,45)]:
    House.forward(n[0])
    House.left(n[1])
House.forward(110)

wn.mainloop()


text:
Q: Why use many sub-projects and dependencies over packages? I've mostly in my career worked in small or mid-sized java projects. I recently saw a huge project comprising of 30 projects in eclipse. I don't really get concept of creating many small projects and then maintain inter-project dependencies. When do we prefer this over simply organizing stuff in packages?
I guessed it's a maven thing (have mostly been using Ant). I've been reading up on Maven's concept of modules as well – I saw some links on net recommending creation of different modules for web, dao and service layers under a parent module. Is it really a common/best practice?
With or without maven – does such division really makes life easier? Isn't it more compact to have everything in a single project with well-defined packages structure for different layers?

A: It's common to split up projects into API, implementation, web, etc. components–when there's a need to do so. Large projects are just that: large.
There are benefits to keeping components separate"

*

*Re-use functionality (e.g., the web layer uses the service layer

*Package individual components (e.g., ship jus the API to a client)

*Version sub-components; define their version dependencies

You can do all the same stuff with one giant project, but it's more difficult to determine what goes where, and why. Life is easier when those lines of demarcation are clearly defined.
How much easier depends on the project, but when you're dealing with hundreds of thousands of lines of code, occasionally millions, breaking that stuff up saves huge headaches.

A: Why choose to create a separate module in maven? To help you with your development. There really is no other reason.
The are a number of different reasons why you may want to create a separate module:

*

*Separation of concerns: yes, you can do this with packages, but if it's in a separate module, then it can be compiled separately, and you can reduce the amount of tangle[*] in your packages.

*The modules are managed by different teams, with release cycles of their own.

*More understandable code: If all of your dao code is in one module, and all of your web in another, you can test them separately.

*A module can be a separate deployable entity. I have a project which has two web apps, 5 batches and two other core modules (one core for the webapp and one core for the batches). I can now build and deploy each module separately.

*The modules are published and used externally. If this is true, then you want the minimum amount of 'other' code in this module.

You choose to break up into modules for the same reasons as you would for separating into packages, but at a higher level, at a group of packages.
30 does seem excessive. But there may be good reasons for it. It's up to you and your project to decide what is the right level for the number of modules.
Personally, I try not to split excessively, unless there is a very good reason to do so.
[*] Tangle: mess which describes the links between packages. Package A uses B, which uses C, which uses both A and B. Something which doesn't help understanding.

A: I think excessive modularisation is akin to over engineering. The best route in my opinion is to start with one module/project and keep with that until such point as it becomes obvious to everyone involved that part of this existing module would benefit from being extracted into its own module. Yes, that means extra work at that point, but for me I'd rather do the work then than endlessly battle with unneeded complexity, in terms of my builds and my development environment, for benefits which are never actually realised.
Unfortunately there seems to be a tendency at the start of a projects to modularise to the nth degree before even a single line of code is written.

A: there is another advantage to this.. if i have to deploy on 'selected' components i dont waste time and resources deploying dependencies that I dont need.


text: Q: Finding Equal-volume Triangulations in Homogenic Coordinates Given the $n$-dimensional triangulation $\mathbb{T}^n$ of a finite set of points $\{p_1,\ ...\ ,\ p_{n+k}\} \subset \mathbb{R}^n$, is it always possible to find $n+k$ positive real weights $\{\omega_1,\ ...\ , \omega_{n+k}\}$  so that all $n$-dimensional volumes of the simplices of $\mathbb{T}^n$ are equal when lifting their corner coordinates to homogenic coordinates via replacing $p_i$ with $(\omega_i p_i,\ \omega_i)\in\mathbb{R}^{n+1},\ i\in\{1,\ ...\ , n+k\}$?


text:
Q: VBA Autofiltering with multiple values from a single column I am using the following VBA in excel to auto filter a "Master" spreadsheet from a secondary tab which features a table filled with formulas and a set of filters Q4:Q12 in the code beelow. The VBA code filters the master to the data currently selected with the Q filters in the table as well as a few other values:
wsData.Range("A1:BZ1").AutoFilter 1, Criteria1:=Array(summaryData.Range("D3").Value, summaryData.Range("F3").Value, summaryData.Range("H3").Value, summaryData.Range("J3").Value, summaryData.Range("L2").Value), Operator:=xlFilterValues
wsData.Range("A1:BZ1").AutoFilter 75, "Added"
wsData.Range("A1:BZ1").AutoFilter 76, "Delivery Date Moved Out"
wsData.Range("A1:BZ1").AutoFilter 24, "Inside LT"
wsData.Range("A1:BZ1").AutoFilter 4, IIf(Trim(summaryData.Range("Q4").Value) = "", "<>", "=") & summaryData.Range("Q4").Value
wsData.Range("A1:BZ1").AutoFilter 3, IIf(Trim(summaryData.Range("Q5").Value) = "", "<>", "=") & summaryData.Range("Q5").Value
wsData.Range("A1:BZ1").AutoFilter 5, IIf(Trim(summaryData.Range("Q6").Value) = "", "<>", "=") & summaryData.Range("Q6").Value
wsData.Range("A1:BZ1").AutoFilter 6, IIf(Trim(summaryData.Range("Q7").Value) = "", "<>", "=") & summaryData.Range("Q7").Value
wsData.Range("A1:BZ1").AutoFilter 7, IIf(Trim(summaryData.Range("Q8").Value) = "", "<>", "=") & summaryData.Range("Q8").Value
wsData.Range("A1:BZ1").AutoFilter 8, IIf(Trim(summaryData.Range("Q9").Value) = "", "<>", "=") & summaryData.Range("Q9").Value
wsData.Range("A1:BZ1").AutoFilter 9, IIf(Trim(summaryData.Range("Q10").Value) = "", "<>", "=") & summaryData.Range("Q10").Value
wsData.Range("A1:BZ1").AutoFilter 10, IIf(Trim(summaryData.Range("Q11").Value) = "", "<>", "=") & summaryData.Range("Q11").Value
wsData.Range("A1:BZ1").AutoFilter 11, IIf(Trim(summaryData.Range("Q12").Value) = "", "<>", "=") & summaryData.Range("Q12").Value

The code is working as is, however I want to add another autofilter. This one is a little different than the ones I already have functioning.
There is a column in the Master (column 4) which has a number of different "program codes". There is also a Q filter, Q6, which groups some of the "program codes" into a single category. For Example if a user selects Group 1 then the Master would be filtered to show program code A,B and C. If the User selected Group 2, then the Master would be filtered to program codes D,E and F and so on.
I know how to filter based on multiple different range values, would this work the same way as that since the program codes are in the same column? Thanks for the help in advance!


text:
Q: Setting the icon for a MessageDialog causes issues I'm trying to set an Icon for a Message Alert popup, and I'm using the methods I've found online. However, they're causing issues where the image:

*

*Doesn't even get set as the icon

*Is way too oversized

*Placed in the JPanel

The screenshot below shows what I mean:
Screenshot of Issue
And my code doesn't seem to have any issues:
final ImageIcon iconF = new ImageIcon(LOGIN.class.getResource("/resources/offline.png"));
JOptionPane.showMessageDialog(null, "ERROR: Please check your username and password then try again.", "Login Failed", JOptionPane.ERROR_MESSAGE, iconF);

I don't understand what's causing this mess of an issue when this seems to be the "answer" to my own question.


text:
Q: React Router only rendering one route I am new to React and react-router-dom.  I have spent a couple hours now and I'm just hitting dead ends.
I'm using create-react-app and bulma for css. My dependencies:
"dependencies": {
  "bulma": "^0.7.1",
  "font-awesome": "^4.7.0",
  "node-sass-chokidar": "^1.3.3",
  "react": "^16.5.2",
  "react-bulma-components": "^2.1.0",
  "react-dom": "^16.5.2",
  "react-fontawesome": "^1.6.1",
  "react-router-dom": "4.3.1",
  "react-scripts": "2.0.4"

},
I've looked at all the related questions on stackoverflow, create-react-app documentation and searched their open issues section in their repo, googled every possible keyword. I'm at a loss.
My router will only render one route (Homeroute).
How do I get this to show '/create' route as well?
I've tried:

*

*combinations of 'exact' and 'strict' attributes

*wrapped everything after <BrowserRouter> or <HashRouter> with a

*tried both (un)wrapping <Route> with <Switch>

*tried both BrowserRouter and HashRouter
import React, { Component } from "react";
import { Switch, Route, NavLink, BrowserRouter, HashRouter } from "react-router-dom";

const Home = () => {
    return (
This is Home
);
}
const Create = () => {
    return (
This is Create page
);
}

class App extends Component {
  render() {
    return (
      <HashRouter>

          <Navigation />

            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/create" exact Component={Create} />
            </Switch>

      </HashRouter>
    );
  }
}
export default App;

URL: http://localhost:3000/#/
Result:  "This is Home"
Expect:  "This is Home"

URL: http://localhost:3000/#/create
URL: http://localhost:3000/#/create/
Result:   nothing
Expect:  "This is Create page"

A: It's a typo. Notice the letter "C", it's supposed to be lower-case.
Make a change, from
<Route path="/create" exact Component={Create} />

to
<Route path="/create" exact component={Create} />

This is the demo: https://codesandbox.io/s/oq0rov0r4q


text:
Q: Angular 2.0 forms callback and logic issue I am very new to Angular, i am truing to create a simple script to update the price when the value of a form input gets changed. There seems to be several different methods for using Angular with class driven and directive driven models. Read the documentation from the main angular website, but no luck.
import { Component } from '@angular/core';
export class Ticket {
  ticketNumber: number;
  name: string;
  price: number;
}
@Component({
  selector: 'my-app',
  template: `
    <form name="myForm">

{{ticket.name}}

        <input type="number" name="myInput" class="ticket_ammount" min="1" max="10" value="{{ticket.ticketNumber}}"required ng-class="updatePrice(price,ticketNumber)">

<input class="ticket_details_input" type="text"  placeholder="Name:" required>

<input class="ticket_details_input" type="email" placeholder="your@email.com" required>

<input class="ticket_details_input" type="text"  placeholder="+852" required>

$ <input type="number" name="price" value="{{ticket.price}}|>
        <button type="button" class="ticket_button">Book</button>

    </form>
    `
})
//creates the class
export class AppComponent {
  ticket: Ticket = {
    ticketNumber: 1,
    name: 'Ticket',
    price: 300
  };
  //updates the price on a new click
  updatePrice(value, ticketN){
      value = value * ticketN;
      return value;
      // this then needs to be passed back to the price input field.
  }
}

----- UPDATE -------
so i was having issues with calling two class's, and trying to make them interact. I striped out the code and started again this is what i put in to make it work.
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <form>

{{title}}

          <input type="number" name="myInput" class="ticket_ammount" min="1" max="10" [(ngModel)]="ticket" (click)="updatePrice()" required>

$<input type="number" [(ngModel)]="totalPrice" class="ticket_price_number" disabled>

            <button type="button" class="ticket_button">Book</button>

    </form>
    `
})
export class AppComponent {
  ticket: number = 1;
  title: string = "Ticket";
  price: number = 300;
  totalPrice: number = 300;
  updatePrice(){
    this.totalPrice = this.price * this.ticket;
    if(this.ticket >= 2){
      this.title = "Tickets";
    }
    else{ this.title = "Ticket";}
  }
}

A: To two way bind value to input you need to user ngModel.
<input [(ngModel)]="ticket.price">


text:
Q: How to insert cell to collection view cell using swift 2.2 Am parsing api to collection view which works fine now i need to insert new cell which should perform action also
import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage

 class EditPendingViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate{

var favDict = NSMutableArray()

 override func viewDidLoad() {
        super.viewDidLoad()
         JsonParsingFromURL()
       self.navigationController!.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        FavCollectionView.backgroundColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1.0)
        FavCollectionView.hidden = false
        NoAdsview.hidden = true
        NoAdsview.backgroundColor = UIColor(red: 249/255, green: 249/255, blue: 249/255, alpha: 1.0)

           JsonParsingFromURL()
        // Do any additional setup after loading the view.
    }

 func JsonParsingFromURL(){
        self.view.makeToastActivity(.Center)
        if Reachability.isConnectedToNetwork() == true
        {
            Alamofire.request(.GET, myapiKeyforsmart + "allad.php?customerid="+MyCustId+"", parameters: nil, encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
                let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
                print(dataString)
                let json = JSON(data: data!)
                let FavMsg = (json["error_msg"]).stringValue
                self.view.hideToastActivity()
                if error != nil{
                    print("error occured = \(error)")
                }
               else if error == nil && FavMsg == "No favourite available"
                {
                   self.FavCollectionView.hidden = true
                   self.NoAdsview.hidden = false

                }
                else{
                       self.startParsing(data!)
                }
            }
        }
        else{
            self.view.hideToastActivity()
            let alert = UIAlertController(title: "No Internet Connection", message: "make sure your device is connected to the internet", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
    func startParsing(data :NSData)
    {
        let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
        for i in 0  ..< (dict.valueForKey("favourite Ads") as! NSArray).count
        {
            favDict.addObject((dict.valueForKey("favourite Ads") as! NSArray) .objectAtIndex(i))
        }
        FavCollectionView.reloadData()
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return favDict.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FavouriteCell", forIndexPath: indexPath) as! ThirdTableViewCell
        let adTitle:NSString = favDict[indexPath.item].valueForKey("adtitle") as! NSString
        let Price:NSString = favDict[indexPath.item].valueForKey("originalprice") as! NSString
        let currencyFormatter = NSNumberFormatter()
        currencyFormatter.usesGroupingSeparator = true
        currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        currencyFormatter.locale = NSLocale.currentLocale()
        let numberFromField = (NSString(string: Price).doubleValue)
        let priceString = currencyFormatter.stringFromNumber(numberFromField)
        let address:NSString = favDict[indexPath.item].valueForKey("districtname") as! NSString
        let ImageString:NSString = favDict[indexPath.row].valueForKey("images") as! NSString
        let parts = ImageString.componentsSeparatedByString(",")
        let firstImage = parts[0]
        cell.FavTitle.text = adTitle as String
        cell.FavPrice.text = priceString! as String
        cell.FavPrice.backgroundColor = UIColor().HexToColor("#8000000", alpha: 0.5)
        cell.FavAddress.text = address as String
        cell.FavImage.sd_setImageWithURL(NSURL(string: imageApikey + (firstImage as String)))
        cell.contentView.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
        cell.layer.cornerRadius = 10
        cell.layer.borderColor = UIColor.clearColor().CGColor
        if Price == "0"{
            cell.FavPrice.hidden = true
        }
        return cell
    }
 }

This is my full code in view controller.I have searched other stack overflow answer nothing helps me can anyone help me to do this one


text:
Q: Why do I get the error "file format not recognized; treating as linker script" when compiling my Unix copy program? I am new to Unix and I want to make a copy program that uses CL for compiling it. I get: "file format not recognized; treating as linker script".
This is my code for copying from source file to destination
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
    FILE *fsource, *fdestination;

    printf("enter the name of source file:\n");
    char sourceName[20], destinationName[20];
    strcpy(sourceName, argv[1]);
    strcpy(destinationName, argv[2]);

    fsource = fopen(sourceName, "r");
    if (fsource == NULL)
        printf("Nije uspjelo otvaranje file-a za citanje\n");
    else
        printf("Uspjesno ste otvorili file za citanje!\n");
    fdestination = fopen(destinationName, "w");
    if (fdestination == NULL)
        printf("Nije uspjelo otvaranje file-a za pisanje\n");
    else
        printf("Uspjesno ste otvorili file za pisanje!\n");

    char pen = fgetc(fsource);
    while (pen != EOF)
    {
        fputc(pen, fdestination);
        pen = fgetc(fsource);
    }

    fclose(fsource);
    fclose(fdestination);
    return 0;
}

I am trying to compile it from vm using "gcc 2.c source.txt destination.txt" command. I've created two files in the same directory.

A: You are trying to compile the program (that means, making an executable application out of the code) and run it at the same time. You need to compile your application first using:
gcc 2.c -o programname
and then execute it via
./programname source.txt destination.txt

A: You supplied the command line arguments which are intended for your program to the gcc compiler, instead. This is wrong. First compile your program using e.g. gcc 2.c -o mycopy and then invoke your program by ./mycopy source.txt destination.txt.
$gcc 2.c -o mycopy
$echo "test1234" > source.txt
$cat source.txt
test1234
$./mycopy source.txt destination.txt
enter the name of source file:
Uspjesno ste otvorili file za citanje!
Uspjesno ste otvorili file za pisanje!
$ls
2.c  destination.txt  mycopy  source.txt
$cat destination.txt
test1234

Voila, seems your copy program produced the desired result!


text:
Q: threeJS Raycaster.set() not detecting intersections ( plane )   const origin = new THREE.Vector3(...point, -100),
        direction = new THREE.Vector3(0, 0, 1)    // is a normalized vector
  const raycaster = new THREE.Raycaster( origin, direction );
  const intersects = raycaster.intersectObject( dem );  // is a planeGeometry (mesh)

  const length = 2000;
  const hex = 0xff0000;

  const arrowHelper = new THREE.ArrowHelper( direction, origin, length, hex );
        cx3d.addObject( arrowHelper );

  if( intersects.length ){
    console.log( intersects[0] )
  }

now intersects = [], but point is in the plane mesh, so I need help, thank everyone
like this https://jsfiddle.net/Hoshua/obm8ke0q/2/

A: You need to update your mesh matrix world with mesh.updateMatrixWorld();. See below.
function seta(){
  const origin = new THREE.Vector3(0.5, 0, 0),
        direction = new THREE.Vector3(-1, 0, 0)
  const raycaster = new THREE.Raycaster( origin, direction );
  mesh.updateMatrixWorld(); // here
  const intersects = raycaster.intersectObject( mesh );

  const length = 1.5;
  const hex = 0xff0000;

  const arrowHelper = new THREE.ArrowHelper( direction, origin, length, hex );
  scene.add( arrowHelper );

  console.log(intersects)

}

Not sure if link will work. In case: https://jsfiddle.net/4n0tgwuo/
Output:
[{
  distance: 0.5,
  face: {
    a: 0,
    b: 2,
    c: 1,
    materialIndex: 0,
    normal: { ... }
  },
  faceIndex: 0,
  object: {
    animations: [],
    castShadow: false,
    children: [],
    frustumCulled: true,
    geometry: { ... },
    isMesh: true,
    isObject3D: true,
    layers: { ... },
    material: { ... },
    matrix: { ... },
    matrixAutoUpdate: true,
    matrixWorld: { ... },
    matrixWorldNeedsUpdate: false,
    name: "",
    parent: { ... },
    position: { ... },
    quaternion: { ... },
    receiveShadow: false,
    renderOrder: 0,
    rotation: { ... },
    scale: { ... },
    type: "Mesh",
    up: { ... },
    userData: { ... },
    uuid: "cb14eb31-b325-4252-8fb6-0d4417cbf39d",
    visible: true
  },
  point: {
    isVector3: true,
    x: 0,
    y: 0,
    z: 0
  },
  uv: {
    isVector2: true,
    x: 0.5,
    y: 0.5
  }
}, {
  distance: 0.5,
  face: {
    a: 2,
    b: 3,
    c: 1,
    materialIndex: 0,
    normal: { ... }
  },
  faceIndex: 1,
  object: [circular object Object],
  point: {
    isVector3: true,
    x: 0,
    y: 0,
    z: 0
  },
  uv: {
    isVector2: true,
    x: 0.5,
    y: 0.5
  }
}]


text:
Q: "Spoof" File Extension In Bash Is there a way to "spoof" the file extension of a file in bash for consumption by another program? I can think of doing some shell scripting and making lots of soft-links, but that isn't very scalable.
Let's imagine I have a program I'm trying to use that requires input files to be of a specific file extension, and it has no method of turning off this check.

A: You could make a fifo with the requisite extension and cat any other file type into it. So, if your crazy program needs to see files that end in .funky, you can do this:
mkfifo file.funky
cat someotherfile > file.funky &
someprogram file.funky

A: Create a symbolic link for each file you want to have a particular extension, then pass the name of the symlink to the command.
For example suppose you have files with names of the form *.foo and you need to refer to them with extensions of .bar:
for file in *.foo ; do
    ln -s $file _$$_$file.bar
done

I precede each symlink name with _$$_ to avoid the possibility of colliding with an existing file name (you don't want to do ln -s file.foo file.bar if file.bar already exists).
With a little more programming, your script can keep track of which symlinks it created and, if you like, clean them up after executing the command.
This assumes, as you stated in the question, that the command can't be forced to accept a different extension.
You could, without too much difficulty, create a wrapper script that replaces the command in question, creating the symlinks, invoking the command, and cleaning up after itself automatically.


text:
Q: Avoid expansion of sys.argv keyword argument in Sphinx documentation I have a class like this one
import sys

class ACommand(object):

    @classmethod
    def cmd(cls, argv=sys.argv):
        " Executes the command. "
        pass

When documenting this with Sphinx it expands sys.argv to its current value, producing something like the following signature
classmethod cmd(argv=['/path/to/sphinx-build', '-b', 'html', '-d', '_build/doctrees', '.', '_build/html'])

I find it more convenient to have sys.argv in the documentation than its expansion. How can I achieve this?

A: You could create a proxy object such as
class ListProxy(object):
    def __init__(self, l):
        self.list = l
    def __getitem__(self, i):
        return self.list[i]

and then
@classmethod
def cmd(cls, argv=ListProxy(sys.argv)):
    " Executes the command. "

Or, easier, you could do
@classmethod
def cmd(cls, argv=None):
    " Executes the command. "
    if argv is None:
        argv = sys.argv


text:
Q: Strong Correlation(89%) but negetive coefficient with value (-0.00) My dataframe has 8 Columns ( target_var='I62' ). when I am running my python pandas corr() it give me a very good correlation between my target_var and IOF2 and H6.
# This data is till 2019-Dec
    df3Train = pd.read_csv('I62Trainv7.csv', parse_dates=['Value_Date'],index_col=['Value_Date'])
    df3Train.corr()

Please see below image
Correlation
Using 'I62'(y), and "[IOF2,H6]" (x), I created the LinearRegression model from sklearn. When I am looking for the coefficient of the model it shows me negative (-0.004) coefficient for H6:
# Model building with I62 and IOF2 and H6
    y = df3TrainClean["I62"]
# Independent Vars
    x = df3TrainClean[['IOF2', 'H6']]
# Training on 80% Testing 20%
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=1)

    lrModel = LinearRegression()
    lrModel.fit(x_train, y_train)
    print(lrModel.score(x_test, y_test))
    print(lrModel.score(x_train, y_train))

# Lets train the model
    lrModel.fit(x,y)
    yPred = lrModel.predict(x_test)

# Coefficients
    coeff_df = pd.DataFrame(lrModel.coef_, x.columns, columns=['Coefficient'])
    coeff_df

Coefficient
I am bit lost, when there is a good correlation, how come the coefficient is too low (and negetive) !!!
Can anyone please explain and the impact of this negetive coefficient on the predictions.
Thanks

A: Negative correlation means that when one value increases, the other decreases. Correlation can take a value of -1, which means that two values always move in opposite directions. A correlation of 0 means that the movement of one does not imply the movement of another -- i.e. they are not correlated at all.


text:
Q: How do I prevent my logos from disappearing when I toggle my menu to close and resize my window? I have a menu of logos that will be clickable. They always display except on smaller screens, where they need to be toggled to show using a hamburger menu. The menu toggles fine when it is on a smaller screen, but when you resize the window (if the menu is closed), all of the logos display as "none" and won't toggle back. I'm not sure if I need to adjust my css or if my JS is off.

document.getElementById('menu').addEventListener('click', myFunction);

function myFunction() {
  let logo = document.getElementsByClassName("team");

  for (i = 0; i < logo.length; i++) {
    if (logo[i].style.display === 'none') {
      logo[i].style.display = 'inline';
    } else {
      logo[i].style.display = 'none';
    }
  }
}
.team {
  width: 55px;
  display: flex;
}

.menu-icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .mobile-container {
    margin: auto;
    height: fit-content;
  }
  .menu-icon {
    display: inline;
    width: 100%;
    background-color: red;
  }
  .team {
    display: none;
  }
}

A: The problem is that when you click on the menu button, you're adding inline styles for all the menu items, so when you hide them all of them have display: none; and they stay like that no matter the screen size.
What you need to do is to alter the display property of the menu items only on mobile. You can achieve this by using a class that affects the styles of the items on mobile only. See below the .hide-mobile class, and the JS code that just toggles that class on and off.

document.getElementById('menu').addEventListener('click', myFunction);

function myFunction() {
  let logo = document.getElementsByClassName("team");

  for (i = 0; i < logo.length; i++) {
    logo[i].classList.toggle('hide-mobile');
  }
}
.team {
  width: 55px;
  display: flex;
}

.menu-icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .mobile-container {
    margin: auto;
    height: fit-content;
  }
  .menu-icon {
    display: inline;
    width: 100%;
    background-color: red;
  }
  .team {
    display: inline;
  }
  .team.hide-mobile {
    display: none;
  }
}

Hope that helps.


text:
Q: BiometricPrompt onAuthenticationSucceeded error when closing parent activity On my application i created an activity dedicated to authentication, in case of the biometric prompt, i need to close the activity when the atuhentication is completed succesfully.
I'm using androidx stable tree, with biometrics
implementation "androidx.biometric:biometric:1.0.1"
public class LockScreenActivity extends AppCompatActivity {

 protected void waitForAuthentication() {
   FragmentActivity activity = this;
   cryptoObject = new BiometricPrompt.CryptoObject(cipher);
    // Callback for biometric authentication result
    final BiometricPrompt biometricPrompt = new BiometricPrompt(activity, ContextCompat.getMainExecutor(this), new BiometricPrompt.AuthenticationCallback() {

        ....

        @Override
        public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
            super.onAuthenticationSucceeded(result);
            finish();
        }

        ....

when the parent activity is closed i foun in logcat the error
2020-10-29 10:49:40.666 1186-1186/xxxxxxxx E/FingerprintDialogFrag: Failed to dismiss fingerprint dialog fragment. Fragment manager was null.


text:
Q: System.InvalidCastException: 'Operator '&' is not defined for string "values('41611027," and type 'DataRowView'.'         conexion.Open()
        Dim cmd As New SqlCommand()
        cmd.Connection = conexion
        Dim Agregar As String
        Dim fec As Date = Fecha.Value.ToString("yyyy-MM-dd")
        Dim fac As Date = FechaC.Value.ToString("yyyy-MM-dd")
        Agregar = "insert into cita (nCuenta, Categoria, Fecha, FechaC, Estado, Usuario)"
        Agregar += "values('" & nCuenta.Text & "," & Categoria.SelectedItem & "','" & fec & "','" & fac & "','" & Estado.SelectedItem
        Agregar += "','" & Usuario.Text & "')"
        cmd.CommandText = Agregar
        cmd.ExecuteNonQuery()
        MsgBox("Guardado Con Exito")
        Limpiar()
        conexion.Close()

A: El problema con tu consulta es que la propiedad SelectedItem no es un string, si no un DataRowView. Primero debes castear esa propiedad a su tipo real y despues obtener la columna que te interesa (en este ejemplo uso la 0, en tu caso la que necesites)
Por otro lado nunca generes tu query usando concatenacion de strings. Utiliza consultas parametrizadas o tu código estará expuesto a la Inyección de SQL. Tu código debe quedar mas o menos asi:
'Convertimos los "SelectedItem" a su tipo real,DataRowView
Dim cat As DataRowView = TryCast(Categoria.SelectedItem, DataRowView)
Dim estad As DataRowView = TryCast(Estado.SelectedItem, DataRowView)

Agregar = "insert into cita (nCuenta, Categoria, Fecha, FechaC, Estado, Usuario)"
Agregar += " values(@nCuenta,@Categoria,@fecha,@fechac,@estado,@usuario)"
cmd.CommandText = Agregar
cmd.Parameters.Add("@nCuenta", SqlDbType.VarChar).Value = nCuenta.Text
cmd.Parameters.Add("@Categoria", SqlDbType.VarChar).Value = cat.Item(0).ToString()
cmd.Parameters.Add("@fecha", SqlDbType.DateTime).Value = fec
cmd.Parameters.Add("@fechac", SqlDbType.DateTime).Value = fac
cmd.Parameters.Add("@estado", SqlDbType.VarChar).Value = estad.Item(0).ToString()
cmd.Parameters.Add("@usuario", SqlDbType.VarChar).Value = Usuario.Text
cmd.ExecuteNonQuery()

Hay otra opcion. Si en tu ComboBox configuraste la propiedad ValueMember, lo que debes hacer es sustituir SelectedItem por SelectedValue.ToString().


text:
Q: Check if field exists in DB using SQL trigger I have a database Users that has four fields: Name, Client, ID, Time. Client is an integer (0-99). How to write a trigger that will find latest user from Users (latest according to Time) during Insert and if the Client of this user equals Client of inserted user then I'd like to Rollback
I tried like this:
CREATE TRIGGER DoubledData ON Users
FOR INSERT
AS
DECLARE @client DECIMAL(2)
DECLARE @client_old DECIMAL(2)
DECLARE @name Varchar(50)
SELECT @name = Name from inserted
SELECT @client = Client from inserted

//This doesn't work, "Syntax error near Select":
SELECT @client_old = Select top(1) Client from Users where Name like @name order by Time desc;

IF @client = @client_old
BEGIN
    ROLLBACK
END

The problem is that I can assign same values to Client for one user but they can't be one after another (eg for client this order is correct 1-2-3-1-3 -> order is important, but this isn't correct: 1-2-3-3 -> after 2nd occurrence of '3' in a row it needs to be rollbacked)
I'm using MS SQL
[EDIT]
I have found that I can execute it without Select top(1) like:
SELECT @client_old = Client from Users where Name like @name order by Time desc;

But the trigger doesn't execute afer insert

A: First, you clearly don't understand triggers in SQL Server and the inserted pseudo-tables.  These can have more than one row, so your code will fail when multiple rows are inserted.  Sadly, there is no compile check for this situation.  And code can unexpectedly fail (even in production, alas).
Second, the right way to do this is probably with a unique constraint.  That would be:
alter table users
    add constraint unq_users_name_client unique (name, client);

This would ensure no duplication, so it is a stronger condition than your trigger.


text:
Q: relationship between nominal voltage and cross-sectional area Is there a reasonable approximation or some standard cross-sectional area that can be inferred from the nominal voltage of a transmission line? I'm only concerned with high-voltage lines, i.e. nothing at the distribution level.  I don't need something exact and even a relative measure of how the cross-sectional area will likely change between a 69kV and 118kV line, for example, would be good. I'm happy to assume the same material for all lines and any other simplifying assumptions that would lead to something reasonable.

A: Power distributors plan their lines for maximum profit. They can allow more losses if that keeps the lifetime cost smaller and the voltage variation norms still can be fulfilled. The cost estimation is stochastic - it takes the probablity of accidents and storms into the account, too.
If you have noticed some dependence between voltage and cross-sectional area, it is the result of forementioned  for lifetime calculations, not only because the current is different at different voltage levels.