text:
Q: How to expose an nginx docker container via Apache 2 with SSL? I have a web app running on docker containers on my Digital Ocean droplet. The app has its own container and is served through an Nginx container on the address 0.0.0.0:8080.
Here is the nginx conf:
server {
    listen 80;
    index index.php index.html;
    root /var/www/public;

    location / {
        try_files $uri /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

and my nginx container dockerfile:
FROM nginx:1.10

ADD ./vhost.conf /etc/nginx/conf.d/default.conf
WORKDIR /var/www

Now, I have domain to which I generated an SSL certificate using certbot and I want to serve my app through this domain but I am failing miserably.
I am using(or trying) Apache2 as a reverse proxy for this but I cannot get it to work. I can now access the main page of the app but without any resources since the page is being served through https but the resources are being fetch from the container via http. I don't know how many things I tried already but I am going nowhere. Any help would be much appreciated.
Here are my virtual hosts configs, if that helps.
vhost-le-ssl.conf:
<IfModule mod_ssl.c>
#Listen 443
#NameVirtualHost *:443
<VirtualHost *:443>

     SSLEngine  On

        # Set the path to SSL certificate
    # Usage: SSLCertificateFile /path/to/cert.pem

 SSLCertificateFile /etc/letsencrypt/live/antonioquadrado.com/cert.pem

    # Servers to proxy the connection, or;
    # List of application servers:
    # Usage:
    # ProxyPass / http://[IP Addr.]:[port]/
    # ProxyPassReverse / http://[IP Addr.]:[port]/
    # Example:
    ProxyPass / http://0.0.0.0:8080/
    ProxyPassReverse / http://0.0.0.0:8080/

        ServerName antonioquadrado.com
        ServerAlias www.antonioquadrado.com

        ServerAdmin webmaster@localhost
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
RewriteEngine on
# Some rewrite rules in this file were disabled on your HTTPS site,
# because they have the potential to create redirection loops.

# RewriteCond %{SERVER_NAME} =antonioquadrado.com [OR]
# RewriteCond %{SERVER_NAME} =www.antonioquadrado.com
# RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/antonioquadrado.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/antonioquadrado.com/privkey.pem
</VirtualHost>
</IfModule>

vhost.conf:
VirtualHost *:80>

        ProxyPreserveHost On

    # Servers to proxy the connection, or;
    # List of application servers:
    # Usage:
    # ProxyPass / http://[IP Addr.]:[port]/
    # ProxyPassReverse / http://[IP Addr.]:[port]/
    # Example:
    ProxyPass / https://0.0.0.0:8080/
    ProxyPassReverse / https://0.0.0.0:8080/

        ServerName antonioquadrado.com
        ServerAlias www.antonioquadrado.com

        ServerAdmin webmaster@localhost
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
RewriteEngine on
RewriteCond %{SERVER_NAME} =antonioquadrado.com [OR]
RewriteCond %{SERVER_NAME} =www.antonioquadrado.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

I have followed this digital ocean tutorial to get at this point.
Thanks in advance!
Edit: after being pointed by @SmileIt to the serverfault answer I have updated my virtualhosts configs to this:
<VirtualHost *:80>
        ServerName antonioquadrado.com
        ServerAlias www.antonioquadrado.com

        Redirect permanent / https://www.antonioquadrado.com/
</VirtualHost>

ssl vhosts:
<IfModule mod_ssl.c>
<VirtualHost *:443>

        ServerName www.antonioquadrado.com
        DirectoryIndex index.php index.html
        SetOutputFilter SUBSTITUTE,DEFLATE

        ProxyPass / http://0.0.0.0:8080/
        ProxyPassReverse / http://0.0.0.0:8080/

        AddOutputFilterByType SUBSTITUTE text/html
        Substitute "s|http://0.0.0.0:8080/|https://www.antonioquadrado.com/|i"

        SSLEngine on
        SSLProtocol all -SSLv2
        SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateKeyFile /etc/letsencrypt/live/antonioquadrado.com/privkey.pem
        SSLCertificateFile /etc/letsencrypt/live/antonioquadrado.com/fullchain.pem
        #SSLCertificateChainFile /path-to/chain.pem
        <Proxy *>
                Order deny,allow
                Allow from all
                Allow from localhost
        </Proxy>
</VirtualHost>
</IfModule>

But I have the same errors about the resources being fetched over the internal ip via http.
Here's also my docker-compose file:
version: '2'
services:
    web:
        build:
            context: ./
            dockerfile: web.docker
        volumes:
            - ./:/var/www
        ports:
            - "8080:80"
        links:
            - app
    app:
        build:
            context: ./
            dockerfile: app.docker
        volumes:
            - ./:/var/www
        links:
            - database
        environment:
            - "DB_PORT=3306"
            - "DB_HOST=database"
    database:
        image: mysql:5.6
        environment:
            - "MYSQL_ROOT_PASSWORD=*****"
            - "MYSQL_DATABASE=*******"
        ports:
            - "33061:3306"

A: Apache output filters are out of order most likely.
Add the following to your VirtualHost config near the top and restart Apache.
SetOutputFilter SUBSTITUTE;DEFLATE

Essentially we have to tell Apache to order output filters. Do substitution first then deflate. If this does not work for you add the following to your VirturalHost config and send the output.
LogLevel trace3 rewrite:error filter:trace8

The output should tell us what filters are running before substitution filter.


text:
Q: C# WPF - MainWindow content gets shown in two separate windows instead of one I want to have a single MainWindow with two columns, a narrow one on the left and a wide one on the right. In the left one should be a menubar and in the right one a grid of Fields (which is a custom ViewModelBase). However, right now when I launch the program, it gives me two windows, one with the grid and one with the menubar on the left. What am I doing wrong? Where might be the error?
Tha XAML looks like this:
<Window x:Class="SavageMaci.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test" Height="500" Width="700">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <Menu Grid.Row="1" Grid.Column="1" Margin="38,0,187,430" Background="White">
            <Menu.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="90"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Menu.RenderTransform >
            <MenuItem Header="Level 1" FontFamily="Roboto" Height="32" Width="65"/>
            <MenuItem Header="Level 2" FontFamily="Roboto" Height="32" Width="65"/>
            <MenuItem Header="Level 3" FontFamily="Roboto" Height="32" Width="65"/>
        </Menu>
        <ItemsControl Grid.Row="1" Grid.Column="2" ItemsSource="{Binding Fields}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Rows="{Binding Size}" Columns="{Binding Size}"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</Window>

The xaml.cs is also basic:
namespace SavageMaci
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

There's only one reference to MainWindow(), in App.xaml.cs, where I instantiate it. Please let me know where else might the error be, I'll update the question with that code, too. Thank you for helping!

A: The solution to your problem is simple. In your App class, you create a MainWindow instance.
This is unnecessary since App creates its own instance whether you create it or not.
Have a look at the App.xaml file and you will see for yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java jax-rs send HTTP GET Request accompanied with JSON Data Input I'm using jax-rs library to create a client testing a Web Service by sending HTTP requests to it, for study purposes. Now a POST Request looks something like this:
Response res = target.
                request().post(Entity.entity(jinput.toString(), MediaType.APPLICATION_JSON));

and GET Request something like this:
Response res = target.
            request().accept(MediaType.APPLICATION_JSON).get(Response.class);

Where target is the targeted URI and jinput the JSON Input used to post a resource...
Now I wonder... is there a way I can send a GET Request accompanied with a JSON input? For the sake of testing how the Web Service reacts to it...
By using cURL to manually send HTTP requests I can do it... but is there a way I can do it using the jax-rs library?
Thanks in advance :)
P.S. I would like to test the same thing with a DELETE Request as well... if possible...


text:
Q: Twitter Request token always fails with 401 in python I am using urllib and urllib2 to get request token from twitter as recommended here https://dev.twitter.com/docs/auth/implementing-sign-twitter, code is below. Can anyone see, what am I doing wrong? I get 'urllib2.HTTPError: HTTP Error 401: Unauthorized'
#! env python

import sys
import os
import urllib
import urllib2
import uuid
import time
import base64
import string

# 1. Obtain a request token
# 2. Redirect the user
# 3. Convert the request token to an access token

consumer_key=           "xxxxxxx"
consumer_secret=        "xxxxxxxxxxxxxxx"

# Request token URL:    https://api.twitter.com/oauth/request_token
# Authorize URL:        https://api.twitter.com/oauth/authorize
# Access token URL:     https://api.twitter.com/oauth/access_token

nonce = base64.b32encode(str(uuid.uuid4().hex))
# example: MYZTMMRYMEYDQN3FMFSDIYJXGNRDCMBWG42TAMJUGVTGGMZRMFSA====
nonce = nonce.rstrip('=')
print 'Nonce', nonce

data = { 'oauth_callback'           : 'http://www.gooogle.com',
         'oauth_consumer_key'       : 'bwKT66akiJSin30L1mGnQ',
         'oauth_nonce'              : nonce,
         'oauth_timestamp'          : int(time.time()),
         'oauth_version'            : "1.1"
}

url_values = urllib.urlencode(data)
url = 'https://api.twitter.com/oauth/request_token'
full= url + '?' + url_values
data = urllib2.urlopen(full)

Which all query parameters are mandatory here?


text:
Q: How can you use submodules with git-managed dotfiles? I use a git repository to manage my dotfiles, and I'm having the hardest time getting submodules to work right (most of my .vim has a lot of external plugins)
I have an alias cgit to do (not sure if it's relevant)
    alias cgit='GIT_DIR=/home/myuser/.config-git GIT_WORK_TREE=/home/myuser/. git'"
So, I can pull the repository with cgit pull, but I can't get submodules to checkout/update:
$ cgit submodule status
-9895285042a2fd5691b2f6582aa979e4d1bdffea .vim/bundle/ack
-e9267044261481fbb6717b482c2f3811eb61b409 .vim/bundle/command-t
<snip>
$ cgit submodule init
$ cgit submodule update
fatal: working tree '/home/myuser/.' already exists.
Clone of 'https://github.com/mileszs/ack.vim.git' into submodule path '.vim/bundle/ack' failed
$

I've tried removing that specific directory and trying again, and it just bombs. My .gitmodules doesn't have /home/myuser/. and my .config-git/config doesn't have any references to my home directory either, so I'm at a loss. If it helps, my version of git is 1.7.4.1
thanks!
UPDATE
It appears that first thing was a weird bug where git submodule wasn't accepting the environment variables (though other git commands were), but it required the command line arg be passed. Now, the clone works, it just complains (I fixed the ack config manually)
Cloning into '.vim/bundle/command-t'...
remote: Counting objects: 2659, done.
remote: Compressing objects: 100% (1089/1089), done.
remote: Total 2659 (delta 1453), reused 2524 (delta 1325)
Receiving objects: 100% (2659/2659), 447.42 KiB, done.
Resolving deltas: 100% (1453/1453), done.
fatal: Could not chdir to '../../../../../../../nfs_mounts/home/myuser/.vim/bundle/command-t': No such file or directory

And if I look in ~/.config-git/modules/.vim/ack/config, I see:
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    worktree = ../../../../../../../nfs_mounts/home/myuser/.vim/bundle/command-t
[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = https://github.com/wincent/Command-T.git
[branch "master"]
    remote = origin
    merge = refs/heads/master

but if I 'ls' that worktree, it appears to be there. If I remove all the ../ , then try the git again it appears to work

A: I think this is because you have GIT_DIR set.  It looks like the submodule clone is trying to put the .git directory for the submodule in ~/.git but your home git directory is already there.
What's the purpose of setting GIT_DIR like that?


text:
Q: How to make a picture work as a background with a blur filter I wanna use an image on my site as a brackground with a blur filter.
I tried using this in a css file:
.bg-image{
    background-image: url("../store/groupLK.jpg");
    filter: blur(8px);
    -webkit-filter: blur(8px);
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

and in the html file:

<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />

/* the rest of the code including some other images */

And it seems to work but it blurs all of the images that I use as well instead of "groupLK.jpg" only. I also tried using the class bg-image before/after the other pictures but it only appears in that position and not in the rest of the site. Thank you in advance.

A: This happens because blur filter is applied to the parent and therefor also effects all its children.
You could wrap your image and the text (or other images) in a container:

.bg-image{
  height: 200px;
  width: 200px;
  background-image: url("https://dummyimage.com/200x200");
  filter: blur(2px);
  position: absolute;
  top: 0;
  left: 0;
}

.text{
  position: absolute;
  top: 0;
  left: 0;
}

    Hallo


text:
Q: Facebook page is not opening with icon link - nightwatch I´m new at using Nightwatch.js
I want to click on facebook icon and make it open in a new page.
How can I test if the icon link is clicked? Thanks.
module.exports = {
        "Facebook link" : function (browser) {
            browser
                .url(http://m.unitel.ao/fit/)
                .waitForElementVisible('.socal', 3000)
                .waitForElementPresent('.fa.fa-facebook', 15000)
                .useCss().click('.fa.fa-facebook')
                .pause(3000)
                .assert.urlContains('facebook')
                .end()}};

Anda whatt i get is this:
> Running:  Facebook link
         ? Element <.socal> was visible after 118 milliseconds.
         ? Element <.fa.fa-facebook> was present after 21 milliseconds.
         ? Testing if the URL contains "facebook".  - expected "facebook" but got: http: //m.unitel.ao/fit/

It´s not opening facebook page. Can anyone help me please?


text:
Q: angular ng-hide when something is already showing Hi I already have a div showing based on a ng-show condition coming from the condition being true.  How can I click on the  tag where it says download later and use ng-hide to make the div go away?

New Guide Found

<button ng-click="download(item.guidebook_file)" class="button    button-block button-positive">
Download</button>

Download Later


text:
Q: How to check the Authentication Token against the serial number and passTypeIdentifier before sending data to database I create a pass for passbook. I also have a web server by using MAMP and database with 3 tabes such devices, registration, and pass_name. When I register device and pass, i need to check Authentication Token and serial number. What is the result of this checking and how can we check ?

A: Further to my comment - your process should be something like:

*

*create a pass and store authenticationToken, passTypeIdentifier and serialNumber and any other data about the pass that you would like to store in your pass_name table, also include a lastUpdated tag.

*install the pass - device registers and provides authenticationToken (in header), passTypeIdentifier,  serialNumber and deviceLibraryIdentifier (in the URL), and  pushToken (in POST body).

*check that your pass_table contains a record matching authenticationToken, passTypeIdentifier and serialNumber provided by the device

*if there is no record, return a 401 Unauthorized response, else

*in your devices table, create a record with a key of deviceLibraryIdentifier-serialNumber and fields deviceLibraryIdentifier, pushToken, serialNumber, passTypeIdentifier and authenticationToken and return a 201 response.

Your authenticationToken should be unique to each pass that you issue.
You need to add serialNumber, deviceLibraryIdentifier, passTypeIdentifier and authenticationToken to your devices table so that your web service can locate the device record when you want to push an update and to respons to other requests as detailed in the Passbook web service specification


text:
Q: Generating Function of distinct way of partitioned square sums of positive integers Let's define a function $p_2(n)$ that it is total distinct way to write $n$ positive integer as sum  of square of positive integers. For example, $9$ can be partitioned as sum of squares in 4 distinct ways:
$$3^2$$
$$2^2 + 2^2+1^2$$
$$2^2 + 1^2+1^2+1^2+1^2+1^2$$
$$1^2+1^2+1^2+1^2+1^2+1^2+1^2+1^2+1^2$$
Thus
$p_2(9)=4$
I used the similar method of partition function to find generating function for $p_2(n)$ and I have gotten
$$\sum\limits_{n=0}^{ \infty }p_2(n)q^n=(1+q^{1^2}+q^{2.1^2}+q^{3.1^2}+......)(1+q^{2^2}+q^{2.2^2}+q^{3.2^2}+......)(1+q^{3^2}+q^{2.3^2}+q^{3.3^2}+......)..$$
$$\sum\limits_{n=0}^{ \infty }p_2(n)q^n=\frac{1}{\prod\limits_{n=1}^{ \infty }(1-q^{n^2})} $$
I expanded first terms of that product function
$$\prod\limits_{n=1}^{ \infty }(1-q^{n^2})=1-q-q^4+q^5-q^9+q^{10}+q^{13}-q^{14}-q^{16}+q^{17}+q^{20}-q^{21}+q^{34}-q^{35}-q^{36}+q^{37}-q^{38}+q^{39}+q^{40}-q^{42}-2q^{49}+q^{51}+q^{52}+........$$
I have not found any references for sum formula for  $\prod\limits_{n=1}^{ \infty }(1-q^{n^2})$.
Is there any sum formula of $\prod\limits_{n=1}^{ \infty }(1-q^{n^2})$  as we can express  $\prod\limits_{n=1}^{ \infty }(1-q^{n})=\sum\limits_{n=-\infty}^{ \infty }(-1)^n q^{\frac{n(3n-1)}{2}}$?
Thanks for references and links to related subject.
UPDATE: 9th December,2014
I have found a relation for that square sum partition function I would like to share it.
$$\Phi_2(q)=\prod\limits_{n=1}^{ \infty }(1-q^{n^2})$$
$$\Phi_2(q)=\prod\limits_{n=1}^{ \infty }(1-q^{(2n-1)^2})\prod\limits_{n=1}^{ \infty }(1-q^{(2n)^2})$$
$$\Phi_2(q)=\prod\limits_{n=1}^{ \infty }(1-q^{(2n-1)^2})\prod\limits_{n=1}^{ \infty }(1-(q^4)^{n^2})$$
$$\Phi_2(q)=\Phi_2(q^4)\prod\limits_{n=1}^{ \infty }(1-q^{(2n-1)^2}) \tag 1$$
$$\Phi_2(-q)=\Phi_2(q^4)\prod\limits_{n=1}^{ \infty }(1+q^{(2n-1)^2})$$
$$\Phi_2(-q)\Phi_2(q)=\Phi^2_2(q^4)\prod\limits_{n=1}^{ \infty }(1+q^{(2n-1)^2})\prod\limits_{n=1}^{ \infty }(1-q^{(2n-1)^2})$$
$$\Phi_2(-q)\Phi_2(q)=\Phi^2_2(q^4)\prod\limits_{n=1}^{ \infty }(1-(q^2)^{(2n-1)^2}) \tag 2$$
If we use Equation 1 and put $q -->q^2$
$$\Phi_2(q^2)=\Phi_2(q^8)\prod\limits_{n=1}^{ \infty }(1-(q^2)^{(2n-1)^2}) \tag 3$$
Now we can find and function relation for $\Phi_2(q)$ if we divide Equation 2 and  3
$$\frac{\Phi_2(-q)\Phi_2(q)}{\Phi_2(q^2)}=\frac{\Phi^2_2(q^4)}{\Phi_2(q^8)}$$
$$\Phi_2(-q)\Phi_2(q)\Phi_2(q^8)=\Phi^2_2(q^4)\Phi_2(q^2)  \tag 4$$
$$\sum\limits_{n=0}^{ \infty }p_2(n)q^n=\frac{1}{\prod\limits_{n=1}^{ \infty }(1-q^{n^2})} =\frac{1}{\Phi_2(q)}$$
If we define $$P_2(q)=\sum\limits_{n=0}^{ \infty }p_2(n)q^n$$
$$P_2(q)=\frac{1}{\Phi_2(q)}$$
If we put in Equation 4,
$$P_2(-q)P_2(q)P_2(q^8)=P^2_2(q^4)P_2(q^2)  \tag 5$$
Finally we can write square sum partition as function relation,
$$\left( \sum\limits_{n=0}^{ \infty }p_2(n)(-1)^nq^n \right) \left( \sum\limits_{n=0}^{ \infty }p_2(n)q^n \right) \left( \sum\limits_{n=0}^{ \infty }p_2(n)q^{8n}\right)=\left( \sum\limits_{n=0}^{ \infty }p_2(n)q^{4n} \right)^2 \left( \sum\limits_{n=0}^{ \infty }p_2(n)q^{2n} \right) $$
n terms can be sum both side and a relation can be found for square sum partition function but It is quite complex relationship. I could not get further. Can someone please help me or advice how to simplify it and get further from that point
Thanks a lot


text:
Q: Update checkbox at click event vue.js I have a checkbox function.I am getting the value from backend. When i click the checkbox it makes a post or delete call based on the checkbox is checked or not.Then i am getting the updated value and displaying.But seems like the checkbox is not always displaying updated value.The api seems like correct but the value is not always updating.

        <input type="checkbox" v-model="test.checked" @click="update(test.checked)">

    data() {
      return {
        tests:[],
      };
    },
    mounted() {
      this.getData();
    },
    methods: {
      getData() {
          const data = await axios.get('getdata')
      },
      update(checked) {
        if(!checked){
          const data = await axios.post('checktrue');
        } else {
          axios.delete('checkfalse')
        }
        this.getData();
      }
    }

A:

    <input type="checkbox" v-model="test.checked" @click="update(test.checked)">

Adding the key to the for loop should fix this, because vue v-for loops are a bit tricky. They can't really detect any change in objects. However it should detect, that the indexes change and rerender accordingly.

A: try with below answer:

    <input type="checkbox" v-model="test.checked" @click="update(!test.checked)">


text:
Q: Determine which Button was pressed in Tkinter? I'm making a simple little utility while learning Python.  It dynamically generates a list of buttons:
for method in methods:
    button = Button(self.methodFrame, text=method, command=self.populateMethod)
    button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})

That part works fine.  However, I need to know which of the buttons was pressed inside self.populateMethod.  Any advice on how I might be able to tell?

A: You can use lambda to pass arguments to a command:
def populateMethod(self, method):
    print "method:", method

for method in ["one","two","three"]:
    button = Button(self.methodFrame, text=method,
        command=lambda m=method: self.populateMethod(m))
    button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})

A: It seems that the command method is not passed any event object.
I can think of two workarounds:

*

*associate a unique callback to each button

*call button.bind('<Button-1>', self.populateMethod) instead of passing self.populateMethod as command. self.populateMethod must then accept a second argument which will be an event object.
Assuming that this second argument is called event, event.widget is a reference to the button that was clicked.


text:
Q: L_ERRORCODE0 : 10401 returned by DoReferenceTransaction I have done payment of $990, it gets success. After that I am trying to do payment of $2490 it giving error : 10401.
For both payments I am using DoReferenceTransaction API call (same billing agreement ID).
Why its happening?
Here is my NVP:
    $nvpstr = '&REFERENCEID=' . $billing_agreement_id;
    $nvpstr.='&PAYMENTACTION=' . $paymentType;
    $nvpstr.= '&AMT=' . $FinalPaymentAmt;
    $nvpstr.= '&CURRENCYCODE=' . $currencyCodeType;
    $nvpstr.='&L_ITEMCATEGORY0=Digital';
    $nvpstr.='&DESC=' . urlencode("LMS Recurring Payment( $" . $_SESSION["Payment_Amount"] . " )");
    $nvpstr.="&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital";
    $nvpstr.="&L_PAYMENTREQUEST_0_QTY0=1";
    $nvpstr.="&L_PAYMENTREQUEST_0_NAME0=LMS Billing";
    $nvpstr.="&L_PAYMENTREQUEST_0_AMT0=" . $_SESSION["Payment_Amount"];
    $nvpstr.="&L_NAME0=Test Name";
    $nvpstr.="&L_DESC0=" . urlencode("LMS Recurring Payment( $" . $_SESSION["Payment_Amount"] . " )");
    $nvpstr.="&L_AMT0=" . $_SESSION["Payment_Amount"];
    $nvpstr.="&ITEMAMT=" . $_SESSION["Payment_Amount"];
    $nvpstr.="&L_QTY0=1";
    $nvpstr.="&RECURRING=Y";

Please guide me, so that I can overcome this error.
Note: Error not comes when transaction payments are done in sequence like:
$99
$249
$3990

A: Paypal documentation says:

Code 10401 Transaction refused because of an invalid argument.Order total is invalid. TotalOrder amount is invalid.

In my experience error 10004 has appear when has incompatibility between methods SetExpressCheckout and ( in your case ) DoReferenceTransaction
So please check TotalOrder amount!


text:
Q: Comparing DID and HAD Why does did require the base form of the verb, while had requires the third form of the verb when both are auxiliary verbs?

Did he like the marshmallow?

Had he liked the marshmallow?

A:
Did he like the marshmallow?

is a perfectly acceptable sentence.

Had he liked the marshmallow?

is not usually valid as an independent sentence. It looks like part of a counterfactual form:

Had he liked the marshmallow, he would have eaten more of it.

This uses the Past Perfect counterfactual to express an event that might have happened, but did not. This is a form of counterfactual conditional   sometimes classified as a version of the subjunctive mood. This uses a past participle because that is how the past perfect forms work. The inversion of subject and verb marks this as a conditional form.
A non-conditional and non-counterfactual use of the past perfect might be something like

He had liked the marshmallow when he first tried it.  (This may imply that he didn't like it so much later, or that he previously thought he would not like it.)

Notice that past perfect forms normally indicate a sequence of events, show one thing happening before another. These forms should not usually be used for simple, single past events with no sense of sequence or process.
"Had he liked the marshmallow?" could be a valid sentence if it was reported speech that had been backshifted. Backshifted speech is often part of a larger sentence, as in:

She asked me if he had liked the marshmallow.

If a multi-sentence speech is being reported, such a form could be a separate sentence. (See this comment) Otherwise such a form would not normally be used.


text:
Q: Adding WFS service to ArcMap? I was under the impression that the Data Interop extension was needed to use a WFS service in ArcGIS Desktop, as outlined here. The page specifically mentions that a DI license is required.
Now I found another page that shows something different:

There is no mention of DI, and apparently there is a new option under GIS Servers ('Add WFS Server').
I don't have this option, in ArcGIS 10.3.1 or 10.4.1, so how do I get it? I thought I needed to install DI after all, so I did that, but the option is still not there, nor can I find a way to add it manually. Is this part of the Production Mapping extension?
I have an ArcGIS Enterprise license.

A: According to this guide you will be able to add a WFS under Interoperability Connections not under GIS Servers.

At first I did not have this option either, then I realized that I did not install the interoperability extension, I merely added the license. So make sure you both have a license and install the extension.


text:
Q: Is there any restriction in defining constants in PHP? Should I define constant and use it?
OR
Can I use Magic numbers?
I am working in project where I am using Magic number in many places do I want to change it? because I am using more that 1000 Magic number? Is this rite way or I should use constant?
Is there any restriction in the number of constants?
Ex:
 Magic numbers:
    $common->getDBMessage(25);
 Constants:
    $common->getDBMessage(ERROR_MESSAGE_INVALID_PHONE);

A: There are no restrictions for constants in PHP - at least, no native restrictions.
It's a matter of good practice - if you'll have 1000 constants with bad naming, this will be difficult to understand by those who will read your code. And - I do not understand why use constants for numbers unless they have model-defined (or application-defined) meaning.
I.e. if you have some service 'FOO' with id=1, then SERVICE_FOO_ID constant with value 1 is normal solution, but if you want to create constant with value 1 for case for($i=1; ...) - that's sounds weird.
The common answer will be, of cause: it's opinion-bases. It's up to you.

A: You can have as many constants as you like. PHP already has a very large number of constants built in.
You might want to consider making them class constants (const within a class) rather than global constants (using define). Having them organised will help you structure your code better and make things easier to work with.
In addition, if some of the constants are related, you might consider using bit-masks for groups of values, so you can specify them together. This will avoid the need to create an additional constant for the combined value.
But all this is just advice for making your life easier; it's not related to whether you can do it or not.


text:
Q: Camel send modified body to AMQ without modifying route's body I have a rest-api which create a resource and send it on a AMQ queue.
I am using camel rest dsl and created the something like that :
rest("/api")
            .consumes("application/json").produces("application/json")
                .post("/test").type(Test.class)
                    .route()
                    .to(ExchangePattern.InOnly, "direct:sendTestAmq")
                    .endRest()
from("direct:sendTestAmq")
            .convertBodyTo(TestProtos.Test.class)
            .marshal().protobuf()
            .to(ExchangePattern.InOnly, "amq:queue:test.queue");

When I call the endpoint, I get a base64 response corresponding to the protobuf binary.
I would like to get the Test.class json response.
I thought using "to(ExchangePattern.InOnly,...)" would permit that by not modifying the body.
This is another example, the response is "After" and I wanted it to be "Before".
Does anybody knows how I could do it ?
Thanks

A: Based on @ClausIbsen answer I found that multicast() also use a copy of the exchange for each route but instead of wiretap, it is not parallele per default.
I could achieve my goal by replacing .to(ExchangePattern.InOnly, "direct:sendTestAmq") by multicast().to(ExchangePattern.InOnly, "direct:sendTestAmq", "direct:mock").end().
Since multicast takes as an output the last route exchange, "direct:mock" is a route which does nothing but preserves the original body.


text:
Q: How long will it take to fill this cistern? Pipes $A$ and $B$ call fill a cistern in $20$ and $30$ minutes and C can empty it in $15$ minutes. If the three are opened and closed after the other successively for $1$ min each in that order, how soon will the cistern be filled?
So from this we can say that part filled in $3$ min $= \frac 1 {20} +\frac 1{30}-\frac 1{15} = \frac {1}{60}$th
But now how to form the rest of the solution, any ideas?

A: Since you add $\frac{1}{20}+\frac{1}{30}$ before subtracting $\frac{1}{15}$, it is sensible to see how long it takes to fill $1-\frac{1}{20}-\frac{1}{30}$ of the tank using the three steps.
This is $\frac{11}{12}=\frac{55}{60}$ of the tank and so takes $55 \times 3 = 165$ minutes.
You then add $\frac{1}{20}$ in the $166$th minute and $\frac{1}{30}$ in the $167$th minute to reach a full tank, so the answer is  $167$ minutes.

A: Not sure if you're looking for a hint or a solution here.  In any case, you already know that after every complete 3 minute cycle, the cistern will be another $\frac1{60}$ full.  During each cycle, the cistern is at it's fullest just before pipe C opens to empty it.  This partial cycle yields $\frac3{60}$ from pipe A, then another $\frac2{60}$ from pipe B.
Can you finish it from here?

A: woops!! ...
Tank is full at $180$ minutes after $1/15$th part is drained by last minute. If we look oppositely, $1$ (or full tank) in $180$ the minute, $1+1/15$ in $179$, $1+1/15 - 1/30$ in $178$, $1+1/15 - 1/30-1/20$ in $177$ ..
If we look oppositely it is essentially the time required to build up extra $1/15$ th in $179$the minute volume and drain it in the last. The filling up equation from opposite will be of the following form. So we are trying to find the least positive integer solution of one of these equations.
$$ {n \over 15} - {n \over 30} - {n \over 20} = -{1 \over 15} \\
{n +1\over 15} - {n \over 30} - {n \over 20} = -{1 \over 15}\\
{n +1\over 15} - {n+1 \over 30} - {n \over 20} = -{1 \over 15} $$
So we have $n = 4$ for the first equaton so $4 + 4 + 4 = 12$, (from opposite view) it takes $12$ minute  to build up $1 /15$ th volume and another min to drain it. So, $180 - 13 = 167$.


text:
Q: How can I get all documents that were created by a certain user in Firebase Firestore? Using Swift 4, Firebase Auth, Firebase Cloud Firestore.
I have a chat DB and a user DB. I am using phone authentication with Firebase and am saving the UID to store for each user in the user DB. For each chat DB, I am storing the current user's UID to allow a lookup to happen. It's here where I am stuck. Is there anyway I can get all chats from a specific user if the sender ID is a attribute to each document in the chat DB?

A: I actually figured it out
func getChatsFromUser() {
    let db = Firestore.firestore()
    db.collection("chats").whereField("senderID", isEqualTo: String(describing: Auth.auth().currentUser!.uid))
        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                }
            }
    }
}


text:
Q: Is there any callback on permission change for web push notification? Let say a user set permission to allow for receiving push notification but later changed those permissions to denied or default .
Is there some callback for this exposed in Serviceworker.

A: There's no event that's exposed to the service worker.
There's an event that you could listen for from the context of pages, via the Permissions API:
navigator.permissions.query({name: 'notifications'}).then(function(permission) {
  // Initial status is available at permission.state

  permission.onchange = function() {
    // Whenever there's a change, updated status is available at this.state
  };
});


text:
Q: cmd prompt works fine, but Batch file cannot handle % strings I have this image sitting in my folder named
hello%5B1%5D.png
I run this command prompt script to copy an image with a new name
COPY "hello%5B1%5D.png" "New_Image_Name.png"
which works fine
but if I dump it inside a .bat file and double click .bat, it outputs this instead:
COPY "helloB1D.png" "New_Image_Name.png"
taking out the 5 and % inside the image name.
Is there an option to allow command prompt to handle % strings as input values, if they are enclosed by double quotation marks? ""

A: COPY "hello%%5B1%%5D.png" "New_Image_Name.png"


text:
Q: Finding difference between 2 tables in MS Access or SQL Server I have 2 Excel files which I imported into MS Access as two tables. These two tables are identical but imported on different dates.
Now, how can I find out what rows and what fields are updated on the later date? Any help would be highly appreciated.

A: Finding Inserted records is easy
select * from B where not exists (select 1 from A where A.pk=B.pk)

Finding Deleted records is just as easy
select * from A where not exists (select 1 from B where A.pk=B.pk)

Finding Updated records is a pain. The following rigorous query assumes you have nullable columns and it should work in all situations.
select B.*
  from B
  inner join A on B.pk=A.pk
 where A.col1<>B.col1 or (IsNull(A.col1) and not IsNull(B.col1)) or (not IsNull(A.col1) and  IsNull(B.col1))
    or A.col2<>B.col2 or (IsNull(A.col2) and not IsNull(B.col2)) or (not IsNull(A.col2) and  IsNull(B.col2))
    or A.col3<>B.col3 or (IsNull(A.col3) and not IsNull(B.col3)) or (not IsNull(A.col3) and  IsNull(B.col3))
    etc...

If the columns are defined as NOT NULL then the query is much simper, just remove all the NULL tests.
If the columns are nullable but you can identify a value that will never appear in the data, then use a simple comparison like:
Nz(A.col1,neverAppearingValue)<>Nz(B.col1,neverAppearingValue)

A: I believe this should be as simple as running a query like this:
SELECT *
FROM Table1
    JOIN Table2
         ON Table1.ID = Table2.ID AND Table1.Date != Table2.Date

A: One way to do this is by unpivoting both tables, so you get a new table with , , .  Note, though, that you have to take types into account.
For example, the following gets differences in fields:
with oldt as (select id, col, val
              from <old table> t
              unpivot (val for col in (<column list>)) unpvt
             ),
     newt as (select id, col, val
              from <new table> t
              unpivot (val for col in (<column list>)) unpvit
             )
select *
from oldt full outer join newt on oldt.id = newt.id
where oldt.id is null or newt.id is null

The alternative way with a join is rather cumbersome.  This version shows whether columns are added, deleted, and which columns changed if any:
select *
from (select coalesce(oldt.id, newt.id) as id,
             (case when oldt.id is null and newt.id is not null then 'ADDED'
                   when oldt.id is not null and newt.id is null then 'DELETED'
                   else 'SAME'
              end) as stat,
             (case when oldt.col1 <> newt.col1 or oldt.col1 is null and newt.col1 is null
                   then 1 else 0 end) as diff_col1,
             (case when oldt.col2 <> newt.col2 or oldt.col2 is null and newt.col2 is null
                   then 1 else 0 end) as diff_col2,
             ...
      from <old table> oldt full outer join <new table> newt on oldt.id = newt.id
     ) c
where status in ('ADDED', 'DELETED') or
     (diff_col1 + diff_col2 + ... ) > 0

It does have the advantage of working for any data types.

A: (Select * from OldTable Except Select *from NewTable)
Union All
(Select * from NewTable Except Select *from OldTable)


text:
Q: Is there a restriction on the no. of HERE API Calls I can make in a loop (using R) I am trying to loop through a list of origin destination lat long locations to get the transit time. I am getting the following error when I loop. However when I do a single call (without looping), I get an output without error. I use the freemium HERE-API and I am allowed 250k transactions a month.
 `for (i in 1:nrow(test))
   {
            call <- paste0("https://route.api.here.com/routing/7.2/calculateroute.json",
                           "?app_id=","appid",
                           "&app_code=","appcode",
                           "&waypoint0=geo!",y$dc_lat[i],",",y$dc_long[i],
                           "&waypoint1=geo!",y$store_lat[i],",",y$store_long[i],
                           "&mode=","fastest;truck;traffic:enabled",
                           "&trailerscount=","1",
                           "&routeattributes=","sh",
                           "&maneuverattributes=","di,sh",
                           "&limitedweight=","20")

                  response <-fromJSON(call, simplify = TRUE)
            Traffic_time = (response[["response"]][["route"]][[1]][["summary"]][["trafficTime"]]) / 60
            Base_time = (response[["response"]][["route"]][[1]][["summary"]][["baseTime"]]) / 60
            print(Traffic_time)
}`

Error in file(con, "r"): cannot open the connection to 'https://route.api.here.com/routing/7.2/calculateroute.json?app_id=appid&app_code=appcode&waypoint0=geo!45.1005200,-93.2452000&waypoint1=geo!45.0978500,-95.0413620&mode=fastest;truck;traffic:enabled&trailerscount=1&routeattributes=sh&maneuverattributes=di,sh&limitedweight=20'
  Traceback:

A: As per the error, this suggests that there is problem with the file at your end.  it could be corrupt, good to try with changing the extension of the file. Can also try to restart your IDE. The number of API calls depend on the plans that you have opted for freemium or pro plans. You can have more details : https://developer.here.com/faqs


text:
Q: How to load this kind of data in pandas Background: I have logs which are generated during the testing of the devices after manufacture. Each device has a serial number and a corresponding csv log file with all the data. Something like this.
DATE,TESTSTEP,READING,LIMIT,RESULT
01/01/2019 07:37:17.432 AM,1,23,10,FAIL
01/01/2019 07:37:23.661 AM,2,3,3,PASS

So there are many such log files. Each with the test data.
I have the the serial number of devices which failed in field. I want to create a model using these log files. And then use it to predict if the given device has a chance of failing in field given its log file.
Till now as a part of learning, I have worked with data like housing price. Every row was complete. Depending on area, number of rooms etc, it was easy to define a model for expected selling price.
Here I wish to find a way to somehow flatten all the logs into a single row. I am thinking of having something like:
DATE_1,TESTSTEP_1,READING_1,LIMIT_1,RESULT_1,DATE_2,TESTSTEP_2,READING_2,LIMIT_2,RESULT_2
1/1/2019 07:37:17.432 AM,1,23,10,FAIL,01/01/2019 07:37:23.661 AM,2,3,3,PASS

Is this the right way to deal with this kind of data?
If so, then does Pandas has any inbuilt support for this?
I will be using scikit-learn to create models.

A: First convert columns to ordered CategoricalIndex for same order of columns in output, convert DATE column by to_datetime and convert datetimes to dates by Series.dt.date with cumcount for counter, create MultiIndex by set_index, reshape by unstack and sort second level of MultiIndex in columns by sort_index. Last flatten it by list comprehension with reset_index:
df['DATE'] = pd.to_datetime(df['DATE'])
dates = df['DATE'].dt.date

df.columns = pd.CategoricalIndex(df.columns,categories=df.columns, ordered=True)
g = df.groupby(dates).cumcount().add(1)
df = df.set_index([dates, g]).unstack().sort_index(axis=1, level=1)
df.columns = [f'{a}_{b}' for a, b in df.columns]
df = df.reset_index(drop=True)
print (df)
                   DATE_1  TESTSTEP_1  READING_1  LIMIT_1 RESULT_1  \
0 2019-01-01 07:37:17.432           1         23       10     FAIL

                   DATE_2  TESTSTEP_2  READING_2  LIMIT_2 RESULT_2
0 2019-01-01 07:37:23.661           2          3        3     PASS

If need also dates in separate first column:
df['DATE'] = pd.to_datetime(df['DATE'])
dates = df['DATE'].dt.date

df.columns = pd.CategoricalIndex(df.columns,categories=df.columns, ordered=True)
g = df.groupby(dates).cumcount().add(1)
df = df.set_index([dates.rename('DAT'), g]).unstack().sort_index(axis=1, level=1)
df.columns = [f'{a}_{b}' for a, b in df.columns]
df = df.reset_index()
print (df)
         DAT                  DATE_1  TESTSTEP_1  READING_1  LIMIT_1 RESULT_1  \
0 2019-01-01 2019-01-01 07:37:17.432           1         23       10     FAIL

                   DATE_2  TESTSTEP_2  READING_2  LIMIT_2 RESULT_2
0 2019-01-01 07:37:23.661           2          3        3     PASS


text:
Q: How to check the time taken by a chunk of code in R I want to check the time taken by a piece of code. Is there any way to do this.I would like  to know all the times like (user, system, and elapsed) time taken for a small portion of my code.
say my code have different segments
code 1......
...........
...........
code2.........
...............
...............
so i want the time taken by code 1 . Thanks

A: The simplest way:
system.time({ code chunk })

A: That analysis is called 'profiling' and described here in the Writing R Extensions manual as well as in Hadley's adv-R book.  My website also has a few (older) presentations covering this as part of introductions to High-Performance Computing, and the CRAN Task View on High-Performance Computing lists tools in the area.

A: To start the clock at your desired location by:
ptm <- proc.time() ## start of clock and then to end
proc.time()-ptm  ## end of clock.


text:
Q: why is null == 0 outputs false since both are falsey values? When I run
null == 0

or
0 == null

both outputs false even when both are falsey values, why?

A: == doesn't only check for values but also for types (and not in the same way that ===)
You can see more details here : The Abstract Equality Comparison Algorithm


text:
Q: Connection problem after a big impdp This morning i had a weird problem just opening the SQL developer i cannot connect to my database. I checked the log file of the impdp operation launched before (14G), all the data is imported without errors. But I cannot access to the database, I tried with the SQL Developer or with SQL*Plus.
I obtained the following error message:

I think the problem came with the log or archiving. I think i did a little mistake creating the oracle's instance. After having beed seen this error message i've seen that the oraarch folder is full of big sized files. I deleted them but this didn't solved the connection problem.
I think the problem is in the Ora parameters' file. Creating the instance in archivelog mode
 shutdown immediate
    startup mount
    alter database archivelog;
    alter database open;
    spool off

and archivelog folder and name files definition :
echo "log_archive_dest_1='LOCATION=$ORADATA_BASE/$SID/oraarch'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "log_archive_format='${SID}_%r_%s_%t.arc'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora

Here the file creating when creating the instance:
echo "db_domain=''" > $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "db_name='$SID'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "instance_name='$SID'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "db_block_size=8192" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "aq_tm_processes=0" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "optimizer_mode=CHOOSE" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "O7_dictionary_accessibility=FALSE" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "Remote_os_roles=FALSE" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "timed_statistics=TRUE" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "Workarea_size_policy='AUTO'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "undo_management='AUTO'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "undo_tablespace='UNDO'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "undo_retention=1800" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "java_pool_size=0" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "filesystemio_options=setall" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "remote_login_passwordfile=EXCLUSIVE" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "audit_file_dest='$STRUCTURE_ADMIN/$SID/audit'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "background_dump_dest='$STRUCTURE_ADMIN/$SID/bdump'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "core_dump_dest='$STRUCTURE_ADMIN/$SID/cdump'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "user_dump_dest='$STRUCTURE_ADMIN/$SID/udump'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "Remote_os_authent=FALSE" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "optimizer_index_caching=90" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "optimizer_index_cost_adj=10" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "db_file_multiblock_read_count=16" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "control_files='$ORADATA_BASE/$SID/oractl01/${SID}_ctrl01.ctl','$ORADATA_BASE/$SID/oractl02/${SID}_ctrl02.ctl','$ORADATA_BASE/$SID/oradata01/${SID}_ctrl03.ctl'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "log_archive_dest_1='LOCATION=$ORADATA_BASE/$SID/oraarch'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "log_archive_format='${SID}_%r_%s_%t.arc'" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "pga_aggregate_target=256M" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "processes=151" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "sga_target=2G" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
 echo "sessions=151" >> $STRUCTURE_ADMIN/$SID/create/init$SID.ora
echo "Connect par SQLPLUS*"

A: Basically your database has stalled because it has ran out of space to store archive logs, and needs to switch one.
To remedy, delete the generated logs (assuming you don't need them for backup and recovery purposes), then execute (as SYSDBA):
alter system archive log all;

alter system switch logfile;

If you don't need to run your database in archivelog mode (ie: you don't need to be able to do any disaster recovery & don't care if your data goes AWOL), you can turn archivelog mode off (as SYSDBA, database in MOUNT mode):
alter database noarchivelog;

alter database open;


text:
Q: A word for an object that doesn't fit in. I am looking for a word that describes an object that doesn't fit in, preferably a word that also can be applied to describe a person as well.
For example with clothing, you talk about 'regular fit', what is the opposite of a fit for bodies with an unusual shape.
Or a word for an object that doesn't fit into a box. Not necessarily an oversized object.
Or a person that doesn't fit into set categories, someone who doesn't have a box to tick.
I am either looking for single words and expressions.

A: Simplest word I can come up with is "misfit". Though please note the discrepancies among the dictionaries that I will outline below.

n
  1. a person not suited in behaviour or attitude to a particular social environment
  2. something that does not fit or fits badly vb (intr) to fail to fit or be fitted Collins English Dictionary
noun 1 : something that fits badly 2 : a person who is poorly
  adapted to a situation or environment "social misfits"
Merriam-Webster Dictionary

There's considerable variation among the dictionaries as to exactly what uses "misfit" can have. For example Collins English Dictionary lists it also as an intransitive verb, Merriam-Webster Dictionary doesn't. Oxford Living Dictionaries gives the meaning referring to a person, yet labels:

Something that does not fit or that fits badly.

As archaic.
Although "misfit" is usually used to describe a person who doesn't fit in, or is outside the realm of conformity or normality of a certain group, in my opinion it can be used for non-person objects as well.
For your own reference, you can see the Free Dictionary, which has definitions from three dictionaries, some mention ill-fitting garments, the American Heritage Dictionary labels it as archaic, while the Random House Kernerman Webster's College Dictionary doesn't.
Dictionary.com lists the following:

noun
  1.a person not suited in behaviour or attitude to a particular social environment
  2.something that does not fit or fits badly verb (intr)
  3.to fail to fit or be fitted dictionary.com

Cambridge Dictionary only lists the person definition. As I said, there is some variation among the dictionaries.

A: square-peg (Collins)

or square peg in a round hole
informal
  a person or thing that is a misfit, such as an employee in a job for which he or she is unsuited

See also the idiom on Wikipedia:

"As they say, you can't fit a square peg in a round hole. If your boss is like that round hole and you are that square peg, you aren't going to fit in unless you re-shape your edges." -- Gini Graham Scott in A Survival Guide for Working with Bad Bosses: Dealing with Bullies, Idiots, Back-stabbers, and Other Managers from Hell (2005).

A: Outlier
From Collins(emphasis mine):

*

*(Geological Science) an outcrop of rocks that is entirely surrounded by older rocks

*a person, thing, or part situated away from a main or related body

*a person who lives away from his place of work, duty, etc

  4. (Statistics) statistics a point in a sample widely separated from the main cluster of points in the sample.

The fourth definition fits your third example: a person who doesn't fit into the defined categories is a statistical outlier.
(Might be a bit formal for your usage).


text:
Q: Android FTP Client can't send a file to a Docker FTP Server I try to connect a FTP client from my Android device to a FTP server, hosted in a docker (via the stilliard/pure-ftpd image). Connection : Ok, Login : Ok, but when I try send a file, I have this exception from my Android device :
failed to connect to localhost/127.0.0.1 (port 30007): connect failed: ECONNREFUSED (Connection refused)

I tried with a "regular" FTP server (vsftpd, not in docker). It works.
I use the apache commons library, via gradle's dependencies.
compile group: 'commons-net', name: 'commons-net', version: '3.5'

Code use by the Android app (this code is a quick-written-testing-code) :
            FTPClient ftp = new FTPClient();
            try {
                ftp.connect("myhostname", 21);

                if (!ftp.login(mLogin, mPassword)) {
                    throw new RuntimeException();
                }

                int reply = ftp.getReplyCode();

                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return false;
                }

                ftp.enterLocalPassiveMode();

                if (!ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE)) {
                    throw new RuntimeException();
                }
                for (String docPath : docPaths) {
                    Log.d(TAG, "doInBackground: sending " + docPath + "...");
                    File file = new File(docPath);
                    InputStream inputStream = new FileInputStream(file);
                    if (!ftp.storeUniqueFile(file.getName(), inputStream)) {
                        Log.e(TAG, "doInBackground: error while sending");
                        ftp.disconnect();
                        return false;
                    }
                    inputStream.close();
                }
                if (!ftp.logout()) {
                    throw new RuntimeException();
                }

                ftp.disconnect();

                return true;
            } catch (Exception e) {
                Log.e(TAG, "doInBackground: ", e);
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException e1) {
                        Log.e(TAG, "doInBackground: ", e1);
                    }
                }
                return false;
            }


text:
Q: I want to run a javascript code without using the browser but Vscode directly I wrote a code on the vscode but I want to run the code directly on the  vscode  for the output. After downloading the  "JUA HAN" as the code runner but is giving me this output. 'node' is not recognized as an internal or external command,
operable program or batch file.
I wrote console.log("Hello world") on vscode. My expectation is to see Hello world on the vscode directly with the help of code runner.


text:
Q: Thread in Service Android For my App. I am using the Background service i.e, Lifecycle that excutes for every 200 ms . Now i want the Thread in Service which checks some condition if the lifecycle is on. Can anyone please suggest me how can i implement this logic.

A: Simply create a Thread in the Service class with come kind of callback. Services are not some magical, remote components of the app, you can create Threads in them just fine. Or even better, go for an AsyncTask instead of Thread, as it has a callback mechanism already implemented (the onProgressUpdate() method) :-)


text: Q: Book on History of mathematics? (till current date) I'm looking for a book on history of mathematics that pays less attention on history and teaches you math(more attention), like when and how calculus was invented,what is calculus and where it is used, when and how number theory was discovered,what is number theory and where it is used, same about geometry,topology,combinatorics,analysis,concept of proof etc. (till current date)


text:
Q: Check If a FileUpload hase done Nothing in Client Side As you know I can click on a FileUpload Button to see a Open File dialog, but I can choose nothing and simply close or cancel it. I need to find this event and do something withing this. For example if FileUpload is fired and user does not select any file then I hide a button.
Here is a function which will call when you select on a input file button and it will make a button invisible if you have canceled selecting a file.
        function CancelCheck(element) {
        var file = elemeny.files[0];
        if (file == undefined)
            document.getElementbyId("Btn1").style.visibility = 'hidden';
        }

AND HERE is my input file control:
<input id="Upload1" type="file" name="file" onchange="javascript:CancelCheck(this)" runat="server" accept=".txt" />

It will work if you have previously selected a file ( I mean input file contains a file), But if you are clicking on int for the first time and canceling it, it won't work.
Hope I'm Clear Enough.

A: There is no such event but there is some dirty solution. However I wouldn't recommend it unless really necessary.
So we should consider what happens when the "Cancel" button is clicked - the browser and the HTML document are focused. To handle "dialog cancel event" we can attach an event handler for onfocus event on the HTML body (for example). Once this handler is reached, we must remove it and then we can check if the value of the file uploader is empty.
Here is sample example:
HTML
<input type="file" id="fileUpload" />

JavaScript
var fileUpload = document.getElementById('fileUpload')

fileUpload.addEventListener('click', onUploadClick);

function onUploadClick() {
    document.body.addEventListener('focus', onBodyFocus, true);
}

function onBodyFocus() {
    setTimeout(function() {
        if(!fileUpload.value || !fileUpload.value.length)
        {
            alert('cancelled');
        }
    }, 100);

    document.body.removeEventListener('focus', onBodyFocus);
}

Click for JsFiddle demo


text:
Q: C++ / How does a iterator work for a Set of class object? I've been teaching myself C++, and found an interesting thing.
According to this web page,:

The most obvious form of iterator is a pointer.

So, I used to think that an iterator object works in almost the same way as a pointer (e.g. int *i);
However, now I guess that it would be more accurate to say an iterator object is like a pointer of a pointer (such as int **i) rather than a pointer (int *i).
I noticed this, when I was coding the following one.
set<Point*, Point> points; //This class encapsulates x and y coordinates for a 2 dimensional point
set<Point*, Point>::iterator it;

int x = 22;
int y = 4;
Point* pt = new Point(x, y);
points.insert(pt);
//Similar statements are here, to insert other Point objects with different arguments

for (it = points.begin(); it != points.end(); it++) {
    cout << "**it: " << **it << ", *it :" << *it << ", Address : " << &it << endl;
}

As a result,

*

***it showed values of Pointer class objects

**it showed addresses

*&it showed the address of the it object

So, is it right to say that an iterator object (it) is basically the same as **it?
Another question which is a bit different from iterators:
If I need to make a set of class object, like: set<ClassName*, ClassName> SetName;, what would be the correct way? (as long as this class contains comparable data type, like int or double)
I'd appreciate if you'd give some advice.

A: It is a wrong assumption. In your example the value_type of the set is pointer Point *. And *it gives you an element in the set that is a reference to some object of this value_type that is of type Point * and ++it "points" to the next element in the set. So the iterator behaves the same way as pointer to an object of value_type.
When you use expression like **it then the second dereference is not applied to the iterator. It is applied to an object in the set. You can imagine expression **it the following way
Point *pp = *it;

Point p = *pp;

Iterator of a container is responsible to provide you access to elements of the container. Thus if elements in the container has type value_type then the iterator provides access to these elements of this value_type. The elements in turn can be pointers to objects or even pointers to pointers to objects and so on.
As for your second question then if the class has the corresponding operator function and the class itself has some simple default constructor then you may use such an approach though it would be better to define a separatw comparator or simply to define operator < for objects of the class. In the last case you can write
std::set<Point> s;

without explicit second template argument.
Here is demonstrative program of your approach
#include <iostream>
#include <set>

int main()
{
    struct Point
    {
        int x, y;
        bool operator ()( const Point &p1, const Point &p2 ) const
        {
            return p1.x < p2.x && p1.y < p2.y;
        }
    };

    std::set<Point, Point> s;
    s.insert( { 2, 2 } );
    s.insert( { 1, 1 } );

    for ( const Point &p : s ) std::cout << p.x << ' ' << p.y << std::endl;

    return 0;
}

The program output is
1 1
2 2


text:
Q: Run postinstall hook for any local dependency If we have this:
{
  "scripts":{
    "postinstall":"./scripts/postinstall.sh"
  }
}

Then this postinstall hook will run whenever we do an
$ npm install
At the command line
What I am wondering however, is if there is a way to run a postinstall hook when we install a dependency like this
$ npm install x
Is there some NPM hook that we can use for that?

A: Short answer There's no functionality built-in to npm which provides this kind of hook that I'm aware of.

Possible solution, albeit a bash one, would be to completely override the npm install x command with your own custom logic. For example:

*

*Create a .sh script as follows. Lets name the file custom-npm-install.sh:
#!/usr/bin/env bash

npm() {
  if [[ $* == "install "* || $* == "i "* ]]; then

    # When running `$ npm install <name>` (i.e. `$ npm install ...` followed
    # by a space char and some other chars such as a package name - run
    # the command provided.
    command npm "$@"

    # Then run a pseudo `postinstall` command, such as another shell script.
    command path/to/postinstall.sh
  else
    # Run the `$ npm install` command and all others as per normal.
    command npm "$@"
  fi
}

*Add the following snippet to your .bash_profile file ( Note: you'll need to define the actual path to custom-npm-install.sh):
# Custom logic applied when the `npm install <name>` or the
# shorthand equivalent `npm i <name>` command is run.
. path/to/custom-npm-install.sh

Notes

*

*After configuring your .bash_proile as per point two above, you'll need to create a new terminal session/window for it to be effective. The logic will be effective in all terminal sessions thereafter.

*Now, whenever you run npm install <name> or the many other variations such as:

*

*npm install <name>@<version>

*npm install <name> <name> --save-dev

*npm i -D <name>

*etc, etc...
custom-npm-install.sh will run the command as per normal and then run the command ./scripts/postinstall.sh (i.e. whatever the subsequently given command is set to).

*All other npm commands will be run as normal, e.g. npm install

*Given custom-npm-install.sh current logic the ./scripts/postinstall.sh will be run whenever npm install <name> ... is entered via the CLI. However, if you wanted it to run ONLY when a specific package is installed then you'll need to change the conditional logic in the if statement. For example if you want ./scripts/postinstall.sh to run ONLY when installing shelljs then change the if statement to:
if [[ $* == "install "*" shelljs"* || $* == "i "*" shelljs"* ]];


text:
Q: Im trying to create an object using JQuery UI Autocomplete, following the example given, however its currently not working I've tried to copy the example for jQuery UI with my code, however the autocomplete isn't showing currently.
The example is from here:
https://jqueryui.com/autocomplete/#custom-data
<input id="FeatureSearch" tabindex="1" class="form-control" @*id="child-name"*@ placeholder="" required="" aria-required="true" type="text" style="width:420px;float:right">

                    @*<input id="autoComplete" tabindex="1">*@
                    <input type="hidden" id="search-id">

                    <input type="hidden" id="parent-id">

$(function () {
        var ProductFeatures = @Html.Raw(Json.Encode(Model.AllFeatureNames))/*Json.Encode(*/@*'@Model.AllFeatureNames'*@;

        $("#FeatureSearch").autocomplete({
            source: ProductFeatures,
            focus: function (event, ui) {
                $("#FeatureSearch").val(ui.item.Name);
                return false;
            },
            select: function (event, ui) {
                $("#FeatureSearch").val(ui.item.Name);
                $("#search-id").val(ui.item.Id);
                if (ui.item.ParentId != null) {
                    $("#parent-name").val(ui.item.ParentName);
                    $("#parent-id").val(ui.item.ParentId);
                }
                return false;
            },
            appendTo: "#searchbox",
        }).autocomplete("instance")._renderItem = function (ul, item) {
            return $("
")
                .append("
" + item.Name + "
" + item.ParentName + "
")
                .appendTo(ul);
        };
    });


text:
Q: Attaching animations to a single entity using entity generator - A-Frame I'm creating a bunch of entities using <a-entity generator>, but I also want each to animate when an event happens (in this case, a collision). I'm using <a-mixin> to define the properties of the entity that I'm making.
Here's the mixin:
<a-mixin id="octa" geometry="primitive: octahedron; radius:4" material="src:#asteroid"></a-mixin>

And here's the entity generation:
<a-entity entity-generator="mixin: octa position; num: 50;"></a-entity>

If I put the <a-animation> behavior in the <a-entity-generator>, every one of the entities animates rather than just a single entity (I get why that happens though). But if I put the animation behavior between <a-mixin> tags, nothing happens. Any advice on how to approach this?

A: Try the animation component https://github.com/ngokevin/kframe/tree/master/components/animation
<a-mixin id="octa" geometry="primitive: octahedron; radius:4" material="src:#asteroid" animation="attribute: rotation: to: 0 360 0"></a-mixin>


text:
Q: jquery applying css tag $($("#myDiv")).append("<b>Hello</b>");

how can i apply to mydiv display:none

A: Don't manipulate the display CSS property with css(). Use hide():
$("#myDiv").hide().append("Hello");

Why are you doing:
$($("#myDiv"))...

?

A: $("#myDiv").css("display","none");  should do the trick but look into the jquery hide method too (hide) which can hide the div "smoothly" if you want that.


text:
Q: I want to sort data present in excel file in sheet with respect to column. (The excel file has multiple sheets) Excel Data
This is the data I've in an excel file. There are 10 sheets containing different data and I want to sort data present in each sheet by the 'BA_Rank' column in descending order.
After sorting the data, I've to write the sorted data in an excel file.
(for eg. the data which was present in sheet1 of the unsorted sheet should be written in sheet1 of the sorted list and so on...)
If I remove the heading from the first row, I can use the pandas (sort_values()) function to sort the data present in the first sheet and save it in another list.
like this
import pandas as pd
import xlrd

doc = xlrd.open_workbook('without_sort.xlsx')
xl = pd.read_excel('without_sort.xlsx')
length = doc.nsheets
#print(length)

#for i in range(0,length):
#sheet = xl.parse(i)

result = xl.sort_values('BA_Rank', ascending = False)
result.to_excel('SortedData.xlsx')
print(result)

So is there any way I can sort the data without removing the header file from the first row?
and how can I iterate between sheets so as to sort the data present in multiple sheets?
(Note: All the sheets contain the same columns and I need to sort every sheet using 'BA_Rank' in descending order.)

A: First input, you don't need to call xlrd when using pandas, it's done under the hood.
Secondly, the read_excel method its REALLY smart. You can (imo should) define the sheet you're pulling data from. You can also set up lines to skip, inform where the header line is or to ignore it (and then set column names manually). Check the docs, it's quite extensive.
If this "10 sheets" it's merely anecdotal, you could use something like xlrd to extract the workbook's sheet quantity and work by index (or extract names directly).
The sorting looks right to me.
Finally, if you wanna save it all in the same workbook, I would use openpyxl or some similar library (there are many others, like pyexcelerate for large files).
This procedure pretty much always looks like:

*

*Create/Open destination file (often it's the same method)

*Write down data, sheet by sheet

*Close/Save file

If the data is to be writen all on the same sheet, pd.concat([all_dataframes]).to_excel("path_to_store") should get it done


text:
Q: Get buttons to open custom dialog with camera preview in surface view I have two buttons that need to open a custom dialog that has a surface view that's supposed to hold a camera preview. I need to not have the default camera controls, just the preview itself, behind another included layout that's holding buttons.
Here's the code for my buttons:
topeyebtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View arg3) {

                                //Starting a new Intent

                                Intent topClick = new Intent(Intent.ACTION_VIEW,      Uri.parse("http://funnmag.com"));

                                // starting new activity

                                startActivity(topClick);
             }});

And here's the code for my surface view and camera preview:
package com.adanawtn.FunnMagViewerWindow;

import java.io.IOException;
import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.ViewGroup.LayoutParams;

 public class camerapreview extends Activity {

 private SurfaceView surface_view;
 private Camera mCamera;
 SurfaceHolder.Callback sh_ob = null;
 SurfaceHolder surface_holder        = null;
 SurfaceHolder.Callback sh_callback  = null;

@Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     getWindow().setFormat(PixelFormat.TRANSLUCENT);

     surface_view = new SurfaceView(getApplicationContext());
     addContentView(surface_view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

     if (surface_holder == null) {
         surface_holder = surface_view.getHolder();
     }

     sh_callback = my_callback();
     surface_holder.addCallback(sh_callback);
 }

     SurfaceHolder.Callback my_callback() {
         SurfaceHolder.Callback ob1 = new SurfaceHolder.Callback() {

             @Override
             public void surfaceDestroyed(SurfaceHolder holder) {
                   mCamera.stopPreview();
                   mCamera.release();
                   mCamera = null;
             }

             @Override
             public void surfaceCreated(SurfaceHolder holder) {
                 mCamera = Camera.open();

                   try {
                        mCamera.setPreviewDisplay(holder);
                   } catch (IOException exception) {
                         mCamera.release();
                         mCamera = null;
                   }
             }

             @Override
             public void surfaceChanged(SurfaceHolder holder, int format, int width,
                     int height) {
                 mCamera.startPreview();
             }
         };
         return ob1;
 }
}


text:
Q: Kivy/MD - why is my MDLabel in Scrollview showing the last line when it initially displays (w/image and code)? I have a Scrollview with an MDLabel in it.  When I invoke this MDDialog the MDLabel displays but it display the last page of text on screen initially.  I want it to display the first page of text and then let me scroll down.
In this example, if I click and drag my mouse, I can scroll up, but my mousewheel will not scroll up as it does on other Scrollviews I have.
How do I display the first page of text in MDLabel intially?
What my scrollview and MDLabel look like - click here for image
Py - complete run-able minimal code:
from kivymd.app import MDApp
from kivy.lang import Builder

kv = """
MDBoxLayout:
    orientation: "vertical"
    size_hint_y: None
    height: "400dp"
    markup: True
    ScrollView:
        do_scroll_x: False
        do_scroll_y: True
        size_hint: None, None
        size: "500dp", "700dp"
        pos_hint: {"center_x": .5, "center_y": 1}
        MDLabel:
            id: MLogfileText
            size_hint: 1,None
            text: "Log file"
            halign: "left"
            text_color: self.theme_cls.primary_light

"""

class ColorLabelApp(MDApp):
    def build(self):

        screen = Builder.load_string(kv)

        screen.ids.MLogfileText.text = (" (first line) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. (last line)")

        return screen

ColorLabelApp().run()

A: Bind the label's height to its texture_size[1] (i.e. height) as,
        MDLabel:
            padding: [20, 20]
            id: MLogfileText
            size_hint: 1,None
            height: self.texture_size[1]


text:
Q: sceneUpdated() vs invalidate() What is the difference between viewer.impl.sceneUpdated() and viewer.impl.invalidate()? I've seen them used interchangeably all the time but haven't been able to figure out why.
In the case of invalidate(), I have seen it used accepting 1 to 3 boolean arguments with every possible combination and it seems to give the same result every time.

A: viewer.impl.invalidate is basically:
invalidate(needsClear, needsRender, overlayDirty)
//needsClear - full render - not (currently) interruptible, runs until completion, "locks" application, needs to re-render the whole scene from start
//needRender - progressive render - show a bit more each tick, runs unless interrupted by a move, control, etc.
//overlayDirty - overlay (like rollover highlighting etc) needs to be re-rendered

And sceneUpdated(objectsMoved, skipRepaint) is basically
this.invalidate(!skipRepaint, false, !skipRepaint);

Plus the scene bounds are getting remarked for update and the shadows'd get re-rendered.


text:
Q: Validate scanf parameters I need to validate the scanf parameters
for example
if (scanf("%c,%f,%f", &ch, &p1, &p2) != 3)
// How can I tell which parameter failed?
// If I want to output message such as "Second parameter must be a real nubmer".

A: scanf will stop scanning as soon as the first encountered symbol that does not match a format specifier. So if your scanf returns 1 then only the first format parameter was interpreted.
switch (scanf("%c,%f,%f", &ch, &p1, &p2)) {
  case 0:
  // no parameters were parsed successfully
  case 1:
  // only first parameter succeeded
  case 2:
  // only the first two parameters succeeded
  case 3:
  // all three parameter succeeded
  default:
  // error
}

Also please note that a return value smaller than the maximum number of successful parses may also indicate an error. In which case you should consult ferror().


text:
Q: strip new line character from end from char* I have a char* line on which I used while (fgets(line, line_size, fNames) != NULL). now the problem is I also get a new line character, which I want to strip.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main() {
    int i;
    char fileName[30];
    FILE *fNames, *fCurrent;
    char *line = NULL, command[100];
    char letters3[3];
    size_t len = 0;
    //size_t read;
    const size_t line_size = 300;
    line = malloc(line_size);
    if (access("fileNames.lst", F_OK) == -1)
        system("crunch 3 3 abcd -o fileNames.lst");
    else
        printf("fileNames.lst already exists.\n");
    fNames = fopen("./fileNames.lst","r");

    while (fgets(line, line_size, fNames) != NULL) {
        printf("Making File: %s.lst\n", line);
        strcpy(command, "crunch 8 8 -t ");
        strcpy(command, line);
        strcpy(command, strcat(command," -o"));
        puts(command);
        strcpy(line, strcat(line, ".lst"));
        fCurrent = fopen(line, "w");
        //system(command);
        fclose(fCurrent);
        //system("read -r -p \"Press space to continue...\" key");
    }
    return 0;
}

A: There are problems in your code:

*

*You do not check the return value of fopen(), nor that of malloc().

*strcpy(command, strcat(command," -o")); and strcpy(line, strcat(line, ".lst")); invoke undefined behavior as you call strcpy on overlapping strings.

*strcpy(command, line); overwrites the string you just copied to command with strcpy(command, "crunch 8 8 -t ");.

*You do not check the lengths before copying or concatenating strings into line and command.  You should use snprintf() for both a safer and simpler method.
To get rid of the trailing linefeed in line left by fgets(), you can either write:
line[strcspn(line, "\n")] = '\0';

or you can write this:
char *p = strchr(line, '\n');
if (p != NULL)
    *p = '\0';

or even this one that removes the linefeed at the end of the string:
size_t len = strlen(line);
if (len > 0 && line[len - 1] == '\n')
    line[--len] = '\0';

With both of the latter methods, you can track whether there was indeed a linefeed or not.  The absence of a linefeed at the end of the line can mean one of several possibilities:

*

*The line was truncated because it does not fit in the buffer provided.  You should be careful to handle this condition because the string read does not correspond to the actual file contents. It could happen in your case if a filename is longer than 298 bytes, which is possible on many modern file systems.

*The end of file was reached but no linefeed is present in the file at the end of the last line.  This is probably not an error, but could indicate that the input file was truncated somehow.

*The input file contains a '\0' byte, which causes early termination of the line read by fgets(). This would not be allowed as part of a filename and is quite unlikely to occur in text files, unless the file was encoded as ucs2 or UTF-16.

A: I think you are searching for this one. It is very easy to use and it does the job.
line[strcspn(line, "\n")] = '\0';


text:
Q: Update from many rows to one without cursor I have a table with a field that stores comma delimited values as a string. I would like to add more values to that string in one row from multiple rows in another table. Below you will see an example.
I had it in my head that COALESCE() would work, and I have an idea for how I could use that trick to load a variable, but I think that means I would have to use a cursor to gather all the values I want for each row of t1, and I would really like to avoid cursors. This table design is a mess that I inherited and I would rather avoid making it worse by using cursors everywhere to deal with it.
CREATE Table t1(
StringColumn VARCHAR(10)
)

CREATE Table T2(
    TestString VARCHAR(10),
    ConcatString VARCHAR(10)
)

INSERT INTO t1(StringColumn) VALUES('1,2,3')

INSERT INTO T2(TestString,ConcatString) VALUES('2','4')
INSERT INTO T2(TestString,ConcatString) VALUES('2','5')
INSERT INTO T2(TestString,ConcatString) VALUES('2','6')

INSERT INTO t1(StringColumn) VALUES('A,B,C')

INSERT INTO T2(TestString,ConcatString) VALUES('A','D')
INSERT INTO T2(TestString,ConcatString) VALUES('B','E')
INSERT INTO T2(TestString,ConcatString) VALUES('B','F')

Begin Tran --Commit Rollback
UPDATE t1
Set t1.StringColumn = t1.StringColumn + ',' + t2.ConcatString
FROM t1
INNER JOIN t2 ON charindex(t2.TestString,t1.StringColumn) <> 0

SELECT * FROM t1

Per this example the results are:
1,2,3,4
A,B,C,D
I would like the two rows of t1 to look like:
1,2,3,4,5,6
A,B,C,D,E,F
Thanks. Any advice would be appreciated.

A: why don't you use the row processing in here.
You can use a value table and then a while like this example:
DECLARE @T TABLE(Id int identity,Value int)
DECLARE @MinId INT = (SELECT MIN(Id) FROM @T)
DECLARE @MaxId INT = (SELECT MAX(Id) FROM @T)

DECLARE @ResultTable TABLE (Value int)

WHILE(@MinId <= @MaxId)
BEGIN
    INSERT @ResultTable
        SELECT Value
        FROM @T
        WHERE Id = @MinId

        SET @MinId += 1
END

SELECT *
FROM @ResultTable

I think this will help U ...

A: This solution will work if you want to stay away from cursors, loops, and are running at least SQL 2008. This actually ends up being more efficient (in SQL 2008+) than any function or cursor you could create.
You want to use some of the new XML features 2008 (or 2005?) introduced. Specifically, in your query, you want to construct an XML string using XML PATH mode. Once all of the results are jammed into a single XML String, you can construct a complex expression to return what you are after. Explained more in detail from msdn:
MSDN Path Mode
Using the sample tables you provided, try this query:
SELECT
Test_String = T.StringColumn + (SELECT
                            (',' + t2.ConcatString)
                            FROM
                                T1 t1
                            INNER JOIN T2 t2
                                ON charindex(t2.TestString,t1.StringColumn) <> 0
                            WHERE
                            t1.StringColumn = t.StringColumn
                            FOR XML PATH( '' ))
FROM
    T1 T

Based on everything you said, it sounds like you may need to modify my query. You may need to do some additional joins, or perhaps change the guts of the query some. Let me know!


text:
Q: QT Unclear shift-operator behaviour I need to get 2 high bits from one byte in array. I have enum, that defines all values of those 2 bits:
...
enum elems{
    elem1 = 0,
    elem2 = 1,
    elem3 = 2,
    elem4 = 3
}
...
elems getElems(const QByteArray &data)
{
    return (elems)(data[3] >> 6);
}
...
qDebug() << (data[3] >> 6); // return 0 or 1 or 2 or 3 (true way)
qDebug() << getElems(data); // return 0 or 1 or -1 or -2 (wrong way)
...

When data[3] == 0 it return 0, when data[3] == 64 it return 1, but when data[3] == 192 it return -1 and when data[3] == 128 it return -2.
Why it's happens?

A: QByteArray is an array to char, which most probably is signed. Therefore 192 is outside char's range and wraps back to -64
When you return (elems)(data[3] >> 6) it will do an arithmetic shift like most compiler implementations on a signed type (because right shift in C++ is implementation defined). That will propagate the sign bit (1 in this case because of -64) to the left, making all the bits in the byte 1 and is the reason why you see -1 returned.
If you only want the 2 high bits, mask the result before returning
return (elems)((data[3] >> 6) & 0x03);

Or cast the type to unsigned
return (elems)((qint8)data[3] >> 6);

Alternatively this will also work
return (elems)((data[3] >> 6) & 0xFF);

A: Lưu Vĩnh Phúc is correct. you can also modify your function as:
return (elems)((unsigned char)data[3] >> 6);


text:
Q: Stuck on a particular 2nd order non-homogeneous ODE ($y'' + 4y' + 5y = t^2$)
$y'' + 4y' + 5y = t^2$

So I solve for $r^2 + 4r + 5 = 0$ returning $r = 2 \pm 2i$. So $y_c = e^{-2t}(C_1\cos(2t) + C_2\sin(2t)$. For $y_p(t)$ I pick $At^2$. So $2A + 8At + 5At^2 = t^2$. I have been stuck on finding a particular solution for 30 minutes now.
My first question: Is there any particular method for finding $y_p(t)$?
Secondly, how to find $y_p(t)$ here?

A: Hint:  try a quadratic polynomial

A: I haven't solved one using this method in awhile, but I think to get this to work, one needs more room to maneuver.  Try
$y_p(t) = At^2 + Bt + C, \tag{1}$
then
$y_p' = 2At + B, \tag{2}$
$y_p'' = 2A, \tag{3}$
all of which, when inserted into
$y'' + 4y' + 5y = t^2 \tag{4}$
lead to
$2A + 4(2At + B) + 5(At^2 + Bt + C) = t^2, \tag{5}$
which in turn leads to the three equations
$2A + 4B + 5C = 0, \tag{6}$
$8A + 5B = 0, \tag{7}$
$5A = 1, \tag{8}$
so that
$A = \frac{1}{5}, \tag{9}$
$B = - \frac{8}{25}, \tag{10}$
$C = \frac{22}{125}, \tag{11}$
whence
$y_p(t) = \frac{1}{5}t^2 -  \frac{8}{25}t + \frac{22}{125}. \tag{12}$
That should work if the arithmetic is right!

A: First question: Look for these in your book...
(1) method of undetermined coefficients
(2) variation of parameters

A: You should use method of undetermined coefficients.
Take
$$y_{p}(t)=at^2+bt+c$$
then
$$
y'_{p}(t)=2at+b
$$
$$
y''_{p}(t)=2a
$$
and substitue it in differential equation
$$2a+8at+4b+5at^2+5bt+5c=t^2$$
from equality of polynomials we have
$5a=1,8a+5b=0,2a+4b+5c=0$
from here we can find $a=\frac{1}{5},b=\frac{-8}{25},c=\frac{22}{125}$.
So
$$
y_{p}(t)=\frac{1}{5}t^2+\frac{-8}{25}t+\frac{22}{125}
$$

A: How to find the particular and general solution to $y''+4y'+5y=t^2$.
Given $y''+4y'+5y=t^2$, we must assume this is a non-homogeneous second order ODE.
We from this there are two general forms to solve this problem, undetermined coefficients and variation of parameters. Here we will use undetermined coefficients.
We must now also assume that the Method of Undetermined Coefficients is a systematic way to determine the general form/type of the particular solution $y_p$ based on the non-homogeneous term (forcing function) $f(x)$ in the given ODE.
First, we should find the homogeneous solution so we can apply this to the general solution later on. We do this by using $λ$ in place of the $y$ and using exponents in place of the order of the derivative and setting the equation equal to zero. After doing this we will solve for $λ$.
$y''+4y'+5y=t^2$
$λ^2+4λ+5=0$
We have to use the quadratic formula in order to solve for $λ$.
We know the quadratic formula is,
$\frac{-b±\sqrt{(b)^2-4ac}}{2a}$
Thus,
$\frac{-(4)±\sqrt{(4)^2-4(1)(5)}}{2(1)}=\frac{-4±\sqrt{(16-20)}}{2}=\frac{-4±2i}{2}=-2±i$
From this we can write our homogeneous solution:
$y_h(t)=c_1e^{-2t}\cos(t)+c_2e^{-2t}\sin(t)$
Now we must find and use a trial solution, $y_t$. We know the forcing function is $t^2$. Thus the basic trial function for a function with the exponential $2$, we know the trial must be a polynomial function.
$y_t=at^2+bt+c$
From here, the derivative and second derivative must be taken.
$y'_t=2at+b$
$y''_t=2a$
Now, plugging in these results into our original ODE we should get:
$2a+4(2at+b)+5(at^2+bt+c)=t^2$
$5at^2+t[8a+5b]+[2a+4b+c]=t^2$
Here, we can equate the coefficients in order to solve for the unknowns.
$x^2: 5a=1$
$a=\frac{1}{5}$
$x: 8a+5b=0$
$8(\frac{1}{5})+5b=0$
$b=\frac{-8}{25}$
constants:$2a+4b+c=0$
$2(\frac{1}{5})+4(\frac{-8}{25})+c=0$
$c=\frac{22}{25}$
Thus,
$a=\frac{1}{5}, b=\frac{-8}{25}, \text{ and } c=\frac{22}{25}$
We can then plug these into our trial solution to form our particular solution:
$y_p=\frac{1}{5}t^2-\frac{8}{25}t+\frac{22}{25}$
To find the general solution, we know that:
$y_g(t)=y_h(t)+y_p(t)$
Thus, our general solution is:
$y_g(t)=c_1e^{-2t}\cos(t)+c_2e^{-2t}\sin(t)+\frac{1}{5}t^2-\frac{8}{25}t+\frac{22}{25}$


text:
Q: NSE India Quote History Download Automation first of all I'm not a programmer, I just want to Download A quote history from https://www.nseindia.com/products/content/equities/equities/eq_security.htm by putting some input data in Excel. I somehow managed to put data in VBA. Could anyone please help me how to click on "Download File in CSV Format" & save it to my local disk.
Here is my VBA code:
Private Sub CommandButton1_Click()
  Dim IE As Object
  With IE
  Set IE = CreateObject("InternetExplorer.Application")

'create new instance of IE. use reference to return current open IE if
'you want to use open IE window. Easiest way I know of is via title bar.
  IE.Navigate "https://www.nseindia.com/products/content/equities/equities/eq_security.htm"
'go to web page listed inside quotes
  IE.Visible = True
  While IE.busy
    DoEvents  'wait until IE is done loading page.
  Wend
  IE.document.ALL("symbol").Value = ThisWorkbook.Sheets("sheet1").Range("b1")
  IE.document.ALL("series").Value = ThisWorkbook.Sheets("sheet1").Range("b2")

  IE.document.getElementById("rdDateToDate").Click

  IE.document.ALL("fromDate").Value = ThisWorkbook.Sheets("sheet1").Range("b4")

  IE.document.ALL("toDate").Value = ThisWorkbook.Sheets("sheet1").Range("c4")
  IE.document.getElementById("submitMe").Click

  End With

End Sub

A: Below UDF will do what you are looking for:
Private Sub CommandButton1_Click()
    Dim IE As New InternetExplorer
    Dim oW As Worksheet: Set oW = ThisWorkbook.Worksheets("Sheet4")
    Dim oEleCol As MSHTML.IHTMLElementCollection
    Dim oEle As MSHTML.IHTMLElement

    With IE
    'Set IE = CreateObject("InternetExplorer.Application")

        ' Set IE
        .Visible = True
        'ShowWindow .hwnd, SW_SHOWMAXIMIZED

        ' Navigate to URL
        .Navigate "https://www.nseindia.com/products/content/equities/equities/eq_security.htm"

        ' Wait for page to be ready
        While .Busy
          DoEvents  'wait until IE is done loading page.
        Wend

        ' Set criteria
        .document.all("symbol").Value = oW.Range("I2")
        .document.all("series").Value = oW.Range("I3")
        .document.getElementById("rdDateToDate").Click

        ' Wait for page to be ready
        While .Busy
          DoEvents  'wait until IE is done loading page.
        Wend

        ' Set remaining criteria
        .document.all("fromDate").Value = oW.Range("I4")
        .document.all("toDate").Value = oW.Range("I5")

        ' Submit criteria
        .document.getElementById("submitMe").Click

        ' Wait for page to be ready
        While .Busy
          DoEvents  'wait until IE is done loading page.
        Wend

        ' Find the link to download file
        Set oEleCol = .document.getElementsByTagName("A")
        For Each oEle In oEleCol
            If oEle.innerText = "Download file in csv format" Then
                oEle.Click
                Exit For
            End If
        Next

        ' Wait for page to be ready
        While .Busy
          DoEvents  'wait until IE is done loading page.
        Wend

        ' Download file
        DownloadFile .hwnd

        ' Close IE
        .Quit

    End With

End Sub

NOTE:
1. You can comment out this line as I use it to maximise the browser window: ShowWindow .hwnd, SW_SHOWMAXIMIZED
2. DownloadFile is a function call. You can find the function here: How to download a file from internet explorer using VBA
3. Change the sheet name to whatever your sheet is
4. Change the cell references to whatever your references are


text:
Q: Why does the Keras sequence-to-sequence tutorial not mention the TimeDistributed layer wrapper? The Keras sequence to sequence tutorial explains the implementation of a sequence-to-sequence RNN, without even mentioning the usage of a TimeDistributed layer wrapper.  The accepted answer to another question in stackoverflow seems to imply however, that the usage of a TimeDistributed layer is indispensable to separate the individual time steps in the Dense layer (which seems logical to me).
So why is the TimeDistributed layer wrapper not even mentioned in the Keras tutorial? To keep things simple? Or does the tutorial use an architecture which doesn't require TimeDistributed? Or is it based on a Keras version that does not include or require TimeDistributed?

A: For a Dense layer, it's absolutely optional and it makes no difference.
The (current) behavior for Dense layers is to act on the last dimension and leave the others untouched. (In previous versions, like keras 1, this wasn't true and you actually needed the TimeDistributed wrapper).
So, if you input (samples, steps, input_dimension) into a Dense layer, you will get the output (samples, steps, units_or_output_dimension), which is exactly the same thing that a TimeDistributed(Dense(...)) would do.
For other layers, the use of TimeDistributed may be necessary, indeed. For instance, when you're processing movies in convolutional networks, you may want 2D convolutions with an input shape of (samples, frames, imageWidth, imageHeight, channels), and then you will need the TimeDistributed(Conv2D(...)) in order to have the additional frames dimension.


text:
Q: Node.js & Eclipse integration I have installed updates of nodeclipse,but i am not able to  run my java script file even though when i run them in node folder.
i get these errors like:
1)provisioning exception
2)No repository found

A: Correct name is nodeclipse
As said in http://www.nodeclipse.org/#support you should

I got this error and I'm sure it's a bug -- raise an issue!
Should you report a bug, please include the following:

*

*Nodeclipse version number (like 0.4 or 0.8)

*Eclipse version number (like 4.3.1 Kepler or 4.4.0)

*Eclipse distribution (e.g. Eclipse for JEE Developers)

*A detailed description of the steps necessary to reproduce the problem.

*Screenshot and stack trace, that you can get from Eclipse Error Log View (Window -> Show View ...) or from '.log' file from the directory '.metadata' in your workspace.

*See example issue #78