Q: Can't continue deploying after for while via capistrano My environment is following the below.

Environment
Version

Rails
7.0.0

Ruby
3.0.0

capistrano
3.16.0

Production environment
Amazon EC2 Linux

After for while from deploying, I got these logs.
Then deploying stopped, not working anymore.
INFO [41bfeeb4] Running /usr/bin/env sudo /bin/systemctl stop puma_〇〇_production as deploy@〇〇

 DEBUG [41bfeeb4] Command: ( export RBENV_ROOT="/usr/local/src/rbenv" RBENV_VERSION="3.0.0" ; /usr/bin/env sudo /bin/systemctl stop puma_〇〇_production )

 DEBUG [41bfeeb4]

あなたはシステム管理者から通常の講習を受けたはずです。

これは通常、以下の3点に要約されます:

    #1) 他人のプライバシーを尊重すること。

    #2) タイプする前に考えること。

    #3) 大いなる力には大いなる責任が伴うこと。

 DEBUG [41bfeeb4]       [sudo] deploy password:

I think it's related to authorization.
I have no idea for fixing.
How can I do?
deploy.rb
set :application, '〇〇'
set :repo_url, '〇〇'

set :deploy_to, '/var/www/〇〇'

set :puma_threads, [4, 16]
set :puma_workers, 0
set :pty, true
set :use_sudo, false
set :stage, :staging
set :deploy_via, :remote_cache
set :deploy_to, "/var/www/#{fetch(:application)}"
set :puma_bind,
    "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.access.log"
set :puma_error_log, "#{release_path}/log/puma.error.log"
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :puma_restart_command, 'bundle exec puma'
set :rbenv_type, :system
set :rbenv_path, '/usr/local/src/rbenv'
set :rbenv_ruby, '3.0.0'
set :linked_dirs,
    fetch(:linked_dirs, []).push(
      'log',
      'tmp/pids',
      'tmp/cache',
      'tmp/sockets',
      'vendor/bundle',
      'public/system',
      'public/uploads',
    )
set :linked_files,
    fetch(:linked_files, []).push(
      'config/database.yml',
      'config/secrets.yml',
      'config/puma.rb',
      '.env',
    )

namespace :puma do
  Rake::Task[:restart].clear_actions

  desc 'Overwritten puma:restart task'
  task :restart do
    puts 'Overwriting puma:restart to ensure that puma is running. Effectively, we are just starting Puma.'
    puts 'A solution to this should be found.'
    invoke 'puma:stop'
    invoke 'puma:start'
  end

  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end
  before :start, :make_dirs
end

namespace :deploy do
  desc 'Make sure local git is in sync with remote.'
  task :check_revision do
    on roles(:app) do
      unless `git rev-parse HEAD` == `git rev-parse origin/master`
        puts 'WARNING: HEAD is not the same as origin/master'
        puts 'Run `git push` to sync changes.'
        exit
      end
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  before :starting, :check_revision
  after :finishing, :compile_assets
  after :finishing, :cleanup
end

after 'deploy', 'sitemap:refresh'

Capfile
require 'capistrano/setup'

require 'capistrano/deploy'

require 'capistrano/scm/git'
install_plugin Capistrano::SCM::Git
require 'capistrano/rails'
require 'capistrano/rbenv'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano/bundler'
require 'capistrano/puma'
require 'capistrano/sitemap_generator'
require 'whenever/capistrano'

require 'dotenv'
Dotenv.load

install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Systemd
# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.cap').each { |r| import r }

A: The deploy user needs to be a sudo user in order to restart the puma systemctl service.
You can fix the issue by creating new file inside /etc/sudoers.d directory and add this line
deploy ALL=(ALL) NOPASSWD:/bin/systemctl


Q: Is the a ScriptEngine or eval()-like function in Swift? In Java, we can build up expressions to be called using ScriptEngine.  This is nice for building up frameworks based on a common naming convention.  In JavaScript, there is of course eval().  Does Swift have some sort of mechanism for evaluating a string which contains a swift expression?  I'm aware that this could be potentially abused; however, it would simplify my present development.

A: No.  Swift is a compiled language, and the runtime doesn't include the compiler.  The iOS SDK doesn't provide a way to evaluate run-time Swift code.
You can execute JavaScript using JavaScriptCore, and JavaScriptCore makes it pretty easy to expose Swift objects and functions to the script.  Maybe that will help you.


Q: Distribution of objects in equal size groups Let there be a large set of objects, each providing a getSize() method that returns a number representing a "size" of some kind. This set is (or can be) sorted according to size.
For simplicity, also assume that:

*

*The group size is larger than the largest object size, so that each group contains at least one object

*There is no limitation to the total number of groups

Given the above, what would be an efficient way of distributing those objects into groups, so that the total size of all objects in a group is (approximately) the same to that of all other groups?
Obviously one can walk the set linearly and put an object into a group if it fits, or create another group and put it there if is does not, but this approach does not achieve equal size distribution.
The problem is independent of programming languages, but an example implementation in Java would also be interesting.


Q: Elasticsearch Python - No viable nodes were discovered on the initial sniff attempt I have a cluster of Elasticsearch nodes running on different AWS EC2 instances. They internally connect via a network within AWS, so their network and discovery addresses are set up within this internal network. I want to use the python elasticsearch library to connect to these nodes from the outside. The EC2 instances have static public IP addresses attached, and the elastic instances allow https connections from anywhere. The connection works fine, i.e. I can connect to the instances via browser and via the Python elasticsearch library. However, I now want to set up sniffing, so I set up my Python code as follows:
        self.es = Elasticsearch([f'https://{elastic_host}:{elastic_port}' for elastic_host in elastic_hosts],
                                sniff_on_start=True, sniff_on_connection_fail=True, sniffer_timeout=60,
                                sniff_timeout=10, ca_certs=ca_location, verify_certs=True,
                                http_auth=(elastic_user, elastic_password))

If I remove the sniffing parameters, I can connect to the instances just fine. However, with sniffing, I immediately get elastic_transport.SniffingError: No viable nodes were discovered on the initial sniff attempt upon startup.
http.publish_host in the elasticsearch.yml configuration is set to the public IP address of my EC2 machines, and the /_nodes/_all/http endpoint returns the public IPs as the publish_address (i.e. x.x.x.x:9200).
We have localized this problem to the elasticsearch-py library after further testing with our other microservices, which could perform sniffing with no problem.

A: After testing with our other microservices, we found out that this problem was related to the elasticsearch-py library rather than our elasticsearch configuration, as our other microservice, which is golang based, could perform sniffing with no problem.
After further investigation we linked the problem to this open issue on the elasticsearch-py library: https://github.com/elastic/elasticsearch-py/issues/2005.
The problem is that the authorization headers are not properly passed to the request made to Elasticsearch to discover the nodes. To my knowledge, there is currently no fix that does not involve altering the library itself. However, the error message is clearly misleading.


Q: Drupal Page View not being added to Main Menu Drupal 7 Views has a "Menu" button that should allow one to add a Page View to the Main Menu. I have cloned a view, modified the "Path" and "Menu" parameter. It seems simple enough, because when I create a View via "Add View" I can add that view to the main menu. But, cloning a view and then modifying the "Menu" params does not cause a menu item to show up in the main menu. I have cleared cache a number of times but still nothing appears in the main menu.
Thanks

A: I know this may be silly, but do you happen to save the view after cloning?
Also, make sure that the path is not already existing within you Drupal site.
A view creates a menu entry, check within you menu items listing that this entry is enabled.


Q: how to normalize the output of neural network in tensorflow 1 I have created a neural network using tensorflow 1.x as below:
def coder(x):
    layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['encoder_h1']),biases['encoder_b1']))
    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2']))
    layer_3 = tf.nn.tanh(tf.add(tf.matmul(layer_2, weights['encoder_h3']),biases['encoder_b3']))
    return layer_3

What I need is to normalize the output of that neural network. I have tried to do that manually by:
layer_4 = (layer_3  * tf.sqrt(tf.cast(tf.shape(layer_3 )[0], dtype=tf.float32))) / tf.norm(layer_3 )
return layer_4

But, I think this way is not correct, is there a way I can normalize the output of the neural network such as adding a normalization layer or something like that.


Q: Vagrant and symfony2 I'm having kind of a bizzare issue related to installing Symfony2 from within a vagrant environment. The environment is set up correctly and is running a web server that is serving files from a folder that is shared with the vagrant environment that is located in the base directory of vagrant.
Basically, vagrant is initiated in directory foo and then within foo, there is a directory called webroot. Vagrant automagically shares the foo directory. An apache server is set up to run so that webroot is the base http directory. This all works fine and I am able to serve basic HTML, PHP and the MySQL connection is tested to be fine.
I used composer to install vagrant the recommended way, into directory inside /webroot/ called Symfony. All of the files now exist within the correct directory. The configuration is correct  and there are no items that Symfony claims need to be changed in /config.php.
The issue comes when I attempt to load /app_dev.php. It throws an exception claiming that it cannot create a file named cache in the /app directory.
As chmod +a is not supported within the vagrant box I am using, I elected to set permissions by uncommenting umask(0000) in app_dev. Assuming it was a permission problem, I tried using chmod to adjust the permissions both within the vagrant environment and within osx to 777 for everything.
What's strange is that when I chmod a file or directory inside the vagrant environment, it claims to set 777 correctly but then when I ls -l, the permissions have not changed. However, when I chmod a file or directory from OUTSIDE The vagrant environment within the webroot folder, the permissions persist. As symfony does not have r/w permissions within the environment, it cannot create the necessary cache and log files. When i run symfony from the command from osx, everything works fine.
Does anyone have any insight as to how to change the permissions for the /webroot directory so things within the vagrant environment can actually read and write to it as chmod doesn't appear to work?

A: I think it's a question of user rights. Your apache + php is probably launched by root. You have to set rights with root.
Two possibilities :
sudo su
chmod -R 777 app/cache

or
sudo chown -v app/cache
sudo chmod -R 777 app/cache

You will probably have to do the same thing with the log file.
My vagrant file if you need it :
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "precise64"  #Box Name
  config.vm.box_url = "http://files.vagrantup.com/precise64.box" #Box Location
  config.vm.provider :virtualbox do |virtualbox|
      virtualbox.customize ["modifyvm", :id, "--memory", "2048"]
  end
  config.vm.synced_folder ".", "/home/vagrant/synced/", :nfs => true
  #config.vm.network :forwarded_port, guest: 80, host: 8080 # Forward 8080 rquest to vagrant 80 port
  config.vm.network :private_network, ip: "1.2.3.4"
  config.vm.network :public_network
  config.vm.provision :shell, :path => "vagrant.sh"
end

vagrant.sh
#!/usr/bin/env bash

#VM Global Config
apt-get update

#Linux requirement
apt-get install -y vim git

#Apache Install
apt-get install -y apache2

#Apache Configuration
rm -rf /var/www
ln -fs /home/vagrant/synced/web /var/www
chmod -R 755 /home/vagrant/synced

#Php Install
apt-get install -y python-software-properties
add-apt-repository -y ppa:ondrej/php5
apt-get update

apt-get install -y php5 libapache2-mod-php5

#Php Divers
apt-get install -y php5-intl php-apc php5-gd php5-curl

#PhpUnit
apt-get install -y phpunit
pear upgrade pear
pear channel-discover pear.phpunit.de
pear channel-discover components.ez.no
pear channel-discover pear.symfony.com
pear install --alldeps phpunit/PHPUnit

#Php Configuration
sed -i "s/upload_max_filesize = 2M/upload_max_filesize = 10M/" /etc/php5/apache2/php.ini
sed -i "s/short_open_tag = On/short_open_tag = Off/" /etc/php5/apache2/php.ini
sed -i "s/;date.timezone =/date.timezone = Europe\/London/" /etc/php5/apache2/php.ini
sed -i "s/memory_limit = 128M/memory_limit = 1024M/" /etc/php5/apache2/php.ini
sed -i "s/_errors = Off/_errors = On/" /etc/php5/apache2/php.ini

#Reload apache configuration
/etc/init.d/apache2 reload

#Composer
php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"
mv -f composer.phar /usr/local/bin/composer.phar
alias composer='/usr/local/bin/composer.phar'

#Postgres
apt-get install -y postgresql postgresql-client postgresql-client php5-pgsql
su - postgres -c "psql -U postgres -d postgres -c \"alter user postgres with password 'vagrant';\""

A: An updated answer for nfs:
config.vm.synced_folder "www", "/var/www", type:nfs, :nfs => { :mount_options => ["dmode=777","fmode=777"] }

A:
Update as of 15th Jan 2016. Instructions for Vagrant 1.7.4+ and Symfony 3. This works.

On a fresh Ubuntu 14.04 install, ACL was installed but I couldn't use +a or setfacl to fix the permissions issues, and of course, as soon as you change any permissions in terminal in vagrant, they're reset to vagrant:vagrant again.
I added the following to my vagrant file:
# Symfony needs to be able to write to it's cache, logs and sessions directory in var/
config.vm.synced_folder "./var", "/vagrant/var",
 :owner => 'vagrant',
 :group => 'www-data',
 :mount_options => ["dmode=775","fmode=666"]

This tells Vagrant to sync var/logs and var/cache (not to be confused with /var/, these are in the root Symfony directory) and have them owned by vagrant:www-data. This is the same as doing a sudo chown vagrant:www-data var/, except Vagrant now does it for you and enforces that instead of enforcing vagrant:vagrant.
Note there are no 777 'hacks' here.
As soon as I added that, I didn't get any more permissions errors in the apache log and I got a nice Symfony welcome screen. I hope that helps someone!

A: Nothing worked for me other than changing location of cache and logs folder to /tmp
AppKernel.php
public function getCacheDir()
{
    if (in_array($this->getEnvironment(), ['test','dev'])) {
        return '/tmp/sfcache/'.$this->getEnvironment();
    }
    return parent::getCacheDir();
}

public function getLogDir()
{
    if (in_array($this->getEnvironment(), ['test','dev'])) {
        return '/tmp/sflogs/'.$this->getEnvironment();
    }
    return parent::getLogDir();
}


Q: Duplicating items already in array Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.
I tried to fix that with contains code, but it hasn't worked.
What am I missing?
    for days in results! {
        let nD = DayClass()
        nD.dayOfTheWeek = days[“D”] as! String
        let defaults = NSUserDefaults.standardUserDefaults()
            if var existingArr = defaults.arrayForKey("D") as? [String] {
                if existingArr.contains(days["D"] as! String) == false {
                    existingArr.append(nd.dayOfTheWeek)
                }
            } else {
                defaults.setObject([nD.dayOfTheWeek], forKey: "D")
            }
        }

A:
Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.

Yes, because that's exactly what your code does:
defaults.setObject(existingArr, forKey: "D")

But what is existingArr? It's the defaults you've just loaded before:
if var existingArr = NSUserDefaults.standardUserDefaults().arrayForKey("D") as? [String]

So what happens is that when you enter the .contains branch, you always do the same operation: you save the existing array.
Contrary to what your comment in the code states, you're not appending anything to any array in that block, you're saving the existing one.


Q: Single postgres transaction locks xmin for the whole cluster One of my applications performs a lock with a following request
SELECT … FROM locks WHERE id = 1 FOR UPDATE SKIP LOCKED;

This query lasts as long as application lifetime. Table itself contains only one column with a single row id = 1. I know it's not the best approach to acquire locks and I expect xmin for that database to stuck with this SELECT … FOR UPDATE … xid.
But in fact I'm getting situation where all transactions in my cluster, even in another databases are stuck with that xmin, including autovacuum process.
At first I was thinking that streaming replication with enabled hot_standby_feedback may be involved somehow, but it's continues to happen even with replication turned off at all.
Server version is 11.3.
There is no long running prepared transactions in pg_prepared_xacts or any replication running. Xmin blocks cluster-wide exactly on SELECT FOR UPDATE xid.


Q: Vim: no highlighting at startup I am using vim together with NERDTree and MiniBufExplorer. My colorscheme is peaksea. If I start vim, no syntax is highlighted in the first buffer. The other buffers have syntax highlighted. I have "syntax enable" in my vimrc. If I type :edit the syntax gets highlighted. So I tried
autocmd VimEnter * edit

but still nothing is highlighted. Did anyone encounter a similar problem or has anyone an idea how to fix this?

A: I remapped F12 to redo my syntax highlighting in case it gets messed up:
nnoremap <F12> :syntax sync fromstart<cr>

Maybe you can just run it as an autocmd event in your vimrc based on reading a new buffer?
autocmd BufReadPost * :syntax sync fromstart


Q: AWK Replace strings by the same strings with underscores I have three files. One is the original file, another contains a part of the lines of the original and another file with the modified parts have to replace the original.
And do not even know where to start. Can you help me?
Match file:

a demandé de montrer
grandes vacances
de faire
a montré
a remis
bien posé
n '
quand il l '
arrière du véhicule
modèle essence

Replace file:

a_demandé_de_montrer
grandes_vacances
de_faire
a_montré
a_remis
bien_posé
n_'
quand_il_l_'
arrière_du_véhicule
modèle_essence

Original file:

A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos...
A ce jour, je suis totalement satisfaite
A ce moment-là aux grandes vacances on m'a demandé de montrer le bon.
A chacun son choix
A chaque fois c'est moi qui dois les recontacter.
A eux de faire leurs avis....
A l'achat, le vendeur m'a montré comment rabattre le siège arrière, mais quand il l'a remis en place, ce n'était pas bien posé.
A l'arrière du véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle essence.
A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ...
A la limite, chacun son garagiste.

Desired output:

A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos...
A ce jour, je suis totalement satisfaite
A ce moment-là aux grandes vacances on m'a_demandé_de_montrer le bon.
A chacun son choix
J'avais droit aux grandes_vacances à l'entretien kit vacances.
A chaque fois c'est moi qui dois les recontacter.
A eux de_faire leurs avis....
A l'achat, le vendeur m'a_montré comment rabattre le siège arrière, mais quand il l'a_remis en place, ce n'était pas **bien_posé**.
A l'arrière_du_véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle_essence.
A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ...
A la limite, chacun son garagiste.

A: You didn't show any effort on the implementation but this should solve your problem.
awk -F"\t" 'NR==FNR{a[$1]=$2;next}
                   {for(k in a) gsub(k,a[k])}1' <(paste search replace) text

create a lookup table, do the replacement based on lookup.

A: There may be a better way to do this, but if you would like to use AWK, you can asssign a variable for each file you read, build some arrays with the find and replace string, and then loop through each find/replace value:
awk '
  file == 1 { source[++s] = $0 }
  file == 2 { replace[++r] = $0 }
  file == 3 {
    for (i = 1; i < s; i++)
      { gsub (source[i], replace[i], $0)  }
    print
  }
' file=1 match_file \
  file=2 replace_file \
  file=3 original_file

I don't claim this is the most efficient way to do it, but I think it will do what you describe.

A: Here is one approach of solving this using awk:
#!/usr/bin/awk -f
FILENAME == ARGV[1] { m[FNR]=$0 } # Store the match word in an array
FILENAME == ARGV[2] { r[FNR]=$0 } # Store the replacement word in a second array
FILENAME == ARGV[3] { for (i in m) gsub(m[i],r[i]); print } # Do the replacement for every line in file3

Run it like this:
./script.awk match_file replace_file original_file

A: This is the output the first three codes.This is the output the first two codes. Perhaps the encoding?

a_demand▒_de_montreraa_demand▒_de_montreria_demand▒_de_montrersa_demand▒_de_montrersa_demand▒_de_montreroa_demand▒_de_montrerna_demand▒_de_montrersa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montrerea_demand▒_de_montrerua_demand▒_de_montrerra_demand▒_de_montrer a_demand▒_de_montrerua_demand▒_de_montrerna_demand▒_de_montrer a_demand▒_de_montrerta_demand▒_de_montrerea_demand▒_de_montrerma_demand▒_de_montrerpa_demand▒_de_montrersa_demand▒_de_montrer a_demand▒_de_montrerda_demand▒_de_montrer a_demand▒_de_montreraa_demand▒_de_montrerda_demand▒_de_montreraa_demand▒_de_montrerpa_demand▒_de_montrerta_demand▒_de_montreraa_demand▒_de_montrerta_deman
d▒_de_montreria_demand▒_de_montreroa_demand▒_de_montrerna_demand▒_de_montrer a_demand▒_de_montrer.a_demand▒_de_montrer.a_demand▒_de_montrer.a_demand▒_de_montrer
a_demand▒_de_montrerAa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montreraa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montreria_demand▒_de_montrerma_demand▒_de_montreria_demand▒_de_montrerta_demand▒_de_montrerea_demand▒_de_montrer,a_demand▒_de_montrer a_demand▒_de_montrerca_demand▒_de_montrerha_demand▒_de_montreraa_demand▒_de_montrerca_demand▒_de_montrerua_demand▒_de_montrerna_demand▒

I tried this..

    BEGIN {
    while ((getline ln1 < mt) > 0)
    {
        source[++s] = ln1;
    }
    while ((getline ln2 < rp) > 0)
    {
        replace[++r] = ln2;
    }
    }
    {
    for ( i = 1; i < s; i++)
        gsub (source[i], replace[i], $0)
        print;
    }

A: With GNU awk for ARGIND (with other awks just add FNR==1{ARGIND++}):
$ cat tst.awk
ARGIND==1 { a[FNR] = $0; next }
ARGIND==2 { map[a[FNR]] = $0; next }
{
    for (m in map) {
        gsub(m,map[m])
    }
    print
}

$ awk -f tst.awk match.txt replace.txt original.txt
A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos...
A ce jour, je suis totalement satisfaite
A ce moment-là aux grandes_vacances on m'a_demandé_de_montrer le bon.
A chacun son choix
A chaque fois c'est moi qui dois les recontacter.
A eux de_faire leurs avis....
A l'achat, le vendeur m'a_montré comment rabattre le siège arrière, mais quand il l'a_remis en place, ce n'était pas bien_posé.
A l'arrière_du_véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle_essence.
A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ...
A la limite, chacun son garagiste.

Like all other solutions posted so far, the above will behave undesirably if you have regexp metachars in your match file or regexp capture group identifiers in your replace file. If that can happen use index() and substr() instead of gsub().


Q: GStreamer - Sample Plugin I am a newbie in gstreamer and trying to develop a sample plugin for captions decoding.
I have downloaded the gStreamer Plugin template: based on this information.
When I launched the plugin from command line, it is working fine.
I wrote a sample application to verify the plugin. But now, I am facing a problem in setting pipeline state to PLAYING. Below is the code snippet
Any inputs would be of great help.
Thanks in advance,
Kranti

gst_init(NULL, NULL);

loop = g_main_loop_new (NULL, TRUE);

g_print("\n Gstreamer is Initialized and Created the loop ");

pipeline = gst_pipeline_new ("pipeline");

source = gst_element_factory_make ("filesrc", "source");

filter = gst_element_factory_make ("myfilter", "testfilter");

sink = gst_element_factory_make ("fakesink", "sink");

if((NULL != pipeline) && (NULL != source) && (NULL != filter) && (NULL != sink))
{
    g_print("\n Successfully created the factory elements ");

    g_object_set(G_OBJECT (source), "location", fileName, NULL);
    g_print("\n Set the file name \n");

    g_object_set(G_OBJECT (filter), "silent", 1, NULL);
    g_print("\n Set the silent type \n");

    /* we add a message handler */
    bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
    bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
    gst_object_unref (bus);
    g_print("\n Created bus and a monitor to watch it");

    gst_bin_add_many(GST_BIN(pipeline), source, filter, sink, NULL);
    gst_element_link_many(source, filter, sink);
    g_print("\n Added and Linked the factory elements");

    g_signal_connect (filter, "pad-added", G_CALLBACK (on_pad_added), filter);

    g_print ("Now reading: %s\n", "test.txt");
    g_print ("Setting the pipeline state to PLAYING ");
    ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
    if(ret == GST_STATE_CHANGE_FAILURE)
    {
        g_print("\n Failure in setting pipeline state to PLAYING \n");
    }

    else
    {
        g_print("\n Successfully set the pipeline state to playing \n");
    }
}

else
{
    g_print("\n Failure in creating factory elements");
}

A: After trying with few examples on gstreamer elements, found the problem.
Apart from filesrc, filter, fakesink:: If I add 'decoder' element also to the pipeline, then I am able to change the state to PLAYING
But why is that required - I am still trying to figure it out
And sometimes, the name used to create pipeline is also causing problems: Better to use some unique name rather than pipeline in gst_pipeline_new ("pipeline");


Q: how to decompose a nested list? I have a nested list and want to decompose it, exactly inverse of merging.
suppose i have list bellow:
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

I am trying to obtain :
a1=[1,1,1,1]
a2=[2,2,2,2]
a3=[3,3,3,3]

I have tried this command:
a1=f[:][0:1]
a2=f[:][1:2]
a3=f[:][2:3]

but it does not work right. do you know my wrong ?

A: Try this:
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

for i in zip(*f):
    print(i)

Output:
(1, 1, 1, 1)
(2, 2, 2, 2)
(3, 3, 3, 3)

A: zip() in conjunction with the * operator can be used to unzip a list and it return iterator of tuples.
Using map() to apply list on the iterator of tuples that we are getting from zip and it return an iterator. And then passing the iterator to list().
a = list(map(list, zip(*f)))

Or
a = []
for i in iter(map(list, zip(*f))):
    a.append(i)

A: What you should do in here is to use a for loop.
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
a1=[x[0] for x in f]
a2=[x[1] for x in f]
a3=[x[2] for x in f]
print(a1,a2,a3)

>>>[1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3]

A: You may do so like the following:
a = [list(i) for i in zip(*f)]

Now:
a[0] will be [1, 1, 1, 1]
a[1] will be [2, 2, 2, 2]
a[2] will be [3, 3, 3, 3]


Q: Building the computation graph form an expression I'm trying to implement different differentiation algorithms.
I'm having trouble breaking up an expression like this:
x = Variable()
y = Variable()
F_x = (x**2) * y + y + 2

I want to build the graph for F_x.
Edit: To clarify the graph of F_x would look something like

       Add
      / \
    Mult  Add
    /  \  / \
  EXP  y  y  2
  /  \
 x   2

A: You can use a python library called scipy which has functions that can produce graphs


Q: Generate 6 digit random number I just want to generate 6 digit random number, and the range should be start from 000000 to 999999.
new Random().nextInt(999999) is returning me number but it is not in 6 digit.

A: Its as simple as that, you can use your code and just do one thing extra here
String.format("%06d", number);

this will return your number in string format, so the "0" will be "000000".
Here is the code.
public static String getRandomNumberString() {
    // It will generate 6 digit random Number.
    // from 0 to 999999
    Random rnd = new Random();
    int number = rnd.nextInt(999999);

    // this will convert any number sequence into 6 character.
    return String.format("%06d", number);
}

A: If you need a six digit number it has to start at 100000
int i = new Random().nextInt(900000) + 100000;

Leading zeros do not have effect, 000000 is the same as 0. You can further simplify it with ThreadLocalRandom if you are on Java 7+:
int i = ThreadLocalRandom.current().nextInt(100000, 1000000)

A: 1 + nextInt(2) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].
already solved here
public int gen()
{
    Random r = new Random( System.currentTimeMillis() );
    return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000));
}

A: i know it’s very difficult but you can do something like this:
create a class for BinaryNumber;
create a constructor that generate a char[] of 6 character where every single one is generated with a randomiser from 0 to 1
override the toStrig() method so that it will return the digits char[] as a string if you want to display it. then crate a method toInt() that esaminate the string char by char with a for and turn it in a decimal base number by multiplying current digit to 10 to the pow of i:
char[] digits = {‘1’ , ‘0’ , ‘1’ , ‘1’ , ‘0’ , ‘1’};
//random

int result = 0;
for( int i = 0; i < digits.length; i++) {
    result += Integer.parseInt(digits[i]) * Math.pow(10, i);
}

return result;

A: This is the code in java which generate a 6 digit random code.
import java.util.*;
public class HelloWorld{

     public static void main(String []args)
     {

        Random r=new Random();
                        HashSet<Integer> set= new HashSet<Integer>();
                        while(set.size()<1)
                        {
                            int ran=r.nextInt(99)+100000;
                            set.add(ran);
                        }
                        int len = 6;
                        String random=String.valueOf(len);
                        for(int  random1:set)
                        {
                            System.out.println(random1);
                            random=Integer.toString(random1);

                        }
     }
}


Q: How could I open an individual python file (or any code file) in an editor from the comand ( os.system (Path) ) or (os.startfile(path/Filename))? I am creating a script that opens an external file through two methods:
os.system(Path)

or
os.startfile(Path)

This works for Test files, however, it runs all code files like python which gets executed. I would like the option to open it in a text editor.
How would I do this in a python 2.7 script?
The text editor I use is VS Code.

A: you can use it like this:
os.system('code test_01.py')

A: You can use either one, but first, read the docs on what os.system and os.startfile does.

os.system(command)

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

So this basically runs the command string you pass to it. If your intention is to open a file in VS Code, then you need to check if you can use the VS Code command for opening files/folders from the command line:
code myfile.py

If that works on your terminal, then your Python script would basically just be:
os.system("code myfile.py")

os.startfile(path[, operation])

Start a file with its associated application.
When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

I assume you are on Windows, because startfile is only available on Windows.
The main thing here is that startfile is the same behavior as double-clicking the file in Windows Explorer. So, first make sure that when you double-click on a file, that it opens in VS Code. If it doesn't, then you need to associate that file with VS Code first. This is usually done by right-click > "Opens with.." then selecting VS Code from the list.

Once double-clicking on a file opens it in VS Code, then your Python script would simply be:
os.startfile("myfile.py", "open")

The "open" here is optional, but I prefer to be explicit.


Q: Setting a select option default to a previously set option In my modal window, I have a select where a user can select a breakfast meal from my database. By selecting a meal and submitting it, a record is saved in the database. However, I would like to achieve that when the user enters into the same modal window, whatever meal they have selected before hand will appear as the default option. I have created a query that checks to see if a meal has already been selected (optionquery1). Any ideas to achieve this? Thanks
On a side note, I'm not sure that I'm setting the date php variable currently. The day, month and year is stored in the html hidden inputs but not sure how to extract the values.

×

  <form action="my_planner.php" method="post">

  <input class="test" type="text" name="id1" value="" style="text-align:center; border:0px; font-weight:bold; font-size: 25px;"/>

  <input type="hidden" name="id" value=""/>
  <input type="hidden" name="month" value=""/>
  <input type="hidden" name="year" value=""/>

Breakfast:

<select id="breakfast" name="breakfast">
<option value="" disabled selected>Select your breakast</option>
<?
$meal='breakfast';
$date='<input type="hidden" name="id" value=""/>'.'<input type="hidden" name="month" value=""/>'.'<input type="hidden" name="year" value=""/>';
$query = $db->prepare("select * from recipe_category where categoryID=1");
$query->execute();

while ($results = $query->fetch()) {
    $recipeID=$results["recipeID"];
    $query3 = $db->prepare("select * from recipe where id=:recipeID");
    $dbParams3=array('recipeID'=>$recipeID);
    $query3->execute($dbParams3);
    $breakfast = $query3->fetchAll();

    $optionquery = $db->prepare("select * from user_planner where userID=:userID and date=:date and meal=:meal");
    $optionParams= array ('userID'=>$thisUser, 'date'=>$date,'meal'=>$meal);
    $optionquery->execute($optionParams);

    while ($results12 = $optionquery->fetch()) {
        $selectedmeal = $results12['recipeID'];
    }

    $optionquery1 = $db->prepare("select * from recipe where id=:recipeID");
    $optionParams1= array ('recipeID'=>$selectedmeal);
    $optionquery1->execute($optionParams1);

    while ($results123 = $optionquery1->fetch()) {
        $selectedrecipe = $results123['name'];
    }

    foreach($breakfast as $breakfast): ?>
        <option  value="<?= $breakfast['id']; ?>"><?= $breakfast['name']; ?></option>
    <?php endforeach;} ?>
</select>

A: Of course you can, you need to use the selected attribute on the <option> you want to show.
First remove the selected attribute from the first <option>:
<option value="" disabled>Select your breakast</option>

Then in the foreach loop you need an if condition:
$results123 = $optionquery1->fetch();
$selectedrecipe = $results123['id'];

foreach($breakfast as $breakfast): ?>
    <option  value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>

Notice I have removed the while loop since we are sure Mysql will return only one record (WHERE ID = <ID>).


Q: How do I test code that uses `requestAnimationFrame` in jest? I want to write a jest unit test for a module that uses requestAnimationFrame and cancelAnimationFrame.
I tried overriding window.requestAnimationFrame with my own mock (as suggested in this answer), but the module keeps on using the implementation provided by jsdom.
My current approach is to use the (somehow) builtin requestAnimationFrame implementation from jsdom, which seems to use setTimeout under the hood, which should be mockable by using jest.useFakeTimers().
jest.useFakeTimers();

describe("fakeTimers", () => {
    test.only("setTimeout and trigger", () => {
        const order: number[] = [];

        expect(order).toEqual([]);
        setTimeout(t => order.push(1));
        expect(order).toEqual([]);
        jest.runAllTimers();
        expect(order).toEqual([1]);
    });

    test.only("requestAnimationFrame and runAllTimers", () => {
        const order: number[] = [];

        expect(order).toEqual([]);
        requestAnimationFrame(t => order.push(1));
        expect(order).toEqual([]);
        jest.runAllTimers();
        expect(order).toEqual([1]);
    });
});

The first test is successful, while the second fails, because order is empty.
What is the correct way to test code that relies on requestAnimationFrame(). Especially if I need to test conditions where a frame was cancelled?

A: I'm not sure this solution is perfect but this works for my case.
There are two key principles working here.
1) Create a delay that is based on requestAnimationFrame:
const waitRAF = () => new Promise(resolve => requestAnimationFrame(resolve));

2) Make the animation I am testing run very fast:
In my case the animation I was waiting on has a configurable duration which is set to 1 in my props data.
Another solution to this could potentially be running the waitRaf method multiple times but this will slow down tests.
You may also need to mock requestAnimationFrame but that is dependant on your setup, testing framework and implementation
My example test file (Vue app with Jest):
import { mount } from '@vue/test-utils';
import AnimatedCount from '@/components/AnimatedCount.vue';

const waitRAF = () => new Promise(resolve => requestAnimationFrame(resolve));

let wrapper;
describe('AnimatedCount.vue', () => {
  beforeEach(() => {
    wrapper = mount(AnimatedCount, {
      propsData: {
        value: 9,
        duration: 1,
        formatDisplayFn: (val) => "£" + val
      }
    });
  });

  it('renders a vue instance', () => {
    expect(wrapper.isVueInstance()).toBe(true);
  });

  describe('When a value is passed in', () => {
    it('should render the correct amount', async () => {
      const valueOutputElement = wrapper.get("span");
      wrapper.setProps({ value: 10 });

      await wrapper.vm.$nextTick();
      await waitRAF();

      expect(valueOutputElement.text()).toBe("£10");
    })
  })
});

A: So, I found the solution myself.
I really needed to override window.requestAnimationFrame and window.cancelAnimationFrame.
The problem was, that I did not include the mock module properly.
// mock_requestAnimationFrame.js

class RequestAnimationFrameMockSession {
    handleCounter = 0;
    queue = new Map();
    requestAnimationFrame(callback) {
        const handle = this.handleCounter++;
        this.queue.set(handle, callback);
        return handle;
    }
    cancelAnimationFrame(handle) {
        this.queue.delete(handle);
    }
    triggerNextAnimationFrame(time=performance.now()) {
        const nextEntry = this.queue.entries().next().value;
        if(nextEntry === undefined) return;

        const [nextHandle, nextCallback] = nextEntry;

        nextCallback(time);
        this.queue.delete(nextHandle);
    }
    triggerAllAnimationFrames(time=performance.now()) {
        while(this.queue.size > 0) this.triggerNextAnimationFrame(time);
    }
    reset() {
        this.queue.clear();
        this.handleCounter = 0;
    }
};

export const requestAnimationFrameMock = new RequestAnimationFrameMockSession();

window.requestAnimationFrame = requestAnimationFrameMock.requestAnimationFrame.bind(requestAnimationFrameMock);
window.cancelAnimationFrame = requestAnimationFrameMock.cancelAnimationFrame.bind(requestAnimationFrameMock);

The mock must be imported BEFORE any module is imported that might call requestAnimationFrame.
// mock_requestAnimationFrame.test.js

import { requestAnimationFrameMock } from "./mock_requestAnimationFrame";

describe("mock_requestAnimationFrame", () => {
    beforeEach(() => {
        requestAnimationFrameMock.reset();
    })
    test("reqest -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([1]);
    });

    test("reqest -> request -> trigger -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));
        requestAnimationFrame(t => order.push(2));

        expect(requestAnimationFrameMock.queue.size).toBe(2);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([1]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([1, 2]);
    });

    test("reqest -> cancel", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        const handle = requestAnimationFrame(t => order.push(1));

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        cancelAnimationFrame(handle);

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);
    });

    test("reqest -> request -> cancel(1) -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        const handle = requestAnimationFrame(t => order.push(1));
        requestAnimationFrame(t => order.push(2));

        expect(requestAnimationFrameMock.queue.size).toBe(2);
        expect(order).toEqual([]);

        cancelAnimationFrame(handle);

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([2]);
    });

    test("reqest -> request -> cancel(2) -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));
        const handle = requestAnimationFrame(t => order.push(2));

        expect(requestAnimationFrameMock.queue.size).toBe(2);
        expect(order).toEqual([]);

        cancelAnimationFrame(handle);

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([1]);
    });

    test("triggerAllAnimationFrames", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));
        requestAnimationFrame(t => order.push(2));

        requestAnimationFrameMock.triggerAllAnimationFrames();

        expect(order).toEqual([1,2]);

    });

    test("does not fail if triggerNextAnimationFrame() is called with an empty queue.", () => {
        requestAnimationFrameMock.triggerNextAnimationFrame();
    })
});

A: Here solution from the jest issue:
beforeEach(() => {
  jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => cb());
});

afterEach(() => {
  window.requestAnimationFrame.mockRestore();
});

A: Here is my solution inspired by the first answer.
beforeEach(() => {
  jest.useFakeTimers();

  let count = 0;
  jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => setTimeout(() => cb(100*(++count)), 100));
});

afterEach(() => {
  window.requestAnimationFrame.mockRestore();
  jest.clearAllTimers();
});

Then in test mock the timer:
act(() => {
  jest.advanceTimersByTime(200);
});

Directly call cb in mockImplementation will produce infinite call loop. So I make use of the Jest Timer Mocks to get it under control.

A: My solution in typescript. I figured by making time go very quickly each frame, it would make the animations go very (basically instant) fast. Might not be the right solution in certain cases but I'd say this will help many.
let requestAnimationFrameSpy: jest.SpyInstance<number, [callback: FrameRequestCallback]>;

beforeEach(() => {
    let time = 0;
    requestAnimationFrameSpy = jest.spyOn(window, 'requestAnimationFrame')
      .mockImplementation((callback: FrameRequestCallback): number => {
        callback(time+=1000000);
        return 0;
      });
});

afterEach(() => {
    requestAnimationFrameSpy.mockRestore();
});

A: The problem with previous version is that callbacks are called directly, which does not reflect the asynchronous nature of requestAnimationFrame.
Here is a mock which uses jest.useFakeTimers() to achieve this while giving you control when the code is executed:

beforeAll(() => {
  jest.useFakeTimers()
  let time = 0
  jest.spyOn(window, 'requestAnimationFrame').mockImplementation(
    // @ts-expect-error
    (cb) => {
    // we can then use fake timers to preserve the async nature of this call

    setTimeout(() => {
      time = time + 16 // 16 ms
      cb(time)
    }, 0)
  })
})
afterAll(() => {
  jest.useRealTimers()

  // @ts-expect-error
  window.requestAnimationFrame.mockRestore()
})

in your test you can then use:
yourFunction() // will schedule a requestAnimation
jest.runAllTimers() // execute the callback
expect(....) // check that it happened

This helps to contain Zalgo.


Q: How can I print information from a database (retrieved using java code) into html? I'm doing a web-development project in Java Eclipse IDE. I was wondering if there is a way I can print information from a database and show it on html. In my code below, I have a login function which searches the database table in mySQL for employee_id and password and then validates the login. In that table, there is a column called FirstName, which is the first name of the employee. How can I print the first name of the employee on the home page when they log in? (employeeHome.html)
Validate.java
public static boolean userIsAdmin(String employee_id, String password)
    {
        boolean st = false;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
            PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ? and Admin = 1 ");
            ps.setString(1, employee_id);
            ps.setString(2, password);
            ResultSet rs =ps.executeQuery();
             st = rs.next();

Login.java
if(Validate.userIsNotAdmin(employee_id, password)) {
            RequestDispatcher rs = request.getRequestDispatcher("employeeHome.html");
            rs.forward(request, response);

employeeHome.html
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Employee Home Page</title>

  <form action="Welcome" method="post">

Employee Home Page

    <input type="submit" value="View Personal Information" name="vpi">

    <input type="submit" value="View Expense Claims" name="vec">

    <input type="submit" value="View Payslips" name="vps">

    <input type="submit" value="Change Password" name="cp">
     </form>

A: We use Apache Wicket. We have been using it for 9 years or so and have built large scale enterprise applications for financial institutions. It works well with many technologies and it also has a unit testing framework which we use quite a bit. I highly recommend it. Here's a link. http://wicket.apache.org/
I've never used JSF so I can't vouch for it, but a lot of people use it and it is a Java standard. Either one of these technologies are built for solving the problem that you need to solve in an efficient way.
Now, if you want to do everything yourself and you don't want any frameworks in the way you could write a Java Servlet and output the HTML yourself. Here's a tutorial. There are many on the web. http://www.tutorialspoint.com/servlets/servlets-first-example
I recommend using a framework. Hopefully my answer will help you make an educated decision for your needs.


Q: Git commands in Visual Studio Code Terminal are not working, yet they work on the cmd prompt Error when trying a Git command in cmd:

The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I need this to work in the integrated terminal on Visual Studio Code!
I've already tried editing the path variables and the settings in Visual Studio Code. Nothing works.

A: "Not recognized" is normally the way terminals politely tell you they don't know what you typed means.
If you can use Git from a command line, then it's installed properly. You can use where git or which git depending on your command line to find the path of the functioning Git (if those don't work, please specify your terminal type in the question).
Once done, open Visual Studio Code, hit Ctrl + , to open settings and type git path in the search. Add this path, and you should be able to use Git in Visual Studio Code.


Q: Is it possible to store PART of the URL in to a variable or somehow using cypress and use it later? i need to store the url from my website in to an URL and use part of it for an API call

A: ...coming from the comments, I leave an answer here:
With version 6.0.0, Cypress introduced a new command: .intercept().
.intercept() allows you to manage the behavior of network requests. It supports fetch, it can intercept both request and response of your app API calls and so much more, official docs here.
Related to your case, make sure you declare your intercept command before the proper fetch action, let's say on the top of the test. Then, simply call it below in the body of the test by its alias:
cy.intercept('GET', '/project/*').as('myObject')

// ...

cy.wait('@myObject').its('response.body.data.id').then(objUUID => {
// here is your uuid
   cy.log(objUUID)
})

Note, that any other action related to this uuid should be done inside above callback: .then(objUUID => {}). In case you need it shared between different tests, then intercept your request inside .beforeEach() hook and assign the uuid in a context shared variable, however, this is a bad practice (more about aliases and variables, here)


Q: Call function when PyQt QWebEngineView is finished rendering QWebEngineView and QWebEnginePage have loadFinished, however, per the docs, "This signal is independent of script execution or page rendering." I want to call QWidget.render() (QWebEngineView implements QWidget) when the website is finished RENDERING... the only solution i've seen to this problem is to just give up and use QTimer to just wait 1000ms, which is a very bad solution in my opinion. If it takes less than 1000ms to render, time is wasted just waiting. If it takes more than 1000ms, then it's not finished rendering and even bigger problems emerge. I need to know exactly when QWebEnginePage completes its rendering so I can save it as an image as fast as possible.


Q: Cleanup after exception I have a bit of code that resembles the following:
try:
    fn()
except ErrorA as e:
    ... do something unique ...
    cleanup()
except ErrorB as e:
    ... do something unique ...
    cleanup()
except ErrorC as e:
    ... do something unique ...
    cleanup()

Is there any mechanism in Python that would allow me to call cleanup just once, only if an exception is raised? Basically the opposite of else.
The best I can think of is:
error = True
try:
    fn()
    error = False
except ErrorA as e:
    ... do something unique ...
except ErrorB as e:
    ... do something unique ...
except ErrorC as e:
    ... do something unique ...

if error:
    cleanup()

A: def _cleanup():
    # clean it up
    return

cleanup = _cleanup

try:
    # stuff
except:
    # handle it
else:
    cleanup = lambda: None

cleanup()

A: The most clear way I can think of is do exactly the opposite of else:
do_cleanup = True
try:
    fn()
except ErrorA as e:
    ... do something unique ...
except ErrorB as e:
    ... do something unique ...
except ErrorC as e:
    ... do something unique ...
else:
   do_cleanup = False

if do_cleanup:
    cleanup()

If the code is enclosed and lets itself be done, you can simplify it by returning or breaking in the else.

A: How about catching all the exceptions with one except clause and dividing up the different parts of your handling with if/elif blocks:
try:
    fn()
except (ErrorA, ErrorB, ErrorC) as e:
    if isinstance(e, ErrorA):
        ... do something unique ...
    elif isinstance(e, ErrorB):
        ... do something unique ...
    else: # isinstance(e, ErrorC)
        ... do something unique ...
    cleanup()


Q: Why gradle plugin 3.3.0 doesn't want to build google-services? I'm trying to Sync my project with gradle:3.3.0 , but in result file values.xml for google-services is not generated in folder: D:\Android\workspace\myproject\app\build\generated\res\google-services\debug\values\values.xml
Top level build file build.gradle:
 apply plugin: 'kotlin'

    buildscript {
        ext.kotlin_version = '1.3.11'
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.3.0'
            classpath 'com.google.gms:google-services:4.1.0'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
          }
    }

    allprojects {
        repositories {
            mavenLocal()
            google()
            jcenter()
            mavenCentral()
            maven { url "https://jitpack.io" }
        }

        configurations.all {
            exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib-jre7'
        }
    }

    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }

    compileKotlin {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }

app/build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    ...
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation "com.google.firebase:firebase-database:16.0.5"
implementation "com.google.firebase:firebase-messaging:17.3.4"
implementation "com.google.firebase:firebase-auth:16.1.0"
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.5'
}

apply plugin: 'com.google.gms.google-services'

google-services.json
File google-services.json is located in D:\Android\workspace\myproject\app\google-services.json
In result after run of app the error occurs:
 01-23 10:31:31.578 30044-30073/E/FA: GoogleService failed to initialize, status: 10, Missing google app id value from from string resources with name google_app_id.
01-23 10:31:31.578 30044-30073/E/FA: Missing google_app_id. Firebase Analytics disabled. See
01-23 10:31:33.758 30044-30044/ E/AndroidRuntime: FATAL EXCEPTION: main
    Process: , PID: 30044
    java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process . Make sure to call FirebaseApp.initializeApp(Context) first.
        at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.4:240)
        at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)

A: Remove dependencies block from top-level gradle file:
dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }

And update to classpath 'com.android.tools.build:gradle:3.3.0' and classpath 'com.google.gms:google-services:4.2.0'
In result your Gradle Files should be Like This For Android Studio 3.3 (stable channel)
build.gradle(project:yourProject)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.11'
    repositories {
        google()
        jcenter()

        // Add repository
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.2.0'
        classpath 'io.fabric.tools:gradle:1.26.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // Add repository
        maven {
            url 'https://maven.google.com/'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(Module:app)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

apply plugin: 'com.google.gms.google-services'

apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "sanaebadi.info.teacherhandler"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    def room_version = "2.1.0-alpha03"
    def lifecycle_version = "2.0.0"

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha02'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'

    //Firebase
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.8'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-storage:16.0.5'
    implementation 'com.google.firebase:firebase-auth:16.1.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'com.google.firebase:firebase-database:16.0.5'
}

gradle-wrapper.properties
#Tue Jan 15 07:24:23 EST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip

A: update to classpath 'com.google.gms:google-services:4.2.0' in project level build.gradle.


Q: ASP.NET Error with Database I have been learning ASP.NET and building a little customer portal. I used the built in CreateUserWizard. I wanted to look inside the ASPNETDB.MDF file to see how it was storing the users and maybe add some rows of my own. I opened the file in SQL Server Management Studio and viewed the file. I closed it with out saving.
Now when I try to run the program I get this new error:
The database 'C:\PROJECTS\PORTAL\PORTAL\APP_DATA\ASPNETDB.MDF' cannot be opened because it is version 706. This server supports version 662 and earlier. A downgrade path is not supported.
So I assume opening the project in SQL Server it upgraded the version to 706, How can I either delete this database and create a new one or change the version of the database to an support version.
Thanks

A: The following blog entry will help you
http://conceptdev.blogspot.com/2009/04/mdf-cannot-be-opened-because-it-is.html

A: As soon as you attached it to SQL Server 2012, the database was upgraded to version 706. As the error message suggests, there is no way to downgrade the file back to version 662 (SQL Server 2008 R2).
You can run the script found in your Visual Studio folder -
[drive:]\%windir%\Microsoft.NET\Framework\version\asp_regsql.

It'll display a UI for you to select the server to install a new copy on. Here's a MSDN article about it.


Q: css - vertical nested menu - can't get the nested styles right, it makes a bigger rectangle I am trying to make a vertical menu, but everytime when i show the sub menu on hover, it expands the previous element, making a 'bigger box'. I have no idea how to style that.
Dont want to use some jquery plugin if there is an css solution. I have also bootstrap3, but there is no support for nested dropdowns, dropdowns inside dropdowns ... the nested ones did not open...
JSFiddle link:  http://jsfiddle.net/WqW5j/
index.html

1

2

   3

3-1

3-2

3-2-1

3-2-2

3-2-2-1

3-2-2-2

css
        .main{
            list-style: none;
            padding:0px;
            margin: 0px;
        }
        .main li{
            background-color:#f1f1f1;
            padding: 10px;
            margin: 5px;
            float:left;
            clear:both;
        }
        .main li:hover{
            background-color:#d8d8d8;
        }

          .main .sub{
            display: none;
          }
          .sub > li > .sub{
            display: none;
          }

          .main > li:hover > .sub:nth-of-type(1){
            display: block;
            position: relative;
            left: 20px;
            top:-30px;
            list-style: none;
            float:left;
            width: 100px;
            clear: both;
          }

          .sub > li:hover > .sub{
            display: block;
            position: relative;
            left: 20px;
            top:-30px;
            list-style: none;
            float:left;
            width: 100px;
          }

A: To get the nested menu work make all the li items position:relative and make the ul displayed on hover as position:absolute.
Check this fiddle
HTML:

1

1-1

1-1-1

1-2-1

1-2

1-2-1

1-2-2

2

CSS
.main{
    list-style: none;
    padding:0px;
    margin: 0px;
  }
  .main li{
    background-color:#f1f1f1;
    padding: 10px;
    margin: 5px;
    float:left;
    clear:both;
    position:relative;
  }
  .main li:hover{
   background-color:#d8d8d8;
  }

  .main .sub{
    display: none;
    list-style:none;
    padding-left:0;
    width:auto;
  }

.main .sub li{
    float:none;
}

.main > li:hover > .sub{
    display:block;
    position:absolute;
    top:0;
    left:100%;
}

.sub li:hover .sub{
    display:block;
    position:absolute;
    top:0;
    left:100%;
}


Q: Best Practices consuming a Soap request over SSL Just have a quick a question regarding best practices.
I am connecting to a 3rd party api via soap over HTTPS.
To do this I have simply added a service reference to my application by entering the 3rd party wsdl address.
In my C# application I have simply instantiated the service passed in my api key and can successfully retrieve data.
I am aware that this would of failed if the servers ssl certificate didn't meet the following requirements.

*

*the URL in the certificate matches the URL I'm posting to

*the certificate is valid and trusted

*the certificate has not expired

However, is this secure enough? Is it possible for the ssl certificate to be hijacked or faked? Do I need to store a copy of the valid certificate locally and check the server certificate against the local copy?
Thanks
Ant


Q: UWP SerialDevice works only if I read it's properties So, I have some code for setting up my serial port in UWP (which is used with an USB-to-Serial adapter):
public async Task Init()
{
        string qFilter = SerialDevice.GetDeviceSelector("COM5");
        DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);
        deviceId = devices.First().Id;
        var serialPort = await SerialDevice.FromIdAsync(deviceId);

        serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
        serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
        serialPort.BaudRate = 4800;
        serialPort.Parity = SerialParity.None;
        serialPort.StopBits = SerialStopBitCount.One;
        serialPort.DataBits = 8;
        serialPort.Handshake = SerialHandshake.None;
}

now, somewhere later in the code, I read a stream from the SerialDevice:
public async Task<string> ReadValueFromSerial()
{
        var dataReaderObject = new DataReader(serialPort.InputStream);
        uint ReadBufferLength = 1024;
        dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;

        CancellationTokenSource cts = new CancellationTokenSource();
        //set timeout here.
        cts.CancelAfter(10000);
        var bytesRead = await dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cts.Token);
        (...)
}

no above code hangs on the last line, altough I know, that the serial device is sending bytes to the serial port.
Funny thing is, that it works, when I put a breakpoint on the set-up part (the first snippet). But without a breakpoint and stepping through it, it just hangs, or times out.
By trials and errors I found out, that reading the serial device properties which I set in the set-up code, makes it magically work.
So after the code in the first snippet, I have added:
public async Task Init()
{
         (...)
         var s1 = " " + serialPort.BaudRate;
         var s2 = " " + serialPort.DataBits;
         var s3 = " " + serialPort.Parity.ToString();
}

And now the var bytesRead = await dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cts.Token); doesn't hang anymore and the bytes are loaded. It works, which is great, but why?


Q: Is it necessary to build another project to fit mobile devices when using reactjs plus redux? As a simple project, we built the website using reactjs+redux. But now, business grows, we need to build the native apps to fit mobile devices, not only the mobile browser.
I did some read work about React Native, it seems not possible to use current JS code directly to build native apps for mobile.
Some of my colleague suggested to build another project for the mobile. But I'm wandering, how could the JS technique show its power to do fast iteration if I have to build another project just to do the same thing on the mobile.
I know Cordova and did some work on it, but not very much.
So, is there some guideline of integrating current JS code to Cordova?
or is there any suggestion?
Thanks.


Q: Updating displayed results after modifying Firestore doc React Native I have a list of games that I'm able to add to without issue using UseEffect and onSnapshot. I can modify an item in the list without issue, and return one set of results (with the updated data properly displaying). When I try to modify another item (or the item same again), I get this error:
Could not update game: TypeError: undefined is not an object (evaluating '_doc.data().numPlayers') because the results/list of games are null. I'm sure I have something wrong with my code, but I can't figure it out.
Thanks in advance!
Here is my code:
useEffect(() => {
      setIsLoading(true)
      let results = [];
      const unsubscribe = db
        .collection('games')
        .onSnapshot(
          (querySnapshot) => {
            querySnapshot.docChanges().forEach(change => {
              const id = change.doc.id;

              if (change.type === 'added') {
                const gameData = change.doc.data();
                gameData.id = id;
                results.push(gameData);
              }
              if (change.type === 'modified') {
                console.log('Modified game: ', id);
                results = results.map(game => {
                  if (game.id === id) {
                    return change.doc.data()
                  }
                  return game
                })
                console.log(results)
              }
              if (change.type === 'removed') {
                console.log('Removed game: ', id);
              }

          });
          setIsLoading(false);
          setGame(results);
          return () => unsubscribe
        },
        (err) => {
          setIsLoading(false);
          console.log("Data could not be fetched", err);
        }
      );
    }, []);

A: I forgot to add the doc ID to the gameData before adding it to the results. I did that in the "added" section, but not in the "modified" section (thinking that it was already included), forgetting that I hadn't added it as an actual field in the database (it just exists as the doc id).


Q: How to make HTML element square I would like to have square tiles in my react calendar. Currently width is calculated based on width of the whole calendar and I would like my height to be the same.

Html
<button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="flex: 0 0 14.2857%; overflow: hidden;">
    14
</button>

I have tried this
.booking-calendar .react-calendar__tile {
    flex: 0 0 14.2857%;
    overflow: hidden;
}
.booking-calendar .react-calendar__tile--active abbr {
    outline: 2px solid #444444;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    border-radius: 40px;
    font-weight: 700;
}

.booking-calendar .react-calendar__month-view__days__day abbr {
    padding: 10px;
    border-radius: 40px;
    display: inline-block;
    vertical-align: middle;
}

A: You can use the aspect-ration css property
https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

.booking-calendar  {
    width: 400px;
    display: flex;
}

.booking-calendar .react-calendar__tile {
    width: 100%;
    aspect-ratio: 1 / 1;
    margin: 10px;
}

.booking-calendar .react-calendar__tile--active abbr {
    outline: 2px solid #444444;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    border-radius: 40px;
    font-weight: 700;
}

.booking-calendar .react-calendar__month-view__days__day abbr {
    padding: 10px;
    border-radius: 40px;
    display: flex;
    justify-content: center;
    align-items: center;

}

     <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    11
</button>
  <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    12
</button>
  <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    13
</button>
  <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    14
</button>

You will need to remove the flex inline style that collides with the aspect-ratio effect.


Q: ngcsv - Trouble in safari and IE Browsers I am using Angular js to load table in my page. Now i want to export the data to excel. For that i find a solution of using ngcsv. It is mentioned as it can easily convert json array to .csv file. I tried with that and got succeeded in Firefox and Chrome Browser. But in safari and IE it is not working.
  I tried the following fiddler example given in internet
`http://jsfiddle.net/asafdav/dR6Nb/`

It is also not working in Safari and IE. Is there any work around for this?

A: No, there is no workaround as such, unless you decide to write your own library.
On the github page of ng-csv : https://github.com/asafdav/ng-csv
It is clearly stated that Safari is not supported and only IE 10+ are supported.


Q: Reverse order of glDatePicker selectable date range Specs changed apparently and I can't get my head around why this won't work. I have a form with a #StartDate and #EndDate fields

        Start Date
        <input type="text" id="StartDate" name="StartDate">

        End Date
        <input type="text" id="EndDate" name="EndDate">
        <input type="submit" id="Button6" value="foo" />

        <input type="checkbox" name="AllDates" id="AllDates" value="YES">All Dates

Previously when the date range was from today - forward this worked:
$("#bottomContent").on('focus', "#StartDate", function(){
    var today = new Date();
    var datelimit = new Date(today);
    datelimit.setDate(today.getDate() + 31);

    $(this).glDatePicker({
        showAlways: false,
        allowMonthSelect: true,
        allowYearSelect: true,
        prevArrow:'<',
        nextArrow:'>',
        selectedDate:today,
        selectableDateRange: [{
            from: today,
            to: datelimit
        }, ],
        onClick: function (target, cell, date, data) {
            target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
            $('#AllDates').prop('checked', false);
            if (data != null) {
                alert(data.message + '\n' + date);
            }
        }
}).glDatePicker(true);

var to = $('#EndDate').glDatePicker({
    showAlways: false,
    onClick: function (target, cell, date, data) {
        target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
        $('#AllDates').prop('checked', false);
        if (data != null) {
            alert(data.message + '\n' + date);
        }
    }
}).glDatePicker(true);
$("#bottomContent").on('focus', "#EndDate", function(){
    var dateFrom = new Date($("#StartDate").val());
    var toLimit = new Date();
    toLimit.setDate(dateFrom.getDate() + 31);
    to.options.selectableDateRange = [{
    from: dateFrom,
    to: toLimit
}, ],
    to.options.showAlways = false;
    to.render();
});});

I need to make it start from today = newDate() and have it go BACKWARDS (-365 days), but simply switching all the "+ 31" which makes it go forward a month to "- 365" is not working, any ideas?

A: This did it, if anyone ever runs across the same problem.
$("#bottomContent").on('focus', "#StartDate", function(){
var today = new Date("January 1, 2013");
var datelimit = new Date();
datelimit.setDate(today.getDate() +14);

$(this).glDatePicker({
    showAlways: false,
    allowMonthSelect: true,
    allowYearSelect: true,
    prevArrow:'<',
    nextArrow:'>',
    selectedDate:today,
    selectableDateRange: [{
        from: today,
        to: datelimit
    }, ],
    onClick: function (target, cell, date, data) {
    target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
        $('#AllDates').prop('checked', false);
    if (data != null) {
        alert(data.message + '\n' + date);
    }
}
}).glDatePicker(true);

var to = $('#EndDate').glDatePicker({
    showAlways: false,
    prevArrow:'<',
    nextArrow:'>',
    selectedDate:today,
    onClick: function (target, cell, date, data) {
        target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
        $('#AllDates').prop('checked', false);
        if (data != null) {
            alert(data.message + '\n' + date);
        }
    }
    }).glDatePicker(true);
$("#bottomContent").on('focus', "#EndDate", function(){

var dateFrom = new Date($("#StartDate").val());
var toLimit = new Date();
//toLimit.setDate(dateFrom.getDate());
to.options.selectableDateRange = [{
    from: dateFrom,
    to: toLimit
}, ],
to.options.showAlways = false;
to.render();
});
});


Q: Matlab face alignment code I am attempting to do some face recognition and hallucination experiments and in order to get the best results, I first need to ensure all the facial images are aligned. I am using several thousand images for experimenting.
I have been scouring the Internet for past few days and have found many different programs which claim to do so, however due to Matlabs poor backwards compatibility, many of the programs no longer work. I have tried several different programs which don't run as they are calling onto Matlab functions which have since been removed.
The closest I found was using the SIFT algorithm, code found here
http://people.csail.mit.edu/celiu/ECCV2008/
Which does help align the images, but unfortunately it also downsamples the image, so the result ends up quite blurry looking which would have a negative effect on any experiments  I ran.
Does anyone have any Matlab code samples or be able to point me in the right direction to code that actually aligns faces in a database.
Any help would be much appreciated.

A: You can find this recent work on Face Detection, Pose Estimation and Landmark Localization in the Wild. It has a working Matlab implementation and it is quite a good method.
Once you identify keypoints on all your faces you can morph them into a single reference and work from there.

A: The easiest way it with PCA and the eigen vector. To found X and Y most representative data. So you'll get the direction of the face.
You can found explication in this document : PCA Aligment

A: Do you need to detect the faces first, or are they already cropped?  If you need to detect the faces, you can use vision.CascadeObjectDetector object in the Computer Vision System Toolbox.
To align the faces you can try the imregister function in the Image Processing Toolbox.  Alternatively, you can use a feature-based approach.  The Computer Vision System Toolbox includes a number of interest point detectors, feature descriptors, and a matchFeatures function to match the descriptors between a pair of images.  You can then use the estimateGeometricTransform function to estimate an affine or even a projective transformation between two images. See this example for details.


Q: How to sed output of a command and not supress output I have the example text stored in test.sh:
echo 'Hello world 123'
echo 'some other text'

With the following command in a bash script:
word123=$(./test.sh |sed -nr 's/Hello world (.*)/\1/p' )
This works correctly and outputs:
123
However, this does output
Hello world 123
some other text

Is there a way to capture the text in 123 and also output everything else in the file?

A: With Linux, bash and tee:
word123=$( ./test.sh | tee >&255 >(sed -nr 's/Hello world (.*)/\1/p') )

File descriptor 255 is a non-redirected copy of stdout.
See: What is the use of file descriptor 255 in bash process


Q: multiple dex files define landroid/support/annotation/AnimRes The moment I added the android support annotations to my dependencies
compile 'com.android.support:support-annotations:20.0.0'
I got this error:

Error Code:
      2   Output:
      UNEXPECTED TOP-LEVEL EXCEPTION:
      com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;
          at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
          at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
          at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
          at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
          at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
          at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
          at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
          at com.android.dx.command.dexer.Main.run(Main.java:230)
          at com.android.dx.command.dexer.Main.main(Main.java:199)
          at com.android.dx.command.Main.main(Main.java:103)

build.gradle
android {
    compileSdkVersion 19
    buildToolsVersion '20.0.0'

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 19
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.0.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'com.android.support:support-annotations:20.0.0'
}

Anybody else experienced this issue? I have tried the solutions from here.

A: The problem is that android-support-annotations.jar used to be a separate library containing the android annotations, but for some reason these annotations are already included in recent versions of the android-support-v4.jar file.
Deleting the annotations jar solved the issue.

A: Solved this exact issue in a Cordova project that used the facebook plugin.  I was able to successfully build by commenting out this line from platforms\android\project.properties, as shown:
# cordova.system.library.1=com.android.support:support-v4:+

And by commenting out this line from platforms\android\build.gradle, as shown:
// compile "com.android.support:support-v4:+"

Then doing the build.  The problem started when I installed (katzer/cordova-plugin-local-notifications) which added these lines, but it created a conflict since the library it was adding to the build was already part of the facebook plugin build.

A: Build->clean Project ,and it worked

A: As other users said, the first elements to troubleshoot are dependencies. Although, sometimes you can struggle for hours and you don't find any problem so you can focus on the build process instead.
Changing the way in which the .dex files are produced sometimes solves the problem. You can go through these steps:

*

*Open your Build.gradle (app)  file

*Search for the task dexOptions

*Change it to:
dexOptions {
  incremental false
}

If you don't find the task in your file then you can add it.

A: I deleted the android-support-v4.jar and it worked.

A: For me the reason was the new data-binding lib
com.android.databinding:dataBinder:1.0-rc2

it somehow used a conflicting version of the annotations lib, which I could not force with
configurations.all {
    resolutionStrategy {
        force group: 'com.android.support', name: 'support-v4', version: '23.1.0'
        force group: 'com.android.support', name: 'appcompat-v7', version: '23.1.0'
        force group: 'com.android.support', name: 'support-annotations', version: '23.1.0'
    }
}

but the new rc3 and rc4 versions seem to have fixed it, so just use those versions

A: I had the same problem , but i deleted build files from the build folder
projectname/app/build
and it removed all the related error. "can't clean the project" and also "dex errow with $anim"

A: If this is cordova / ionic project this worked for me
add these line to build.gradle under platforms/android after line number 22 i.e after apply plugin: 'android'
configurations {
   all*.exclude group: 'com.android.support', module: 'support-v4'
}

A: I managed to fix this issue. The reason was that I included the android support library 19.0.0 as a dependency, but 19.1.0 is required. See here for more information
So it has to be
dependencies {
    compile 'com.android.support:support-v4:19.1.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'com.android.support:support-annotations:20.0.0'
}

A: If you import AppCompat as a library project and you also have android-support-annotations.jar in libs elsewhere, make sure to import everywhere AppCompat library only (it already includes this annotations lib). Then delete all android-support-annotations.jar to avoid merging multiple versions of this library.

A: Updating Android SDK Tools fixed it for me, now it just sees the copy in android-support-v4.jar.
I had the same problem when using ant, and the annotations library was being included automatically by an outdated sdk.dir/tools/ant/build.xml.

A: Clean project works as a temporary fix, but the issue will reappear on next compilation error.
To fix more reliably, I had to update the dependency to android support-v4 to com.android.support:support-v4:22.2.0.

A: Put in your build.gradle the dependency of support-annotations according with your compileSdkVersion. For instance: A project with the compileSdkVersion 25 you can put the following dependence:
compile 'com.android.support:support-annotations:25.0.1'

This will solve your problem.

A: In my case I had a file called cache.xml under /build/intermediates/dex-cache/cache.xml in the root project folder. I deleted this file, rebuild the project and it worked for me.

A: I deleted the android-support-v4.jar and it worked.
Explain - android-support-v4.jar is conflicting with my other .jar files of project\libs files ** specially when you are running with java 8 on AS.

A: Put android-support-v4.jar in your libs folder in eclipse. Clean and build the project. It will resolve the issue.

A: Another reason that messages such as these can come up in Android Studio when building and launching can be the cause of application tags in your libraries.
If you have several Android Library projects that you imported as modules.  Go into those projects and remove the <application> ... </application> tags and everything between them.  These can cause issues in the build process along with the support library issues already mentioned.

A: From /platforms/android/libs/
delete android-support-v4.jar.
It works for me.


Q: xcode 7.2.1+ os 10.11.9 + opencv3.1.0 Undefined symbols for architecture x86_64? I have a cpp file which works fine with g++ before upgrading these stuff.
Currently, when running : g++ -I/usr/local/Cellar/opencv3/3.1.0_1/include  -stdlib=libc++  bs.cpp -o bs
Results are following:
Undefined symbols for architecture x86_64:
"cv::namedWindow(cv::String const&, int)", referenced from:
  _main in bs-df9f1a.o
"cv::VideoCapture::read(cv::_OutputArray const&)", referenced from:
  processVideo(char*) in bs-df9f1a.o
"cv::VideoCapture::release()", referenced from:
  processVideo(char*) in bs-df9f1a.o
"cv::VideoCapture::VideoCapture(cv::String const&)", referenced from:
  processVideo(char*) in bs-df9f1a.o
"cv::VideoCapture::~VideoCapture()", referenced from:
  processVideo(char*) in bs-df9f1a.o
"cv::destroyAllWindows()", referenced from:
  _main in bs-df9f1a.o
"cv::createBackgroundSubtractorMOG2(int, double, bool)", referenced from:
  _main in bs-df9f1a.o
"cv::Mat::deallocate()", referenced from:
  cv::Mat::release() in bs-df9f1a.o
"cv::Mat::copySize(cv::Mat const&)", referenced from:
  cv::Mat::operator=(cv::Mat const&) in bs-df9f1a.o
"cv::String::deallocate()", referenced from:
  cv::String::~String() in bs-df9f1a.o
"cv::String::allocate(unsigned long)", referenced from:
  cv::String::String(char const*) in bs-df9f1a.o
  cv::String::String(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in bs-df9f1a.o
"cv::imread(cv::String const&, int)", referenced from:
  processImages(char*) in bs-df9f1a.o
"cv::imshow(cv::String const&, cv::_InputArray const&)", referenced from:
  processVideo(char*) in bs-df9f1a.o
  processImages(char*) in bs-df9f1a.o
"cv::putText(cv::_InputOutputArray const&, cv::String const&, cv::Point_<int>, int, double, cv::Scalar_<double>, int, int, bool)", referenced from:
  processVideo(char*) in bs-df9f1a.o
  processImages(char*) in bs-df9f1a.o
"cv::waitKey(int)", referenced from:
  processVideo(char*) in bs-df9f1a.o
  processImages(char*) in bs-df9f1a.o
"cv::fastFree(void*)", referenced from:
  cv::Mat::~Mat() in bs-df9f1a.o
"cv::rectangle(cv::_InputOutputArray const&, cv::Point_<int>, cv::Point_<int>, cv::Scalar_<double> const&, int, int, int)", referenced from:
  processVideo(char*) in bs-df9f1a.o
  processImages(char*) in bs-df9f1a.o
"cv::VideoCapture::get(int) const", referenced from:
  processVideo(char*) in bs-df9f1a.o
"cv::VideoCapture::isOpened() const", referenced from:
  processVideo(char*) in bs-df9f1a.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I do not know how to solve this problem, it's not related to source code or include, it's related to the linker. I see the post:C++ linking error after upgrading to Mac OS X 10.9 / Xcode 5.0.1
Which really sounds reasonable, but I do not know how to add -stdlib=libstdc++ to the linking command. ?
Hope sb could help. Thanks in advance.


Q: C# Method overloading is calling the wrong method when using string args I'm trying to make a log plugin for myself and I want to have a method where I overload it with different parameters.
The key is, it needs to be possible to add multiple strings, which I will print on different lines. I like the idea of using params, that way I don't need to add string[] { strings here } everytime.
The issue I currently have is that the Log.L() method will not trigger the first, but the second method, which kinda makes sense.
How can I solve this issue, while keeping the params?
Log.L("line1", "line2", "line3");

public static class Log
{
   public static void L(params string[] message)
   {
       Write(LogType.Log, message);
   }

   public static void L(string location, params string[] message)
   {
       Write(LogType.Log, message, false, location);
   }
}

A: It will always assume that the first string is location so, just use the second overload:
public static void L(string location, params string[] message)
   {
       Write(LogType.Log, message, false, location);
   }

you can simply pass null or empty string when location is not available and deal with it in the method.

A: You can create two classes and use them to differentiate between the two overloads. You can even go so far as having one class inherit from the other if you want.
public class LoginWithMessages {
    public string[] Messages {get; set;}
}

public class LoginWithLocation : LoginWithMessages {
    public string Location {get; set;}
}

Then your method signatures will be:
public static void L(LoginWithMessages loginMessage)

public static void L(LoginWithLocation loginLocation)


Q: Wordpress Custom Post Types add Taxonomies/SubTaxonomies to URL Hi StackOverflow Heroes -
I'm using CPT UI to manage my custom post types (that can change if needed). I'd like to be able to display posts within a custom post type in categories and subcategories in the URL.
Right now, if I create a post in my custom post type and assign it a taxonomy and a category and sub category within that taxonomy - it lists the URL as:
domainname.com/custom_post_type/post

I'm confused as to why it won't show the post like this (Clearly I don't understand custom post types / taxonomies well enough and look to you for some enlightenment):
domainname.com/custom_post_type/taxonomy/subtaxonomy/post

The end result has to be flexible - meaning, sometimes the post will end up in a taxonomy and sometimes in a subtaxonomy.
I would love to use a plugin that just solves it all, but have tried several and they don't seem to work.
Basically, I'd like my custom post types to work just like the built in blog feature seems to work as it does show the correct folder structure when putting posts in to categories/subcategories.
Here's the menu structure I'm trying to achieve (for clarification)
Products(Top level - no page)
-Category(page with content)
--SubCategory(page displaying posts)
---Single Post

Sometimes the structure might need to be like this:
Products(Top level - no page)
-Category(page with content)
--Single Post

I've been working at this for several hours, and searching high and low across the internet to find a solution, but haven't been able to find one that fits. I appreciate your help and suggestions!

A: While you're using CPT UI, I thought use of another plugin to extend the functionality is a better solution in your case.
Use Custom Post Type Permalinks and configure the permalink option as:
/%custom-taxonomy-slug%/%postname%/


Q: Change Firebase Public Facing Name How can I change the public-facing name? Let's say I want to use States as the public name, how can I change ...firebaseapp.com to States here?
Thanks!


Q: Getting the value of first array from the array In php I have an array look like this.
Array ( [0] =>
  [1] => Array ([id] => 9 [slot] => 2 [name] => Test Ad [alt] => Test Ad [dimension_width] => 300 [dimension_height] => 400 [clicks] => 1 [start_date] => 06/07/2013 [end_date] => 07/07/2013 [status] => 1 [target] => http://images.google.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-151553.jpeg [pre_exp_email] => 0 )
  [2] => Array ( [id] => 12 [slot] => 1 [name] => Test Ad [alt] => Test Ad [dimension_width] => 200 [dimension_height] => 300 [clicks] => 0 [start_date] => 06/08/2013 [end_date] => 07/08/2013 [status] => 1 [target] => http://facebook.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-1515532.jpeg [pre_exp_email] => 0 )
  [3] => Array ( [id] => 14 [slot] => 1 [name] => Test Ad [alt] => Test Ad [dimension_width] => 200 [dimension_height] => 300 [clicks] => 0 [start_date] => 06/08/2013 [end_date] => 07/08/2013 [status] => 1 [target] => http://facebook.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-1515532.jpeg [pre_exp_email] => 0 )
   )

From here I want to get the first value of array. For example I want to get the value of first array
[1] => Array ([id] => 9 [slot] => 2 [name] => Test Ad [alt] => Test Ad [dimension_width] => 300 [dimension_height] => 400 [clicks] => 1 [start_date] => 06/07/2013 [end_date] => 07/07/2013 [status] => 1 [target] => http://images.google.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-151553.jpeg [pre_exp_email] => 0 )

So can someone kindly tell me how to get the value of 1st array?Any help and suggestions will be really appreciable. Thanks

A: say all your array was in a variable $myArray, then

myArray[1]

will give you your first array


Q: Django char field with choices list So, I want to implement a char field with choices list. The idea is that it looks like a common char field but when you click on it and start typing something in, a dropdown menu pops up and you can choose something (also it sorts choices depending on what user types in). How do we do that?

A: You probably want something like django-easy-select2 [readthedocs.io]. You can install this (in your local environment) with:
pip3 install django-easy-select2
Next you add 'easy_select2' to the INSTALLED_APPS setting [Django-doc]:
# settings.py

# …

INSTALLED_APPS = [
    # …,
    'easy_select2',
    # …,
]

# …
Now you can make use of the Select2 widget in your Form (or ModelForm):
from easy_select2 import Select2

class MyModelForm(forms.ModelForm):

    # …

    class Meta:
        model = MyModel
        widgets = {
            'my_field': Select2
        }