text:
Q: Video editing using PHP Is it possible to record a voice onto the uploaded video using PHP?

A: you can use the MLT library and my class. You can download it from this link https://github.com/1fer/mlt
Features

*

*Cut and join videos

*Join videos with transitions

*10 ready-made transitions with options

*Customizable Wipe transitions

*Add background audio

*Add watermark

*Add text overlay with options

*Add animated text

*Run rendering on background

*Get rendering progress percent

To install this melt library on server use this command:
sudo apt install melt
take a look at documentation how to use it, for example, to join clips use this code:
require __DIR__ . '/vendor/autoload.php';

$videoProcessing = new Andchir\VideoProcessing([
    'melt_path' => '/usr/bin/melt',
    'session_start' => true
]);

// Join clips
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['joinClips' => [
        $rootPath . '/uploads/tmp/Social.mp4',
        $rootPath . '/uploads/tmp/Dog.mp4',
        $rootPath . '/uploads/tmp/Swans.mp4'
    ]])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out1.mp4');

// Black color and fade transition
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        'colour:black', ['out' => 24],
        $rootPath . '/uploads/tmp/Dog.mp4'
    ]])
    ->addOption(['mix' => 25])
    ->addOption(['mixer' => 'luma'])
    ->addOption(['inputSource' => [
        'colour:black', ['out' => 24]
    ]])
    ->addOption(['mix' => 25])
    ->addOption(['mixer' => 'luma'])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out2.mp4');

// Join clips with transition
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4',
        $rootPath . '/uploads/tmp/Dog.mp4'
    ]])
    ->addOption(['mix' => 25])
    ->addOption(['mixer' => 'luma'])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out3.mp4');

// Cut clips and join with transition
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Social.mp4', ['in' => 200, 'out' => 275]
    ]])
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Dog.mp4', ['in' => 50, 'out' => 125]
    ]])
    ->addReadyMadeTransition('fade', 25)
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4', ['in' => 50, 'out' => 125]
    ]])
    ->addReadyMadeTransition('shiftRightIn', 25, [
        'width' => 1280,
        'height' => 720
    ])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out4.mp4');

// Add background audio with delay
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4', ['in' => 50, 'out' => 125]
    ]])
    ->disableAudio()
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Dog.mp4', ['in' => 50, 'out' => 200]
    ]])
    ->addReadyMadeTransition('shiftLeftIn', 25)
    ->addBackgroundAudio($rootPath . '/uploads/tmp/Reformat.mp3', ['in' => 0, 'out' => 150, 'delay' => 50])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out7.mp4');

// Add watermark
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4', ['in' => 50, 'out' => 125]
    ]])
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Dog.mp4', ['in' => 50, 'out' => 200]
    ]])
    ->addWatermark($rootPath . '/uploads/tmp/SampleLogo.png', false, [
        'distort' => 1
    ])
    ->addReadyMadeTransition('shiftLeftIn', 25)
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out8.mp4');

// Add text overlay
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4', ['out' => 120]
    ]])
    ->addTextOverlay('This is my best video', true, [
        'fgcolour' => '#004fed',
        'olcolour' => '#fff200',
        'outline' => 3,
        'pad' => '50x0',
        'size' => 80,
        'weight' => 700,
        'style' => 'italic',
        'halign' => 'center',
        'valign' => 'top',
        'family' => 'Ubuntu'
    ])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out10.mp4');

// Animated text
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4', ['out' => 120]
    ]])
    ->addTextOverlay('This is my best video', true, [
        'pad' => '50x0',
        'size' => 80,
        'halign' => 'center',
        'valign' => 'top',
        'family' => 'Ubuntu',
        'slideFrom' => 'bottom',
        'duration' => 50,
        'inOpacity' => 0,
        'outOpacity' => 100
    ])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out11.mp4');

// Rendering
$videoProcessing
    ->setProfile('hdv_720_25p')
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Swans.mp4', ['out' => 120]
    ]])
    ->disableAudio()
    ->addOption(['inputSource' => [
        $rootPath . '/uploads/tmp/Dog.mp4', ['out' => 120]
    ]])
    ->addReadyMadeTransition('shiftLeftIn', 25)
    ->addBackgroundAudio($rootPath . '/uploads/tmp/Reformat.mp3', ['out' => 215])
    ->setOutputVideoOptions($rootPath . '/uploads/tmp/out.mp4');

// Start rendering in background
$progressLogPath = $videoProcessing->render();

// Rendering progress
$percent = $videoProcessing->getRenderingPercent();

You can also make some filter effects like in Instagram and so on. Read more here:
https://www.mltframework.org/plugins/PluginsFilters/

A: No you can't, at least not by just using PHP, because PHP in itself doesn't provide the necessary libraries for recording sound and editing videos.
To actually record video and sound you'll need libraries like ffmpeg (there's a handy extension for PHP) for video editing and SoX for sound installed on your server. You can then access these programmes by using the the exec() function in PHP, for example. The implementation wouldn't be that simple, though.

A: I'd say no, because I don't know of any Hardware-Layer (Client-Side) for PHP...it might be possible with AJAX, but I don't think so.
But PHP might be able to overlay a video with a provided sound file, that should work if you find a library for that.

A: Strange idea.
PHP is for server side scripting, but record vioce you can only on client side (need sound card/codec for it)
PHP have nothing for it.
It can be more relative if you'd ask about JavaScript as it client sided.
But still, most ready to use and featurefull thing for such task if Adobe Flash technology.
If you not notice it -- if you right click on some flash banner, you'd see a property page where above other features you can see vioce recording.

A: Technically you could write a PHP plugin that binds with C libraries for audio/video editing. However, that's probably not the best path. A better option would be to invoke a ffmpeg/mencoder/... process from PHP.

A: PHP is for server side scripting, but record vioce you can only on client side (need sound card/codec for it)
PHP have nothing for it.

A: You can use PHP to edit video using a 3rd party service like the Shotstack video editing API. They have a PHP library that lets you perform all sorts of video editing and manipulation.
The library is available as a Composer package so you can install it using:
composer require shotstack/shotstack-sdk-php

The code below is an example of trimming a video clip start and end point:
<?php

require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'REGISTER FOR A KEY');

$client = new EditApi(null, $config);

$videoAsset = new VideoAsset();
$videoAsset
    ->setSrc('https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/footage/skater.hd.mp4')
    ->setTrim(3);

$videoClip = new Clip();
$videoClip
    ->setAsset($videoAsset)
    ->setLength(8)
    ->setStart(0);

$track = new Track();
$track->setClips([$videoClip]);

$timeline = new Timeline();
$timeline->setTracks([$track]);

$output = new Output();
$output
    ->setFormat('mp4')
    ->setResolution('hd');

$edit = new Edit();
$edit
    ->setTimeline($timeline)
    ->setOutput($output);

$render = $client->postRender($edit)->getResponse();

sleep(30);

$video = $client->getRender($render->getId())->getResponse();

if ($video->getStatus() === 'done') {
    echo $video->getUrl();
}

The library is open source but the platform it self is a paid service, with free account options.


text:
Q: Как скомпилировать программу находясь на каталог выше go.mod? У меня есть программа которая компилирует другие программы:
compiler.go:
package main

import (
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("go", "build", "projects/helloword/main.go")
    cmd.Stdout = os.Stdout
    cmd.Stdin = os.Stdin
    cmd.Stderr = os.Stderr
    cmd.Run()
}

Всё дерево каталогов выглядит так:
.
├── compiler <- Исполняемый файл который билдит проект ниже.
└── projects
    └── helloword
        ├── go.mod
        ├── hi
        │   └── hi.go
        └── main.go

Проблема в том что насколько я понял компилятор не видит go.mod так как go build запускается на каталог выше go.mod.
projects/helloword/main.go:3:8: no required module provides package github.com/c0caina/helloword/hi: go.mod file not found in current directory or any parent directory; see 'go help modules'

Как скомпилировать проект из другой программы?
Я не могу опустить compiler на уровень ниже что бы он находился в одной папке с go.mod.
Есть какие то другие способы скомпилировать?
Например вызвать exec.Command не в том же месте где лежит исполняемый файл а в каталоге helloword. Или может есть какой то другой способ об котором я не догадываюсь?

A: в cmd есть специальное поле Dir, отвечающее за рабочую директорию. можно ее определить, задать из какой директории будет выполняться программа.
cmd := exec.Command("go", "build", "projects/helloword/main.go")
cmd.Dir = "/path/to/dir/"
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Run()

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create C style union in java? I have to convert one of my code segment from C to java. Code is given below.
union commandString{
    char commndStr[20];
    struct{
        char commnd[4];
        char separator1;
        char agr1[5];
        char separator2;
        char arg2[3];
        char separator3;
        char additionalArg[5];
    };
};

I don't want to use any explicit parser or I do not want to use
System.arraycopy

method.
Is there any way to do that in my preferred way?

A: The best library for doing Struct and Union would be Javolutions which has been around for many years.  These were designed to do this.
I suggest if you are going to use these Unsafe you wrap it up in a library which abstracts it away.  This can avoid continuously running into bugs which crash your JVM (and I mean crash in the sense a C programmer would understand)
I have a library called Java-Lang which allows you to do the sort of things Java doesn't normally allow such as 63 bit sized off heap and memory mapped, thread safe off heap operations, sharing of memory between JVM on the same machine. And as I said, I use my own library to abstract away use of Unsafe.

A: The Java language does not support unions or direct control memory layout the way that languages like C do directly.
However Oracle does offer a backdoor that was added in Java 5 that can be used by using the class sun.misc.Unsafe.  It takes a bit of work, the full details have been documented by Martin Thompson on his blog.
The other option would be to write it in C and access it from Java as native functions via JNI.

A: Reading about the Javolution Union led me to ByteBuffer, which can be used as a Union.  Being an Abstract Class with only one provided class, you may need to create a temp file using File.createTempFile(), a RandomAccessFile(File,"rw"), a FileChannel RandomAccessFile.getChannel(), a MappedByteBuffer FileChannel.map().  It has controls for whether you want a big endian (default) or little endian relationship of bytes to other types.  If you just need one Union for mapping types to bytes, such as for a trie, this would suffice.


text:
Q: Symfony2 datetime field form I have a Symfony2 application which receive a JSON data in a form. One of the field is a date time. If I renderize the field form in this way:
->add('startDate', 'date', array(
        'widget' => 'single_text',
        'format' => 'yyyy-MM-dd HH:mm:ss'))

This accept something like:
"startDate": "2015-05-03 12:30:00"

But I need to introduce a datetime in this way:
"startDate": "2015-05-12T15:43:00+0200"

How can I set this format in the field?

A: On http://php.net/manual/en/function.date.php
"c" => ISO 8601 date (added in PHP 5)   => 2004-02-12T15:19:21+00:00
Try this:
->add('startDate', 'date', array(
    'widget' => 'single_text',
    'format' => 'c'))

I hope it helps.


text:
Q: Remove all white space from string JavaScript How can I remove all the white space from a given string.
Say:
var str = "  abc de fog   ";
str.trim();

Gives abc de fog AND NOT abcdefog, which I want.
How can I get all the white space removed using JavaScript?

A: Use this:
str.replace(/\s+/g, '');

Instead of this:
str.trim()


text:
Q: Rails4 ActiveRecord Association: create a parent and child record at the same time using a nested form? I've been trying to get this to work for a while, would appreciate it if someone could let me know if i am on the right path or point me to some documentation which may help.:
I have two active record models, Parent.rb and Child.rb (which has belongs_to: parent set).
I'm trying to create a parent then a child record at the same time and associate them(so that if a child record is invalid, the parent is not created at all).
below is what i have so far:
create_child.haml
= be_form_for @child do |f|
  = ff.text_field :name, 'child name'
  = f.fields_for :parent do |ff|
    = ff.text_field :name, 'parent name'

  = f.submit_tag 'Create'

children_controller.rb
children_controller.rb
def create
  Parent.create(child_params[:parent])
  Child.create(child_params)
end

def child_params
  params.require(:child).permit(:name, :parent)
end

A: There is a lot missing in this code.
railscasts.com is an old resource but this link covers the idea which is still used.
http://railscasts.com/episodes/196-nested-model-form-part-1
As a general idea:

*

*create a form for parent model, then put fields for child(ren) inside

*use accepts_nested_attributes_for, it will automatically create two objects and show errors when one is not valid

*I think you can enforce a child on form, but it is not natural order I believe

*create method needs some validation, please follow what rails guides say about standard behavious

It can look like below

def create
  @parent = Parent.new(parent_params) # params include child params as well, accepting nested attributes resolves that
  if @parent.save
    redirect_to root_path
  else
    render 'new'
  end
end

A: I know what you're more or less trying to do, and this would be my suggestions as the "railsiest" way possible:
class Parent < ActiveRecord::Base
    has_one :child

    validates :name, presence: true
    validates :age, presence: true
end

class Child < ActiveRecord::Base
    belongs_to :parent

    validates :name, presence: true
    validates :age, presence: true
    validates :favorite_color, presence: true
end

class ParentsController < ApplicationController
    # Display the form and initialize the form variables
    def new
        @parent = Parent.new
        @parent.build_child  #=> use if has_one relationship
        @parent.childs.build #=> use if has_many relationship
    end

    def create
        @parent = Parent.new(parent_params)

        if @parent.save
            flash[:notice] = "Parent and child were successfully saved."
            redirect_to some_path
        else
            flash[:error] = "Could not create parent and child."
            render :new
        end
    end

    private
    def parent_params
        params.require(:parent).permit(:name, :age, child_attributes: [:name, :age, :favorite_color])
    end
end

In your view (since you're using haml):
= form_for @parent do |f|
  = f.text_field :name
  = f.text_field :age

  / Here's the magic
  = f.fields_for :child do |c|
    = c.text_field :name
    = c.text_field :age
    = c.text_field :favorite_color

    = f.submit :submit

If you add the proper validations to both models, when using the fields_for method in your view, Rails will not save the Parent or the Child when so long as the Child and Parent validations pass for each.


text:
Q: underbrace under matrix I have managed to create under braces under my matrix and evened out the spaced using \phantom.
However, there are very large spaces between the columns, the dots, and the brackets. It would be great to make everything more compact horizontally, but I have no idea how to do so.
Could someone help?
\newcommand*{\vertbar}{\rule[-1ex]{0.5pt}{2.5ex}}
\newcommand\undermat[2]{% http://tex.stackexchange.com/a/102468/5764
  \makebox[0pt][l]{$\smash{\underbrace{\phantom{%
    \begin{matrix}#2\end{matrix}}}_{\text{$#1$}}}$}#2}

\begin{align}
    \mathbf{W}_{BA} &
    \begin{pmatrix}
\vertbar &  & \vertbar & & \vertbar &  & \vertbar  \\
\mathbf{x}^B_1 & \dots & \mathbf{x}^B_1 & \dots & \mathbf{x}^B_p & \dots & \mathbf{x}^B_p  \\
\undermat{k}{\vertbar &  & \phantom{--}\vertbar\phantom{--}} & & \undermat{k}{\vertbar &  & {\phantom{--}\vertbar\phantom{--}}}
\end{pmatrix}
= \notag \\\\
& \begin{pmatrix}
\vertbar &  & \vertbar & & \vertbar &  & \vertbar  \\
\mathcal{N}(\mathbf{x}^B_1)_1 & \dots & \mathcal{N}(\mathbf{x}^B_1)_k & \dots & \mathcal{N}(\mathbf{x}^B_p)_1 & \dots & \mathcal{N}(\mathbf{x}^B_p)_k  \\
\undermat{k}{\vertbar &  & \phantom{---}\vertbar\phantom{---}} & & \undermat{k}{\vertbar &  & {\phantom{---}\vertbar\phantom{---}}}
\end{pmatrix}.
\\
\end{align}

A: Below I use some measurements to correctly align the \underbrace width with its contents.

\documentclass{article}

\usepackage{amsmath,xcolor}

\newcommand*{\vertbar}{\rule[-1ex]{0.5pt}{2.5ex}}
\newcommand\undermat[2]{% http://tex.stackexchange.com/a/102468/5764
  \makebox[0pt][l]{$\smash{\underbrace{\phantom{%
    \begin{matrix}#2\end{matrix}}}_{\text{$#1$}}}$}#2}

\begin{document}

Original:
\begin{align}
    \mathbf{W}_{BA} &
    \begin{pmatrix}
  \vertbar &  & \vertbar & & \vertbar &  & \vertbar  \\
  \mathbf{x}^B_1 & \dots & \mathbf{x}^B_1 & \dots & \mathbf{x}^B_p & \dots & \mathbf{x}^B_p  \\
  \undermat{k}{\vertbar &  & \phantom{--}\vertbar\phantom{--}} & & \undermat{k}{\vertbar &  & {\phantom{--}\vertbar\phantom{--}}}
  \end{pmatrix}
  = \notag \\\\
  & \begin{pmatrix}
  \vertbar &  & \vertbar & & \vertbar &  & \vertbar  \\
  \mathcal{N}(\mathbf{x}^B_1)_1 & \dots & \mathcal{N}(\mathbf{x}^B_1)_k & \dots & \mathcal{N}(\mathbf{x}^B_p)_1 & \dots & \mathcal{N}(\mathbf{x}^B_p)_k  \\
  \undermat{k}{\vertbar &  & \phantom{---}\vertbar\phantom{---}} & & \undermat{k}{\vertbar &  & {\phantom{---}\vertbar\phantom{---}}}
  \end{pmatrix}.
  \\
\end{align}

% Update \vertbar
\renewcommand{\vertbar}[2]{{%
  \setlength{\fboxsep}{.5\fboxsep}
  \ooalign{%
    \hidewidth\rule[-1.5\ht\strutbox]{.4pt}{3.5\ht\strutbox}\hidewidth\cr%
    \colorbox{white}{$#2\strut$}\rule[-1.5\ht\strutbox]{0pt}{3.5\ht\strutbox}%
  }
}}
% Measure some components of the construction
\newlength{\xpB}\settowidth{\xpB}{$\mathbf{x}_p^B$}
\newlength{\NxaB}\settowidth{\NxaB}{$\mathcal{N} \bigl( \mathbf{x}_p^B \bigr)_1$}
\newlength{\NxpB}\settowidth{\NxpB}{$\mathcal{N} \bigl( \mathbf{x}_p^B \bigr)_k$}

Updated:
\begin{align}
  \mathbf{W}_{BA} &
  \Biggl(
    \hspace{0.5\xpB}
    \underbrace{
      \hspace{-0.5\xpB}
      \vertbar{x1B}{\mathbf{x}_1^B} \hspace{0.5em} \cdots \hspace{0.5em} \vertbar{x1B}{\mathbf{x}_1^B}
      \hspace{-0.5\xpB}
    }_k
    \hspace{0.5\xpB}
    \quad \cdots \quad
    \hspace{0.5\xpB}
    \underbrace{
      \hspace{-0.5\xpB}
      \vertbar{xpB}{\mathbf{x}_p^B} \hspace{0.5em} \cdots \hspace{0.5em} \vertbar{xpB}{\mathbf{x}_p^B}
      \hspace{-0.5\xpB}
    }_k
    \hspace{0.5\xpB}
  \Biggr) = \notag \\
  & \Biggl(
    \hspace{0.5\NxaB}
    \underbrace{
      \hspace{-0.5\NxaB}
      \vertbar{Nx1B}{\mathcal{N} \bigl( \mathbf{x}_1^B \bigr)_1} \hspace{0.5em} \cdots \hspace{0.5em} \vertbar{Nx1B}{\mathcal{N} \bigl( \mathbf{x}_1^B \bigr)_k}
      \hspace{-0.5\NxaB}
    }_k
    \hspace{0.5\NxaB}
    \quad \cdots \quad
    \hspace{0.5\NxpB}
    \underbrace{
      \hspace{-0.5\NxpB}
      \vertbar{NxpB}{\mathcal{N} \bigl( \mathbf{x}_p^B \bigr)_1} \hspace{0.5em} \cdots \hspace{0.5em} \vertbar{NxpB}{\mathcal{N} \bigl( \mathbf{x}_p^B \bigr)_k}
      \hspace{-0.5\NxpB}
    }_k
    \hspace{0.5\NxpB}
  \Biggr)
\end{align}

\end{document}


text:
Q: Pandas Melt with Multiple Value Vars I have a data set which is in wide format like this
   Index Country     Variable 2000 2001 2002 2003 2004 2005
   0     Argentina   var1     12   15   18    17  23   29
   1     Argentina   var2     1    3    2     5   7    5
   2     Brazil      var1     20   23   25   29   31   32
   3     Brazil      var2     0    1    2    2    3    3

I want to reshape my data to long so that year, var1, and var2 become new columns
  Index Country     year   var1 var2
  0     Argentina   2000   12   1
  1     Argentina   2001   15   3
  2     Argentina   2002   18   2
  ....
  6     Brazil      2000   20   0
  7     Brazil      2001   23   1

I got my code to work when I only had one variable by writing
df=(pd.melt(df,id_vars='Country',value_name='Var1', var_name='year'))

I cant figure out how to do this for a var1,var2, var3, etc.

A: Instead of melt, you can use a combination of stack and unstack:
(df.set_index(['Country', 'Variable'])
   .rename_axis(['Year'], axis=1)
   .stack()
   .unstack('Variable')
   .reset_index())

Variable    Country  Year  var1  var2
0         Argentina  2000    12     1
1         Argentina  2001    15     3
2         Argentina  2002    18     2
3         Argentina  2003    17     5
4         Argentina  2004    23     7
5         Argentina  2005    29     5
6            Brazil  2000    20     0
7            Brazil  2001    23     1
8            Brazil  2002    25     2
9            Brazil  2003    29     2
10           Brazil  2004    31     3
11           Brazil  2005    32     3

A: Option 1
Using melt then unstack for var1, var2, etc...
(df1.melt(id_vars=['Country','Variable'],var_name='Year')
    .set_index(['Country','Year','Variable'])
    .squeeze()
    .unstack()
    .reset_index())

Output:
Variable    Country  Year  var1  var2
0         Argentina  2000    12     1
1         Argentina  2001    15     3
2         Argentina  2002    18     2
3         Argentina  2003    17     5
4         Argentina  2004    23     7
5         Argentina  2005    29     5
6            Brazil  2000    20     0
7            Brazil  2001    23     1
8            Brazil  2002    25     2
9            Brazil  2003    29     2
10           Brazil  2004    31     3
11           Brazil  2005    32     3

Option 2
Using pivot then stack:
(df1.pivot(index='Country',columns='Variable')
   .stack(0)
   .rename_axis(['Country','Year'])
   .reset_index())

Output:
Variable    Country  Year  var1  var2
0         Argentina  2000    12     1
1         Argentina  2001    15     3
2         Argentina  2002    18     2
3         Argentina  2003    17     5
4         Argentina  2004    23     7
5         Argentina  2005    29     5
6            Brazil  2000    20     0
7            Brazil  2001    23     1
8            Brazil  2002    25     2
9            Brazil  2003    29     2
10           Brazil  2004    31     3
11           Brazil  2005    32     3

Option 3 (ayhan's solution)
Using set_index, stack, and unstack:
(df.set_index(['Country', 'Variable'])
   .rename_axis(['Year'], axis=1)
   .stack()
   .unstack('Variable')
   .reset_index())

Output:
Variable    Country  Year  var1  var2
0         Argentina  2000    12     1
1         Argentina  2001    15     3
2         Argentina  2002    18     2
3         Argentina  2003    17     5
4         Argentina  2004    23     7
5         Argentina  2005    29     5
6            Brazil  2000    20     0
7            Brazil  2001    23     1
8            Brazil  2002    25     2
9            Brazil  2003    29     2
10           Brazil  2004    31     3
11           Brazil  2005    32     3

A: numpy
years = df.drop(['Country', 'Variable'], 1)
y = years.values
m = y.shape[1]
c = df.Country.values
v = df.Variable.values

f0, u0 = pd.factorize(df.Country.values)
f1, u1 = pd.factorize(df.Variable.values)

w = np.empty((u1.size, u0.size, m), dtype=y.dtype)
w[f1, f0] = y

results = pd.DataFrame(dict(
        Country=u0.repeat(m),
        Year=np.tile(years.columns.values, u0.size),
    )).join(pd.DataFrame(w.reshape(-1, m * u1.size).T, columns=u1))

results

      Country  Year  var1  var2
0   Argentina  2000    12     1
1   Argentina  2001    15     3
2   Argentina  2002    18     2
3   Argentina  2003    17     5
4   Argentina  2004    23     7
5   Argentina  2005    29     5
6      Brazil  2000    20     0
7      Brazil  2001    23     1
8      Brazil  2002    25     2
9      Brazil  2003    29     2
10     Brazil  2004    31     3
11     Brazil  2005    32     3


text:
Q: Picking up high frequency in fast fourier transform and inverse fourier transforms Given a function f(t) and its second derivative, ddf(t)==g(t), I am interested in how their Fourier transforms relate. Mathematically speaking, noting F(w) and G(w) the transforms of f(t) and g(t) respectively, we should have
G(w) = -w^2F(w)
I wanted to investigate this numerically in Python and I am hitting the common roadblocks that I never completely understood in the Gibbs effect, and ringing effects when handling discrete fourier transforms. Below is the mwe python code snippet I was working with.
import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft, fftfreq, ifft
t=np.linspace(-5,5,100)
dt=t[1]-t[0]
w=fftfreq(len(t),dt)
a=3.0

#some sigmoid function
f=1/(1+np.exp(-a*t))
plt.plot(f)
Fw=fft(f) #its fourier transform

plt.plot(np.real(4*np.pi*np.pi*ifft(-Fw*w*w))) #The ifft/fft way of computing the     second derivative
plt.plot(np.gradient(np.gradient(f))/dt**2) #the finite difference way of computing     the second derivative

plt.ylim(-2,2)
plt.legend(['f(t)',r'ifft(fft(-$\omega^2$F[$\omega$]))]','ddf(t)'], fontsize=15)

This is the result of this code snippet
Computing the second derivative as the inverse transform of -F[w]*w^2 should in principle yield the second derivative of f(t). But I am picking up extremely large weights at either end of my time scale, and there is a high frequency ringing on top of my signal.
I am aware this might originate from rounding issues in frequency space or improperly binned frequencies, but I do not know how to correct these issues and do not fully understand them. The results do not depend on how fine-grained the time axis is.
Any help appreciated


text:
Q: How to pass command line arguments to a exported method of an c++ DLL? I am trying to pass the command line arguments from the client console app.CPP to DLL.
subscriber.DLL method was created in VS using code here
In my DLL I have a method based on ace tao
ACE_TMAIN(int argc, ACE_TCHAR **argv[])
{
 // user code
}

ACE_TMAIN is exported in a header file
in the command line, it uses the following command when running them as executables
command --> Subscriber -DCPSConfigFile dds_tcp_conf.ini
the last part is the transport configuration .ini file.
Subscriber is an exe in the above command. but now here it is used as a subscriber.DLL by exporting ACE_TMAIN with arguments.
So how to pass these command line with arguments to DLL from the client console application?


text:
Q: Need to use dd, but no /dev/sd* Using Beaglebone.
Need to run dd to backup an image and then restore it.
dd bs=64K if=/dev/sdX of=/dev/mmcblk1/myImage.img

But I don't see any sdX, where X is a number.
So, what should be the input file path for a full backup?

A: Run lsblk to see what disks/partitions you have. On the far right  you will see mountpoints, this info will help you with what partition/drive you are trying to make image of.
$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vda    253:0    0   10G  0 disk
└─vda1 253:1    0   10G  0 part /
vdb    253:16   0  366K  0 disk


text:
Q: File: file:/C:/Python/HDFS/program1/mapper.py is not readable I am getting below error while executing starting Hadoop job
File: file:/C:/Python/HDFS/program1/mapper.py is not readable.
Using below command
hadoop jar C:\hadoop\share\hadoop\tools\lib\hadoop-streaming-3.2.0.jar -file C:/Python/HDFS/program1/mapper.py -file C:/Python/HDFS/program1/reducer.py -mapper "python mapper.py" -reducer "python reducer.py" -input /sample/input_word.txt -output /sample/owc1.txt

Here is my mapper.py file content
import sys

for line in sys.stdin:
    line = line.strip()
    words = line.split()
    for word in words:
        print ("%s\t%s" % (word, 1))

And reducer.py content as below
import sys
import collections

counter = collections.Counter()

for line in sys.stdin:
    word, count = line.strip().split("\t", 1)

    counter[word] += int(count)

for x in counter.most_common(9999):
    print(x[0],"\t",x[1])

I am using the below environment:
Java Version : java version "1.8.0_291"
Hadoop Version: Hadoop 3.2.0
and Windows 10

A: Try to change the version of your hadoop by an oldest version, i had a version 3.2.4 and I've had the same error when I tried to execute the hadoop job command, until I change it by version 2.10.2 the problem was solved.


text:
Q: css 2 column left fixed-only-by-image-width, right col to take up rest of container width I think my title says it all.
I need a two column css div structure.  The left column, I'm going to place an image.  The image will have a variable width, and I want the right column to take up the rest of the container.  I have this, which doesn't really work, because the right column takes up only as much room as is required.  I want the right col to take up the whole of the right side of the div containing the image.
Your help is greatly appreciated.

        right content

        left content flexible width left content flexible width left content flexible width left content flexible width left content flexible width

With Respect

A: your base is the good technique , except that .left should be the one floatting and first in the flow.

DEMO

other techniques, if you do not want to switch div position in your HTML, would be

*

*display:table + direction DEMO
or

*

*display:flex; + order DEMO


text:
Q: Why doesn't resultSet next doesn't return any value from my oracle SQL database, even though initiating the same command inside sql developer works? I am trying to get a values from database so I can check them inside the while loop but the rsRoles.next() returns false even before anything happens.
This is my table:
Name                 Null?    Type
-------------------- -------- ----------
USER_ID_USER         NOT NULL NUMBER(38)
ROLE_ID_ROLE         NOT NULL NUMBER(38)

And this are its values:
USER_ID_USER | ROLE_ID_ROLE
-------------|-------------
3            |  1
3            |  2

I used this query inside oracle database:
SELECT user_id_user, role_id_role
FROM user_roles
WHERE user_id_user=3;

This statement returns the table above, which is correct. Although when I do this in my Java code:

Connection conn = database.getConnection();

String getRoles = "SELECT role_id_role, user_id_user\n"
                    + "FROM user_roles\n"
                    + "WHERE user_id_user=?";

            PreparedStatement prstm = conn.prepareStatement(getRoles);

            prstm.setInt(1, ManageUsersDialogController.getEditingUser().getAccountID());

            ResultSet rsRoles = prstm.executeQuery();

            while (rsRoles.next()) { // returns false

                int role = rsRoles.getInt("role_id_role");

                switch (role) {
                    case 1:
                        checkBoxAdmin.setSelected(true);
                        adminWasSelected = true;
                        break;
                    case 2:
                        checkBoxTeacher.setSelected(true);
                        teacherWasSelected = true;
                        break;
                    case 3:
                        checkBoxStudent.setSelected(true);
                        studentWasSelected = true;

                }

it never gets into the while cycle.
What could be the issue?

A: The reason this didn't work was because said table was busy. So I couldn't enter data via code and neither could I see data that I had in the database (because it was not committed even though it said it has been committed.
The solution that I came across was that once I gave up I suddenly got like 10 popup messages from IDE as well as database saying that connection has been stopped, so I guess timeout did its work.


text:
Q: Image outside the page size in altaCV based CV I'm a beginner in Latex and I'm using this template as base to go ahead and learn latex in the same process. I'm stuck on one point where my profile image is going outside the bounds of paper on right side. I've tried to search about AltaCV but the method in parent altaCV class isn't working in this customised template.
Preview of the problem:

The code in altaCV class is as follows:
\newcommand{\makecvheader}{%
  \begingroup
    \ifdef{\@photodiameter}{\begin{minipage}{\dimexpr\linewidth-\@photodiameter-2em}}{}%
    \raggedright\color{emphasis}%
    {\Huge\bfseries\MakeUppercase{\@name}\par}
    \medskip
    {\large\bfseries\color{accent}\@tagline\par}
    \medskip
    {\footnotesize\bfseries\@personalinfo\par}
    \ifdef{\@photodiameter}{%
    \end{minipage}\hfill%
    \begin{minipage}{\@photodiameter}
    \if@normalphoto
      \includegraphics[width=\linewidth]{\@photo}
    \else
      \tikz\path[fill overzoom image={\@photo}]circle[radius=0.5\linewidth];
    \fi%
    \end{minipage}\par}{}%
  \endgroup\medskip
}

I can't seem to find the piece of code which adjusts the position of image. If anyone can help me with this problem, it'd be great.
Thanks in advance.


text:
Q: Treating 'Don't know/Refused' levels of categorical variables I am modeling Diabetes Prediction using Logistic Regression. The dataset used is the  Behavioral Risk Factor Surveillance System (BRFSS) of the Center for Disease Control (CDC). One of the independent variables is High Blood Pressure. It is categorical with the following levels 'Yes', 'No', 'Don't know/Refused'. Should I remove those rows with 'Don't know/Refused' while building the model? What difference does it make to keep or remove those rows from the model?

A: I was just wondering about exactly the same question when analyzing the latest National Hospital Discharge Survey data.  Several variables have substantial missing values, such as marital status and type of procedure.  This issue came to my attention because these categories showed up with strong (and significant) effects in most logistic regression analyses I was running.
One is inclined to wonder why a missing code is given.  In the case of marital status, for instance, it is plausible that failure to provide this information could be linked to important factors such as socioeconomic status or type of disease.  In your case of high blood pressure, we should ask why would the value not be known or refused?  This could be related to practices at the institution (perhaps reflecting lax procedures) or even to the individuals (such as religious beliefs).  Those characteristics in turn could be associated with diabetes. Therefore, it seems prudent to continue as you have, rather than to code these values as missing (thereby excluding them from analysis altogether) or attempting to impute the values (which effectively masks the information they provide and could bias the results).  It's really not any more difficult to do: you merely have to make sure this variable is treated as categorical and you'll get one more coefficient in the regression output. Furthermore, I suspect the BRFSS datasets are large enough that you don't have to worry about power.

A: First you have to think over if the missing data are missing completely at random (MCAR), missing at random (MAR) or missing not at random (MNAR) as deletion (in other words complete-case analysis) may lead to biased results. Alternatives are inverse probability weighting, multiple imputation, the full-likelihood method and doubly-robust methods. Multiple imputation with chained equations (MICE) if often the easiest way to go.

A: Do you have any reason to think that study subjects with diabetes were more likely or less likely to end up with the DK/R response? If not (and I'd be pretty surprised to find out you did), including this predictor in the model w/o excluding these cases will result in noise. That is, you'll end up with less precision in your assessment of how "yes" vs. "no"  influences the estimated probability of diabetes (because you'll be trying to model the influence of either "yes" or "no" vs. random DK/R responses as opposed to just "yes" vs. "no"). The most straightforward option is to exclude the cases with DK/R responses. Assuming that their "yes/no" responses were indeed missing at random, excluding them will not bias your estimate of the influence of "yes" vs. "no." That approach, however, will reduce your sample size and thus reduce statistical power with regard to the remaining predictors. If you have a lot of DK/R on this variable, you might want to impute "yes"/"no" responses by multiple imputation (arguably the most, maybe only, defensible missing-value imputation strategy).


text:
Q: Adapter Edit text get String value on another activity I have one scenario like i want open layout from number of adult passenger coming from previous activity. On current Activity i have open list of number passenger details like name,dob  in edit text in adapter using custom adapter. i want to get String value of name, dob on another activity using intent or share preference. Thanks In advance.

A: Welcome to StackOverflow.
I assume you have RecyclerView and RecyclerViewAdapter class already created, and inside the list of RecyclerView, you want to get any kind of data passed from the list into your next opened activity, right? to do that, inside your adapter view holder class, you could try this:

public class Holder extends RecyclerView.ViewHolder {
  TextView textObject;
  public Holder(View itemView) {
    super(itemView);
    itemView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        Intent intent = new Intent(itemView.getContext(), YourActivity.class);
        Bundle bundle = new Bundle();

        bundle.putString("string_id", textObject.getText().toString().trim());

        intent.putExtras(bundle);
        itemView.getContext().startActivity(intent);

      }
    });
    ...
  }
}

And in your destination activity, let's call it YourActivity.class, you can add this code to get extras by adding this code:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_krs_detail);

  TextView output;

  Bundle bundle = getIntent().getExtras();
  output.setText(bundle.getString("string_id"));

  ...

}

Correct me if I'm wrong but I didn't understand your question correctly, anyway, I hope this helps.
Cheers.


text:
Q: what is fastest way to draw chartjs charts I have a lot of charts I need to draw with a huge amount of data on bobble plots.
I wonder what is the fastest and the most efficient way to plot them using chartjs.
I made the dots smaller, yet it still takes 5 sec to load the page.

A: A couple things come to mind:

*

*I would check that nothing else on your page is slowing your load times.

*If chart.js is the issue due to the high number of dots, do you need every data point entered? Could you do every other? I'm not sure what your data is, but if you're just looking at trends, this might work for you.


text:
Q: Ordering ordinals by size
Well define $\omega,\omega_1, \omega_2$ to be the first three infinite ordinals. Order them according to their size:

*

*$2\cdot\omega_1+\omega\cdot3+3,$

*$\omega\cdot3+\omega_1+3,$

*$\omega_1^{\omega_2}+\omega_2+\omega_1,$

*$\omega_1\cdot \omega_2 $

I think 3 is the biggest, 4 is equal to $\omega_2$ so that's second largest, third largest is probably 1 because the there are two limit ordinals in succession.
How do you treat the ordinal in the exponent ?

A: The answer to this question depends quite heavily on the answer to the following two questions:

*

*Are we are dealing with ordinal or cardinal arithmetic?

*Is "size" intended to mean cardinality, or order type?

Ordinal and cardinal arithmetic agree on finite ordinals, but otherwise may differ greatly. As for the second question, there are (for example) uncountably many ordinals having the same cardinality as $\omega.$
Let's see how the answers will differ in each case. I will denote cardinal addition, multiplication, and exponentiation by $\alpha\oplus\beta,\alpha\odot\beta,$ and ${}^\beta\alpha,$ respectively, to distinguish from the standard notation (which I will use for ordinal arithmetic).
It's worth noting that cardinal arithmetic makes things simpler in some ways and more frustrating in others. In particular, given non-$0$ initial ordinals (that is, natural numbers or ordinals $\omega_\alpha$) $\beta,\gamma,$ if at least one of $\beta,\gamma$ is infinite, then $\beta\oplus\gamma=\beta\odot\gamma=\max\{\beta,\gamma\}.$ That's fairly nice. However, without the Axiom of Choice, it turns out that cardinal exponentiation fails to be an operation on the initial ordinals--that is, for sufficiently large initial ordinals $\gamma$, we have that ${}^\gamma\beta$ fails to be an ordinal whenever $\beta$ is an initial ordinal with $2\le\beta\le\gamma.$ Let's put such concerns aside, though, and simply note that if $\gamma$ is an infinite initial ordinal, and $\beta$ is an initial ordinal with $2\le\beta\le\gamma,$ then ${}^\gamma\beta={}^\gamma2,$ whatever that may mean.
It's also worth noting that ordinal arithmetic on initial ordinals has certain properties known as indecomposability properties. In particular:

*

*If $\beta=1$ or $\beta$ is an infinite initial ordinal, then for all ordinals $\alpha<\beta,$ we have $\alpha+\beta=\beta.$ (Ordinals $\beta$ with this property are known as additively indecomposable.)

*If $\beta=1,$ $\beta=2,$ or $\beta$ is an infinite initial ordinal, then for all ordinals $0<\alpha<\beta,$ we have $\alpha\cdot\beta=\beta.$ (Ordinals $\beta$ with this property are known as multiplicatively indecomposable.)

*If $\beta=2$ or $\beta$ is an infinite initial ordinal, then for all ordinals $1<\alpha<\beta,$ we have $\alpha^\beta=\beta.$ (Ordinals $\beta$ with this property are known as exponentially indecomposable.)

There are other ordinals with these indecomposability properties (such as the ordinals called epsilon numbers), but we're only concerned with the initial ordinals, here.
Now, let's get down to business.

Using cardinal arithmetic is simple enough: $$2\odot\omega_1\oplus\omega\odot 3\oplus 3=\omega_1\oplus\omega\oplus 3=\max\{\omega_1,\omega,3\}=\omega_1\\\omega\odot 3\oplus\omega_1\oplus 3=\omega\oplus\omega_1\oplus 3=\max\{\omega,\omega_1,3\}=\omega_1\\{}^{\omega_2}\omega_1\oplus\omega_2\oplus\omega_1={}^{\omega_2}2\oplus\omega_2\oplus\omega_1=\max\left\{{}^{\omega_2}2,\omega_2,\omega_1\right\}={}^{\omega_2}2\\\omega_1\odot\omega_2=\max\{\omega_1,\omega_2\}=\omega_2$$
Hence, in terms of cardinality, the third is the largest, followed by the fourth, followed by the first two. Without sufficient Choice, though, the third need not be an initial ordinal at all, and so sorting them that way may no longer make sense. With sufficient choice, the sorting in terms of order type will be the same as that in terms of cardinality.
The ordinal arithmetic is a bit less simple until indecomposability properties (and left-distributivity) are observed: $$2\cdot\omega_1+\omega\cdot 3+3=\omega_1+\omega\cdot 3+3\\\omega\cdot 3+\omega_1+3=\omega\cdot 3+\omega\cdot\omega_1+3=\omega\cdot(3+\omega_1)+3=\omega\cdot\omega_1+3=\omega_1+3\\\omega_1^{\omega_2}+\omega_2+\omega_1=\omega_2+\omega_2+\omega_1=\omega_2\cdot 2+\omega_1\\\omega_1\cdot\omega_2=\omega_2$$ Here, the third and fourth have the same cardinality, which is greater than the (shared) cardinality of the first and second. In terms of order type, from greatest to least, it goes: third, fourth, first, second.

My suspicion is that it is supposed to be ordinal arithmetic and that "size" is intended to mean order type, but I can't say for sure. If I used any results that are unfamiliar to you, it would be a good exercise to try to prove them. Please feel free to ask for clarification if you need it.


text:
Q: Entering textfield values into an URL So I'm in the progress of developing an app but I'm kinda stuck at the moment. I have 2 textfields right now that the user will have to enter:
Ordernr:xxxxxxxx
Referencenr:xxxxxxx

these 2 values have to be added to this link:
http://www.artis-web.de/cgi-bin/WebObjects/Artis.woa/wa/detailedTrack?referencenr=xxxxxxxx&ordernr=xxxxxxxxxx
now I want safari to open this link. The ideal situation would be the user entering the 2 textfields values and then pressing a button called "open in safari"
What would be the best way to implement this?

A: Just add the following code to your button action:
NSString *urlString = [NSString stringWithFormat:@"http://www.artis-web.de/cgi-bin/WebObjects/Artis.woa/wa/detailedTrack?referencenr=%@&ordernr=%@", referenceNrTextField.text, orderNrTextField.text];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: urlString]];

A: To create the URL you can use...
NSURL *url = [NSURL urlWithString:[NSString stringWithFormat:@"http://www.artis-web.de/cgi-bin/WebObjects/Artis.woa/wa/detailedTrack?referencenr=%@&ordernr=%@", referenceTextField.text, ordernoTextField.text]];

To open in safari...
[[UIApplication sharedApplication] openURL:url];

A: Check whether the both fields have data and then hit the url with the given data.This condition would be sufficient.
 if (Ordernr.text.length!=0 && Referencenr.text.length!=0)
   {
      NSLog(@"Hit the Url with the entered data");
   }
   else
   {
    NSLog (@"Show Error Alert Message");
   }


text:
Q: how to access android emulator and SDK manager without using any IDE I want to create a website in php as like as developer.samsung.com. In this User will download any of the emulator given in the list, and try their apps with that device before downloading or paying for that application.
You may please check this link:
http://developer.samsung.com/remotetestlab/rtlDeviceList.action
Is it possible that i use android sdk to run the virtual device without using any IDE.
Thanks in advance.

A: You can start the sdk and avd managers directly from the android-SDK directory. You do not need an IDE to work with them.
After you start an emulator you can connecto to it through adb.
Take a look here and here.
In theory you can achieve what you need to do but efficiency is another matter of discussion...


text:
Q: Could you anybody see my code & say any alternative for %s in integer? How %s is work for int ??
   package loops;

    public class Checking {
    public static void main(String[] args) {
        String formatter = "hello";
        int formatter1 = 2;
        System.out.printf("%s friend %n",formatter);
        System.out.printf("%s cup of coffee please",formatter1);
        /* problem is
        %s stands for string
        How %s is work for integer in formatter 1 (System.out.printf("%s cup of coffee please",formatter1);
        "i am beginner in java,
        */
    }
    }

Output is correct
But I want to know is there alternative for integer?

A: The symbol for integral numbers is %d (see documentation). And %s works for int by simply calling Integer.toString.
From the Doc:
's', 'S'  IfargimplementsFormattable, thenarg.formatTois invoked. Otherwise, the result is obtained by invokingarg.toString().
So, when you pass an int is is autoboxed to Integer and on that Integer the method .toString is called, so your int becomes a String.
In general I recommend to read the manual, especially if you are a novice programmer. A lot of wisdom from the authors is distilled into the docs.


text:
Q: how change value sequelize migration? How to change values in columns using only sequelize migration without clean requests? upsert or other?
Sequelize CLI [Node: 8.11.3, CLI: 4.0.0, ORM: 5.0.0-beta.5]
Loaded configuration file "config/database.json".
   Using environment "development".
   == 2018061713010-changeColumn: migrating =======
ERROR: Cannot read property 'uniqueKeys' of undefined
what it is error?
'use strict';

 module.exports = {
   up: (queryInterface, Sequelize) => {
    queryInterface.upsert(
      'table',
      {
        style: 2,
      },
      {
        style: 2,
      },
      {}, //model
      {} // options
    );
  },

  down: (queryInterface, Sequelize) => {

  },
};

enter image description here
database image

A: It seems I came up with a solution:
'use strict';
 const sequelize = require('..yourpath').sequelize;
 module.exports = {
   up: (queryInterface, Sequelize) => {
    queryInterface.upsert(
      'table',
      {
        style: 2,
      },
      {
        style: 2,
      },
      sequelize.define('your Model', {
      id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
      {} // options
    );
  },

You have to create either a temporary Model or you can just use your shortcut then instead wherever you store your models. Hope this helps! Worked for me.

A: I also was struggling with the same problem.
It's the same approach you have used.
In case someone comes across this, here's the code I used.
const tableName = 'some_config_table';

module.exports = {
  up: (queryInterface, Sequelize) => {
    const { sequelize } = queryInterface;

    const model = sequelize.define(tableName, {
      key: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
      },
      value: Sequelize.STRING,
      createdAt: Sequelize.DATE,
      updatedAt: Sequelize.DATE,
    });

    return queryInterface.upsert(
      tableName,
      {
        key: 'my_config_key',
        value: 1,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        value: 1,
      },
      {
        key: 'my_config_key',
      },
      model,
      {},
    );
  },

  down: (queryInterface, Sequelize) => {
    const { sequelize } = queryInterface;

    const model = sequelize.define(tableName, {
      key: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
      },
      value: Sequelize.STRING,
      createdAt: Sequelize.DATE,
      updatedAt: Sequelize.DATE,
    });

    return queryInterface.upsert(
      tableName,
      {
        key: 'my_config_key',
        value: 10,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        value: 10,
      },
      {
        key: 'my_config_key',
      },
      model,
      {},
    );
  },
};


text:
Q: Copy Azure Sql Database to another server I have a SQL database hosted on Azure by using SQL Server 2014. Now, I want to make a complete copy which will run again on Azure but this time by using SQL Server 2016. I tried to script the database an create it again by executing the query on the 2016's one, but there is a problem. On the old database I have some security implemented (3-4 security certificates and the same number of encrypted columns). When I script the database, somehow these things are not included in the query, so I have to do them manually (not that this is a problem, but imagine a db where the security is not so simple). Broadly speaking, my question is how to make a full copy of the database and implement it on another (already created) azure db.

A: There are several ways to copy a database:

*

*Using the Copy Database Wizard

You can use the Copy Database Wizard to copy or move databases between servers or to upgrade a SQL Server database to a later version. For more information, see Use the Copy Database Wizard.

*Restoring a database backup

To copy an entire database, you can use the BACKUP and RESTORE Transact-SQL statements. Typically, restoring a full backup of a database is used to copy the database from one computer to another for a variety of reasons. For information on using backup and restore to copy a database, see Copy Databases with Backup and Restore.

*Using the Generate Scripts Wizard to publish databases

You can use the Generate Scripts Wizard to transfer a database from a local computer to a Web hosting provider. For more information, see Generate and Publish Scripts Wizard.

A: Taking a backup of the database and restoring it sounds like the best bet here (as Steve Newton was mentioning). I'm understanding from your question that you'd like to have a new copy of the same database on SQL Server 2016.
As long as the relevant certificates and symmetric keys used to encrypt these columns are stored in the database, the backup will include them and restore them to your target instance.
If the certs and keys are on physical master, you'll need to back them up separately and restore them on the new instance.


text:
Q: Java applet authenticity issue I implemented an applet in java to authenticate users at my website by the usage of MIFARE cards and everything is working good. However I am concerned about the applet's authenticity, in other words, how can I guarantee that is my applet who is communicating with my website ? and is not a script-kiddie that made an applet that simulates my applets behaviours in order to hack into my website.
I am having some difficulties to imagine a way to guarantee my applet authenticity to my website since this applet is developed in Java and code reverse engineering is possible.
best regards,


text:
Q: I want to make the button text unchanged once it has been changed on a click I was working on my project in which i have grid view of which there is a status field which has button in it .
When user clicks on that button the text of that button gets changed from pending to confirm .
The problem is that when I close the browser and load the .aspx page again through visual studio the text of the button again gets set to pending which i does not want.
Can any one tell me how to keep the button text to confirm only once the button get clicked and also when I click on first row status field button all the rest  status field gets updated with confirm status in database.
Here is my code: (Front End Code)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
    Font-Bold="True" Font-Size="Small" GridLines="None">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
        <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
        <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
        <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
        <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
        <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
        <asp:TemplateField HeaderText="Status Field">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
                    Text="Pending" BorderStyle="None" Font-Bold="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

(Back end Code):
 protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<string> lst = new List<string>() { "asd", "xxx" };
        GridView1.DataSource = lst;
        this.BindGrid();
    }

}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
    Response.Redirect("~/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
    Session.Abandon();
    Session.Clear();
    Response.Redirect("~/Admin Panel/LoginForm.aspx");

}
private void BindGrid()
{

    using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT packagename,name, gender,mobileno,email,noofdays,child,adults FROM enquiry"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName == "MYCOMMAND")
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True");
        string sql;
        Button Button1 = (Button)e.CommandSource;
        if (Button1 != null)
            Button1.Text = "Confirm";
        sql = "update enquiry set statusfield='" + Button1.Text + "'";

        SqlCommand comm = new SqlCommand(sql, con);

        con.Open();
        comm.ExecuteNonQuery();

    }
}

A: You can use the Bind function from asp.net so your button text will be taken from DB result. like below.
In aspx page
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
    Font-Bold="True" Font-Size="Small" GridLines="None">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="enquiryid" HeaderText="Enquiryid" />
        <asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
        <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
        <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
        <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
        <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
        <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
        <asp:TemplateField HeaderText="Status Field">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
                    Text='<%# Bind("statusfield")%>' BorderStyle="None" Font-Bold="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In .cs file modify your BindGrid method, so that it can return the statusfield column.
 private void BindGrid()
{

   using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
    {

    using (SqlCommand cmd = new SqlCommand("SELECT enquiryid,packagename,name, gender,mobileno,email,noofdays,child,adults,statusfield FROM enquiry"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}


text:
Q: SIP js UserAgent API, I don't kown how to establish relationship with dom element, version 0.15x I don't kown how to establish relationship with dom element, version 0.15x,
in 0.06x version it's options.media.render ,but what's it in 0.15x
<div class="chat-sip">
  <video id="remoteVideo"></video>
  <video id="localVideo" muted="muted"></video>
  <button (click)="push()">push</button>
  <button id="endCall">End Call</button>
</div>

var userAgent = new UA();
var session = userAgent.invite("example@onsip.com");

resolved see this Attach Media


text:
Q: Prove that if X and Y are random variables (possibly on two different probability spaces) and $\tilde{X}= \tilde{Y}$, then $P_{X} = P_{Y}$ Prove that if X and Y are random variables (possibly on two different probability spaces) and $\tilde{X}= \tilde{Y}$, then $P_{X} = P_{Y}$ where $P_{X}= P(X \in B) = P(X^{-1}(B))$ is the probability distribution and $\tilde{X}: \mathbb{R} \to [0,1] $ defined by $\tilde{X}(s)= P_{X}((-\infty,s]) = P(X \leq s) $ is the distribution function.
I'm not sure exactly what has to be done here or what I may be missing?
If $\tilde{X}(s) = \tilde{Y}(s)$ and $\tilde{X}(s) = P_{X}((-\infty,s])$, $\tilde{Y}(s) = P_{Y}((-\infty,s])$, then  $P_{X}((-\infty,s]) = P_{Y}((-\infty,s])$ for all $s \in \mathbb{R}$. Since sets of the form $(-\infty,s]$ generate the Borel $\sigma$-algebra we get $P_{X} = P_{Y}$.

A: This is an immediate consequence of Dynkin's $\pi - \lambda$ theorem. See https://en.wikipedia.org/wiki/Dynkin_system


text:
Q: xamarin(Android) view equivalent to windows forms panel I am trying to create an app where the user clicks somewhere on the screen and a text field will be created on the point of the click.
If I were to make a windows forms application, I would use the panel control but I struggle to find something similar in Xamarin Android.
Keep in mind that I am using a scrollView.
Is there a xamarin view for Android that works similarly to the windows forms panel or something that will get the job done as well?
Thanks in advance!

A: Here is how I solved it. As W00ly suggested, I used a RelativeLayout as the clickable view. What is good about the RelativeLayout is that you can add views to it in an absolute position, which you cannot do with the view alone.
I started by modifying the Main.axml layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include
        android:id="@+id/toolbar"
        layout="@layout/mainToolBar" />
    <include
        android:id="@+id/overflow"
        layout="@layout/overflowToolBar" />
    <ScrollView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar"
        android:id="@+id/svwMain">
        <RelativeLayout
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="3000px"
            android:id="@+id/relMain"
            android:clickable="true" />
    </ScrollView>
</RelativeLayout>

Please ignore the toolbars.
The clickable property is very important.
In order to track clicks in Android language, you need three things.
In the mainActivity file, I placed a reference to the RelativeLayout and called
its SetOnTouchListener() method.
relMain = FindViewById<RelativeLayout>(Resource.Id.relMain);
relMain.SetOnTouchListener(this);

For this to work, your mainActivity has to derive from and extend View.IOnTouchListener:
public class MainActivity : Activity, View.IOnTouchListener

Finally, you need to add the OnTouch() method to track clicks on any views that have called the SetOnTouchListener() method:
public bool OnTouch(View v, MotionEvent e)
{
    bool doubleClick = false;
    switch (e.Action)
    {
        case MotionEventActions.Down:
            saveClickPosition[0] = clickPosition[0];
            saveClickPosition[1] = clickPosition[1];
            clickPosition[0] = e.GetX();
            clickPosition[1] = e.GetY();
            doubleClick = toggleClick(clickPosition[0], clickPosition[1], saveClickPosition[0], saveClickPosition[1]);
            break;
    }
    if (v.GetType() == typeof(TextView) && doubleClick)
    {
        relMain.RemoveView(v);
        return true;
    }
    switch (v.Id)
    {
        case Resource.Id.relMain:
            if (doubleClick)
            {
                relParams = new RelativeLayout.LayoutParams(300, 140);
                relParams.LeftMargin = (int)clickPosition[0];
                relParams.TopMargin = (int)clickPosition[1];
                var tvwTest = new TextView(relMain.Context);
                tvwTest.Text = string.Format("x: {0} y: {1}", clickPosition[0], clickPosition[1]);
                tvwTest.SetOnTouchListener(this);
                relMain.AddView(tvwTest, relParams);
            }
            break;
    }
    return true;
}

My OnTouch() method does a lot more than it needs to to fulfill what my application needs to do. I still leave the full method here, as some of the things I do may be helpful to others.
Please keep in mind that my method is messy. I am still testing things using it.
Here is a short video showing it all working:
Video


text:
Q: PHP: Get value from string with preg_match, limited characters Sorry for the title, I don't know how to explain it better.
I must get 354607  from the following string:

...jLHoiAAD1037354607Ij0Ij1Ij2...

The "354607" is dynamic, but it has the "1037" in any case before, and is in any case exactly 6 characters long.
The problem is, the string is about 50.000 up to 1.000.000 characters long. So I want a resource-friendly solution.
I tried it with:
preg_match_all("/1037(.*?){0,5}/", $new, $search1037);

and:
preg_match_all("/1037(.*?{0,5})/", $new, $search1037);

but, I don't know how to use regular expressions correctly.
I hope someone could help me!
Thank's a lot!

A: Use, \d{6} represents 6 numbers
preg_match_all("/1037(\d{6})/", $new, $search1037);

returns an array with
array(
    0   =>  array(
        0   =>  1037354607
    ),
    1   =>  array(
        0   =>  354607
    )
)

Check this demo

A: Since you're concerned with finding a resource-friendly solution, you may be better off not using preg_match. Regular expressions tend to require more overhead in general, as discussed in this SO question.
Instead, you could use strstr():
$string = strstr($string,'1037');

Which will return the first instance of '1037' in $string, along with everything following it. Then, use substr():
$string = substr($string,4,6);

Which returns the substring within $string starting at position 4 (where position 0 = 1, position 1 = 0, position 2 = 3, position 3 = 7, position 4 = beginning of 6 digits) and including 6 characters.
For fun, in one line:
$string = substr(strstr($string,'1037'),4,6);


text:
Q: Are there attributes that affect how the CLR optimizes during a JIT compile? As the question says, I am curious if any of you know about attributes that affect how the CLR will compile/optimize the bytecode. Is there an attribute that will affect code inlining decisions? Unroll loops?
Are there undocumented attributes on classes generated for anonymous types/delegates?
There's probably attributes to disable optimizations for debug purposes, but somehow I am not so interested in those.

A: Only one I've used in debugging something:
[MethodImpl(MethodImplOptions.NoInlining)]

This prevents JIT from inlining a method. There's also a:
[MethodImpl(MethodImplOptions.NoOptimization)]

Which just prevents JIT from optimizing anything, in case you found a rare bug in code generation that's actually causing the issue.


text:
Q: Unable to close modal dialog I'm trying to call a screen as a popup. The screen type is set to Modal dialog box and I'm able to call the screen, but unable to close it. Nothing happens when I click on the little cross. The next screen is set to 0.
The screen I'm calling as a popup, doesn't contain any buttons, not any hard coded ones anyway. Any ideas what I'm doing wrong?
I'd also like the screen it returns to, to be refreshed (so it loads the PBO again). How do I do that?
Here is the code:
MODULE werkende_knoppen_subscreen INPUT.
  CASE ok_code.
    WHEN 'X'.
      LEAVE TO SCREEN 0.
  ENDCASE.
ENDMODULE.

A: You should be checking for the 'EXIT' (or, in your case for the custom close button, 'X') user command in the PAI part of your popup.
For example:
MODULE user_command_0010 INPUT.
  ok = sy-ucomm.
  CLEAR sy-ucomm.
  CASE ok.
    WHEN 'EXIT' OR 'X'.
      LEAVE TO SCREEN 0.
  ENDCASE.
ENDMODULE.

A: This is a non-documented feature but in a modal dialog box (popup), the top-right button to close the popup is assigned the F12 key, so you must assign this key to a function code and process it as any other function code.
Step-by-step procedure:
1) Create the ABAP program (transaction code SE38 or SE80)
REPORT.

CALL SCREEN 100 STARTING AT 10 10 ENDING AT 60 20.

MODULE status_0100 OUTPUT. " <=== called "before output"
  SET PF-STATUS '0100'.    " <=== choose the GUI status
ENDMODULE.

MODULE user_command_0100 INPUT. " <=== called "after input" (after user action)
  IF sy-ucomm = 'CANCEL'.       " <=== the function code you chose in your GUI status
    SET SCREEN 0.               " <=== 0 is a special number which ends "CALL SCREEN"
  ENDIF.
ENDMODULE.

Note: SET SCREEN 0 is to close the dialog box (0 means "the current dynpro sequence is ended") ; if you have a complex screen you may also use LEAVE TO SCREEN (which is equivalent to the 2 statements SET SCREEN + LEAVE SCREEN).
2) Create the screen 0100 (transaction code SE51 or double-click 0100 behind CALL SCREEN)
Screen type: modal dialog box
Flow logic:
PROCESS BEFORE OUTPUT.
  MODULE status_0100.

PROCESS AFTER INPUT.
  MODULE user_command_0100.

3) Create the GUI status 0100 (transaction code SE41 or double-click 0100 behind SET PF-STATUS)
Status type: dialog box
Assign the F12 key to an arbitrary function code (I chose the name CANCEL), and activate this function code (button "Function Code"):

4) Test
Run the program, you may now click the top-right button (or press F12 if you prefer) which closes the modal dialog box:


text:
Q: How to execute exe using python and pass parameter as per the output received from the console So far I am able to pass one integer variable after executing an exe. But based on first input passed we have to pass another parameter. Can someone please suggest how to pass the 2nd parameter and so on?
import os, subprocess

executable=("xyz.exe")
p = subprocess.Popen(executable, shell=True, stdin = subprocess.PIPE)
p.communicate(b'4')

A: Let's make an example. Your exe is a c program like:
// test.c
#include <stdio.h>

int main() {
  int a;
  char path[256];

  scanf("%d", &a);
  scanf("%s", path);

  FILE *f;
  if (f = fopen(path, "w")) {
    fprintf(f, "%d, %s\n", a, path);
    fclose(f);
  }
  return 0;
}

from your python you can invoke it like that:
# test.py
from subprocess import Popen, PIPE

exe = ("./test")
with Popen(exe, shell=True, stdin=PIPE) as proc:
    proc.communicate(b'4\n/tmp/test.txt')

to get as result in /tmp/test.txt: 4, /tmp/test.txt\n.


text:
Q: Empty constructor but instance variable still initialized? I am new to java and I have a doubt about object initialization.
What I currently know:
Constructors are used to initialize the instance variables and if we don't explicitly code the constructor, default constructor is provided that automatically provides the default values to the instance variables like 0 for int, etc.
My Question:
How did the following code work(I didn't initialized the instance variable)?
I tried a basic code as follows:
public class hello{

int i;   //Instance variable
         public hello()
         {
         //Constructor is empty!!!
        }

public static void main(String args[])
    {

  System.out.println(new hello().i);

}
}

And the result was 0, but how? I didn't did anything in the constructor and since I explicitly coded the constructor the default constructor shouldn't be invoked(I know I am having a wrong concept in my mind, so please correct me).
How did the above code worked, please clear my doubt.
Thank You!

A: The default constructor does not initialize anything. It is empty. Field level variables are automatically initialized to some default values (like 0 for int types) regardless of constructor.
Other default values are
boolean -> false
double -> 0.0D
[any object reference incl. String] -> null

A: You might be confusing instance variables and local variables. Local variables are the ones that must be initialized before use, otherwise you get a compile error. int i in this case is an instance variable, which can be left uninitialized without causing the compiler to complain. int instance variables are 0 by default.

A: If you provide no explicit initialization to instance variables, they will be awarded predictable default initial values, which are based only on the type of the variable.
Here are the default value of all types:
Type                          Default Value
boolean                          false
byte                            (byte) 0
short                           (short) 0
int                                 0
long                                0L
char                             \u0000
float                              0.0f
double                             0.0d
object reference                   null

Even though You have explicitly created default constructor with empty code in it
In your code when below line will get executed
System.out.println(new hello().i);

If you don't explicitly initialize an instance variable in your constructor, that variable will retain its default initial value when new returns its object reference.At that point of time, Your instance variable is set to its default value by JVM.
And also whenever object needs to be created, JVM will call Instance Initializer Block[IIB] before calling default constructor.
Thanks


text:
Q: 'Invalid value for 'x_range' Bokeh Gmap error The code below is giving me the following error:
ValueError: Invalid value for 'x_range', MapPlot ranges may only be Range1d, not data ranges

I'm almost certain there's nothing wrong with the code considering I had it working with no errors up until today.
I don't think this is relevant, but it stopped working after I ran the following in my command terminal:
sudo lsof -t -i tcp:5000 -s tcp:listen | sudo xargs kill

I restarted my computer several times (in hopes of reseting the ports) but that hasn't worked either.
My code is below:
from bokeh.models import (
   GMapPlot, GMapOptions, ColumnDataSource, Circle, DataRange1d, PanTool,
   WheelZoomTool, BoxSelectTool
)
from bokeh.io import output_file, show, output_notebook

output_notebook()

map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)

plot = GMapPlot(
x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options
)

plot.title.text = "Austin"

plot.api_key = "INSERT PERSONAL GOOGLE API KEY"

completed_lats = [30.265872,30.2900002]

completed_longs = [-97.749270,-97.733322]

completed_source = ColumnDataSource( data=dict(
    lat=completed_lats,
    lon=completed_longs,))

completed_dots = Circle(x="lon", y="lat", size=50, fill_color="blue",
                        fill_alpha=0.1, line_color=None)
plot.add_glyph(completed_source, completed_dots)

plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())

show(plot)

A: There is in fact a problem with the code, it is this:
plot = GMapPlot(

    x_range=DataRange1d(), y_range=DataRange1d(), # BAD

    map_options=map_options
)

Exactly as the message states, only Range1d can be used with GMapPlot. This is because unlike regular Bokeh plots, Google Maps maintains complete control of the plot's axes dimensions. This is inconsistent with using a DataRange1d, because those also try to control the axes dimensions, which can lead to unpredictable and undesirable results.
There was a time before Bokeh checked for this, and would allow DataRange1d to be passed. Once it was discovered that combination was causing problems, a check was added to explicitly disallow it. You just need to use a Range1d instead (you don't need to set start or end):
plot = GMapPlot(

    x_range=Range1d(), y_range=Range1d(), # GOOD

    map_options=map_options
)

However, I should also point you to the gmap function, which makes creating Google Maps plots much simpler. With that it is much like figure in that a reasonable default plot is created automatically, no need to create and add ranges at all. It was announced in version 0.12.5.


text:
Q: Roaming settings not working in the outlook App I am using the roaming setting in my outlook add-in to store the oAuth and other information of my app. The add-in is working fine in the outlook browser but it is not working in the outlook app. can anybody suggest if I am doing anything wrong

A: There are two universal steps I start from:

*

*Try clearing the Office cache on your computer. See For Windows.

*Debug your add-in with runtime logging
You can read more about possible cases in the Troubleshoot development errors with Office Add-ins article.


text:
Q: Detect a user change of a  list created with Jquery ".html()" Is there a way to detect when the value of a select list is changed, when this select list have been added with the .html(htmlString) or .append(content[,content]) jQuery function?
HTML CODE:

JAVASCRIPT CODE:
var MyDropDownMenu= "";
MyDropDownMenu += '<select class="field">';
MyDropDownMenu += '<option value="1">Option 1</option>';
MyDropDownMenu += '<option value="2">Option 2</option>';
MyDropDownMenu += '</select>';
$('ul.htmlClass').html(MyDropDownMenu);

$(".field").change( function() {   //Doesn't work!!!
      alert("test1");
});

$(".htmlClass").change( function() {  //work
      alert("test2");
});

A: You need to use event delegation
$('ul.htmlClass').on('change',".field", function() {
      alert("test1");
});

*

*http://learn.jquery.com/events/event-delegation/

A: Use delegated event handlers
$('ul.htmlClass').on('change','.field', function() {
  alert("test1");
});

See Direct and delegated events for more information.
Another problem in your code is that you're adding your select directly to the ul element. This is not correct.
I see two options
1) wrap select with a li tag
var MyDropDownMenu= "
";
myDropDownMenu += '<select class="field">';
MyDropDownMenu += '<option value="1">Option 1</option>';
MyDropDownMenu += '<option value="2">Option 2</option>';
MyDropDownMenu += '</select>';
MyDropDownMenu += '
';

2) Convert your ul to a div if you don't require a list


text:
Q: ng-show stops working within success callback function If I keep my ng-show outside of a function, then it does the task perfectly but if I keep it inside a success function of an HTTP post method, it doesn't do anything.
I would like to trigger my ng-show right after the post method is successful, but can't get through.
my Angular code:
angular.module('plunker', []).controller('MainCtrl', function($scope,

$http) {
  $scope.data = {
    div1: false,
    div2: false
  };

  $scope.showText = function() {
    $http({
      method: 'post',
      url: '/'
    }).success(
      function(response) {
        $scope.data.div1 = true;
      },
      function(response) {
        var fail_status = response.status;
        console.log('test ' + fail_status);
      }
    );
  };
});

my HTML code:
<!DOCTYPE html>

    <link rel="stylesheet" href="lib/style.css" />

div 1

div 2

      <input type="button" ng-click="showText();" value="click me" />


text:
Q: Sum of the norm of polynomials Let $\bar D$ denote the closed unit disc in the complex plane.
Consider the function $f:\bar D\longrightarrow \mathbb{C}$, defined as $f(z)=z$ for all $z\in \bar D$.
Let $n\in \mathbb{N}$. For $1\leq i\leq n$, let $p_i:\bar D\longrightarrow \mathbb{C}$ be monic complex polynomials on $\bar{D}$, such that $p_i$'s have no roots in $\bar{D}$ and $c_i\in\mathbb{C}$ such that $$f=\sum_{i=1}^{n}c_ip_i.$$ Can we say that for any such representation of $f$, the value $$K=|c_1|\|p_1\|_\infty+|c_2|\|p_2\|_\infty+\cdot+|c_n|\|p_n\|_\infty\geq 2?$$
$\|.\|_\infty$ denotes the uniform norm, defined as $\|p\|_\infty=sup\{|p(t)|: t\in \bar D\}$ for any complex polynomial $p$ on $\bar{D}$.

A: The question basically boils down to how large the coefficient at $z$ of a polynomial $p(z)$ that has no zeroes in the circle can be compared to the uniform norm of the polynomial. Indeed, one direction is clear. For the other direction, notice that if we have a polynomial $P$ of degree $n$ with the coefficient $1$ at $z$ and without zeroes, then for every $N>n$ we can write
$$
z=\frac 1N\sum_{\zeta:\zeta^N=1}\zeta^{-1}P(\zeta z)
$$
(the restriction that $p_j$ are monic is totally pointless because only the products $c_jp_j$ matter in the whole problem setup).
Now, let's try to figure it out in this new formulation. Nothing is special about polynomials here, we can always just take a long enough Taylor series of a function analytic in a slightly larger disk and we can always reduce the radius a bit and expand afterwards. Also, any function $F$ without zeroes in the disk is just $e^g$. So the question becomes something like that: given a function $g=az+\dots$ in the unit disk, what is the least left half-plane we can squeeze its image into. The answer (by the Schwarz lemma) is given by any conformal mapping of the disk to a left half-plane preserving the origin and having the first Taylor coefficient of some fixed absolute value $A$, which is, say, $g(z)=\frac {Az}{z+1}$ corresponding to the left half plane $\Re z\le\frac A2$. Thus, the best constant is $\min_A\frac{e^{\frac A2}}A=\frac e2\approx 1.36$, which is still noticeably above $1$, but definitely not $2$.

A: I am not sure whether a counterexample can be found but you can find one if you relax the polynomial condition and allow general continuous invertibles.
There exists a variation on a partition of unity of the circle, $\mathbb T$, call it $u_1, u_2, u_3 \in C(\mathbb T)$ such that $\|u_j\|_\infty = 1/2$, $u_1+u_2+u_3 = z$ and $u_j = 0$ on the arc $[2\pi(j-1)/3, 2\pi(j)/3]$. Basically, each $u_j$ can be just thought of as $\frac{1}{2}z$ on the other two thirds of the circle.
Define functions $g_j \in C(\overline{\mathbb D})$ by $g_j(\lambda e^{i\theta}) = \lambda u_j(e^{i\theta})$. Thus, $$g_1(z) + g_2(z) + g_3(z) = f(z) = z$$
and we still have that $\|g_j\|_\infty = 1/2$.
Finally, define
$$ f_j(z) = g_j(z) - \frac{1}{9}e^{i(2\pi j/3 - \pi/3)}$$
which is invertible in $C(\overline{\mathbb D})$ because of the definition of $u_j$. Therefore, $$\|f_j\|_\infty \leq \frac{1}{2} + \frac{1}{9}$$
which gives that
$$\|f_1\|_\infty + \|f_2\|_\infty + \|f_3\|_\infty = \frac{3}{2} + \frac{1}{3} < 2$$ and
$$ f_1(z) + f_2(z) + f_3(z) = f(z) = z$$.
By chopping the circle into $n$ pieces and defining $n$ functions in the above manner you can probably bring the sum of the norms asymptotically to 1.


text:
Q: Convert CSV with WKT Polygon Geometry to Shapefile - Python I am trying to convert a CSV file with WKT Polygon geometry to shapefile in Python, but cannot determine how to correctly integrate the geometry into a shapefile.  Below is a segment of the CSV file:
    ID  Day Number  Hours      WKT
    1   10  2      [12,12,13]  POLYGON ((153.101112401 -27.797998206, 153.097860177 -27.807122487, 153.097715464 -27.8163131, 153.100598081 -27.821068293,...)

I am attempting to use the geopandas and shapely libraries and have found documentd to support conversion from CSV to Shapefile from Points geometry and using latitude/longtitude, but I cannot figure out how to do so without lat/lon and from Polygon geometry.  When I attempted to plot the data, I get an "AttributeError: No geometry data set yet (expected in column 'geometry')".  I can still generate a plot graphic, but there is no data associated with it.  Once I can plot the data, I should be able to generate the desired shapefile output that preserves the attributes of the original CSV.  Below is the the code I am using:
import pandas as pd
import geopandas as gpd
from shapely import wkt

test_file = pd.read_csv("C:\\Users\\mdl518\\Desktop\\sample_data.csv")  ## read the CSV
test_file['geometry'] = test_file.WKT.apply(wkt.loads)  ## load the WKT geometry
gdf = gpd.GeoDataFrame(test_file, geometry='geometry')  ## load CRS into Geodataframe

test_file_gdf.plot(markersize = 1.5, figsize = (10,10))  ## plot the data

## Obtaining the ESRI WKT
ESRI_WKT = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]'

## Saving to shapefile
test_file_gdf.to_file(filename = "C:\\Users\\mdl518\\Desktop\\test_sample.shp", driver = "ESRI Shapefile", crs_wkt = ESRI_WKT)

I feel like this should otherwise be fairly straightforward, but I cannot figure out the missing steps in the geodataframe geometry integration, any assistance is most appreciated!


text:
Q: Implementing a Shapes application using the following criteria - small project Create a Shape interface which has an area() method which returns the area of the shape as a double. Create classes Circle and Rectangle which implement the Shape interface. These classes have attributes which reflect their dimensions (radius for a circle, height and width for a rectangle) which are set by their constructors.
Create a Drawable interface with setColour(Color c), setPosition(int x, int y), and draw(Graphics g) methods. Create the classes DrawableCircle and DrawableRectangle with appropriate constructors which extend Circle and Rectangle respectively and implement the Drawable interface.
Create a ShapesDriver class which extends Frame and has the main and  paint(Graphics g) methods in it. Within ShapesDriver create an ArrayList of type Drawable. Place into this array list a DrawableCircle and a DrawableRectangle where you have set the dimensions, position and colour. In the paint method iterate through the ArrayList and the invoke the draw method for each shape.
Here's where I've got to but I can't seem to get the drawable classes to work?
package shape;
public interface Shape
{
    public double area();
}

package shape;
public abstract class Circle implements Shape
{
    private double radius;

    Circle(double radius)
    {
        this.radius = radius;
    }

    public double area()
    {
        return radius;
    }

}

package shape;
public abstract class Rectangle implements Shape
{
    public double height, width;

    Rectangle(double Height, double Width)
    {
        this.height = Height;
        this.width = Width;
    }

    public double area()
    {
        return width * height;
    }
}

package shape;
import java.awt.*;

public interface Drawable
{
    public void setColour(Color c);
    public void setPosition(double x, double y);
    public void draw(Graphics g);
}

package shape;
import java.awt.Color;
import java.awt.Graphics;

public class DrawableCircle extends Circle implements Drawable
{
    public DrawableCircle(double radius)
    {
        super(radius);
    }

    @Override
    public void setColour(Color c)
    {
        c = Color.ORANGE;
    }

    @Override
    public void setPosition(int x, int y)
    {
        x = 100;
        y = 150;
    }

    @Override
    public void draw(Graphics g)
    {
        //g.drawOval(x, y, width, height);
    }

}

package shape;
import java.awt.Color;
import java.awt.Graphics;

public class DrawableRectangle extends Rectangle implements Drawable
{
    private double x, y;

    public DrawableRectangle(double height, double width)
    {
        super(height, width);
    }

    @Override
    public void setColour(Color c)
    {
        this.setColour(c);
    }

    @Override
    public void setPosition(double x, double y)
    {
        this.x = x;
        this.y = y;
    }

    @Override
    public void draw(Graphics g)
    {
        g.drawRect(x, y, width, height);
    }

}

A: This should get you started
public interface Shape {
    public double area();
}

public class Circle implements Shape{
    // constructors
    // radius
    // implement area();
}

public class Rectangle implements Shape {
    // constructors
    // height, width
    // implement area();
}

public interface Drawable {
    public void setColor(Color c);
    public void setPoistion(int x, int y);
    public void draw(Graphics g);
}

public class DrawableCirlce extends Circle implements Drawable {
    // constructors
    // implement setColor();
    // implement setPosition();
    // implement draw();
}

public class DrawableRectangle extends Rectangle implements Drawable {
    // constructors
    // implement setColor();
    // implement setPosition();
    // implement draw();
}


text:
Q: Object selection possible only in very small area of game object with generated sprite and collider shape I have a square based game object with scale (1, 1, 1) in my 2D game. The game object has a script added as component which in turn adds a much bigger collider (100, 100) as well as a sprite of same size in its Start() method call.
When I want to select the object I have to click on the very center of the object (Possibly the 1 by 1 area defined by scale?). If I instead click somewhere on the sprite nothing is selected. This is very unhandy.

How can I get the Unity Editor to select when clicked anywhere on the colliders shape or sprite (increase the click area)?

A: You can use SelectionBaseAttribute
Creat the following script and add it to the parent object you want to select:
[SelectionBase]
public class SelectionBase : MonoBehaviour
{
}

https://docs.unity3d.com/ScriptReference/SelectionBaseAttribute.html


text:
Q: Rxjs how to know how many subscribers observable have? When I have multiple subscribers to one observable, for example:
const myInterval = Rx.Observable.interval(500);

const subscriptionOne = myInterval.subscribe(val => doSomething());
const subscriptionTwo = myInterval.subscribe(val => doSomething());

How can I know how many subscribers still register to the myInterval observable? I need this information for example to prevent memory leaks in case that I forgot to unsubscribe from one of them?

A: When using angular 2, you should try to use the async pipe as much as possible since this will unsubscribe automatically for you when your component gets destroyed.
That being said. Your interval observable here is a cold observable. Meaning, for every subscription the producer of values will be set up. This means, a new subscription is created each time. So knowing how many subscriptions you still have to a cold observable is a question you cannot answer.
I'm afraid the only thing you can do is managing your subscriptions in a clean way and rely on angular as much as possible for this.


text:
Q: Java Me platform issues in NetBeans I have installed Netbeans 8.0 that comes with pre installed Java ME plugin.
Now when I tried to create a new Java ME project it said No Java ME Platform found. Please add at least one
Also, the field "Java ME platform" was blank. So I clicked on Manage platforms and added Java ME CDLC Emulator Platform and gave the path to JAVA ME SDK.
It discovered the platform and added the devices.
After doing this, the field "Java ME platform" is still blank and I'm not able to select the Java Me platform.
Please help!

A: Had the same problem during installation on a new PC.
I'm developing for J2ME, CLDC 1.1, MIDP 2.1,
but I just couldn't manage to add a platform that would allow me to compile and run my app on an emulator.
The PC is a 64-bit PC, and I'm using the SDK 3.4, which is 32 bit
so finally I installed Virtual Box, Windows 7 32-bit as guest, and finally it worked
- installed first java jdk-8u25-windows-i586
- then netbeans 8 netbeans-8.0.1-windows
- once netbeans installed, activated java me plug in, there was no need to install it, it's pre-installed
- then java me sdk 3.4 oracle-jmesdk-3-4-rr-win32-bin
- then in netbeans, tools - java platforms, add the platform java me 3.4 just installed
Now I can emulate my app again

A: There are two kinds of projects available Java ME embedded and Java ME. The Java ME CDLC Emulator Platform is used for Java ME projects.
One thing you should check is the activation step as described here: https://netbeans.org/kb/73/javame/cdc-quickstart.html
For my case I had the EE version of Netbeans 8.0 so I wen to the start page then to plugins and downloaded everything that had to do with JME. I also had to download SDK Java ME SDK 3.2.
I also downloaded the plugins for Netbeans (even though I did the plugin installation through the IDE) Java ME SDK 3.2 Plugins for NetBeans from: http://www.oracle.com/technetwork/java/javame/javamobile/download/sdk/index.html. Then went to Tools->Plugins selected the Downloaded tab and finally Add PLugins ...
UPDATE - Tried with NetBeans 8.0 All (contains JAVA ME)
Even after activating the plugins I still had to download Java ME SDK 3.2 Plugins for NetBeans. Only then the IDE is offering me Java ME when I click at new project.
What I did:
1) Activate Java ME plugin, restart the IDE:

2) Install Java ME SDK 3.2
3) Go to Tools add platform. Restart IDE just in case. Still offered only Java ME embedded as project:

4) Go to http://www.oracle.com/technetwork/java/javame/javamobile/download/sdk/index.html and download the plugins for the Netbeans IDE. Unzip the file and install them (press ctrl-a to select all the nbm files and click open):

5) Click install. This will install everything needed and it will prompt you to restart the IDE:

6) Restart the IDE and there it is:


text:
Q: How to import .pl file on SWI PROLOG? I just downloaded the SWI PROLOG for mac, and for some reason there's no 'import' button in the menu bar. So, I was wondering if there's any way I could import the .pl file using code maybe, and how I can include the path of the .pl file in my code.
Thank you in advance :)

A: You can use the Consult command under the File menu.
From the query prompt (?-), you can put the path to the file as a string inside of square brackets:
?- ['~/Desktop/my_pgm.pl'].

A: You do have a ?- prompt.
type the name of your file in square brackets, like Scott says

A: maybe you renamed the executable in some way ? On Linux, I'm experiencing a similar issue (no menubar at all) if I copy a link from the build folder to desktop, where then it's seen as Link to swipl-win. Renaming the link to swipl-win adjust the menubar as well. So strange...


text:
Q: How to use OnSerializing and OnDeserializing attributes? I have tried to implement auto encryption and decryption in my xml, but it doesn't just work, i.e. The data is not encrypted. What could be the reason? My code is shown below. I'm using the XmlSerializer class. Thanks
[Serializable]
public class User
{
    public string _username;
    public string _password;
    public string[] _roles;

    [XmlIgnore]
    public string Username
    {
        get { return _username; }
        set { _username = value; }
    }

    [XmlIgnore]
    public string Password
    {
        get { return _password; }
        set { _password = value; }
    }

    [XmlIgnore]
    public string[] Roles
    {
        get { return _roles; }
        set { _roles = value; }
    }

    [OnDeserializingAttribute]
    internal void DecryptPersonalData(StreamingContext context)
    {
        _username = Crypto.Decrypt(_username);
        _password = Crypto.Decrypt(_password);
        for (int i = 0; i < _roles.Length; i++)
        {
            _roles[i] = Crypto.Decrypt(_roles[i]);
        }
    }

    [OnSerializingAttribute]
    internal void EncryptPersonalData(StreamingContext context)
    {
        _username = Crypto.Encrypt(_username);
        _password = Crypto.Encrypt(_password);
        for (int i = 0; i < _roles.Length; i++)
        {
            _roles[i] = Crypto.Encrypt(_roles[i]);
        }
    }
}

A: OnDeserializing isn't used by the XmlSerializer....to perform custom serialization with the XmlSerializer, derive from it, and handle the IXmlDeserializationCallback interface.

*

*How do you find out when you've been loaded via XML Serialization?
Here is one suggested workaround (basically you would create a "Twin" class that returned encrypted data in it's gets, and did unecryption in its sets...you wouldn't only use the "Twin" during your serialization task...copy across from User into your User2).

*

*http://codethatworks.wordpress.com/2009/11/15/xmlserializer-and-using-onserializing-ondeserialized-attributes/
Or you might be able to use the DataContractSerializer instead (but it is restrictive in that it doesn't support XML Attributes, only Elements in the serialized stream).

*

*XML Serialisation - When To Use DataContractSerializer / Binary / XMLSerialiser