text:
Q: Snap applications don't show up after re-login using fish shell On Ubuntu 18.04 I've changed my shell to fish via
chsh -s `which fish`

I've installed Maillspring and Visual Studio Code snap apps, they installed fine and could be launched from the dash initially, but after logging in and logging back out none of them showed up in the dash anymore.
Searching for them in software store shows that are installed and I can launch them from there.
Why will the default shell matter for this?

A: The command you had originally in your question chsh -s which bash was as you say a typo which caused a great deal of confusion around your question. Even if it had been properly formed with the ` symbols around which bash as shown below.

it would change the shell to bash (the default). To change the shell to fish use

or simply use the command  chsh and enter the path to the shell you want to use. See below:
me@zippy-64bit:~$ chsh
Password:
Changing the login shell for me
Enter the new value, or press ENTER for the default
    Login Shell [/bin/bash]:

For more information on the fish shell see this.
EDIT: Regarding snap packages: Will the default shell matter? the answer is possibly, as it depends on the assumptions made by and the approach taken by the programmer. Refer to the differences in how bash and how fish handle things in the previous link. For example fish has no implicit subshell which can cause surprising side effects in variable assignment for the programmer that is expecting behavior similar to bash. There's a good example of an expectation of an implicit subshell in the question here.
Why? In an attempt to clarify it appears that the concept of inheritance is handled differently between fish and other more common shells like bash. My understanding is that this can result in unexpected behavior from pipes, loops, and functions (All of which are commonly used programming strategies).
The programmer may also be relying on shell builtins which either may not exist in fish or may be implemented in an unexpected fashion.
Sources:

*

*man chsh

*fish on Wikipedia

*subshells on Unix & Linux

*Related post on SuperUser.com

A: It seems that Ubuntu calls snap apps using the default shell, and it seems to assume that the shell is bash (or compatible with bash, like zsh).
I had the same problem (on Ubuntu 18.10): after chsh -s `which fish` , Gnome Shell was not finding snap apps anymore, even after adding /snap/bin to the $PATH.
I solved it by letting the default shell to Bash, and instead changing the invoked by my terminal application (since I mostly use my shell through my terminal emulator anyway):

*

*open terminal

*go to Preferences, click on your profile then command tab, tick "run a custom command instead of my shell" then in custom command put fish.

*do this for every profile

After that, starting Gnome-Terminal (either from Gnome Shell or with Ctrl+Alt+T) will launch the Fish shell, but the system shell will still be Bash so nothing breaks.
However this means that other applications spawning a user-facing shell (Visual Studio Code for instance) may require customization as well to use Fish instead of Bash.

A: There is a TL;DR at the bottom.
For gnome-shell to be able to start Snaps it needs two things (values in brackets are on my Fedora 29 desktop which has the same problem):

*

*PATH to include Snap (/var/lib/snapd/snap/bin)

*XDG_DATA_DIRS to the Snap Desktop files (/var/lib/snapd/desktop)

These variables are configured in /etc/profile.d/snapd.sh via /etc/profile conventional bash start-up.
When you switch to fish to whole /etc/profile start-up is skipped.
Since most distros assume the usage of bash and install configuration scripts into /etc/profile.d, simply chsh -s /bin/fish will not use them.  Snaps not being found by gnome-shell is one such symptom.
The best solution I have so far is to use fish only an interactive shell and leave bash in place to do the other housekeeping.
TL;DR
Leave the user default shell as bash:
chsh -s /bin/bash

Within ~/.bashrc have the following:
# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

if [ -z "$BASH_EXECUTION_STRING" ]; then
    exec /bin/fish
fi

For the bash --login case (as invoked via X11/Wayland) remove ~/.profile and add .bash_profile (make it bash specific):
# we want to run fish most of the time, but this is invoked by bash --login
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

A: add this to your ~/.config/fish/config.fish file
for file in /etc/profile.d/*.sh
        bass source $file
end

install bass using fisher:
fisher add edc/bass

or install bass using omf:
omf install bass

reload your session, and all should be working now :)

A: The snaps that you have installed, can be found in /snap/bin/
You need to have that directory in your $PATH.
Ubuntu automatically adds /snap/bin to your $PATH.
It happens in /etc/profile.d/apps-bin-path.sh which runs when you get a login shell.
I checked, and fish also adds /snap/bin into $PATH so normally it should be fine.
Can you show us the output of the command
echo $PATH

If the output has /snap/bin, then congratulations you have found a bug in Ubuntu and you can file a report on Launchpad for it.
addition: Ubuntu internally probably uses $SHELL for some of the scripting. The fish shell is not 100% compatible with bash and it looks like this is the cause of the problem. It is a common issue when you change your login shell to something other than bash. See, for example, this report https://youtrack.jetbrains.com/issue/CPP-2919 with users changing their shell to /bin/tcsh.
You need to file a bug report to Ubuntu so that someone investigates and fixes the internal scripting to work with fish. If you really love fish, that's what you need to do. ;-)


text:
Q: Javascript/Ajax/Jquery Dynamically calculate form on change I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based on the other ones.
Example:
Total Parts (Mysql)
Labor (User)
Misc (User)
Sub Total (Dynamic total of above)
Tax (Dynamic calc of above - sub * 13%)
Total (Sub + Tax)
I have searched around but can not quite find what I am looking for, and my skills are zero in Javascript/Ajax/Jquery so I haven't been able to modify anything to work, although I have tried miserably.
Can someone help me out on this or point me to a script that may suit my needs.
Thanks

A: Alright sorry, I thought you were looking for some complex code. Here is a simple example of exactly what you're looking for.

Total Parts: <input type="text" id="parts_input" value="1" readonly="true" />

Labor: <input type="text" id="labor_input" onBlur="doMath();" />

Misc: <input type="text" id="misc_input" onBlur="doMath();" />

Sub Total: <input type="text" id="subtotal_input" readonly="true" />

Tax: <input type="text" id="tax_input" readonly="true" />

Total: <input type="text" id="total_input" readonly="true" />

Obviously this doesn't grab the dynamic value from a database. If you use PHP you can swap this line:

Total Parts: <input type="text" id="parts_input" value="1" readonly="true" />

for one like this:

Total Parts: <input type="text" id="parts_input" value="<?PHP include('getTotalParts.php'); ?>" readonly="true" />

Where the getTotalParts.php is a file you make to get your database information. It can simply grab the information and do a "echo $totalParts;"

A: You can just use onblur (activated when a user leaves each of the input fields) to calcuate the fields.
...<input name="labour" id=total onblur="$('#total').val($('#sub').val() + $('#tax').va())">

You haven't provided enough information to comment on the "Total Parts" field.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection between the Gamma function and gamma distribution The Gamma function is a generalization of the factorial ($\Gamma(n)=(n-1)!$). It is also the normalizing constant for the Gamma distribution and this happens to be (when its rate parameter is $1$) the time of the $n$-th event in a standard Poisson process (with rate $1$). Is there any connection between these two facts? Perhaps relating to the fact that if we switched the order of the events in the Poisson process, the time until the $n$-th event wouldn't change?

A: Sure. Call $T_n$ the time of the $n^{th}$ jump of a rate $1$ Poisson process, which we will call $N(t)$. By independence of the exponentials (or the Markov property), we have
$$\mathbb{P}(T_{n+1} \in (t,t+\delta)) =\mathbb{P}(N(t) = n, T_{n+1} \in (t,t+\delta)) + O(\delta^2)$$.
By the memoryless property of the exponential (or the Markov property of the Poisson process),
$$\mathbb{P}(N(t) = n, T_{n+1} \in (t,t+\delta)) = \frac{t^n}{n!}e^{-t}(1-e^{-\delta})$$.
Divide by $\delta$ and send $\delta \to 0$ to obtain that the density of $T_{n+1}$ is $\frac{t^n e^{-t}}{n!}1_{\{t>0\}}$. It then follows from the fact that this is a density function that $\int_0^\infty t^n e^{-t} dt = n!.$
Your question then boils down to why is it the case that the mass function of a rate 1 Poisson process is $\mathbb{P}(N(t)=n) = \frac{t^n}{n!}e^{-t}$. One way to derive this is to subdivide $[0,t]$ into $M$ intervals of length $\frac{t}{M}$. Assign to each interval a Bernoulli random variable which is equal to $1$ if there is a jump of the Poisson process in that interval and then sum these Bernoullis. By independence of the exponentials, the Bernoullis are independent. There is a finite $M$ after which the sum has stabilized to be equal to the Poisson, so we have a.s. convergence, which implies convergence in distribution. Because an interval of length $\frac{t}{M}$ is very unlikely to have more than one jump in it, the success probability of each Bernoulli is $\frac{t}{M} + O(\frac{1}{M^2})$. The sum is then approximately distributed as Binomial(M,$\frac{t}{M}$). An elementary computation which you may know as the law of rare events then shows that the pmf of $N(t)$ is as described. In this interpretation, the factorial can be seen to come from the permutation invariance of the locations of the jumps.


text:
Q: How to copy a folder into another folder in python copy_tree copies the files and folders under src to dst, it's same as cp -r a/b/* x/y/ in shell
$ tree
.
|__a
|  |__b
|     |__ab.txt
|__x
   |__y

>>> from distutils.dir_util import copy_tree
>>> copy_tree('a/b','x/y')
['x/y/aa.txt']
>>>

How to make it copy the folder b as is? like doing cp -r a/b x/y/
I need to copy b into x/y, so it becomes x/y/b

A: Try to use shutil library.
import shutil
shutil.copytree('a/b','x/y/b')
# Returns 'x/y/b'

See the doc for more info.

A: You can always use os.system to use shell commands. It comes handy when you don't know pythonic way but you know bash way. I use it this way.
import os
os.system("<command that you want to run in shell>")

In this case, you need
import os
os.system("cp -r a/b x/y/")


text:
Q: Why is gpg failing when I have installed pinentry? Despite me installing pinentry, I still get the following error:
xxxxxxxMacxxxxx:~ MAU$ gpg2 -c --cipher-algo=aes
gpg-agent[89931]: can't connect to the PIN entry module: IPC connect call failed
gpg-agent[89931]: command get_passphrase failed: No pinentry
gpg: problem with the agent: No pinentry
gpg: error creating passphrase: Operation cancelled
gpg: symmetric encryption of `[stdin]' failed: Operation cancelled

A: It was actually a gpg-agent.conf file left over from when I had mac GPG installed. Oh yeah and here's a test of gpg's symmetric encryption function (the password is stackexchange (all lowercase) btw.):
-----BEGIN PGP MESSAGE-----
Version: GnuPG v2.0.20 (Darwin)

jA0ECgMC77crPqRqPGLE0pgB6nSD00hMogXLXJ1V2HlCzkFxbJlB7ZOo1HlsHENJ
xDuccBNqlxvSEqZuege04dehYOfKPe3jQEODaywH2sQS9VNR04Wvjeek9lyGHh0A
sWdiUcW1x884oZG0yOdpLXvY8t+Tzc0tWH0amyZACQ5KsX34L2cNsvbGwDejYp0d
C31gNu4lVAH+4EZe3rnY5YImCZNlQM2/CQ==
=z3bc
-----END PGP MESSAGE-----

A: When pinentry dies you need to relaunch it from wherever its launch on start instructions get installed to (I'm pretty sure it's somewhere in /System/Library/, but that doesn't really narrow it down).  It's possible that "kill -HUP $PID" on the process ID of gpg-agent might kick it into gear too.
Alternatively GPG 1.4.x can exist alongside GPG 2.0.x and is usually compiled without gpg-agent.  So it will keep working.  I recommend recompiling from source with the current version, though.  That's how I've avoided all the pain from gpg-agent.


text:
Q: Rails 5 app deployed to heroku does not behave properly on mobile, but behaves properly with inspect on dev tools I have a rails 5 app, which has a collapsible navbar for mobile, and collapsible nav sidebar. When I simulate a mobile environment by running heroku local and then inspect on chrome dev tools, it behaves properly: the navbar collapses to a small icon in the upper right corner, and the side bar collapses to a small icon on the left side of the screen, which is placed with css. However, when I open the app on my actual phone (an iphone 6), the navbar icon is in the wrong place (it has moved down a "row," where the navbar brand is on the left, and the collapse button is beneath it to the right, instead of parallel to it on the right), and the sidebar button does nothing when I press it.
Chrome dev tools do not show any errors.
I'm honestly not sure what the problem is - I figured it was some sort of asset-pipeline-precompile error, and I spent a while trying to get that to work, but precompiling assets both locally and remotely on heroku had no effect.
Any idea what could be wrong?
Here are some code files while may be of help:
app/views/layouts/application.html.erb:
<!DOCTYPE html>

        <title>TheLeagueBuilders</title>
        <%= csrf_meta_tags %>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
        <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

            <%= render 'layouts/sidebar' %>

            <%= render 'layouts/navigationBar' %>

<%= notice %>

<%= alert %>

            <%= yield %>

app/assets/stylesheets/application.scss:
@import "welcome";
@import "font-awesome";
@import "bootstrap";

/*Font awesome icon*/
i {
    padding-top: 308px;
    z-index: 1001;
    position: fixed;
}

config/environments/production.rb:
Rails.application.configure do

  config.cache_classes = true
  config.eager_load = true
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  config.log_level = :debug

  # Prepend all log lines with the following tags.
  config.log_tags = [ :request_id ]

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Use a real queuing backend for Active Job (and separate queues per environment)
  # config.active_job.queue_adapter     = :resque
  # config.active_job.queue_name_prefix = "TheLeagueBuilders_#{Rails.env}"
  config.action_mailer.perform_caching = false

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Use a different logger for distributed setups.
  # require 'syslog/logger'
  # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new(STDOUT)
    logger.formatter = config.log_formatter
    config.logger = ActiveSupport::TaggedLogging.new(logger)
  end

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

  # Emailing
  config.action_mailer.default_url_options = { :host => 'fierce-woodland-66524.herokuapp.com' }

  #These settings are for the sending out email for active admin and consequently the   devise mailer
  config.action_mailer.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    :address => 'smtp.sendgrid.net',
    :port => '587',
    :authentication => :plain,
    :user_name => ENV["SENDGRID_USERNAME"],
    :password => ENV["SENDGRID_PASSWORD"],
    :domain => 'heroku.com',
    :enable_starttls_auto => true
  }
end

And the some of the sidebar code:

    <% if user_signed_in? %>

                    .............

    <% end %>

Any help would be truly truly appreciated. Thank you!


text:
Q: How can i add cover image on mp3 file using ffmpeg? I'm trying to convert audio file to mp3 and I want to add cover image into mp3 file.
I tried this:
ffmpeg.exe -i "input audio file" -i image.png out.mp3

When conversion completes there is no cover image into mp3.
I tried and this which is from the official documentation of ffmpeg. The result is the same mp3 file without cover image.
ffmpeg -i input.mp3 -i cover.png -c copy -metadata:s:v title="Album cover"-metadata:s:v comment="Cover (Front)" out.mp3

Thank you in advance!


text:
Q: Timer job removing web part after 5 minutes I have 3 lists on my home page.

*

*News

*Events

*Alerts

I have 2 sites

*

*English(Master site)

*Arabic

I have added News, Events and Alerts web parts on English home page. News and Events are displaying fine but there is problem with Alerts.
After every 5 minutes, when I refresh page, SharePoint removes it from home page. Looks like some timer job which updates/propagates pages between variations is doing this but I don't know why!
So let's say if I add Alerts on English home page and after 5 minutes if I refresh page, it is gone. Then I have to add it again and after 5 minutes it's gone again.
What's going on?

A: If I remember correct, when using variation sites SharePoint sync the sites so they are identical. If something is missing in one variation site it will be removed from all variation sites.
If you have webparts which should only be available for one language group, try and see if you can use audience instead.


text:
Q: Is it possible to setup Ubuntu Minimal on a device without Ethernet? I have a Chromebook that I would like to install Ubuntu on. I previously had GalliumOS on it, but for several reasons, I choose not to use it. I then installed full Ubuntu on the laptop, leaving only a little more than a gb of free space left on the device.
I finally decided to install Ubuntu Minimal on the Chromebook. I have had experience with Ubuntu Minimal in the past, but never setting it up. However, my Chromebook does not have an Ethernet port on it. I could not download any utilities to connect to WiFi without WiFi.
My question is: is it possible to setup Ubuntu Minimal only using WiFi. If I can not, is there any good very lightweight replacement distributions you recommend? I have previously looked up this answer and got this result

I am not aware of any method to connect to a WPA network only with terminal commands.

While this seems pretty cut and dried, that post was from 2010. Things may have changed.
I have found several similar questions here, but most of them include installing another program. Which requires internet. Thanks for any feedback.

A: I have tried many distribution on my laptop and I run into the same problem. I really dont like gnome but ubuntu-server doesnt work with wifi install. So I use a regular ubuntu desktop version. dd it to a usb and boot from it. Open a terminal and start type the following. Make sure you change your device. (as yours may not sda)

# create gpt table
sudo fdisk /dev/sda
sudo mkfs.fat -F32 /dev/sda1
sudo mkfs.ext4 /dev/sda2
sudo mkfs.ext4 /dev/sda3

cd /tmp && wget http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.114ubuntu1_all.deb
cd /tmp && dpkg -i debootstrap*.deb

sudo mkdir -p /mnt/usb
sudo mount /dev/sda2 /mnt/usb
sudo mkdir /mnt/usb/boot
sudo mount /dev/sda1 /mnt/usb/boot
sudo debootstrap bionic /mnt/usb http://hk.archive.ubuntu.com/ubuntu/

sudo mount -o bind /dev /mnt/usb/dev
sudo mount -o bind /dev/pts /mnt/usb/dev/pts
sudo mount -t sysfs /sys /mnt/usb/sys
sudo mount -t proc /proc /mnt/usb/proc

sudo cp /etc/apt/sources.list /mnt/usb/etc/apt/
sudo chroot /mnt/usb apt-get update

sudo chroot /mnt/usb apt-get -y install grub-efi-amd64 sudo make git ssh linux-firmware linux-image-generic nano intel-microcode curl software-properties-common unzip network-manager net-tools wpasupplicant

# add your packages here, Install your driver here
# sudo chroot /mnt/usb apt-get -y install papirus-icon-theme cpanminus gexec libcpan-distnameinfo-perl libcpan-meta-check-perl libfile-pushd-perl liblocal-lib-p$
# sudo chroot /mnt/usb apt-get -y install xorg openbox obconf lxterminal conky tint2 feh pcmanfm xarchiver chromium-browser gmrun
# sudo chroot /mnt/usb apt-get -y install viewnior ttf-wqy-microhei
# sudo chroot /mnt/usb apt-get -y install transmission-gtk rar unrar zip evince scrot
# sudo chroot /mnt/usb apt-get -y install alsa-utils pulseaudio bluez

sudo chroot /mnt/usb passwd

sudo echo -e "/dev/sda1  /boot       vfat    umask=0077      0       1" | sudo tee -a /mnt/usb/etc/fstab
sudo echo -e "/dev/sda2 /               ext4    errors=remount-ro 0       1"  | sudo tee -a /mnt/usb/etc/fstab
sudo echo -e "/dev/sda3 /home               ext4    defaults        0       2"  | sudo tee -a /mnt/usb/etc/fstab

sudo chroot /mnt/usb
# Following in chroot environment
apt-get install grub-efi-amd64
grub-mkdevicemap
grub-mkconfig -o /boot/grub/grub.cfg
update-grub
grub-install --target=x86_64-efi  --bootloader-id=grub_uefi --efi-directory=/boot

sudo shutdown -r now

After reboot get online with

nmtui


text:
Q: How can I disable the guest account on OSX Lion? I have 'disabled' the guest account on my macbook pro running Lion via System Preferences > Users & Groups.

However the guest account still seems to appear as an option to login at start up and when switching users.
I have never used the guest account for anything, and I have tried a system restore but the guest user has returned as before. How can I get rid of it?
Thanks.
edit: I also just enabled and disabled the account again - but the guest option still appears at startup offering a safari only restart for a guest user.

A: Check Disable restarting to Safari when screen is locked in System Preferences » Security & Privacy » General. This option controls whether Safari Mode is available when starting the computer. It's not an actual (temporary) user account, so the user accounts preferences aren't having an effect.


text:
Q: Pull GitHub repository using Bazel I need to download an entire GitHub repository using Bazel. Since I'm quite new to this tool I'm not really sure how to achieve that.
My main idea is this:
write a custom repository rule in downloadgithubrepo.bzl (which is located in the project root just like the WORKSPACE file) such as:
def _impl(repository_ctx):
    repository_ctx.download("url_to_zipped_github_repo", output='relative_path_to_output_file')

github = repository_rule(
    implementation = _impl

and in the WORKSPACE file to write something like this:
load("//:downloadgithubrepo.bzl", "github")

and to invoke a build a BUILD file is needed (also located at the project root)
its contents are the following:
cc_library(
    name = "testrun",
    srcs = "main.c",
)

I had to add the main.c file otherwise the build is failing - that is one issue and the real issue is that this does not work, as in the build is passing but the GitHub repository is not downloaded.
Am I on the right path at all?? Has anyone done something like this before?

A: What you're looking might already be implemented in the new_git_repository repository rule, or the git_repository rule if the GitHub project already has Bazel BUILD files wired in.
If the GitHub project does not have BUILD files, a BUILD file is required when using new_git_repository. For example, if you want to depend on a file target (e.g. /foo/bar.txt) or rule target (e.g. a cc_library) in https://github.com/example/repository, and the repository does not have BUILD files, write these lines in your project's WORKSPACE file:
new_git_repository(
    name = "example_repository",
    remote = "https://github.com/example/repository.git",
    build_file_content = """
exports_files(["foo/bar.txt"])

# you can also create targets
cc_library(
    name = "remote_cc_library",
    srcs = ["..."],
    hdrs = ["..."],
)
""",
)

In your BUILD file, reference the external repository's targets using the @ prefix:
cc_library(
    name = "testrun",
    srcs = ["main.c"],
    data = ["@example_repository//:foo/bar.txt"],
    deps = ["@example_repository//:remote_cc_library"],
)

When you run bazel build //:testrun, Bazel will..

*

*Analyze the dependencies of //:testrun, which include the file main.c and targets from the external repository @example_repository.

*Look up the WORKSPACE file for an external repository named example_repository, and finds the new_git_repository declaration.

*Perform a git clone on the remote attribute specified in the example_repository declaration.

*Write a BUILD file containing the build_file_content string at the project root of the cloned repository.

*Analyze the targets @example_repository//:foo/bar.txt and @example_repository//:remote_cc_library

*Build the dependencies, and hands them to your //:testrun cc_library.

*Build //:testrun.

If the GitHub project does have BUILD files, you do not need to provide an BUILD file. You can refer to the targets directly after specifying the WORKSPACE dependency with git_repository:
git_repository(
    name = "example_repository",
    remote = "https://github.com/example/repository.git",
)

For more information, check out Bazel's documentation on External Repositories.


text:
Q: WprdPress Custom Post Type - how to display data on Popup or Sidebar I have a custom post type called "team-member" which is in relationship (using ACF) with another custom post type called "speciality".
I have wrote the code to display team member on the page, team member name and speciality and all works perfect.
All the team members have also own description, so I would like to display the team member title, description and speciality within the Popup.
This is the code I have so far:
$relatedTeamMembers = new WP_Query(array(
    'posts_per_page' => -1,
    'post_type' => 'team-member',
    'orderby' => 'title',
    'order' => 'ASC',
    'meta_query' => array(
    array(
        'key' => 'related_team_group',
        'compare' => 'LIKE',
        'value' => '130'
    )
    )
));

if ($relatedTeamMembers->have_posts()) {
    echo '
';
    echo '
OUR DENTISTS
';
    echo '
';
        while($relatedTeamMembers->have_posts()) {
            $relatedTeamMembers->the_post(); ?>

                    <a href="<?php the_permalink(); ?>" target="_blank">
                        <img class="team-member__image" src="<?php
                            if (has_post_thumbnail()) {
                                the_post_thumbnail_url('teamMemberPortrait');
                                } else {
                                echo get_theme_file_uri('img/placeholder.png');
                        } ?> ">

<?php the_title(); ?>

<?php
                            $specialities = get_field('related_speciality');
                            foreach($specialities as $specialities);
                            echo $specialities->post_title; ?>

        <?php }
    echo '
';
    echo '
';
}
wp_reset_postdata();

So looking at this pice <a href="<?php the_permalink(); ?>" target="_blank"> the target attribute behaves similarly, when the team member card is clicked it loads the data in the new window, I would like the same behaviour but instead the data need to be loaded within the popup.
My popup is done in JS and is using injectHTML() function as below:
injectHTML() {
    document.body.insertAdjacentHTML('beforeend', `

Team Member Details

    `)
}

But it I have no idea how to connect click event on the card member with the team member content.
I would be super grateful for a hint or correct way to achieve this type functionality?

A: bind() can pass event when call injectHTML(). Then in injectHTML(), the member info can pass.
As primary these can be use:

*

*Add EventListener() with  as, document.querySelector("a").addEventListener('click',injectHTML.bind(event));

*Then, parse the required information by event.


text:
Q: Native Camera View in Flutter does not occupy the whole width and height I am trying to integrate CameraX inside my flutter project. I am doing so via platform channels. I don't want to integrate any third party lib.
Here is a screenshot of the camera only occupying one third of the height in Android

Below is my code
class ScanQr extends StatelessWidget {
  const ScanQr({super.key});

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;

    return Scaffold(
      backgroundColor: Colors.teal,
      body: SizedBox(
        height: height,
        width: width,
        child: CealScanQrView(
          width: width,
          height: height,
        ),
      ),
    );
  }
}

class CealScanQrView extends StatelessWidget {
  const CealScanQrView({required this.width, required this.height, super.key});

  final double width;
  final double height;

  @override
  Widget build(BuildContext context) {
    final Map<String, dynamic> creationParams = <String, dynamic>{};

    creationParams["width"] = width;
    creationParams["height"] = height;

    return Platform.isAndroid
        ? AndroidView(
            viewType: cealScanQrView,
            layoutDirection: TextDirection.ltr,
            creationParams: creationParams,
            creationParamsCodec: const StandardMessageCodec(),
          )
        : UiKitView(
            viewType: cealScanQrView,
            layoutDirection: TextDirection.ltr,
            creationParams: creationParams,
            creationParamsCodec: const StandardMessageCodec(),
          );
  }
}

Here is my android code
In MainActivity's configureFlutterEngine method
flutterEngine
            .platformViewsController
            .registry
            .registerViewFactory("cealScanQrView", CealScanQrViewFactory(this))

class CealScanQrView(
    private val context: Context, id: Int, creationParams: Map<String?, Any?>?,
    private val activity: FlutterActivity
) : PlatformView {

    private var mCameraProvider: ProcessCameraProvider? = null
    private var linearLayout: LinearLayout = LinearLayout(context)

    private var preview: PreviewView = PreviewView(context)

    private lateinit var cameraExecutor: ExecutorService
    private lateinit var options: BarcodeScannerOptions
    private lateinit var scanner: BarcodeScanner

    private var analysisUseCase: ImageAnalysis = ImageAnalysis.Builder()
        .build()

    companion object {
        private val REQUEST_CODE_PERMISSIONS = 10
        private val REQUIRED_PERMISSIONS = mutableListOf(Manifest.permission.CAMERA).toTypedArray()
    }

    init {
        val linearLayoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

        linearLayout.layoutParams = linearLayoutParams
        linearLayout.orientation = LinearLayout.VERTICAL

        preview.setBackgroundColor(Color.RED)
        preview.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

        linearLayout.addView(preview)
        linearLayout.layoutParams.width = 400
        linearLayout.layoutParams.height = 400
        setUpCamera()

        preview.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                preview.viewTreeObserver.removeOnGlobalLayoutListener(this)
                preview.layoutParams.height =
                    creationParams?.get("height").toString().toDouble().toInt()
                preview.requestLayout()
            }
        })
    }

    private fun setUpCamera() {
        if (allPermissionsGranted()) {
            startCamera()
        } else {
            ActivityCompat.requestPermissions(
                context as FlutterActivity, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS
            )
        }
        cameraExecutor = Executors.newSingleThreadExecutor()

        options = BarcodeScannerOptions.Builder()
            .setBarcodeFormats(
                Barcode.FORMAT_QR_CODE
            )
            .build()
        scanner = BarcodeScanning.getClient(options)
        analysisUseCase.setAnalyzer(
            // newSingleThreadExecutor() will let us perform analysis on a single worker thread
            Executors.newSingleThreadExecutor()
        ) { imageProxy ->
            processImageProxy(scanner, imageProxy)
        }
    }

    override fun getView(): View {
        return linearLayout
    }

    override fun dispose() {
        cameraExecutor.shutdown()
    }

    @SuppressLint("UnsafeOptInUsageError")
    private fun processImageProxy(
        barcodeScanner: BarcodeScanner,
        imageProxy: ImageProxy
    ) {
        imageProxy.image?.let { image ->
            val inputImage =
                InputImage.fromMediaImage(
                    image,
                    imageProxy.imageInfo.rotationDegrees
                )
            barcodeScanner.process(inputImage)
                .addOnSuccessListener { barcodeList ->
                    val barcode = barcodeList.getOrNull(0)
                    // `rawValue` is the decoded value of the barcode
                    barcode?.rawValue?.let { value ->
                        mCameraProvider?.unbindAll()
                        Toast.makeText(context, value, Toast.LENGTH_LONG).show()
                    }
                }
                .addOnFailureListener {
                    // This failure will happen if the barcode scanning model
                    // fails to download from Google Play Services
                }
                .addOnCompleteListener {
                    // When the image is from CameraX analysis use case, must
                    // call image.close() on received images when finished
                    // using them. Otherwise, new images may not be received
                    // or the camera may stall.
                    imageProxy.image?.close()
                    imageProxy.close()
                }
        }
    }

    private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
        ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
        cameraProviderFuture.addListener({
            // Used to bind the lifecycle of cameras to the lifecycle owner
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            mCameraProvider = cameraProvider
            // Preview
            val surfacePreview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(preview.surfaceProvider)
                }
            // Select back camera as a default
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
            try {
                // Unbind use cases before rebinding
                cameraProvider.unbindAll()
                // Bind use cases to camera
                cameraProvider.bindToLifecycle(
                    activity,
                    cameraSelector,
                    surfacePreview,
                    analysisUseCase,
                )
            } catch (exc: Exception) {
                // Do nothing on exception
            }
        }, ContextCompat.getMainExecutor(context))
    }

}

In AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />

There are two problems which I am facing
Firstly I don't see the camera permission when my screen opens even though I am asking the permission for it. I have to manually go to the settings screen to enable camera permission
And secondly the camera does not occupy entire screen
Even if I set  linearLayout.layoutParams.height = 1000  still the height remains the same. I completely stopped the app and reran multiple times but no effect
Edit
I have created a gist where I have removed linear layout. Check here

A: I observed several things which might cause the behavior of your camera preview:

*

*You didn't specify an aspect ratio for your (Preview- & ImageAnalysis-) Usecases. The default is 4:3. Note that the native aspect ratio of most cameras is indeed 4:3. If you use 16:9 the visible part of your image will be smaller, but it fits better for a common phone. E.g.:

Preview.Builder().setTargetAspectRatio(AspectRatio.RATIO_16_9).build()

*You didn't specify a scale type for your PreviewView. This also might result in image cropping. E.g.:

preview.scaleType = PreviewView.ScaleType.FILL_CENTER

*The Camera orientation doesn't fit to your screen. You should update the targetRotation of your usecases. You can read more on that topic in the CameraX documentation

*You should set the LayoutParams for your LinearLayout to MATCH_PARENT as well. And I also think you could just use a FrameLayout. Also remove the viewTreeObserver.

*You have to listen to the result of the permission request. You have to override the method onRequestPermissionsResult in your Activity. It will receive the result together with the request code you've specified: REQUEST_CODE_PERMISSIONS. However it might be easier to use a newer API for requesting those permissions: registerForPermissionResult. E.g.:
val launcher = (context as ComponentActivity).registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
    if (granted) {
        startCamera()
    }
}
launcher.launch(android.Manifest.permission.CAMERA)

A: 1 Don't occupy the entire screen.
It's very simple you might forget to set the width dynamically on android code because of that what happens is that android code gets only 400 widths and 400 heights (in
lins linearLayout.layoutParams.width = 400
linearLayout.layoutParams.height = 400
) and after the flutter call it receives only this size,
so you must make it in an Adaptive way, see this answer.
2 Don't get permission:
Simply using this package permission_handler will help and automate for you across all devices.
If my answer helped you don't forget to like it.

A: check orientation and set it to portrait
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  runApp(MyApp());
...
}

try weap your display area with
SizedBox.expand(
  child: YOUR DISPLAY AREA,
)

also try
Center(
  child: ,
)


text:
Q: How is this variation of this ladder paradox resolved? I understand the ladder paradox but am confused by a variation of it where an action is taken to trap an object that is Lorentz-contracted.
The same question was asked here, but to the best of my understanding they don't address the actual question asked:
In the ladder and barn paradox what happens if we leave the doors closed?
The original scenario is confusing to me becuase it invokes limitations of object rigidity to explain why the door can't be closed to trap the lorentz-contracted object in the room. Also the answers in that post don't really seem to answer the question.
To avoid running into the same issue with this question I'll construct a new scenario that could be run in an actual laboratory (albeit an extremely sophisticated one), as opposed to requiring The Flash, barns and extremely rigid ladders.
Here is the scenario / experiment:
A rod travels in the direction of its lengthwise axis at relativistic speed. We set up a crystal and project a beam of light through it to create a spectrum of colours, such that the rod will pass through the red light first, and the violet last. Both of the rod and the wall eclipsed by the rod as it passes by measure the light landing on it. The beam is projected in such a way that all colors of the spectrum reach the path of the rod at the same time from the perspective of a stationary observer in the room.
The light is completely orthogonal to the path of the rod.
We project a pulse of light, such that, from the perspective of the room, the light hits the rod and some red and violet light lands on the sensors behind the rod, as it was shortened by Lorentz contraction due to its speed.
The orange, yellow, green and blue light landed on the rod.
From the rod's perspective, the experiment and spectrum were contracted. From the rod's perspective the light hit the rod at some point in time, but the red and violet light couldn't have passed through in front of and behind the rod, since they were too close. If the spectrum lands centered on the rod, then it will have eclipsed the full spectrum of colours.
What will we see when we retrieve the rod and inspect the sensors of both the rod and the sensors in the room? We can't both see the full spectrum landing on the rod and still have light landing on the sensors in the room...

A: I think this answer will disappoint you since it doesn't provide much insight into the other question, but with respect to the rest frame of the rod, the light arrives at an oblique angle due to aberration. The cross-sectional width of the rod along the path of the light is narrower than the light beam, so the red and violet light will make it past. It will then proceed toward the wall, which is rapidly receding behind the rod. (The fact that the light must hit this moving target is one way of seeing that its path must be angled in this frame.)

A: I don't think the answer to your question is any different from the answer to the normal ladder paradox.
Your question says:

"The beam is projected in such a way that all colours of the spectrum
reach the path of the rod at the same time from the perspective of a
stationary observer in the room."

But that doesn't mean that all colours will reach at the same time from the perspective of the rod's frame. The Violet will reach the path of the rod before the rod even reaches that point and the red will reach the path of the rod when the rod has already passed that point.
I have here ignored the fact that the colours won't appear the same to the rod's observer as to the observer in the room.


text:
Q: Print statement in if branch not firing The print() statement on the last line isn't working, and I'm unsure why.
import random
List=[1,2,3,4,5,6,7,8,9,10]
Number=print(random.choice(List))
if Number == [3,4,6,8]:
    print("Random Number Generator")

A: There are two issues with your code:

*

*print() returns None. It does not return its argument. Don't assign the return value of print() to a variable.

*Number is probably meant to be an integer, not a list. Since the types of the variables would be different, this condition will never be true. You want if Number in [3, 4, 6, 8]: instead.

Here's a code snippet fixing both issues:
import random
List=[1,2,3,4,5,6,7,8,9,10]
Number=random.choice(List)
print(Number)
if Number in [3,4,6,8]:
    print("Random Number Generator")


text:
Q: RecyclerView not refreshed automatically with submitList() and LiveData here is the situation:
I have a RecyclerView in a Fragment using DataBinding. Its adapter is a ListAdapter.
class MyFragment : Fragment() {
    override fun onCreateView(...) {
        val binding = // inflate layout with DataBindingUtil

        val myListAdapter = MyListAdapter()
        binding.recyclerView.adapter = myListAdapter

        val myViewModel: MyViewModel by activityViewModels()
        myViewModel.myLiveData.observe(viewLifecycleOwner, Observer {
            println("before submit: ${myListAdapter.currentList}")
            myListAdapter.submitList(it)
            println("after submit: ${myListAdapter.currentList}")
        })

        return binding.root
    }
}

Data to display is represented by a List<Double>. Once set, the list is used to initialize a MutableLiveData as follows:
class MyViewModel : ViewModel() {
    val data = listOf<Double>(/* init with some values */)
    val myLiveData = MutableLiveData(data)

    fun onButtonClicked() {
        update()
        println(myLiveData.value) // LiveData is correctly updated according to data
    }
}

Note: the update() method changes the list's values like: data[0] = someValue. It does not use clear() nor addAll() to update it.

*

*In addition, I override ListAdapter.onCurrentListChanged() only to put a println() inside.

At this point, nothing peculiar. When the fragment is created, the RecyclerView shows the initial list. In Logcat:
I/System.out: before submit: []
I/System.out: onCurrentListChanged: [] -> [4.07, 6.29, 13.85, 17.92, 21.42, 23.47, 1.85]
I/System.out: after submit: [4.07, 6.29, 13.85, 17.92, 21.42, 23.47, 1.85]

For now, when I click on the button, the UI does not refresh because I did not assign a new list but only update the current one. Besides, if I navigate to another fragment then come back, the RecyclerView
is displaying the updated values.
So I add the following at the end of onButtonClicked():
myLiveData.value = myLiveData.value

But this does not work, after clicking on the button the UI is still not updating automatically. Moreover, the Logcat prints only the 'before submit' and 'after submit', with the same ListAdapter.currentList value:
I/System.out: before submit: [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85]
I/System.out: after submit: [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85]

To me, prints should rather look like this:
I/System.out: before submit: [4.07, 6.29, 13.85, 17.92, 21.42, 23.47, 1.85]
I/System.out: onCurrentListChanged: [4.07, 6.29, 13.85, 17.92, 21.42, 23.47, 1.85] -> [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85]
I/System.out: after submit: [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85]

It appears that ListAdapter.currentList has already the updated value even before calling submitList(). I guess this is why the RecyclerView is not refreshed since the submitted list is the same as the current one.
I also tried the following at the end of onButtonClicked() with no success:
//myLiveData.value = myLiveData.value
myLiveData.value = emptyList()
myLiveData.value = data

And this...
//myLiveData.value = myLiveData.value
myLiveData.value = emptyList()
//myLiveData.value = data

... gives me that:
I/System.out: before submit: [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85]
I/System.out: after submit: [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85]
I/System.out: onCurrentListChanged: [4.88, 6.77, 13.85, 17.76, 20.93, 22.69, 1.85] -> []

Now onCurrentListChanged() is called but at the end of the 2 prints instead of in the middle.
Also, ListAdapter.currentList seems to contain values in the 'after submit' prints but is actually empty in the onCurrentListChanged() print. Confusing...
The only way I found to make the RecyclerView refresh is to call notifyDataSetChanged(). But then, there is no benefit to use ListAdapter and its submitList() method.
As a newbie, I may have done something not correctly but I do not know what.
The problem is only about the UI not refreshing. I can see in Locgcat that data is properly updating.
Thanks in advance
EDIT
class MyListAdapter() : ListAdapter<Double, MyViewHolder>(MyDiffCallBack()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        MyViewHolder.from(parent, itemCount)

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) =
        holder.bind(getItem(position))

    override fun onCurrentListChanged(previousList: MutableList<Double>, currentList: MutableList<Double>) {
        super.onCurrentListChanged(previousList, currentList)
        println("onCurrentListChanged: $previousList -> $currentList")
    }
}

class MyViewHolder private constructor(private val binding: MyItemViewBinding) : RecyclerView.ViewHolder(binding.root) {

    fun bind(data: Double) {
        binding.dataTxt.text = data.toString()
    }

    companion object {
        fun from(parent: ViewGroup, itemCount: Int): MyViewHolder {
            val binding = // inflate layout
            binding.root.layoutParams.height = parent.height / itemCount // set the height proportionally
            return MyViewHolder(binding)
        }
    }
}

class MyDiffCallBack : DiffUtil.ItemCallback<Double>() {
    override fun areItemsTheSame(oldItem: Double, newItem: Double): Boolean = oldItem == newItem

    override fun areContentsTheSame(oldItem: Double, newItem: Double): Boolean = oldItem == newItem

}

A: It is a problem related to the difference between shallow and deep copies.
As stated in this article about ListAdapter:

Good to know is that the ListAdapter keeps a reference towards the provided list in submitList(). Always make sure to provide an other list with other item instances. If the references to the items are the same, DiffUtil compares the same items which are always equal, and the RecyclerView will not be updated.


text:
Q: MongoDB Composite Key query with one field unknown I have a database that has a unique combination of two fields (x and i) for every entry. So I have set the _id field to be {_id: {a: x, b: i}}. Now I want to retrieve all values that have a certain value x but that have any value for i.
Example:
  {_id: {a: 1, b: 5}},
  {_id: {a: 1, b: 3}},
  {_id: {a: 2, b: 5}}
  {_id: {a: 3, b: 3}}

Now I want to do something like: db.find({_id: {a: 1, b: { $exists: true}}) or even easier: db.find({_id: {a: 1}) that should return:
  {_id: {a: 1, b: 5}},
  {_id: {a: 1, b: 3}}

Is there any way I could achieve this? Or in other words can you query in any way on this composite primary key? Currently I added the fields to the object itself but this is not really an optimal solution as my data set gets really large.
Edit:
db.someCollection.find({"_id.a": 1, "_id.b": { $exists: true}})

Seems to be a solution, this is however just as slow as adding a as a field (not in the key) to the object. Is there a faster method?

A: Have you tried this?
db.someCollection.find({"_id.a": 1, "_id.b": { $exists: true}})


text:
Q: How to validate captcha on register page using codeigniter? I've tried so many tutorial about validate captcha on codeigniter with suitable for my form, but I still don't understand how to validate which when $word == $this->input->post('captcha') then would be true (validation succeded).
I've a registration controller bellow (controller/Registration.php)
<?php
 defined('BASEPATH') OR exit('No direct script access allowed');

 class Register extends CI_Controller {

     function __construct(){
         parent::__construct();
         $this->load->library(array('form_validation'));
         $this->load->library('image_lib');
         $this->load->helper(array('url','form','captcha'));
         $this->load->model('m_account'); //call model
     }

     public function index() {
         $dat = array(
            'img_path' => './static/',
            'img_url' => 'http://localhost/ks/static/',
            'img_width' =>'150',
            'img_height' =>'50'
            );
         $captcha = create_captcha($dat);
         $this->form_validation->set_rules('username', 'USERNAME','required');
         $this->form_validation->set_rules('email','EMAIL','required|valid_email');
         $this->form_validation->set_rules('password','PASSWORD','required');
         $this->form_validation->set_rules('password_conf','PASSWORD','required|matches[password]');
         $this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha');

         if($this->form_validation->run() == FALSE) {
             $this->load->view('reader');
             $this->load->view('account/register',$captcha);
             $this->load->view('footer');
         }else{

             $data['username'] =    $this->input->post('username');
             $data['email']  =    $this->input->post('email');
             $data['password'] =    md5($this->input->post('password'));

             $this->m_account->daftar($data);

             $pesan['message'] =    "Pendaftaran berhasil anda berhasil silahkan login";
             $this->load->view('reader');
             $this->load->view('account/sukses',$pesan);

             $this->load->view('footer');
             header( "refresh:1;url=login" );
         }
     }
    public function validate_captcha(){
    if($this->input->post('captcha') != $this->$captcha)
    {
        $this->form_validation->set_message('validate_captcha', 'Wrong captcha code');
        return false;
    }else{
        return true;
    }

This is my form registration (views/account/register.php):
<?php
 defined('BASEPATH') OR exit('No direct script access allowed');

Pendaftaran Member Baru

     <?php echo form_open('register');?>

Form Pendaftaran

Username

<input type="text" maxlength="15" id="user" name="username" class="form_input" autocomplete="off" width="50" value="<?php echo set_value('username'); ?>"/>

Email:

<input type="email" maxlength="100" name="email" id="email" class="form_input" autocomplete="off" value="<?php echo set_value('email'); ?>"/>

 <?php echo form_error('email'); ?>

Password:

<input type="password" id="pass" maxlength="15" name="password" class="form_input" autocomplete="off" value="<?php echo set_value('password'); ?>"/>

 <?php echo form_error('password'); ?>

Password Confirm:

<input type="password" id="pass" maxlength="15" name="password_conf" class="form_input" autocomplete="off"  value="<?php echo set_value('password_conf'); ?>"/>

 <?php echo form_error('password_conf'); ?>

    <?php
echo $image;
echo $word;
?>
    Captcha:
      <input id="captcha" name="captcha" type="text" value=""/>

     <input type="submit" name="btnSubmit" value="Daftar" />

     <?php echo form_close();?>

 ?>

A: You should try this captcha. It is popular nowadays. A gift for developers from Google.
Google reCAPTCHA
What is reCAPTCHA?
Easy to add, advanced security
reCAPTCHA is a free service from Google that protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc. More Info here


text:
Q: How split mp3 using Naudio? How can i cut a certain time of mp3 file and convert it to wave with N audio with out save any file in hard disk? (i want result in byte array!)

A: Refer Following Code:
string nMP3Folder = "FOLDER PATH";
string nMP3SourceFilename = "SOURCE MP3 FILENAME";
string nMP3OutputFilename = "YOUR OUTPUT MP3 FILENAME";

using (Mp3FileReader rdr = new Mp3FileReader(nMP3Folder + nMP3SourceFilename))
{
    int count = 1;
    Mp3Frame objmp3Frame = reader.ReadNextFrame();
    System.IO.FileStream _fs = new System.IO.FileStream(nMP3Folder + nMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);

    while (objmp3Frame != null)
    {
        if (count > 500) //retrieve a sample of 500 frames
            return;

        _fs.Write(objmp3Frame.RawData, 0, objmp3Frame.RawData.Length);
        count = count + 1;
        objmp3Frame = rdr.ReadNextFrame();
     }

     _fs.Close();
}

Also refer following question to get more links:
Trim an MP3 Programatically


text:
Q: OverlayFS failing with "Stale NFS file handle" error I have a RootFS that's a read-only SquashFS overlayed with writable storage (ext4, if it matters).
This is generally working but, after a while, one file became unaccessible:
# cat  /etc/init.d/update
[  378.714771] overlayfs: failed to get inode (-151)
[  378.719636] overlayfs: failed to get inode (-151)
cat: can't open '/etc/init.d/update': Stale NFS file handle

It seems error is in the directory entry, since i get errors even with plain ls:
# ls  /etc/init.d/update
[ 1256.618431] overlayfs: failed to get inode (-151)
[ 1256.623489] overlayfs: failed to get inode (-151)
ls: /etc/init.d/update: Stale NFS file handle

This error seems to survive reboot.
This specific file was edited, so I have two versions, one on the "lower" SquashFS and one on the "upper" ext4; both are accessible using the respective mount points: the error seems to come from OverlayFS itself.
I seem unable to clean this error (and I'm scared because this system should go in production 24/7), I already ran fsck -fp on all affected systems (not on SquashFS, of course).
Any hint welcome.
Note: I don't have (and don't need) NFS; I assume they reused this errno (151), but I don't know.
UPDATE: I was able to clear the error by manually deleting the "new" copy of the file from the "upper" directory; subsequent editing of the same file worked as expected.
I'm very scared and I would like to understand what happened (and make sure it won't happen again in "production"!).
UPDATE2: I am using defaults for OverlayFS in my kernel v5.7, should I select more options?
   <*> Overlay filesystem support
   [ ] Overlayfs: turn on redirect directory feature by default
   [*] Overlayfs: follow redirects even if redirects are turned off
   [ ] Overlayfs: turn on inodes index feature by default
   [ ] Overlayfs: turn on metadata only copy up feature by default


text:
Q: ElasticSearch - single hit into multiple buckets Lets say i have a single elasticsearch entry with two date fields - t0 and t1.
lets say those t0 and t1 are "2017-10-18T09:00:00" and "2017-10-18T12:00:00" - as in the same date, different hours (for simplicity's sake)
I would like to perform an aggregation query that will give me a bucket hit in every hour - as in, the hourly range is 09:00-12:00, and i would like to get 3 buckets - one for each hour in the range, with a hit in each - for instance:
if were talking about the same range of 09:00-12:00 then i would want that same entry to be counted in the following buckets:
09:00-10:00
10:00-11:00
11:00-12:00
Is this even possible?
Thanks in advance!

A: I inserted 4 documents with dates as :: 9:00, 10:00, 11:00, 11:30
{
"size": 0,
"aggs" : {
    "buckets" : {
        "date_histogram" : {
            "field" : "date",
            "interval" : "1h",
            "format" : "HH:mm"
        }
    }
}
}

This will return a result as follows.
"aggregations": {
  "buckets": {
     "buckets": [
        {
           "key_as_string": "09:00",
           "key": 1508317200000,
           "doc_count": 1
        },
        {
           "key_as_string": "10:00",
           "key": 1508320800000,
           "doc_count": 1
        },
        {
           "key_as_string": "11:00",
           "key": 1508324400000,
           "doc_count": 2
        }
     ]
  }
  }

I guess this is want you need.


text:
Q: countVectorizer error Found input variables with inconsistent numbers of samples when using in sklearn pipeline I have a dataframe:
df = A  B. Text
     1. 2. 'hello and good morning'
     3. 4. 'I am watching TV'

I want to apply sentence classification pipeline:
text_feats = ['Text']
num_feats = ['A','B']
text_transformer = Pipeline(steps=[
   ('tfidf_vectorizer', TfidfVectorizer())])
numeric_transformer = Pipeline(steps=[
    ('scale', StandardScaler())])
preprocessor = ColumnTransformer(
    transformers=[
        ('text', text_transformer, text_feats),
        ('num', numeric_transformer, num_feats))
clf_pipe =  Pipeline(steps=[('preprocessor', preprocessor),
                   ("model", RandomForestClassifier())])
clf_pipe.fit(df, df[Y_COL])

But I get the following error in the TfIDF vectorizer and in CountVectorizer:
Found input variables with inconsistent numbers of samples: [1, 2]

Any idea what is the problem?


text:
Q: Leetcode210. Why my code is wrong in a particular case? Here is the Question(https://leetcode.com/problems/course-schedule-ii/description/).
And my solution is from the "Introduction to Algorithms".
Use the DFS algorithm. And color the node with white, grey, and black.

*

*mark all the nodes white.

*when a node is discovered, mark grey.

*when a node is finished, mark black.

*when an edge is backward, which means has a grey adjacent node. It has a circle, it should null.

But I pass most of the cases. But some of them are not.
Could Anyone help me out?
The Code:
class Solution {
public:
    enum {WHITE, GRAY, BLACK};

    vector<vector<int>> graph;
    vector<int> colors;
    list<int> topo;

    void add_edge(vector<vector<int>>& graph, pair<int, int>& p) {
        graph[p.second].push_back(p.first);
    }
    bool visit(vector<vector<int>>& graph, int i) {
        if (colors[i] == WHITE) {
            colors[i] = GRAY;
            bool ret = true;

            for (int j = 0; j < graph[i].size(); j++) {
                if (colors[graph[i][j]] == WHITE)
                    ret = ret && visit(graph, graph[i][j]);
                else if (colors[graph[i][j]] == GRAY)
                    ret =  false;
                else
                    ret =  false;

            }

            colors[i] = BLACK;
            topo.push_front(i);
            return ret;
        }

        return true;
    }

    bool dfs(vector<vector<int>>& graph) {
        for (int i = 0; i < graph.size(); i++)
            if (!visit(graph, i))
                return false;
        return true;
    }

public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        graph.resize(numCourses, {});
        colors.resize(numCourses, WHITE);

        for (auto& pre: prerequisites)
            add_edge(graph, pre);

        if (!dfs(graph))
            return {};

        vector<int> ret (topo.begin(),topo.end());
        return ret;
    }
};

A: in
        for (int j = 0; j < graph[i].size(); j++) {
            if (colors[graph[i][j]] == WHITE)
                ret = ret && visit(graph, graph[i][j]);
            else if (colors[graph[i][j]] == GRAY)
                ret =  false;
            else
                ret =  false;
        }

The last else is when the node is BLACK, which means it already processed and pushed into the result. So it will not make the graph invalid. Just remove the last else, it will work. Like this:
        for (int j = 0; j < graph[i].size(); j++) {
            if (colors[graph[i][j]] == WHITE)
                ret = ret && visit(graph, graph[i][j]);
            else if (colors[graph[i][j]] == GRAY)
                ret =  false;
            /* else
                ret =  false; */
        }


text:
Q: What is a more readable way to test for one of three strings? Is there a more readable way to test if delivery_status is one of three strings?
if ["partial", "successful", "unsuccessful"].include? delivery_status

Here's what I'd really like, but it doesn't work:
if delivery_status == ("partial" or "successful" or "unsuccessful")

A: While I would not advise this, you can do it anyway:
def String
  def is_one_of?(array)
    array.include?(self)
  end
end

And then:
if delivery_status.is_one_of?([...])

But there is a much better solution: use case (if possible in your situation):
case delivery_status
when 'partial', 'successful', 'unsuccessful'
  #stuff happens here
when ... #other conditions
end

A: if %w[partial successful unsuccessful].include? delivery_status

A: It's not intuitive, but using the Regexp engine can speed these tests up:
STATES = ["partial", "successful", "unsuccessful"]
regex = /\b(?:#{ Regexp.union(STATES).source })\b/i
=> /\b(?:partial|successful|unsuccessful)\b/i

delivery_status = 'this is partial'
!!delivery_status[regex]
=> true

delivery_status = 'that was successful'
!!delivery_status[regex]
=> true

delivery_status = 'Yoda says, "unsuccessful that was not."'
!!delivery_status[regex]
=> true

delivery_status = 'foo bar'
!!delivery_status[regex]
=> false

If I'm not searching a string for the word, I'll use a hash for a lookup:
STATES = %w[partial successful unsuccessful].each_with_object({}) { |s, h| h[s] = true }
=> {"partial"=>true, "successful"=>true, "unsuccessful"=>true}
STATES['partial']
=> true
STATES['foo']
=> nil

Or use:
!!STATES['foo']
=> false

If you want a value besides true/nil/false:
STATES = %w[partial successful unsuccessful].each_with_index.with_object({}) { |(s, i), h| h[s] = i }
=> {"partial"=>0, "successful"=>1, "unsuccessful"=>2}

That'll give you 0, 1, 2 or nil.

A: I ended up doing something similar to @Linuxios's suggestion
class String
  def is_one_of(*these)
    these.include? self
  end

  def is_not_one_of(*these)
    these.include? self ? false : true
  end
end

This allows me to write:
if delivery_status.is_one_of "partial", "successful", "unsuccessful"


text:
Q: How to fix JDK mistake? I have downloaded new Android Studio 2.1 and upgraded my openJDK to version 8.

But I have this issue :

What have I done wrong and what should I do?
Thanks!
added gradl
buildscript {
repositories {
    jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
}
}

apply plugin: 'com.android.application'

repositories {
jcenter()
}

dependencies {
compile 'com.android.support:multidex:1.0.0'
compile 'com.android.support:appcompat-v7:24.0.0-alpha2'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.google.android.gms:play-services:6.5.87'
compile 'com.android.support:cardview-v7:23.3.0'
compile files('libs/svgandroid.jar')
compile 'com.android.support:design:23.3.0'
compile 'com.github.bumptech.glide:glide:3.5.2'

compile files('libs/guava-16.0.1.jar')
compile 'com.google.code.gson:gson:2.6.1'
}

// The sample build uses multiple directories to
// keep boilerplate and common code separate from
// the main sample code.
List<String> dirs = [
    'main',     // main sample code; look here for the interesting stuff.
    'common',   // components that are reused by multiple samples
    'template'] // boilerplate code that is generated by the sample template process

android {

buildTypes {
    release {
        shrinkResources true
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
                'proguard-rules.pro'
    }
}

compileSdkVersion 23
buildToolsVersion "23.0.2"

repositories {
    mavenCentral()
}

defaultConfig {
    minSdkVersion 21
    targetSdkVersion 21
    multiDexEnabled true
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

sourceSets {
    main {
        dirs.each { dir ->
            java.srcDirs "src/${dir}/java"
            res.srcDirs "src/${dir}/res"
        }
    }
    androidTest.setRoot('tests')
    androidTest.java.srcDirs = ['tests/src']
}
}

A: See the documentation: http://tools.android.com/tech-docs/configuration/osx-jdk
It involves setting a $STUDIO_JDK environment variable.


text:
Q: Scaling normal $X$ into (0, 1) range whist maintaining distribution shape Let $X$ be a normally-distributed random variable. How can I transform this $X \in \mathbb{R}$ into another r.v. $Y \in [0; 1]$ whilst maintaining its normal-like shape?
One common way of performing a one-to-one transformation from $\mathbb{R}$ into $[0; 1]$ is to calculate the CDF of the original variable. The "problem" with that approach is that the result will be uniformly-distributed. This is a well-known property, but here is an example to illustrate:
set.seed(2345)
x <- rnorm(1000)
hist(x)
y <- pnorm(x)
hist(y)

The histograms of $x$ and $y$ will look like this:

However, as I mentioned, I would like to transform $X \in \mathbb{R}$ into $Y \in [0; 1]$ and have $Y$ bell-shaped?

A: As you correctly point out, $U=F_X(X)$ will be uniform. Consider now that we have (somehow) identified some sufficiently "normal-like" continuous strictly monotonic distribution function on (0,1) (which we'll call $G$).
Then $Y=G^{-1}(U)$ has distribution $G$. So $Y=G^{-1}(F_X(X))\sim G$
So if we can find some suitable $G$, we're done.

Possible distributions with the kind of properties you want:

*

*The beta distribution. This is very often used as a distribution for the binomial parameter in Bayesian statistics. If you choose the two parameters to be approximately equal and larger than 2, then you have something that looks roughly normal. The inverse cdf is widely available.

*A suitably truncated normal. Rescale a normal so that it has mean near the middle of (0,1) and most of its probability in (0,1). For example, $N(\frac12,\frac16^2)$ truncated to the unit interval. The inverse cdf is fairly convenient and (if you don't need the tails of the original distribution) this can avoid the need to go via the uniform.

*Logit-normal, for some parameter values; to get those, rescale your normal to have a suitable parameter combination such that the logit-normal looks like you want. Typically you'll want $\mu$ not too far from $0$ and $\sigma<1$ (a value like $\frac12$ or $\frac13$ -- or less -- will often be reasonable). Incidentally I think your own answer is a particular case of this with $\sigma=1$. The inverse cdf is quite convenient and this also avoids the need to convert to uniform first.

*A standard Bates distribution. Take the mean of $k$ independent standard uniforms. The inverse cdf isn't particularly convenient if you're doing this from scratch, but if you can find an existing function to do this (or the related Irwin-Hall, followed by a rescaling), this may be convenient.

*Raised cosine. Specifically, the one with $f_Y(y) =  1+\cos(\pi(2x-1))\mathbb{I}_{(0,1)}$.
There are many other fairly obvious choices; for example a suitably truncated $t$ would allow you to push up the kurtosis a little (I think all of the previous examples have lower kurtosis than the normal; you may in some circumstances want to get it a bit closer to that of the normal); you could also consider scale mixtures for example.

A: Thanks to Francis, I ended up doing a simple rescaling of the data in order to achieve what I wanted.
Scaling is achieved by performing the following transformation:
$$
y = \frac{x - \min(x)}{\max(x) - \min(x)}
$$
This is a great solution for me because it's fairly shape-constant. No matter how my original variable $X$ looks, $Y$ will be a horizontally-distorted version of it, squished from its original range to $(0, 1)$. This works for me because I had a bell-shaped $X$ which could take any real value and wanted a bell-shaped $Y$ which was $\in (0, 1)$.

One drawback of the transformation above for my case was that $\min(x)$ becomes 0 and $\max(x)$ becomes 1 by definition. I wanted $Y$ to be a little more concentrated around 0.5, so the transformation I've actually used was this:
$$
y = \frac{x - [\min(x) - \text{IQR}(x)]}{[\max(x) + \text{IQR}(x)] - [\min(x) - \text{IQR}(x)]}
= \frac{x - \min(x) + \text{IQR}(x)}{\max(x) - \min(x) + 2\text{IQR}(x)},
$$
where $\text{IQR}(x) = Q_3(x) - Q_1(x)$ is the interquartile range of $X$.
What happens here is I'm giving the minimum and maximum values extra padding, thus increasing the "range of the observed values of $X$" and, consequently, having the transformed values lay farther from the extremities 0 and 1.

A: One solution would be to use the CDF of a logistic distribution. In the example:
set.seed(2345)
x <- rnorm(1000)
y <- 1 / (1 + exp(-x))  # assumes mu = 0 and sd = 1 for Y.

This should give the following histogram for $y$:

At first this seems to answer my question, but I welcome other solutions very much, since this transformation may be too similar to another method I am using and comparing.


text:
Q: LinearLayout change android:layoutAnimation programmatically Is there any way to change android:layoutAnimation to a different animation resource programmatically using Java?

A:
Is there any way to change android:layoutAnimation to a different animation resource programmatically using Java?

Yes : you can use LayoutAnimationController

*

*A layout animation controller is used to animated a layout's, or a view group's, children. Each child uses the same animation but for every one of them, the animation starts at a different time. A layout animation controller is used by ViewGroup to compute the delay by which each child's animation start must be offset
HERE IS WORKING EXAMPLE CODE
public class MainActivity extends AppCompatActivity {

    LinearLayout rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rootView=findViewById(R.id.rootView);
        LayoutAnimationController anim = AnimationUtils.loadLayoutAnimation(this, R.anim.scale_down);
        rootView.setLayoutAnimation(anim);
    }

}

Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:id="@+id/buttonPanel"
        android:layout_height="wrap_content" />

</LinearLayout>

R.anim.scale_down
 <layoutAnimation
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/scale_up" />

@anim/scale_up
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="1000"
        android:fromXScale="0"
        android:fromYScale="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>


text:
Q: jquery css styleswitcher set cookie to css I run a jQuery styleswitcher that change stylesheet on click.I tried some solutions but i cant find a solution for this.
I dont understand how to set a cookie to this. Please anybody that can help me with this issue?
Markup:

jQuery

(function ($) {
"use strict";
var mainApp = {

    main_fun: function () {

        /*=====================================
         THEME SWITCHER SCRIPTS
        ===================================*/

        //THE CALLING OF PANEL ON CLICKING PLUS BUTTON

        jQuery('#switch-panel').click(function () {
            if (jQuery(this).hasClass('show-panel')) {
                jQuery('.switcher').css({ 'left': '-50px' });
                jQuery('#switch-panel').removeClass('show-panel');
                jQuery('#switch-panel').addClass('hide-panel');
            } else if (jQuery(this).hasClass('hide-panel')) {
                jQuery('.switcher').css({ 'left': 0 });
                jQuery('#switch-panel').removeClass('hide-panel');
                jQuery('#switch-panel').addClass('show-panel');
            }
        });

        $('#black').click(function () {
            $('#mainCSS').attr('href', 'assets/css/style.css');  //THE STYLE SHEETS WITH THEIR PATHS
        });
        $('#blue').click(function () {
            $('#mainCSS').attr('href', 'assets/css/blue.css');  //THE STYLE SHEETS WITH THEIR PATHS
        });
        $('#green').click(function () {
            $('#mainCSS').attr('href', 'assets/css/green.css');   //THE STYLE SHEETS WITH THEIR PATHS
        });
        $('#red').click(function () {
            $('#mainCSS').attr('href', 'assets/css/red.css');    //THE STYLE SHEETS WITH THEIR PATHS
        });

    },

    initialization: function () {
        mainApp.main_fun();

    }

}

$(document).ready(function () {
    mainApp.main_fun();
});

}(jQuery));

A: If you take a look at this thread - How do I create and read a value from cookie?, there's some pre-written JS code for getting and setting a cookie.
In your case, you can set the cookie value in your jQuery .click handlers.
You'll also want some code  that runs when the document is ready, checking to see if a cookie exists on the client.  If it exists, you set the stylesheet to the value of the cookie.
I've made an example for you based on your own code.  You should be able to modify to fit your situation.   http://jsfiddle.net/biz79/pdjmc0n3/1/
JS:
Creating/setting cookie with 1 day expiration
    $('#black').click(function () {
      // stylesheet stuff...
      createCookie('cookie','black',1);
    });
    $('#blue').click(function () {
      // stylesheet stuff...
      createCookie('cookie','blue',1);
    });
    //...

And if a cookie exists:
    $(document).ready(function(){
      updateResult();
    });

    function updateResult() {
      var cookieValue = getCookie('cookie');
      if (cookieValue.length) {
        $('#mainCSS').attr('href', 'assets/css/' + cookieValue + '.css');
      }
    }


text:
Q: How to perform jqXHR.always on jquery form plugin .ajaxSubmit? This one works:
    $.post('url', {
       ...
    }, function(resp) {
       ...
    }, 'json').always(function() {
       ...
    });

This one produces "Uncaught TypeError: undefined is not a function":
    $form.ajaxSubmit({
        url: url,
        type: 'post',
        data: {
            ...
        },
        dataType: 'json',
        beforeSubmit: function() {
            ...
        },
        error: function(jqXHR, exception) {
            ...
        },
        success: function(response, statusText, xhr, $form) {
            ...
        }
    }).always(function() {
            ...
    });

It asks me to write more about my code, which is silly because the question is quite complete and writing more words will not make it more clear.

A: The .always() method belongs to the promise object, the ajaxSubmit() method does not return a promise, it returns the jQuery object on which it was called on.
You can use the complete callback
$form.ajaxSubmit({
    url: url,
    type: 'post',
    data: {
        //...
    },
    dataType: 'json',
    beforeSubmit: function () {
        // ...
    },
    error: function (jqXHR, exception) {
        // ...
    },
    success: function (response, statusText, xhr, $form) {
        // ...
    },
    complete: function () {
        console.log('completed')
    }
})


text:
Q: How to finish one operation in Node.js if some limit time is exceeded? Consider that we want to perform some operation which takes some time to complete in Node.js, say doHeavyWork(). What we usually do is that we pass a callback function like that:
doHeavyWork(params, callbackFunction);

Now, I want to stablish one limit time for the operation to complete. What I want is that if the uptime of that operation exceeds the limit time, the function terminates and informs the callback that the limit time was exceeded.
How can this be accomplished in Node.js?

A: You'd think this is possible with a simple callback, but I'm going to illustrate a problem for you

function doHeavyWork(params, callback) {
  // set the timeout
  var timeout = setTimeout(callback, 5000, Error('timeout'))

  // some debug message
  console.log('Please wait...')

  // begin heavy work
  // we sill simulate heavy work with setTimeout here
  setTimeout(function() {

    // if the function completed in time, clear the timeout
    clearTimeout(timeout)

    // callback without error
    callback(null, 'done')
  }, 3000)
}

// check to see it work
doHeavyWork('some params', function(err, res) {
  if (err)
    throw error
  else
    console.log(res)
})

Now watch what happens if you change the 3000 to a value that exceeds the 5000 ms timeout — for example, try 10000. You will see that the callback is called twice. This is not good! And not trivial to fix unless you want to clutter up your function with a ton of rubbish.
If we use a Promise, we can fix this quite easily tho

function doHeavyWork(params) {
  return new Promise(function(resolve, reject) {
    // set the timeout
    var timeout = setTimeout(reject, 5000, Error('timeout'))

    // some debug message
    console.log('Please wait...')

    // begin heavy work
    // we sill simulate heavy work with setTimeout here
    setTimeout(function() {

      // if the function completed in time, clear the timeout
      clearTimeout(timeout)

      // callback without error
      resolve('done')
    }, 3000)
  })
}

// check to see it work
doHeavyWork('some params').then(
  function(res) { console.log(res) },
  function(err) { console.log(err.message) }
)

Now watch what happens if you change the 3000 to 10000 again. The Promise "callback" will only be called once

Lastly, this code can even be improved just a little bit more using Promise.race. Promise.race will return a new Promise that resolves or rejects as soon as one of the input Promises resolves or rejects. This is perfect for our use case.
Most crucially, notice how the timeout logic is not coupled with doHeavyWork. This keeps your functions clean and nicely organized.

function doHeavyWork(params) {
  return new Promise(function(resolve, reject) {
    // some debug message
    console.log('Please wait...')

    // begin heavy work
    // we sill simulate heavy work with setTimeout here
    setTimeout(resolve, 3000, 'done')
  })
}

function timeout(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(reject, ms, Error('timeout'))
  })
}

// using Promise.race
Promise.race([
  timeout(5000),
  doHeavyWork('some params')
]).then(
  function(res) { console.log(res) },
  function(err) { console.log(err.message) }
)

In the code example above, change the timeout value of 5000 to something shorter like 1000 to see what the error looks like


text:
Q: mat-button-toggle group in reactive from makes other controls disappear? I have a built a basic reactive form but when with 3 text fields, and a mat-button-toggle.
When I add the toggle (the last form filed in the template below), the regular input form fields become invisible.
Without the toggle, I get this:

The template and component code are below:
When I add the toggle, I get this:

 <form [formGroup]="bindingAuthorForm" (submit)="submit()">
  <mat-form-field class="form-field" appearance="outline">
    <mat-label>Binding Name</mat-label>
    <input matInput placeHolder="1.0.0" formControlName="bindingName" required>
    <mat-error *ngIf="bindingAuthorForm.controls['bindingName'].hasError('pattern')">
      This field is
        mandatory.
      Lowercase letters, numbers and
        underscore only.
    </mat-error>
  </mat-form-field>
  <mat-form-field class="form-field" appearance="outline">
    <mat-label>Version</mat-label>
    <input matInput placeHolder="Version" formControlName="version" required>
    <mat-error *ngIf="bindingAuthorForm.controls['version'].hasError('pattern')">
      Version must be Major.Minor.Patch style, e.g. '1.2.3'
    </mat-error>
    <mat-error *ngIf="bindingAuthorForm.controls['version'].hasError('required')">
      Version is required.
    </mat-error>
  </mat-form-field>
  <mat-form-field class="form-field" appearance="outline">
    <mat-label>Author</mat-label>
    <input matInput placeHolder="Binding Author" formControlName="authorName" required>
    <mat-error *ngIf="bindingAuthorForm.controls['authorName'].hasError('required')">
      Author Name is required.
    </mat-error>
  </mat-form-field>

  When I add the below the fields above disappear:
  <mat-form-field class="form-field" appearance="outline">
    <mat-button-toggle-group formControlName="bindingType'">
      <mat-button-toggle value="definitions">Definitions</mat-button-toggle>
      <mat-button-toggle value="entitlements">Entitlements</mat-button-toggle>
    </mat-button-toggle-group>
  </mat-form-field>
</form>

BindingAuthorComponent.ts
import { Component, OnInit  } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-binding-author',
  templateUrl: './binding-author.component.html',
  styleUrls: ['./binding-author.component.scss']
})
export class BindingAuthorComponent implements OnInit {
  bindingAuthorForm : FormGroup;
  constructor(private formBuilder : FormBuilder  ) {   }
  bindingNameRegex :RegExp =  /^[a-z][a-z0-9_]*$/;
  versionNumberRegex : RegExp = /^\d+.\d+.\d+$/
  public foo : string = "I am foo"

  ngOnInit(): void {
    this.bindingAuthorForm = this.formBuilder.group({
      bindingName : [null, [Validators.required, Validators.pattern(this.bindingNameRegex), Validators.maxLength(9)]],
      version : [null, [Validators.required, Validators.pattern(this.versionNumberRegex)]],
      authorName : [null, [Validators.required]],
      bindingType : [""]
    })
  }
  submit() {
    if (!this.bindingAuthorForm.valid) {
      return;
    }
    console.log(this.bindingAuthorForm.value);
  }
}

A: I don't think mat-button-toggle-group is compatible with the mat-form-field. Remove the form field from the button toggle group and you should be fine.


text:
Q: Kivy: change layout when I change orientation I want to create something that changes its general layout when the orientation, or size, of the window is changed.  In the below example, I was trying to do this with 3 buttons.  But it fails, and complains that the buttons already have a parent when I try to add them to a layout.  Why do they already have a parent?  I never added them to the AdaptWidget...
More importantly, how should I achieve what I want to achieve?
Code below:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class AdaptWidget(BoxLayoutWrite failed: Broken pipe
    def __init__(self, **kw):
        super(AdaptWidget, self).__init__(**kw)
        self.but1 = Button(text='but1')
        self.but2 = Button(text='but2')
        self.but3 = Button(text='but3')
        self.layout = None

    def on_size(self, *args):
        self.clear_widgets()

        if self.size[0] > self.size[1]:
            self.layout = BoxLayout(orientation='horizontal')
            self.but1.size_hint = 0.7, 1

            self.layout.add_widget(self.but1)
            vert = BoxLayout(orientation='vertical')
            self.layout.add_widget(vert)
            self.but2.size_hint = (1,0.5)
            self.but3.size_hint = (1,0.5)
            vert.add_widget(self.but2)
            vert.add_widget(self.but3)
        else:
            self.layout = BoxLayout(orientation='vertical')
            self.but1.size_hint = 1, 0.7
            self.layout.add_widget(self.but1)
            horiz = BoxLayout(oreintation='horizontal')
            self.layout.add_widget(horiz)
            self.but2.size_hint = 0.5, 1
            self.but3.size_hint = 0.5, 1
            horiz.add_widget(self.but2)
            horiz.add_widget(self.but3)

        self.add_widget(self.layout)

class TestLayoutApp(App):
    def build(self):
        return AdaptWidget()

if __name__ == '__main__':
    TestLayoutApp().run()

A: Every time the size of your AdaptWidget changes, your on_size callback runs - but the callback doesn't remove any widgets from their parents, so on_size will always crash the second time it is called. You can always ensure a widget is removed from its parent:
if widget.parent is not None:
    widget.parent.remove_widget(widget)

A:

*EDIT:

3 days ago I wrote this "answer", although I could not make the above suggestions work.
But now someone here: https://groups.google.com/forum/#!topic/kivy-users/Z5fjt5tNys8
Showed me how to do it.
So here comes the solution:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class AdaptWidget(BoxLayout):

    def __init__(self, **kw):
        super(AdaptWidget, self).__init__(**kw)
        # but1 = Button(id='but1', text='button1')
        # but1 = ObjectProperty(None)
        # self.but1 = ObjectProperty(None)
        self.add_widget(Button(id='but1', text='button1'))
        self.add_widget(Button(id='but2', text='button2'))
        self.add_widget(Button(id='but3', text='button3'))

    def on_size(self, *args):
        if self.width > self.height:
            self.orientation = 'horizontal'
            # self.child.but1.size_hint = (0.7, 1)
            # but1.size_hint = (0.7, 1)
            # self.ids.but1.size_hint = (0.7, 1)
            self.children[2].size_hint = (0.7, 1)
            self.children[1].size_hint = (0.5, 1)
            self.children[0].size_hint = (0.5, 1)
        else:
            self.orientation = 'vertical'
            self.children[2].size_hint = (1, 0.7)
            self.children[1].size_hint = (1, 0.5)
            self.children[0].size_hint = (1, 0.5)

class TestLayoutApp(App):
    def build(self):
        return AdaptWidget()

if __name__ == '__main__':
    TestLayoutApp().run()

Note that the solution above is much cleaner than the original code. No need to remove or clear any widgets. You just change their attributes.

*

*EDIT:

Part of the problem was that the 'buildozer.spec'-file contained this:
# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

Instead of this:
# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = all


text:
Q: Animate flow lines of time-dependent 3D dynamical system I've spent a bunch of time perusing Stack Exchange to try to find an answer and found nothing; hopefully this isn't a duplicate.
I have a time-dependent vector field $\Phi_t(x,y,z)=(x\lambda^t,y\lambda^{-t},z+t)$, $\lambda>1$ arbitrary; for my example, I'm restricting to the region $[0,1]\times[0,1]\times\mathbb{R}$. What I would like to do is:

*

*fix some $\lambda>1$;

*generate some number of random initial points;

*compute / store the orbits of these points over some length of time;

*plot these orbits in 3D with animation.

I've currently managed to do all of this except animate the flow lines.
Here's my current code:
seeds = RandomReal[{-1, 1}, {250, 3}]; (* 250 random initial points *)
lam = 1.5; (* \[Lambda]>1 fixed *)

func[{x_, y_, z_}, t_] := {x lam^t, y lam^(-t), z + t}; (* the vector field itself *)
orbit[k_] := Table[func[seeds[[k]], n], {n, 0, 9.75, 0.25}]; (* function to compute the orbit for a single initial point *)
orbits = orbit[#] & /@ Range[1, Length[seeds], 1]; (* computes orbits for all initial points *)

Graphics3D[{
    {Red, Arrowheads[{-.01, .01}], Arrow[BezierCurve[orbits[[#]]]] & /@ Range[1, Length[seeds], 1]}
}, PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}, Boxed -> False, Axes -> True, AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}}, ViewPoint -> {2.6056479300835718`, 2.1387445365836095`, 0.29388887642263006`}, ViewVertical -> {0.3985587476649791`, 0.332086389794556`, 0.8549090912915488`}, ImageSize -> 400]

Here's the output:

This is okay, but what I'd really like is something that can either

*

*animate one entire flow line a little at a time, then the next flow line a little at a time, etc. (in the same plot); or

*animate all flow lines simultaneously, a little at a time.

Can anyone help me with this?
Note: By defining an auxiliary function buildorbits[k_,n_]:=orbits[[k, 1 ;; n]];, I can animate single orbits using a very "hackish-feeling" implementation of ListAnimate. For instance:

; is this really my best option, though?

A: Not exactly what was asked, but another way to visualize the flow, based on How can I create a fountain effect?:
DynamicModule[
 {x0, y0, z0, last = 0, lam = 1.5, n = 500, colors, replace},
 last = Clock[Infinity];
 {x0, y0, z0} = RandomReal[{-1, 1}, {3, n}];
 colors = RandomColor[n];

 Graphics3D[GraphicsComplex[
   Dynamic@ With[{t = Clock[Infinity]},
     With[{dt = (t - last)/2}, With[{dl = lam^dt},
       last = t;
       x0 = x0*dl; y0 = y0/dl; z0 = z0 + dt; (* integration of velocity *)
       replace = Pick[Range@n, UnitStep[z0 - 1], 1];
       x0[[replace]] = RandomReal[{-1, 1}, Length@replace];
       y0[[replace]] = RandomReal[{-1, 1}, Length@replace];
       z0[[replace]] = RandomReal[{-1, -1 + dt}, Length@replace];
       Transpose@{x0, y0, z0}
       ]]],
   Point[Range@n, VertexColors -> colors]],
  PlotRange -> {{-2, 2}, {-2, 2}, {-1, 1}}, Axes -> True,
  AxesLabel -> {x, y, z}],

 Initialization :> ({x0, y0, z0} = RandomReal[{-1, 1}, {3, n}])
 ]

The integration is based on the ODE for $\Phi$, which is autonomous and linear and can be done by scalings and translation:
$${d \over dt}\,(x,y,z) = (x \log \lambda, -y \log \lambda, 1)$$

A: You can use ParametricPlot3D to get smoother orbits:
SeedRandom[1]
n = 50;
seeds = RandomReal[{-1, 1}, {n, 3}];
tbar = 10;

Animate[ParametricPlot3D[Evaluate[func[seeds[[#]], t] & /@ Range[Length@seeds]],
   {t, 0, tmax},
    BoxRatios -> 1,
    PlotStyle -> Arrowheads[Medium],
    ImageSize -> 400,
    PlotRange -> {{-60, 60}, {-1, 1}, {-10, 10}}] /. Line -> Arrow,
  {tmax, .01, tbar}]

Update: "Is there a way to use this this implementation to animate as all of orbit 1, followed by all of orbit 2, followed by....?"
colors = Table[Hue@RandomReal[], {n}];

Animate[ParametricPlot3D[Evaluate[ConditionalExpression[func[seeds[[#]], t - (#-1) tbar],
      (# - 1) tbar <= t <= # tbar] & /@ Range[n]],
   {t, 0, tmax},
   BaseStyle -> Arrowheads[Medium],
   BoxRatios -> 1,
   ImageSize -> 400,
   PlotStyle -> colors,
   PerformanceGoal -> "Quality",
   PlotRange -> {{-50, 60}, {-1, 1}, {-5, 15}}] /. Line -> Arrow,
 {tmax, .01, n tbar},
 AnimationRate -> 10]


text:
Q: Give a derivation I'm doing some excercises from the book "The Incompleteness Phenomenom" from Goldstern and Judah.
I have to give a derivation for:
$\forall x(\phi \wedge\xi)\to (\forall x\phi \wedge \forall x \xi)$
The axioms that I can use are:

*

*Tautology

*$\forall x(\phi \to \xi)\to (\forall x\phi \to \forall x \xi) $

*If $\tau$ may be substituted for $x$,  $\forall x\phi\to \phi (x/\tau)$ .(This is substitution)

*If $x$ is not Free in $\phi$, $\phi \to \forall x \phi$.

Thanks :)

A: We need:

1.4.23 Deduction Theorem [page 84]

and:

1.4.27 Generalization Theorem [page 85].

1) $∀x(ϕ∧ξ)$ --- premise
2) $ϕ∧ξ$ --- from 1) and Ax.3 by MP
3) $(ϕ∧ξ) → ϕ$ --- tautology
4) $(ϕ∧ξ) → ξ$ --- tautology
5) $ϕ$ --- from 2) and 3) by MP
6) $ξ$ --- from 2) and 4) by MP
7) $∀xϕ$ --- from 5) by Gen Th [here $\Gamma = \{ ∀x(ϕ∧ξ) \}$ and $x$ is not free in it]
8) $∀xξ$ --- from 6) as above
9) $\alpha \to (\beta \to (\alpha ∧ \beta))$ --- tautology

10) $∀xϕ ∧ ∀xξ$ --- from 9), 7) and 8) by MP twice

11) $\vdash ∀x(ϕ∧ξ) \to (∀xϕ ∧ ∀xξ)$ --- from 1) and 10) by Ded Th [here $\Gamma = \emptyset$].


text:
Q: Differences of Numbers of Helicity States in 4-dimensional Strings The question whether the states in $D=2m + 2$ dimensional string theory,
which carry a representation of $SO(2m)$, span spaces which carry
representations of $SO(2m+1)$ seems hopelessly complicated.
For $m=1$, i.e in  the most interesting case $D=4$, however,
it boils down to the following question.
Let $h(x,q)$ be the function:
$$ h(x,q) = \sum_N (q^N \sum_n h_{N,n} x^n)
          = \prod_{i=1}^{\infty} 1/((1-q^i*x)(1-q^i/x)) $$
Are the differences $d_{N,n}=h_{N,n}-h_{N,n+1}$ nonnegative for all $N\ge 2$ and all $n\ge 0$? ($h_{N,n}=0$ for $|n|>N$)
One easily sees $d_{N,N}=1, d_{N,N-1}=0$.
My calculations of about 20 nontrivial differences confirm the conjecture for $N\le 8$.
Added information: The numerical evaluation of $h(x,q)$ confirms the conjecture
for $N\le 51$: http://www.itp.uni-hannover.de/~dragon/part1.erg , where the
differences $d_{N,n}$ are listed as $A[N,n]$.
To exclude the special case $N=1$ one could add $q$ to $h(x,q)$ and try to prove that
$$d(q,x)=(x-1/x)(q+h(x^2,q))=\sum_{m,n\ge 0}d_{m,n}q^m (x^{2n+1}-x^{-(2n+1)})$$
is a function with $d_{mn}\ge 0$ for all $m\ge 0$ and for all $n \ge 0\,$.


text:
Q: Need a join query in greendao Can someone create a greendao (or android sqllite) query to have the same result like the next sql query?
select b.*, a.MAIN_CATEGORY_ID from MAINCATEGORYS_TO_LISTINGS a
    join APMAIN_CATEGORY b on b._id=a.MAIN_CATEGORY_ID where listing_id=10120

A: You could use the queryRaw() method in GreenDao.
If I understand what you are trying to do correctly, e.g.:
session.getMainCategoryDao().queryRaw(
    " inner join " + MainCategoryToListingsDao.TABLENAME + " MCL "
    + " on T._id = MCL." + MainCategoryToListingsDao.Properties.MainCategoryId.columnName
    + " where MCL." + MainCategoryToListingsDao.Properties.ListingId.columnName
    + " = ?", listing.getId());

It's a little ugly, but should work. Of course you will have to modify based on how your DAOs are named and possibly how you named your properties. But when GreenDao names your primary table in the query, it is aliased by the T and the primary keys are _id
They rest you can pull by using the DAO's properties.

A: This will be supported in greenDAO 1.4, which will be released soon. If want you can build greenDAO from the "join" branch for an early version of it: https://github.com/greenrobot/greenDAO/tree/join


text:
Q: Click a button from a drop-down menu with RSelenium I have problem. I have to click the line "in codici prodotto".

 " 67D16EA#ABZ "
                                                {{model.inputheaderlg | limitTo: 50}} 50">...  in informazioni

 " 67D16EA#ABZ "
                                                {{model.inputheaderlg | limitTo: 50}} 50">...  in prodotti

 " 67D16EA#ABZ "
                                                {{model.inputheaderlg | limitTo: 50}} 50">...  in codici prodotto <img style="margin-bottom:3px" alt="vai" src="/opencms/opencms/immagini/rifacimento_nuovo_portale/HP/frecciatype.png"

I have tried CSS and with XPATH......
#css
  webelem4 <- remote_driver$findElement(using = "css",'#headersearchformlg .ng-scope+ .ng-scope span:nth-child(1)')
  webelem4$clickElement

#xpath
  webelem4 <- remote_driver$findElement(using = "xpath",'//*
  [@id="headersearchformlg"]/fieldset/div/div[3]/div/div[3]')
  webelem4$clickElement

.....but I always get the same answer.
Class method definition for method clickElement()
function ()
{
    "Click the element."
    qpath <- sprintf("%s/session/%s/element/%s/click",
        serverURL, sessionInfo[["id"]], elementId)
    queryRD(qpath, "POST")
}
<environment: 0x00000248bd0ad708>

Methods used:
     "queryRD"