text:
Q: Why Unicode Encoding/Decoding is Necessary in JavaScript I am wondering why unicode encoding is necessary in JavaScript. I am looking at utf8.js as an example. I am also looking at the utf8 spec, but am not really following the different pieces of data. Also, I don't fully understand when and where you are supposed to encode/decode, and what the "current" format is of some set of bytes in a programming language, so that's making it difficult to follow this.

UTF-8's encoder's handler, given a stream and code point, runs these steps:...

I would like to know what the stream is, and what the code point is. I understand that code points are characters, which in utf8 might be composed of multiple 8-bit code units.
I would also just generally like to know why you can't just have in a language "unicode", and there is no utf8/utf16 encoding/decoding, because it is already in let's say utf8 format. This makes me wonder if JavaScript needs to do this encoding/decoding for some reason, such as maybe because JavaScript uses utf16 encoding, and so the stream of bits you pass to utf8.js is a stream of utf16 encoded bits. Or maybe it's not that, and instead the stream of bits you pass to utf8.js is a stream of x (something else) such as decimal encoding or whatever that may mean.
I am just not sure what format/encoding the bytes are coming in as, and also why we need to do the conversion. For example, in here when they mention the "Buffer class is ... raw binary data" (in Node.js), I am not sure what that raw binary data means. Maybe that just means it is UTF16, which is why it would then maybe need to be converted to UTF8, I am not sure. And when this mentions JSON.parse doesn't do any string decoding, I start to wonder if this means that JSON.parse assumes UTF16 encoding, or perhaps it assumes UTF8 encoding, I'm not sure. Searching for the "encoding JSON.parse uses" doesn't reveal anything.

A:
I am not sure what raw binary data means.

It means nothing here is sure what it means.
If I hold up two fingers am I saying 2, V for victory, or the peace sign?
Knowing the encoding lets you know the meaning behind the symbol. With out knowing the encoding all you know is that I'm holding up two fingers. When you process data without knowing the encoding, the meaning, that's raw binary data.
The vocabulary we use for this is weird. We sound like what it is changes just because we understand it. But I'm holding up the same fingers regardless of how well you understand.
What changes is what you can do with it. If you need to tell people what I'm signaling and they've never heard of a victory sign you might show them a fist held high in celebration to show the same thing. You can't do that if you don't know what a victory sign is. All you can do is say "he's holding up two fingers".
Lets try an exercise. If I hold up 5 fingers on one hand and 2 on another you might assume I mean 7. You could be right. But if you see me count through 0 to 5 on my right hand then hold up 1 on my left only to again count though 0 to 5 on my right and then hold up 2 on my left, well you might assume I'm counting by 5's.
They're the same fingers.  But how you think about them changes what they mean.
ASCII is one way to think about bits. UTF-8 is another. Raw binary is a way to think about bits that says "I have no clue, let something else figure out what this means. I'm just going to report what I see".

A: Code points are often characters, but could be other things, such as control characters (carriage return, etc.), white spaces or accents.  Code points can be represented by 21-bit numbers from hex 0 to 1FFFFF.
Unicode started off using 16 bits per code point (hex 0 to FFFF), but rather embarrassingly ran out of code points and had to increase it to 21 bits.  So the idea of just using a 16 bit number for a code point had to be scrapped.
We have now ended up with three different encodings.
UTF-32 just pads out the 21 bits to a 32-bit number.  It's simple but wastes a lot of space.
UTF-16 is the old 16-bit characters, but with a bodge where certain characters are reserved, and sticking two of the reserved ones together makes a 21-bit character.  To make it worse, UTF-16 comes in big-endian and little-endian versions.
UTF-8 was invented as a nice clean way to pack Unicode in an efficient way.  It uses between 1 and 4 bytes per code point.  By a bit of clever design, the ASCII characters are also valid 1-byte UTF-8 characters.
So you need the encoding to convert the 21-bit Unicode code points into a series of 8-bit bytes in UTF-8 format.  The sequence of bytes you get after you have encoded them is the stream.
The term "stream" implies that you can just treat it as a series of bytes, and not worry about what they are until you get to the place where you need to decode them again.


text:
Q: OSX Terminal: Color correction
I am running Byobu on my server and it looks good with the exception of my OS X terminal confusing the blacks. I remember seeing somewhere you can change some mode and the colors actually look right, do you know what option that is?

A: I don't have access to an OSX machine, but you can try tweaking the black that's used for the status bar at the bottom.
You'll need to edit the file ~/.byobu/color.  Try changing:
BACKGROUND=k

to
BACKGROUND=K

That's from a lower case to an upper case 'K'.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Travis Can't Find Debian Package in Custom Source Repo, Why? The instructions here appear to be logical, i've tried both with, and without docker enabled:

https://docs.travis-ci.com/user/installing-dependencies/

Here is the log:
Adding APT Sources (BETA)
$ export DEBIAN_FRONTEND=noninteractive
0.01s$ echo "deb https://dl.bintray.com/solvingj/public-deb unstable main" | sudo tee -a /etc/apt/sources.list > /dev/null
Installing APT Packages (BETA)
$ export DEBIAN_FRONTEND=noninteractive
3.03s$ sudo -E apt-get -yq update &>> ~/apt-get-update.log
0.30s$ sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install cmake go-bin-deb
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package go-bin-deb
apt-get.diagnostics
apt-get install failed
$ cat ~/apt-get-update.log
Ign:1 http://us-central1.gce.archive.ubuntu.com/ubuntu precise InRelease
Hit:2 http://us-central1.gce.archive.ubuntu.com/ubuntu precise-updates InRelease
Hit:3 http://us-central1.gce.archive.ubuntu.com/ubuntu precise-backports InRelease
Hit:4 http://us-central1.gce.archive.ubuntu.com/ubuntu precise Release
Ign:5 http://downloads-distro.mongodb.org/repo/debian-sysvinit dist InRelease
Get:6 http://downloads-distro.mongodb.org/repo/debian-sysvinit dist Release [2,040 B]
Get:7 http://downloads-distro.mongodb.org/repo/debian-sysvinit dist Release.gpg [490 B]
Hit:8 http://security.ubuntu.com/ubuntu precise-security InRelease
Hit:9 http://apt.postgresql.org/pub/repos/apt precise-pgdg InRelease
Hit:11 http://ppa.launchpad.net/chris-lea/redis-server/ubuntu precise InRelease
Get:12 http://downloads-distro.mongodb.org/repo/debian-sysvinit dist/10gen amd64 Packages [30.9 kB]
Ign:13 http://ppa.launchpad.net/couchdb/stable/ubuntu precise InRelease
Ign:14 http://ppa.launchpad.net/git-core/v1.8/ubuntu precise InRelease
Get:15 http://downloads-distro.mongodb.org/repo/debian-sysvinit dist/10gen i386 Packages [30.5 kB]
Hit:16 http://ppa.launchpad.net/pollinate/ppa/ubuntu precise InRelease
Ign:17 https://dl.bintray.com/solvingj/public-deb unstable InRelease
Hit:18 http://ppa.launchpad.net/travis-ci/zero-mq/ubuntu precise InRelease
Hit:19 http://ppa.launchpad.net/ubuntugis/ppa/ubuntu precise InRelease
Hit:20 http://ppa.launchpad.net/webupd8team/java/ubuntu precise InRelease
Hit:21 https://packagecloud.io/basho/riak/ubuntu precise InRelease
Hit:22 http://ppa.launchpad.net/couchdb/stable/ubuntu precise Release
Hit:24 https://packagecloud.io/computology/apt-backport/ubuntu precise InRelease
Hit:25 http://ppa.launchpad.net/git-core/v1.8/ubuntu precise Release
Get:27 https://dl.bintray.com/solvingj/public-deb unstable Release [2,673 B]
Ign:28 https://dl.bintray.com/solvingj/public-deb unstable Release.gpg
Get:29 https://dl.bintray.com/solvingj/public-deb unstable/main amd64 Packages [14 B]
Get:30 https://dl.bintray.com/solvingj/public-deb unstable/main i386 Packages [14 B]
Fetched 66.7 kB in 1s (38.0 kB/s)
Reading package lists...
W: http://us-central1.gce.archive.ubuntu.com/ubuntu/dists/precise-updates/InRelease: Signature by key 630239CC130E1A7FD81A27B140976EAF437D05B5 uses weak digest algorithm (SHA1)
W: http://us-central1.gce.archive.ubuntu.com/ubuntu/dists/precise-backports/InRelease: Signature by key 630239CC130E1A7FD81A27B140976EAF437D05B5 uses weak digest algorithm (SHA1)
W: http://us-central1.gce.archive.ubuntu.com/ubuntu/dists/precise/Release.gpg: Signature by key 630239CC130E1A7FD81A27B140976EAF437D05B5 uses weak digest algorithm (SHA1)
W: http://downloads-distro.mongodb.org/repo/debian-sysvinit/dists/dist/Release.gpg: Signature by key 492EAFE8CD016A07919F1D2B9ECBEC467F0CEB10 uses weak digest algorithm (SHA1)
W: http://security.ubuntu.com/ubuntu/dists/precise-security/InRelease: Signature by key 630239CC130E1A7FD81A27B140976EAF437D05B5 uses weak digest algorithm (SHA1)
W: http://ppa.launchpad.net/couchdb/stable/ubuntu/dists/precise/Release.gpg: Signature by key 15866BAFD9BCC4F3C1E0DFC7D69548E1C17EAB57 uses weak digest algorithm (SHA1)
W: http://ppa.launchpad.net/git-core/v1.8/ubuntu/dists/precise/Release.gpg: Signature by key E1DD270288B4E6030699E45FA1715D88E1DF1F24 uses weak digest algorithm (SHA1)
W: The repository 'https://dl.bintray.com/solvingj/public-deb unstable Release' is not signed.
The command "sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install cmake go-bin-deb" failed and exited with 100 during .

Here is the start of my travis.yml file:
sudo: required
language: cpp
compiler:
- gcc
os:
- linux
addons:
  apt:
    sources:
    - sourceline: deb https://dl.bintray.com/solvingj/public-deb unstable main
    packages:
    - cmake
    - go-bin-deb

You can visit the custom repo, add it to a debian machine, and find the package without issue:

https://bintray.com/solvingj/public-deb

root@debian:/home/myprofile/go-github-release-test# apt-get clean
root@debian:/home/myprofile/go-github-release-test# more /etc/apt/sources.list
deb https://dl.bintray.com/solvingj/public-deb unstable main

root@debian:/home/myprofile/go-github-release-test# apt-get install go-bin-deb
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  go-bin-deb
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,074 kB of archives.
After this operation, 3,072 B of additional disk space will be used.
Get:1 https://mh-cbon.github.io/go-bin-deb/apt/public/ all/contrib go-bin-deb i386 0.0.18 [1,074 kB]
Fetched 1,074 kB in 1s (865 kB/s)
Selecting previously unselected package go-bin-deb.
(Reading database ... 36957 files and directories currently installed.)
Preparing to unpack .../go-bin-deb_0.0.18_i386.deb ...
Unpacking go-bin-deb (0.0.18) ...
Setting up go-bin-deb (0.0.18) ...
root@debian:/home/myprofile/go-github-release-test#

A: The problem was that the repository only contained the 32 bit version of the package.  My successful tests were on a 32 bit OS.  My failing tests were on Travis and Windows Subsystem for Linux, both of which are 64 bit.  Once I uploaded the 64 bit build to the debian repository, it found the package.

A: Well, the warning is pretty clear:
W: The repository 'https://dl.bintray.com/solvingj/public-deb unstable Release' is not signed.

apt does gpg-verification of each package, in order to make it hard for attackers to replace packages by malicious versions.
Therefore, you should sign the repository, so apt can validate the package authenticity.
An insecure, dangerous and generally bad alternative is to add the --allow-unauthenticated flag:
   --allow-unauthenticated
       Ignore if packages can't be authenticated and don't prompt about it. This can be useful while working with
       local repositories, but is a huge security risk if data authenticity isn't ensured in another way by the user
       itself. The usage of the Trusted option for sources.list(5) entries should usually be preferred over this
       global override. Configuration Item: APT::Get::AllowUnauthenticated.

Don't use it. You have been warned!
Instead sign your repository.


text:
Q: openstack ansible deployment fail after creating lxc containers while running apt-get update command inside container The openstack ansible created containers where running but they don't have access to internet. When I manually add routing then I get following error:
Err:1 http://archive.ubuntu.com/ubuntu bionic InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)

# lxc-ls -f
NAME                                STATE   AUTOSTART GROUPS            IPV4                         IPV6 UNPRIVILEGED
infra1_galera_container-40eb8c2c    RUNNING 1         onboot, openstack 192.168.56.232               -    false
infra1_glance_container-fe32f950    RUNNING 1         onboot, openstack 192.168.56.194, 10.200.75.51 -    false
infra1_heat_api_container-fcdda89c  RUNNING 1         onboot, openstack 192.168.56.207               -    false
infra1_horizon_container-29382c02   RUNNING 1         onboot, openstack 192.168.56.140               -    false
infra1_keystone_container-c4b4bca5  RUNNING 1         onboot, openstack 192.168.56.61                -    false
infra1_memcached_container-667ec859 RUNNING 1         onboot, openstack 192.168.56.183               -    false
infra1_nova_api_container-6dcd2a9b  RUNNING 1         onboot, openstack 192.168.56.114               -    false
infra1_placement_container-d9a47077 RUNNING 1         onboot, openstack 192.168.56.218               -    false
infra1_rabbit_mq_container-34797cf1 RUNNING 1         onboot, openstack 192.168.56.210               -    false
infra1_repo_container-02a62c03      RUNNING 1         onboot, openstack 192.168.56.94                -    false
infra1_utility_container-a23621d0   RUNNING 1         onboot, openstack 192.168.56.90                -    false

also thing is my lxc bridge has some different network & that is not getting assigned
lxcbr0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.3.1  netmask 255.255.255.0  broadcast 10.0.3.255

my openstack_user_config.yml defines all infra components on 192.168.56.0/24 network.
Why by default when I run the playbook I don't get internet access on containers? did I missed anything?

A: Internet access to lxc containers is provided through lxcbr0. Each container should get an IP 10.0.3.0/24 subnet assigned to eth0 (default interface). I have the same issue, which is caused by dnsmasq not handling DHCP request sent to lxcbr0. Restarting dnsmasq works. Following are the steps I took:
Check if DHCP requests are handled with tcpdump on controller host:
tcpdump -ntv -i lxcbr0

Restart dnsmasq:
ps aux | grep dnsmasq
# note pid and copy dnsmasq command
kill dnsmasq-pid
rerun dnsmasq command

or with
    systemctl start lxc-dnsmasq.service

A: There should be a need to check the /etc/resolv.conf
The correct nameserver is not added there because this under container apt update is failed.


text:
Q: Rails active record dynamic finders, creators etc I am trying to learn Rails and I am currently reading on active record. I am trying to understand the many different dynamic finders and ways you can create objects however I do not find a place where all the different combinations are listed. Where do I find this? I have tried reading in three different books but no luck.

A: You might find this useful: http://www.kesava.me/blog/2011/08/15/dynamic-finders/. The different combinations are generated by method_missing, so they are not listed explicitly anywhere in the Rails codebase.
Also, you might find this Railscast useful too.

A: read this http://guides.rubyonrails.org/active_record_querying.html, really helpful information


text:
Q: Define attributes as compile-time data? I'm writing classes to be a "higher-level" representation of some binary structures as binary files, tcp packets, etc.
For this, and for the sake of readability, that would be very nice if I could define some custom attribute to determine some information about each class' field (e.g. the offset of that field in the binary buffer, the size of the field, etc).
I could accomplish this by declaring constant integers, but IMHO the code would be very ugly and mucky. So I thought about using attributes, which are a very elegant way to accomplish what I want. Features like the InteropServices.Marshal actually uses attributes (as StructLayout, MarshalAs and FieldOffset) to accomplish something very similar to what I want, so I can only assume the performance tradeoff is advantageous compared to the gain of readability (please correct me if I'm wrong).
So, how the forementioned InteropServices' attributes are handled by the compiler/CLR?
Do you guys think the forementioned tradeoff is worth? If yes, the best way to deal with the attributes is using the default method using Refletion? I'm assuming that there could be other ways to access attributes rather than Reflection because I know this is a bit expensive and Marshal uses it in almost every method.
Any helpful thought would be very appreciated, thanks.

A: What you are proposing sounds reasonable assuming the parallels to the Interop are as clear as you are describing. To avoid the performance issues of using reflection for every property access you can use reflection once, maybe via a static constructor, and build compiled Expressions for each property instead. The performance should be the equivalent of calling a virtual method I would think.
Here is a link to a blog post denoting the performance differences between different dynamic invocation types. Compiled expressions are ~10x faster then cached reflection and "only" 2x slower then compiled property access.
http://www.palmmedia.de/Blog/2012/2/4/reflection-vs-compiled-expressions-vs-delegates-performance-comparision


text:
Q: Multiple filter data dropdown table with plotly in python I am currently trying to generate a table with multiple dropdown options (in a Jupiter Notebook). I have been able to create the scenario but the dropdown buttons work independently, meaning that if I select one dropdown from my 'Decision' dropdown with option 'A' and then select the other downtown 'Sex' with option 'Female' I either get option A or option 2 depending on the button last selected. However, what I really want is to have both filters applied at the same time. So I would get all Decisions 'A' that are 'Female' as filters for my table.
This is my code:
fig = go.Figure(go.Table(header={"values": df_dash.columns,'fill_color':'navy','align':'left',
                                 'font':dict(color='white', size=12)},
                         cells={"values": df_dash.T.values,'fill_color':'white','align':'left'}))
fig.update_layout(
    updatemenus=[
        {
            "y": 1 - (i / 5),
            "buttons": [
                {
                    "label": c,
                    "method": "restyle",
                    "args": [
                        {
                            "cells": {
                                "values": df_dash.T.values
                                if c == "All"
                                else df_dash.loc[df_dash[menu].eq(c)].T.values
                            }
                        }
                    ],
                }
                for c in ["All"] + df_dash[menu].unique().tolist()

            ],

        }
        for i, menu in enumerate(["Decision", "Sex",])
    ]
)

And this is how it looks:

Any ideas what am I doing wrong or what can I add to make both buttons actively filtering my df table at the same time?

A: Based on this answer in the plotly forums, you cannot create buttons that are dependent on each other.
The best you could probably do is create one dropdown with every possible combination in your current Decision and Sex dropdowns – which I understand probably isn't ideal.
If you are willing to use plotly-dash, then it is possible as you can create two dropdowns that are inputs to a basic callback that updates the fig, as shown in this example in the plotly-dash documentation


text:
Q: Html Form If statement in OnSubmit Field I'm fairly new to html/php/js and I'm running into an issue when conditionally submitting my form. Basically, what Im trying to do is have it where the confirm('Do you want to submit this form?') function only shows up if every field has a value entered (the checkform() function). If both are true, then the form will submit. Any help would be greatly appreciated, thanks!

<script type="text/javascript">
function checkform()
{
 var myForm=document.frmhot;

 if(myForm.status.value==""){
  alert("Please select a timeframe status.");
  return false;
  myForm.status.focus();
 }
    if (myForm.line.value==""){
  alert("Please select a line.");
  return false;
 }
 if(myForm.reason.value==""){
  alert("Please select a reason code.");
  return false;
 }
 if(myForm.partnum.value==""){
  alert("Please enter a part number.");
  return false;
 }
 if(myForm.badgescan.value==""){
  alert("Please enter a badge number.");
  return false;
 }
 return true;

}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot"
onclick="if(checkform();){
 confirm('Do you want to submit the form?');
}
>

<input class="button_text" type="submit"  value="Submit" name="submit" onclick= "checkform();"  />
</form>

A: Complete working solution with corrections and tweaks for IE compatibility to a certain extend.
<script>
    function checkform(evt)    {
        var myForm = document.frmhot;
        var condition = true;
        if(myForm.status.value==""){
            alert("Please select a timeframe status.");
            myForm.status.focus();
            condition = false;
        }
        if (myForm.line.value==""){
            alert("Please select a line.");
            condition = false;
        }
        if(myForm.reason.value==""){
            alert("Please select a reason code.");
            condition = false;
        }
        if(myForm.partnum.value==""){
            alert("Please enter a part number.");
            condition = false;
        }
        if(myForm.badgescan.value==""){
            alert("Please enter a badge number.");
            condition = false;
        }
        if(condition){ condition =  confirm('Do you want to submit the form?'); }

        if(!condition) {
            if(evt.preventDefault) { event.preventDefault(); }
            else if(evt.returnValue) { evt.returnValue = false; }
            else { return false; }
        }
    }
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
    <input type="text" name="status"/>
    <input type="text" name="line"/>
    <input type="text" name="reason"/>
    <input type="text" name="partnum"/>
    <input type="text" name="badgescan"/>
    <input class="button_text" type="submit" value="Submit"/>
 </form>

A: You have the right idea, just extract your code into its own function and then call that in the onclick.
Add this function:
function checkAndConfirm() {
     if(checkform()) {
        if (confirm('Do you want to submit the form?')) {
            // submit the form
     }
}

And then call it from the onclick attribute:
<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">


text:
Q: Remove item from Firefox context menu With new version 89 of Firefox,
when you are in some webpages,
(I noticed it on YouTube and Mozilla Support)
appears a new item when you right-click on the address bar
screenshot below:
you can notice Add "Mozilla Support" as last item in the context menu.
Question is: how can I remove it?

A: Looks like the Add "Mozilla Support" registers Mozilla Support as a Search Engine in the list of available search engines that Firefox has registered for you.
To remove it in FF.v91 , go to your Settings > Search page (url is about:preferences#search). In the "Search Shortcuts" section, you'll see any addresses you've accidentally added. Highlight the entry to remove and click the "Remove" button.


text:
Q: Rotation of a moving 2d plot in Octave/Matlab I have to create a program which simulates a vacuum cleaner robot. We have to do it with Octave.
Main()
  clear all;

  %Initalisierung der Raummatrix, damit nachher abgefragt werden kann
  XMatrix = 0;
  YMatrix = 0;

  %"Winkel festsetzten"
  t=1;
  h=1;
  hold on
  %Startpunkte vom Punkt
  x = 20;
  y = 15;
  alpha = 45;

  xalt= 10;
  yalt= 10;

  %Hier die Methode ändern um verschiedene Räume einzulesen
  [XMatrix,YMatrix] = RaummitsechsEcken();

  %plot Funktion wird gespeichert
  p =  plot(x,y,'*');
  %p1 = plot(x,y,xalt,yalt);

 while(true)

  pause(0.001)

  %alte Position speichern
  xalt = get(p,'XData');
  yalt = get(p,'YData');

  %Bewegungsberechnung
  set(p,'YData',get(p,'YData')+0.1*t);
  set(p,'XData',get(p,'XData')+0.1*h);

  % Strich plot

    %Kollisionabfrage
    if(inpolygon(get(p,'XData'),get(p,'YData'),XMatrix,YMatrix) == false)

      %Alte Position zurückspielen
      set(p,'XData',xalt);
      set(p,'YData',yalt);

      %Neue Winkelberechnung(random)
     t =  -1+rand(1)*(1-(-1));
      h =  -1+rand(1)*(1-(-1));

    endif

  endwhile

endfunction

function[X,Y] = RaummitsechsEcken()

X = [10 18 10 30 22 30 10];
Y = [1 16 30 30 16 1 1];

plot(X,Y)
hold on
endfunction

The problem with the code is when the "robot" hits the wall, that he is randomly generate a new angel and moves now in this way. The problem is here that the robot has the same variable for the angle and the speed. So the speed varies with the angle. My question is now if someone knows how to move my point on the same speed but change the direction apart from the speed when the robot hits the wall. I have searched for a rotationmatrix but I can not make it work with that.
I hope you can help!
Felix

A: The solution is little bit tricky. As you are setting new location of robot in cartesian coordinates system, the angle and speed are always going to change simultaneously because x and y coordinates control both parameters. But there is very simple solution, if you use convert cartesian coordinates to polar coordinates you will get angle and magnitude. Replace the magnitude with a constant speed factor and calculate the h and t values again i.e. cartesian coordinates. So you just need to add these three lines in your code.
angle = atan2(t,h);
t = speedFactor*sin(angle);
h = speedFactor*cos(angle);

Your code will look like:
Main()
  clear all;

  % You can control speed by increasing or decreasing this parameter.
  speedFactor = 0.1;

  %Initalisierung der Raummatrix, damit nachher abgefragt werden kann
  XMatrix = 0;
  YMatrix = 0;

  %"Winkel festsetzten"
  t=1;
  h=1;

  hold on
  %Startpunkte vom Punkt
  x = 20;
  y = 15;
  alpha = 45;

  xalt= 10;
  yalt= 10;

  %Hier die Methode ändern um verschiedene Räume einzulesen
  [XMatrix,YMatrix] = RaummitsechsEcken();

  %plot Funktion wird gespeichert
  p =  plot(x,y,'*');
  %p1 = plot(x,y,xalt,yalt);

 while(true)

  pause(0.001)

  %alte Position speichern
  xalt = get(p,'XData');
  yalt = get(p,'YData');

  %Bewegungsberechnung
  set(p,'YData',get(p,'YData')+0.1*t);
  set(p,'XData',get(p,'XData')+0.1*h);

  % Strich plot

    %Kollisionabfrage
    if(inpolygon(get(p,'XData'),get(p,'YData'),XMatrix,YMatrix) == false)

      %Alte Position zurückspielen
      set(p,'XData',xalt);
      set(p,'YData',yalt);

      %Neue Winkelberechnung(random)
       t =  -1+rand(1)*(1-(-1));
      h =  -1+rand(1)*(1-(-1));

      angle = atan2(t,h);
      t = speedFactor*sin(angle);
      h = speedFactor*cos(angle);

    endif

  endwhile

endfunction

function[X,Y] = RaummitsechsEcken()

X = [10 18 10 30 22 30 10];
Y = [1 16 30 30 16 1 1];

plot(X,Y)
hold on
endfunction

A: Beside using just the angle, you should also set the axis to "equal" to get the correct visual impression of velocity.
p =  plot (x, y, '*');
axis ("equal");

and in the calculation pf the new position
set(p,'YData',get(p,'YData')+0.2*sin(alpha));
set(p,'XData',get(p,'XData')+0.2*cos(alpha));

After collision
alpha = 2*pi*rand ();

which gives (I also modified your room to make it more interesting)


text:
Q: Provide full access over terminal for child, while it alive I use fork() in order to exec some another program, for example "vim" or "man bash". But, at that moment I lost control, I can't print anything in vim or scroll or quite.
So, my question: how give child full access over terminal(input/output) and get it back for parent after child death?

A:
So, my question: how give child full access over terminal(input/output) and get it back for parent after child death?

waitpid() and SIGCHLD are mechanisms for knowing when a child process has finished.  The functions tcgetpgrp(fd) and tcsetpgrp(fd,pgrp) and ctermid() can be used to place a program in the foreground of a terminal.
Otherwise, the information in tcsetpgrp() in 'C' is probably instructive.


text:
Q: Define the file location in the same folder as the python file I want to define the file paths of the following files which are in the same location as the python file. All the questions from the google searches deal with opening the file but not getting the location. How can this be done?
abaqus_input_template_path = '/30_30_0-8.inp'
cost_path = '/CostEstimation_001.xlsx'
pole_option_path = '/지주.xlsx'
chord_option_path = '/상,하현재 .xlsx'
diagonal_option_path = '/사재.xlsx'
element_label_by_type_path = '/Element label number by Type.xlsx'
tunnel_png_path = '/tunnel.png'
mip_obj_path = '/mip_res.obj'

Edit:
test =project(abaqus_input_template_path,cost_path,pole_option_path,chord_option_path,
             diagonal_option_path,element_label_by_type_path,tunnel_png_path,mip_obj_path)

The location is used in another function.

A: You need to provide absolute paths
import os

CURRENT_DIR = os.path.dirname(__file__)  # Gets directory path of the current python module
cost_path = os.path.join(CURRENT_DIR , 'CostEstimation_001.xlsx')

A: If you import the os module, there are a few functions that can help you:
os.path.abspath, which gets you something's path if it's already in the same directory, and
os.walk, which searches for it and gives you it's location.
import os
exe = 'something.exe'
#if the exe just in current dir
print os.path.abspath(exe)
# output
# D:\python\note\something.exe

#if we need find it first
for root, dirs, files in os.walk(r'D:\python'):
    for name in files:
        if name == exe:
            print os.path.abspath(os.path.join(root, name))

# output
# D:\python\note\something.exe

A: You're probably looking for __file__.
Create a script called try_this.py and run it:
from pathlib import Path

print(__file__)
print(Path(__file__).parent)
print(Path(__file__).parent / 'some_other_file.csv')

The result should be something like:
C:/Location/try_this.py
C:\Location
C:\Location\some_other_file.csv

A: For example to find a directory named mattermost in root directory you can use following.
sudo find / -name "mattermost" -type d

for finding file location
sudo find / -name "mattermost" -type f

If you want to get the file locations in your script use os module as suggested by grismar


text:
Q: Pandas apply discounts using equal cell values in different dataframes I am desperate. I am solving this problem for 3 days now. I did try all the solutions in similar posts. My solution worked on other dataframes but fails on a this one.
I have two datasets: one contains item, regular price and discount group column. The second one - discount group and the discount of that group.
I need  take item, get a discount group, look up for discount and multiply it by price. But in some rows I get error. Here is my code:
for index, row in df1.iterrows():

   discount_group = df1['Discount group'][index]
   #this returns data frame with discount group and relevant discount
   discounts_df = df2.loc[df2['Discount group'] == discount_group], 'Discount'
   discount = discounts_df[0].values[0][1]
   row ['Discounted price'] = row['Price'] * discount

But in some cases discounts_df = df2.loc[df2['Discount group'] == discount_group], 'Discount' returns empty data frame. I did convert discount groups columns to float to be sure there is no type mismatch with  df1['RG'] = df1['Discount group'].astype(float). It didn't help.
Maybe there is another solution?
Thanks for help!

A: Using .merge() would be a better solution than .iterrows() I think. .merge() allows database-style joins, see documentation. Here is a toy example that applies a percentage discount (between 0 and 1) to a price column.
import pandas as pd
import numpy as np

facts = pd.DataFrame(
    {
        'price': np.random.randn(10),
        'discount_id': np.tile([1, 2], 5)
    }
)

discount = pd.DataFrame(
    {
        'discount_id': [1, 2],
        'discount_value': [.5, .1]
    }
)

merged = facts.merge(discount, on = 'discount_id')

# Adapt this line to apply your specific discounting logic.

merged['discounted_price'] = merged['price'] - (merged['price'] * merged['discount_value'])

print(merged)

Gives:
      price  discount_id  discount_value  discounted_price
0 -0.186169            1             0.5         -0.093084
1 -1.345143            1             0.5         -0.672572
2 -0.044090            1             0.5         -0.022045
3  0.325579            1             0.5          0.162790
4  0.794152            1             0.5          0.397076
5  1.271465            2             0.1          1.144318
6  1.041492            2             0.1          0.937342
7 -0.774214            2             0.1         -0.696793
8  0.917996            2             0.1          0.826196
9  1.055927            2             0.1          0.950334


text:
Q: White line on screen - software issue My kids just played with my PC and now there's a white line and I can't get it back to normal.
It's a software issue because when I take a screenshot there's nothing wrong

but actually is this

It's some kind of split screen but I don't know exactly.
I'm on windows 7 64bit and dual monitor. The first monitor is normal, but not with this second monitor.
Main display (2) Samsung VGA - the trouble screen
Second display (1) Chimei DVI- normal
Update 1:

*

*I try to swap between main display and second display, vice versa. Still don't work

*Sometimes the monitor is shakes up and down but only below the line. The upper line don't move

A:
It's a software issue because when I take a screenshot there's nothing wrong

On the contrary that means its a hardware issue. Screenshots are not made by reading the physical LCD, they are made by reading internal memory.
You probably need to re-seat the connectors or replace the screen.
Here's what Dell say

The most common cause of these lines is simply a loose connection. As notebook systems are carried around, no matter how careful we try to be, they have a tendency to be bumped, jarred, and even sometimes the heart stopping drop. Though  today's notebooks are designed to better absorb and dissipate small shocks, it can still have adverse affects on the notebook's internal components. A good bump or series of bumps and random movements can cause the LCD cable to become loose.

...

If these simple fixes don't seem to work, then we need to look at the actual failure possibilities. Vertical or horizontal lines that don't disappear after the basic troubleshooting are usually caused by circumstantial failures. The most common type of failure that leads to lines on the display is an open circuit connection between the driver IC (flexible circuit board) and LCD glass. This is usually caused by external stresses (mechanical, thermal, etc…), which causes the flex circuit to detach from the glass.


text:
Q: I can't understand how can i load fastcgi module to apache and run php :S …? Is there anyone may explain how to run fastcgi as a module in Apache server ( 2.x ) on windows platform, step by step.
I ve googled many sites and tested many things but i couldnt make it.
I want to run php with fastcgi using Apache server.
Please help. Thank you.
I ve already have latest fastcgi.dll and added http.conf file LoadModule fastcgi_module "/xampp/apache/modules/mod_fastcgi-2.4.6-AP22.dll"
and its loaded because apache can restart.
What should i do next steps ?

A: In Http.conf file;
1 - You need to load fast_cgi module
LoadModule fcgid_module modules/mod_fcgid.dll
2 - add this :
     <IfModule mod_fcgid.c>
AddHandler fcgid-script .fcgi .php
# Where to look for the php.ini file?
FcgidInitialEnv PHPRC        "c:/xampp/php"
# Set PHP_FCGI_MAX_REQUESTS to greater than or equal to FcgidMaxRequestsPerProcess
# to prevent php-cgi process from exiting before all requests completed
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS      1000
# Maximum requests a process should handle before it is terminated
FcgidMaxRequestsPerProcess       1000
# Maximum number of PHP processes
FcgidMaxProcesses             15
# Number of seconds of idle time before a php-cgi process is terminated
FcgidIOTimeout             120
FcgidIdleTimeout                120
#Path to php-cgi
FcgidWrapper "c:/xampp/php/php-cgi.exe" .php
# Define the MIME-Type for ".php" files
AddType application/x-httpd-php .php
</IfModule>

3 - make sure you give permission to your root directory to run CGI
Options Indexes FollowSymLinks ExecCGI
For a good information you may visit here.


text:
Q: landing on 1st div, scroll down to next div, and disable to scroll back to 1st div. how to achieve this? I have saw something similar effect like this:
The user landed on first div which is the landing section, then the user scroll down to the next div which is where the website start.
And they can't scroll back to the first div/landing section anymore after scrolling down.
I have attached an image here to explain.

How can I do something like this? I remember I have seen it somewhere, but I can't recall back now.
Please help me, thank you.

A: (function($jq) {
$jq(document).ready(function() {
  function FirstScrool() {
    var cScrollVal = $jq(document).scrollTop(),
      body = $jq("body"),
      header = $jq("#Landing"),
      hHeight = header.outerHeight(),
      hClass = "hide-landing";
    console.log("cScrollVal ==>" + cScrollVal)
    console.log("hHeight ==>" + hHeight)
    if (cScrollVal >= (hHeight / 2)) {
      if (!body.hasClass(hClass)) { body.addClass(hClass); }
    }
  }
  $jq(window).scroll(function() {
    FirstScrool();
  });
});
})(jQuery)

Check the below link:
https://codepen.io/gopimx/pen/yLLjbGv


text:
Q: getState() return value for java.util.concurrent.locks.Condition The AbstractQueuedSynchronizer class, a base class for the java.util.concurrent.locks.Condition interface,  has a function called getState()

protected final int getState()
Returns the current value of synchronization state. This operation has memory semantics of > a volatile read.
Returns:
current state value

This function returns the current state of the Condition which I assume to be something like waiting, timed out waiting, aborted, signaled in int form.   Does anyone know where I can find the integer definitions of the getState() function?

A: The meaning of the "state" value is up to the subclass - from the JavaDocs:

This class is designed to be a useful basis for most kinds of synchronizers that rely on a single atomic int value to represent state. Subclasses must define the protected methods that change this state, and which define what that state means in terms of this object being acquired or released.

(my bold)

A: Found in com.google.common.util.concurrent.AbstractFuture.Sync
/* Valid states. */
static final int RUNNING = 0;
static final int COMPLETING = 1;
static final int COMPLETED = 2;
static final int CANCELLED = 4;
static final int INTERRUPTED = 8;

Though interfaces usually don't describe implementation details, so the values might be associated to different events in other implementations.


text:
Q: Using icons from system versus copying them into your project For common Android icons (such as context menu icons) I typically copy the standard Android icons into my project. I realized recently that you can also get those icons from the system using android.R.drawable.blablabla. So my question is, is there any reason to prefer one approach over the other?
And if using the system ones is better, how do you access them in XML?
Thanks!

A: You can access them by prepending '@android', i.e.:
<Image android:src="@android:drawable/ic_menu_add" android:layout_height="wrap_content" android:layout_width="wrap_content"/>

If you use the system resources you'll have less control about how exactly the ressource will look like. You will get the ressource installed on the current device, and that differs throughout devices, manufactures and android version.

A: Reference system images
The general advice is to reference system images where possible

*

*GOOD: Will match the OS level (some icons change during the iterations)

*GOOD: Will play well with stock UI and custom Themes

*GOOD: No need to show the Apache2 license (IANAL)

*BAD: May break the appearance of your app

*BAD: Limited to officially exported images

As you can see there are downsides to both solutions. You can, for example, use the black and white Browser icon to symbolize a link to the browser. The icon is not officially exported, you thus need to copy it. But you have to obey the license of the used artwork in this case. This includes an attribution to content created by the Android Open Source Project (see your copy of the License file for details)
Usage in XML
You can always use the android: prefix to reference system icons in your app. An example would be
@android:drawable/ic_menu_add

This applies to strings and other resources as well, like the "OK" text.

A: It's better to copy them into your project, as the system icons are not guaranteed to remain in future builds or keep the same name.  Copying them into your project gives your app a consistent look and feel across builds and gives you the peace of mind that your icons will always work.


text:
Q: Issues when using while loop When I use a simple while loop like the one below, my app's UI will freeze:
func viewDidLoad(){
  super.viewDidLoad()
  while(true){
  print(CheckDB());
  }
}

Again, the program with that one is that the UI freezes but it does output the data. When I try to make it asynchronous the UI does not freeze and my data is still being printed, but the problem now is that adjusting a slider I have in my UI does not do anything when it should be printing the number it is at, so while the UI does work at that point, it is literally just the UI and nothing else.
func viewDidLoad(){
 DispatchQueue.global(qos: .default).async {
   while(true){
   super.viewDidLoad()
   print(CheckDB());
  }
}

So my question now is, how do I have a constant loop running in the background updating some UI elements like Labels without messing up other parts of the app?

A: Sounds like you have some threading issues you need to work out, but this is generally a bad approach anyway.
If you need to change something in you UI when your DB changes, you should be using a notification or listener/delegate from the DB rather constantly checking in your VC.


text:
Q: exit from click handler How do you exit from an event?
$('.more').click(function() {
   if (condition1) {
      if (condition2) {
         // abort, exit completely out of click handler
      ...

A: Use the return there:
$('.more').click(function() {
   if (condition1) {
      if (condition2) {
         // abort, exit completely out of click handler
         return;

See:
Interrupting a function Safely

A: return;
That will take you out of the function that is associated with the on click handler;

A: Note that you can also use break here.
$('.more').click(function() {
   if (condition1) {
      if (condition2) {
         // abort, exit completely out of click handler
         break;

A: I no longer use anonymous functions because my understanding of JavaScript jumped to a new plateau when I started naming them. And besides, naming your functions provides a kind of inline documentation:
$('.more').click(myFunction)

function myFunction() {
   if (condition1) {
      if (condition2) {
         return
      }
   }
}


text:
Q: my ios developer account can't access "Certificates, Identifiers & Profiles" anymore Recently I login my ios developer account and try to access "Certificates, Identifiers & Profiles", it shows need review the new license agreement. I clicked the Review button, it always jump to this page: http://devimages.apple.com/maintenance/#updateAgreement.
I can't found any agree button on this page. How can I review and agree the program license agreement?

A: Apple's dev centre was recently the target of a security breach which resulted in the dev centre being made unavailable for 8 days. Apple have since re-enabled the certificates part of the dev centre and you should be able to access it again.
I would suggest removing any cookies and emptying your browser caches, as it seems it's still cached for you.
You can keep up to date on the dev centre's status here: https://developer.apple.com/support/system-status/


text:
Q: Splitting multiple values into different arrays have been stuck on this for the past few days
my array contains
int a={1,2,3,4,5,6,7,8,9,10,11,12};
I have to split them up into 2 different arrays such that
int b={1,2,3,7,8,9};
int c={4,5,6,10,11,12};
is there any function for this? I have tried using the for loop but I am unable to print c without printing the first few values.
any help would be much appreciated
#include <stdio.h>

int main(){

    int a[12];
    int b[6];
    int c[6];

    for(int i=0;i<12;i++){

        b[i]=a[i];
        for(int b=3;b<12;b++){
            c[i]=a[i]
        }
    }

}


text:
Q: An add-in in Excel for Mac cannot be updated I have an add-in 10 Studio in AppSource.
The current version (on 08/22/2019) is 1.5.1.0. We load well this version in Excel for Windows:

However, when we load the same add-in from the add-in Store in Excel for Mac, it returns the version 1.3.0.0.

It seems that the old version in Excel for Mac cannot be overridden. I followed this method, cleared web cache by using the personality menu from the task pane, and remove everything in ~/Library/Containers/com.microsoft.Excel/Data/Library/Caches/. But the old version was still there and could not be overridden by the new version from the Store.
Does anyone know what's happening here?

A: Did you try first removing the old version?
How to uninstall an Add-in (Mac)
If you wish to uninstall an Add-in completely, delete, move or rename the original Add-in file.
When ticking or unticking the Add-in, a message box will appear, asking for permission to delete the reference to the Add-in. Click Yes.
The Add-in will no longer appear in the list of Add-ins.
(Source)


text:
Q: HttpClient postasync request not working with fully qualified hostname, but works using IP address for windows service This is strange, I have C# HttpClient PostAsync method, it works with IP and without fully qualified hostname however, it does not work with the fully qualified hostname though it works with postman, any idea what is the issue.
Eg; if I enter IP:portname or myvdi:postname it works
but I enter myvdi.swq.tst.local it does not work and it throws error "Method not found"
I repeat no issue with the postman, both cases work in postman.
var client = new HttpClient();
var requestData = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("grant_type", "password"),
    new KeyValuePair<string, string>("username", "myusername"),
    new KeyValuePair<string, string>("password", "mypassword")
};

var payload = new FormUrlEncodedContent(requestData);

payload.Headers.ContentType =
    new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "UTF-8" };

var response = client.PostAsync(new Uri("https://myvdi.swq.tst.local:8096/SourceCtl/source/api/token"), payload).ConfigureAwait(false).GetAwaiter().GetResult();

The URL is windows service and it is configured with OWIN token so it first calls OWIN.
Fiddler

A: Finally, I have to help myself, this might help someone else, you need to make sure that you register all the endpoints in OWIN, I registered it for a fully qualified name and it worked.
    var options = new StartOptions();
    options.Urls.Add($"https://myvdi.swq.tst.local:portno/source/api/token");

    WebApp.Start<Startup>(options);


text:
Q: boolean iteration with python for some reason this isn't working for me. trying to remove element in list 'lst' that exist in list 'ex'. This should work and it doesn't. However, when i have only one of the elements in the list 'ex', it works. FOr instance it list 'ex' only contained '1' it removes it from the list lst.
lst=['1A','1B','1C','1D','1E', \
    '2A','2B','2C','2D','2E', '2F', \
    '3A','3B','3C','3D','3E','3F', \
    '4A','4B','5A','1X','2X','5B','5C','1','2']
ex = ['1','2','1X','2X']
for el in lst:
    if any(el != x for x in ex):
        print el

A: I wouldn't call this exactly remove, but what you should use here is all instead of any.
A more clear alternate is to use in operator.
for el in lst:
    if el not in x:
        print el

Note this is actually equivalent of saying that all of elements in x must not be the same as el, not any.


text:
Q: Introduction to the Theory of Distributions, Friedlander and Joshi, Exercises 1.3 and 1.4 The problems are:

*

*Show that for each $\phi \in C_{C}^{\infty}(\mathbb{R})$, the principal value integral $$\text{p.v.}\int\frac{\phi(x)}{x}\text{d}x = \lim_{\epsilon \to 0^+}(\int_{(-\infty,-\epsilon)}\frac{\phi(x)}{x}\text{d}x+\int_{(\epsilon,\infty)}\frac{\phi(x)}{x}\text{d}x)$$ exists and is a distribution. What is its order?

*Find a distribution $u \in \mathcal{D}'(\mathbb{R})$ such that $u=1/x$ on $(0,\infty)$ and $u=0$ on $(-\infty,0)$.
So far I think I can show that given $\phi \in C_{C}^{\infty}(\mathbb{R})$ and the function $f$ defined by $$f: (0,\infty) \to \mathbb{C}$$ $$x \mapsto \frac{\phi(x)-\phi(-x)}{x},$$ we have that $f$ is continuous and $\int_{[0,1]}f$ exists. Furthermore, I can show that, by the Mean Value Theorem, $|\int_{[0,1]}f| \leq 2\sup_{x \in \mathbb{R}}|\phi'(x)|$, $|\int_{[1,\infty)}f\text|<2\sup_{x\in\mathbb{R}}|x\phi(x)|$.
This then means the principal value integral is (obviously) linear and bounded by the appropriate semi-norm, and is therefore a distribution, correct? The inequalities above tell me it's order is then $1$, correct? This then settles the first question, correct?
(The above is based on: https://en.wikipedia.org/wiki/Cauchy_principal_value#Well-definedness_as_a_distribution)
Now, for question 2, I'm supposed to find a function $u: C_C^{\infty}(\mathbb{R}) \to \mathbb{C}$, correct? I am then having trouble understanding what it means to say that "$u=1/x$ on $(0,\infty)$ and $u=0$ on $(-\infty,0)$", given the that the domain of $u$ is not (a subset of) the real line. Anyway, I think that this entire problem has something to do with the fact that $(\log \circ |.|)'=\frac{1}{.}$, correct?

A: For your question 2 (it's nice when a question only has one question!) consider
the function $g(x)=\ln x$ for $x>0$ and $g(x)=0$ for $x\le0$. Then $g$ is locally $L^1$, so defines a distribution, and $g'(x)=1/x$ for $x>0$. So $g'$ (considered
as a distribution) is an admissible $u$. Therefore
$$\left<u,\phi\right>=-\int_0^\infty\phi'(x)\ln x\,dx$$
works.
If you don't like derivatives, then integration by parts will give
you the alternative formula
$$\left<u,\phi\right>=\int_0^1\frac{\phi(x)-\phi(0)}{x}\,dx
+\int_1^\infty\frac{\phi(x)}{x}\,dx.$$
Of course, this $u$ is not unique, as you can add any linear combination
of the Dirac delta function (at $0$) and its derivatives to $u$.


text:
Q: How to get a rout information with trafic flow information included for a past date? I am trying to use Azure Maps API. It will be nice to have route information which should include the locations of course and a speed profile. As you can understand speed profile is not an east one. Free flow speed profile is ok. But we want to simulate real-world conditions meaning that we want to select date and time of departure to get accurate speed information as close to as possible to a real world traffic influence.
Is there any feature that Azure provide this? If not, which API can provide this
I don't have any code at this moment to show since ı don't know which API to use.

A: Historical traffic data is not currently available in Azure Maps but is being investigated as a potential future feature.


text:
Q: Apache Beam With GCP Dataflow throws INVALID_ARGUMENT I have been trying to migrate data from one BigQuery project to another BigQuery project. When I try to execute it for 20 tables it works fine. But, whenever try to add more tables then it crashes with :

Reporting job status failed with error code: INVALID_ARGUMENT

My Code looks like:
PCollection<TableRow> rows;
List<String> tablesNames = fetchTablesFromSourceBigQuery();
PipelineOptionsFactory.register(MyOptions.class);
MyOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(MyOptions.class);
Pipeline p = Pipeline.create(options);
for(String tableName: tableNames){
   rows = p.apply("Reading from table",  BigQueryIO.readTableRows().from("sourceProject:sourceDataset."+tableName);
   rows.apply("Writing to table", BigQueryIO.writeTableRows().to("destProject:destDataset."+tableName);
}
p.run();

A: This issue is caused because the job graph is too large.
The Issue can be resolved by including the flag --experiments=upload_graph in the code.
For more information this code and stack link can be referred.


text:
Q: Search functionality django I've been following the tango with django book and I came across the search chapter using Bing's Search API. I tried to use it but it seems like Bing no longer offers those services. Now I want to make the search functionality local so that it could just search through my categories in the rango app but I don't know how to do this without the Bing search API. Anyone who could help me with a way around it if there is. Thanks in advance.

A: Here's an example to implement basic search in django:
1) templates/base.html
note: use GET method to get search input from form.
<form name="exampleform" method="GET" action="{% url 'search' %}">

2) views.py
def search(request):
    try:
        if 'q' in request.GET:# this will be GET now
            querystring = request.GET.get('q')# passing in the query value to search view using the 'q' parameter
            if len(querystring) == 0:
                return redirect('index')
            else:
                pass
    except:
        pass

    results = {}

    if 'q' in request.GET:
        querystring = request.GET.get('q')
        if querystring is not None:
            results = UserModel.objects.filter(
                Q(email__icontains=querystring) |
                Q(first_name__icontains=querystring) |
                Q(last_name__icontains=querystring)).order_by('pk')# filter returns a list
            context = {'results': results}
            template = 'templates/search_result.html'
            return render(request, template, context)
        else:
            return redirect('index')
            context = {}
    else:
        return render(request, "templates/search_result.html")

2) urls.py
url(r'^search',views.search, name='search'),

3) templates/search_result.html
{% for each_object in results %} // results is list here so pick each element object using for loop

{{each_object.email}}

{{each_object.first_name}}

{{each_object.last_name}}

{% endfor %}

There are a few projects around to do search. Here's a non-exhaustive list: djangosearch, django-search (with a dash), django-sphinx.


text:
Q: is there a Windows Forms control that will allow the user to select multiple folders? I tried both the OpenFileDialog and the FolderBrowserDialog controls and the first one does not allow me to select folders while the second one allows me to select only 1 folder.
Any other controls that will do what I want or will I need to create my own?

A: The FolderBrowserDialog only allows to select one folder. Try this:
http://www.codeproject.com/Articles/4472/Enhanced-BrowseForFolder-styled-TreeView

A: Why don't you look at these references:

*

*Browse Multiple folders using FolderBrowserDialog in windows application

*C# - How to customize OpenFileDialog to select multiple folders and files?
Hope this will help you.


text:
Q: Non cyclic group of order $p^3$ satisfies $G \simeq H \rtimes_{\theta}K$ Let $G$ be a non-cyclic group of order $p^3$ for an odd prime $p$. Prove that $G \simeq H \rtimes_{\theta}K$, where $H$ is a normal subgroup of $G$ of order $p^2$, $K$ is a subgroup of order $p$, and $\theta : K \to Aut(H)$ is a homomorphism.

I managed to prove that there exists a normal subgroup $H$ of order $p^2$. Then I took some $g \in G-H$. If $g$ is of order $p$, I am done since $G \simeq H \rtimes \langle g \rangle $. But what if all $g \in G - H$ are of order $p^2 $?

A: The result follows immediately if all elements of $G$ have order $1$ or $p$, so we can assume that there exists an element of order $p^2$. This generates a cyclic subgroup of index $p$, which is normal in $G$, so we can assume that $H$ is cyclic of order $p^2$.
So let $g \in G \setminus H$, and assume that $g$ has order $p^2$ (if it has order $p$ then we are done). So $g^p = h^p$ for some $h \in H$. We claim that $(gh^{-1})^p=1$, and hence $gh^{-1}$ has order $p$ and we are done.
This is immediate if $G$ is abelian, so suppose not. Then $[G,G]=Z(G)$ has order $p$, so commutators are central, and $(xy^{-1})^p = x^py^{-p}[y^{-1},x]^{p(p-1)/2}$ (where $[a,b]$ denotes the commutator $a^{-1}b^{-1}ab$).
Then, since $p$ is odd and $[y^{-1},x]$ has order $p$, we get $[y^{-1},x]^{p(p-1)/2}=1$ and the claim follows. (Note that this result is false when $p=2$, and the quaternion group $Q_8$ is a counterexample.)


text:
Q: Traversing recursively through a matrix in java to find the best path I am trying to write some Java code that I will later translate into MIPS assembly. So I am trying to keep it as simple as possible. I need to traverse diagonally down a matrix, summing up the numbers, to find the highest sum path. I am completely lost on how to write this recursive method, any help will be much appreciated!
This is the code I've written so far, first being the main method, which creates the 'game board' and calls the method. The method then translates the given single array into a 2D array. Taking that 2d array and recursively finding the best path is what I am stuck on.
public class intro {
    public static void main (String[] args){
        int[] board = {10, 5, 3, 9, 6, 3, 1, 7, 10, 2, 9, 8, 4, 1, 11, 14, 18, 20, 13, 12};
        int max_rows = 4;
        int max_cols = 5;
        playCheckers newGame = new playCheckers(board, max_rows, max_cols);
        newGame.play();
    }
}

public class playCheckers {

    private int[] board;
    private int max_rows;
    private int max_cols;

    public playCheckers(int[] board, int max_rows, int max_cols){
        this.board = board;
        this.max_rows = max_rows;
        this.max_cols = max_cols;
    }

    public void play(){
        int[] sum = new int[max_cols];
        int[][] newArr = new int [max_rows][max_cols];
        int result = 0;
        int arrCount = 0;
        ///Turns single array into 2D array///
        for(int i=0; i < max_rows; i++){
            for(int j=0; j < max_cols; j++){
                newArr[i][j] = board[arrCount];
                arrCount++;
            }
        }

        System.out.println("The max value is " + result + " starting at column " + col);
    }
}


text:
Q: Azure Logic App - Assign variable to another variable results in a different value. Possible bug? I created a simple Azure Logic App that loops through every row in an excel table and assigns the value of a field in the file called "Input ID" to a variable called "Input ID" and then assigns the value of Input ID to another variable called "Message to User"; however, the values of "Input ID" and "Message to User" are different. Could someone help explain what I may be doing wrong?
enter image description here
enter image description here

A: The default behaviour of Foreach LINK is to execute all steps concurrently or in parallel which would possibly explain why you are seeing the different values.
If you want to change this behaviour to execute each step only after the previous one has finished(i.e. sequentially), you can do this following the instructions HERE.


text:
Q: CloudPageURL via SMS broken link I've found that using CloudPagesURL via SMS will always result in the Server Error 500 page, no matter if the URLEncode is used or not, even if the CloudPage itself just holds simple text.
CloudPage is published and in the same MID.
No additional parameters aside from the CloudPage ID are being passed, yet I see the full URL of it does contain something else.
SMS Example:
%%[
var @link
set @link = CloudPagesURL(2298)
]%%

The output of the link will be: https://pub.s7.exacttarget.com/r4a1bz43j0p?qs=ac100395ce51f9cd5513c02ebeb86e36e2b6f299cccd594e
While the actual page is just https://pub.s7.exacttarget.com/r4a1bz43j0p
Why does it get some parameter added?
Why does the page with this parameter always end up in Server Error 500?
Also, an interesting detail - when sending out test SMS, then I am able to access the page.

A: Well then, got this issue solved.
When using CloudPagesURL ampscript function link creation via MobileConnect, then the Contact this SMS is sent to, needs to exist in Email channel AllSubscribers list with the same SubscriberKey/ContactKey.
Apparently the CloudPagesURL will use Email channel data to generate the URL, thus when it cannot find a matching Contact in AllSubscribers list - the link it generates will be broken.

A: Why does it get some parameter added?
- Normally CloudPagesURL will add parameters like jobid, listid, sk (subscriberkey) when being sent from Email Studio. I tried getting these values when sending from MobileConnect but it seems none of them were there. I would recommend opening a ticket with SF to get information on what values are added in MobileConnect
Why does the page with this parameter always end up in Server Error 500?
- In my testing there was no issues when using CloudPage %%=CloudPagesURL(55)=%% in MobileConnect.My Guess is that the Cloud Page itself has issues in it, potentially one of the parameters passed in the QS is causing conflict. Does the cloud page contain anything like %%=RequestParameter('sk')=%%?

A: Could you try the following and see whether it works?
%%[
SET @link = RedirectTo(CloudPagesURL(2298))
]%%


text:
Q: Using WMI Code Creator to Create Code to Scan for Attached USB Devices How can I use the WMI Code Creator to create code to scan for attached USB devices?  I've downloaded the utility, but I'm a bit lost on how to use it.  Thanks.

A: In the WMI Code Creator select these options:
Namespace: root\WMI
Class: MSWmi_PnPInstanceNames
Select InstanceNames from the Results box for the following code:
using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\WMI",
                    "SELECT * FROM MSWmi_PnPInstanceNames");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("MSWmi_PnPInstanceNames instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}


text:
Q: What happens to a backup job, if it is scheduled and some prompt occurs? For years we've backed up our system, using a tape drive on one of our Windows 2003 R2 servers.  And we've done this manually.  Whenever we do this, we'll put the tape into the drive, and get into the Windows Backup and Restore utility, bring up the saved backup job script, and run it.  It always prompts us twice; once to ask if we want to overwrite the data on the tape and to confirm the old save set.
That's nice and all, but I'd like to schedule this so that it happens automatically.  I've found on enter link description here an article that describes how to schedule backups using the Windows Backup and Restore utility.  So that's great and all, but what about those prompts?  I certainly don't want this backup job waiting hours for some human to come along and click the OK button.

A: Assuming you're using the Windows 2003 Backup and Restore Utility - are there not options you can set when you create the backup schedule job that make sure it doesn't prompt?  Maybe you should try and find out?
Here's how to schedule a backup.
Here's how to set options, and advanced options.


text:
Q: Load svg through react: currentColor from CSS variable I am loading svgs through react: my problem now would be to load it using currentColor from CSS variable
import SvgItem from '-!svg-react-loader!./item.svg';

const MyComponent: React.FunctionComponent = () => {
  return (

            <SvgItem />

   );
}

It works using style={{color:"blue"}} but not using the CSS var.
<svg fill="currentColor" >
    <path d="M170.056 30.0762L97.089"/>
</svg>

My only way now is to create a react component for each SVG file...
Thanks a lot!

A: It works for both css variables and currentColor, I think the reason it doesn't work is because your d of the SVG path is corrupted(if you didn't crop it).

    <svg fill="var(--color-primary)" width="100" height="100" viewBox="0 0 1 1">
        <path d="M.5,0 L1,1 H0" />
    </svg>

    <svg fill="var(--color-primary)" width="100" height="100" viewBox="0 0 1 1">
        <path d="M.5,0 L1,1 H0" />
    </svg>

    <svg fill="currentColor" width="100" height="100" viewBox="0 0 1 1">
        <path d="M.5,0 L1,1 H0" />
    </svg>

Then you can just pass in the color props to assign color dynamically:
import SvgItem from '-!svg-react-loader!./item.svg';

const MyComponent: React.FunctionComponent = ({ color }) => {
  return (

            <SvgItem />

   );
}

For the SvgItem:
<svg fill="currentColor" >
    <path d="M170.056 30.0762L97.089"/>
</svg>

To assign its color:
<MyComponent color="red" />


text:
Q: Unable to remove user Glance Installed and removed glance but the user glance is listing at the time of login. How can I remove user glance?
Already tried sudo apt remove glance
glance is removed but not the user.

A: Have you tried sudo deluser glance?
If there is a home directory as well, use sudo deluser --remove-home glance
You can find more info about it here

A: At first, Clicked Activities and searched for users. There I've got all the users then selected user glance and clicked delete, the user is deleted.


text:
Q: ConcurrentModificationException while displaying chats in recyclerView I am displaying chats in fragment through firebase but it gives ConcurrentModificationException error.

Below is the code in which error is occuring.
CODE:
public void readChats() {
    mUsers = new ArrayList<>();
    reference = FirebaseDatabase.getInstance().getReference("Users");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            mUsers.clear();
            for (DataSnapshot snapshots: dataSnapshot.getChildren()) {
                User user = snapshots.getValue(User.class);
                for (String id :usersList) {
                    if (user.getID().equals(id)) {
                        if (mUsers.size()!=0) {
                            for (User user1 : mUsers) {
                                if (!user.getID().equals(user1.getID())) {
                                    mUsers.add(user);
                                }
                            }
                        } else {
                            mUsers.add(user);
                        }
                    }
                }
            }
            userAdapter = new adapter(getContext(), mUsers);
            recyclerView.setAdapter(userAdapter);
        }

A: If you're looping over a Collection via its Iterator (like in a for(var : collection) loop ), you can't change that collection while you do so.  Doing so is a ConcurrentModification, and invalidates the iterator.
In addition, your code would be broken anyway.  If the last item in mUsers isn't user1, it would infinite loop even if it concurrent modifications were allowed.


text:
Q: Update ListView Items I have a strange problem, I have a few different items in my ListView, which are enabled/disabled based on a preference. They show up in their enabled/disabled state correctly based on the preference, but if they were visible in the list when you open up the preference activity, they wont go to their correct state until they move off screen and back
I've tried calling getListView().refreshDrawableState() onResume of the main activity that the ListView is in, but it didn't seem to do anything.
@Override
public void onResume(){
    super.onResume();
    getListView().refreshDrawableState();
}


text:
Q: Can't upgrade Dropbox on headless Ubuntu 14.04 server Every time I run dropbox update I get the following error. Yeah, no idea what that means.
Traceback (most recent call last):
  File "/usr/bin/dropbox", line 1436, in <module>
    ret = main(sys.argv)
  File "/usr/bin/dropbox", line 1425, in main
    result = commands[argv[i]](argv[i+1:])
  File "/usr/bin/dropbox", line 845, in update
    download()
  File "/usr/bin/dropbox", line 586, in download
    get_download_debug_info(download.url, ex))
UnboundLocalError: local variable 'ex' referenced before assignment

A: I had the same problem and solved it as follows:
(Note, you might have dropbox installed in various ways, it can be installed as a package nautilus-dropbox or in your home directory at ~/.dropbox-dist and possibly both which is confusing.)

*

*Uninstall all dropbox installations:

*

*If you've got the package nautilus-dropbox installed then uninstall it: sudo apt-get remove nautilus-dropbox and check there's nothing left in /var/lib/dropbox

*Follow the steps to uninstall (click "Linux" in the top right of this page) which is basically
sudo apt-get remove dropbox; rm -rvf ~/.dropbox ~/.dropbox-dist (avoid deleting your actual files from ~/Dropbox)

*Install latest version:

*

*Follow steps here (under "Install Dropbox via command line") to install it in your home directory

*it ends up in ~/.dropbox-dist (avoid installing the package nautilus-dropbox on a server, it'll give you another copy of dropbox in /var/lib/dropbox which gets confusing).

*To control Dropbox from command line:

*

*Download the command line control script dropbox.py (should also be linked to from here)

*Make it executable chmod +x ~/Scripts/dropbox.py and then make a symlink to it sudo ln -s ~/Scripts/dropbox.py /usr/bin/dropbox

*Then you can control it with things like dropbox status see dropbox help for more

*If you want Dropbox to auto-start on startup, follow a guide like this to make a service script /etc/init.d/dropbox


text:
Q: Hive: joining multiple tables with same key I am trying to join multiple tables in hive which have a common key col
create table merged_table as
select a.*,b.*,c.* from table1 a
join table 2 b
on a.col = b.col
join table3 c
on c.col = d.col

But this gives the following error:

FAILED: SemanticException [Error 10036]: Duplicate column name: col

These tables have many columns. Is there any way by which this can be done without explicitly writng the column names in the query?

A: You cannot create a table with duplicate column names. While it is possible in SQL top level SELECT statements to produce ambiguous / duplicate column names, such queries cannot be used in CREATE TABLE AS SELECT. You should rename each individual column name, possibly prefixing them all with the origin table name:
create table merged_table as
select a.col1 as a_col1, a.col2 as a_col2, ..., b.col1 as b_col1, ...
from table1 a
join table2 b on a.col = b.col
join table3 c on b.col = c.col


text:
Q: How to handle a subscribed user logging out? In an application I am building, it is possible for a logged in user to receive specific push notifications related to activity their user account is participating in or subscribing to.
As it stands at the moment, if a user logs out, they remain subscribed and the service worker remains registered.
However, it would mean that push notifications they've subscribed to will still be received.
On the plus side, however, it means that if the original user logs in again, they won't need to go to their preferences and re-enable notifications and re-register a new service worker/subscription.
Does anyone have any examples of how to approach this in a secure way so notifications are not leaked after logging out, but maintaining the existing subscription in case they log back in? Is it even possible?
Thanks,
P

A: Usually you have an endpoint in your database associated to a user ID, so that you can target that user with push notifications.
When the user logs out you can simply remove the association between the endpoint and the user ID in your database.


text:
Q: Shopify Multi-currency is not working for orders in customer account page I am trying to implement multi-currency in one of my testing store.
Everything works great but in customer's account page where orders are displyed currency is not updating.
The symbol of currency is changed but the price is not updating.
Please check attached screenshot for the reference.

The theme I am using is simple theme from free themes.
Is there any particular reason for that?
Or Do I need to update the liquid code?
Do I missing some steps for multi-currency feature?
Any help will be awesome.


text:
Q: GWT - Vertical border line divides panel on two parts Does anyone know how to make, in GWT, panel which has a vertical boundary line that divides the panel on two parts same like this http://code.google.com/webtoolkit/overview.html ?
I want when click on the blue border line to hide/show left menu same as on the above link.
I can't to find any example of that.
Thank you.

A: Here is your boy : http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/user/client/ui/VerticalSplitPanel.html
You can configure the handler of the bar so that it does what you want.


text:
Q: How to change
* background image while hover on a specific
*? I know that 'li' it is a child of the parent 'ul' so We can't achieve it only with CSS3 or is it possible? I can add JavaScript but i can't change HTML because it is generated by PHP.
With this simple example:

#container{width: 500px;
  min-height: 300px;
  background: url("https://cdn.pixabay.com/photo/2016/03/09/11/44/network-1246209_960_720.jpg");}
ul{list-style: none}
a { text-decoration: none;
color: white;
font-size: 32px;}
a:hover { text-decoration: none;
color: Chartreuse;
font-size: 32px;}
li{padding-top: 1em;}

/* url("https://cdn.pixabay.com/photo/2016/08/12/14/25/abstract-1588720_1280.jpg")

url("https://cdn.pixabay.com/photo/2015/01/12/17/40/padlock-597495_960_720.jpg")

  url("https://cdn.pixabay.com/photo/2016/01/14/05/51/rj45-1139366_960_720.jpg")

  */

    Number 1

    Number 2

    Number 3

when I hover 'Number 1' I want that ul background it will be this image:
url("https://cdn.pixabay.com/photo/2016/08/12/14/25/abstract-1588720_1280.jpg")
hovering 'Number 2' I want this ul background image:
url("https://cdn.pixabay.com/photo/2015/01/12/17/40/padlock-597495_960_720.jpg")
and finally when I hover li 'Number 3' the correspondent ul background change for this image:
url("https://cdn.pixabay.com/photo/2016/01/14/05/51/rj45-1139366_960_720.jpg")
Thank You

A: You can not alter the parent with CSS at this current time. You can alter a sibling.

#container {
  width: 500px;
  position: relative;
  min-height: 300px;
}

ul {
  list-style: none
}

a {
  text-decoration: none;
  color: white;
  font-size: 32px;
}

a:hover {
  text-decoration: none;
  color: Chartreuse;
  font-size: 32px;
}

li {
  padding-top: 1em;
}

.bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: url("https://cdn.pixabay.com/photo/2016/03/09/11/44/network-1246209_960_720.jpg");
  transition: background-image 0.3s ease-in-out;
}

#option1:hover~.bg {
  background: url("https://cdn.pixabay.com/photo/2016/08/12/14/25/abstract-1588720_1280.jpg");
}

#option2:hover~.bg {
  background: url("https://cdn.pixabay.com/photo/2015/01/12/17/40/padlock-597495_960_720.jpg");
}

#option3:hover~.bg {
  background: url("https://cdn.pixabay.com/photo/2016/01/14/05/51/rj45-1139366_960_720.jpg");
}

    Number 1

    Number 2

    Number 3

If you want to keep it with the parent, you need to use JavaScript.

var ul = document.querySelector("#container");

function toggleIt(event) {
  const onOff = event.type === 'mouseenter';
  var li = event.currentTarget;
  var cls = li.dataset.bg;
  console.log(onOff, cls);
  ul.classList.toggle(cls, onOff);
}

var lis = document.querySelectorAll("ul li")
lis.forEach(function(li) {
  li.addEventListener("mouseenter", toggleIt);
  li.addEventListener("mouseleave", toggleIt);
});
#container {
  width: 500px;
  min-height: 300px;
  background: url("https://cdn.pixabay.com/photo/2016/03/09/11/44/network-1246209_960_720.jpg");
  transition: background-image 0.3s ease-in-out;
}

ul {
  list-style: none
}

a {
  text-decoration: none;
  color: white;
  font-size: 32px;
}

a:hover {
  text-decoration: none;
  color: Chartreuse;
  font-size: 32px;
}

li {
  padding-top: 1em;
}

#container.bg1 {
  background-image: url("https://cdn.pixabay.com/photo/2016/08/12/14/25/abstract-1588720_1280.jpg");
}

#container.bg2 {
  background-image: url("https://cdn.pixabay.com/photo/2015/01/12/17/40/padlock-597495_960_720.jpg");
}

#container.bg3 {
  background-image: url("https://cdn.pixabay.com/photo/2016/01/14/05/51/rj45-1139366_960_720.jpg");
}

    Number 1

    Number 2

    Number 3

because you said you do not want to change anything, use the ids

var ul = document.querySelector("#container");

function toggleIt(event) {
  const onOff = event.type === 'mouseenter';
  var li = event.currentTarget;
  var cls = li.id;
  console.log(onOff, cls);
  ul.classList.toggle(cls, onOff);
}

var lis = document.querySelectorAll("ul li")
lis.forEach(function(li) {
  li.addEventListener("mouseenter", toggleIt);
  li.addEventListener("mouseleave", toggleIt);
});
#container {
  width: 500px;
  min-height: 300px;
  background: url("https://cdn.pixabay.com/photo/2016/03/09/11/44/network-1246209_960_720.jpg");
  transition: background-image 0.3s ease-in-out;
}

ul {
  list-style: none
}

a {
  text-decoration: none;
  color: white;
  font-size: 32px;
}

a:hover {
  text-decoration: none;
  color: Chartreuse;
  font-size: 32px;
}

li {
  padding-top: 1em;
}

#container.option1 {
  background-image: url("https://cdn.pixabay.com/photo/2016/08/12/14/25/abstract-1588720_1280.jpg");
}

#container.option2 {
  background-image: url("https://cdn.pixabay.com/photo/2015/01/12/17/40/padlock-597495_960_720.jpg");
}

#container.option3 {
  background-image: url("https://cdn.pixabay.com/photo/2016/01/14/05/51/rj45-1139366_960_720.jpg");
}

Number 1

Number 2

Number 3


text:
Q: iterate through arraylist and display elements respectively using a button I want to iterate through this array.
const array = ['item1', 'item2', 'item3', 'item4', 'item5'];

and display the first item by default in a div and use a button to display the next item (also replace the old item) in the same div i did try this but it didn't work
const quizConainer = document.getElementById('quiz');
const next = document.getElementById('next');

    const array = [
      '
item1
',
      '
item2
',
      '
item3
',
      '
item4
',
      '
item5
',
    ];

    quizConainer.innerHTML = array[0];

    function nextItem() {
      for (let i = 0; i < array.length; i++) {
        if (quizConainer.innerHTML === array[i]) {
          quizConainer.innerHTML = array[i++];
        }
      }
    }

    next.addEventListener('click', nextItem);

and thats the html

 <button id="next">Next</button>

A: You can create a counter and keep a track of the current element in display.Also as the first element is default shown there may not be any need to put it in the array.

const quizConainer = document.getElementById('quiz');
const next = document.getElementById('next');
const array = [
  '
item2
',
  '
item3
',
  '
item4
',
  '
item5
',
];
let counter = 0

function nextItem() {
  if (counter < array.length) {
    quizConainer.innerHTML = array[counter];
    counter++;
  }

}

next.addEventListener('click', nextItem);

item1

<button id="next">Next</button>

A: Declare a global variable . That can help you here instead of loop .
Edit : Added jsfiddle

<button id="next">Next</button>

A: Please check this one
In this example, I added a global variable to hold the current position of the array that's being used. And the check is done with that particular variable only.
Also, it is not a good practice to hold HTML tags in an array. So I changed it as well.
This example will start from the zeroth position and will iterate till the end of the array and then will again start from the beginning.

const quizConainer = document.getElementById('quiz');
const next = document.getElementById('next');
let currPosition = 0; //To hold the element which is currently in DOM

const array = ['item1', 'item2', 'item3', 'item4', 'item5'];

quizConainer.innerHTML = '
' + array[0] + '
';

function nextItem() {
  if(currPosition === array.length - 1)
    currPosition = 0;
  else
    currPosition++;

  quizConainer.innerHTML = '
' + array[currPosition] + '
'
}

next.addEventListener('click', nextItem);

 <button id="next">Next</button>


text:
Q: com/mongodb/MongoException in Siddhi app mongo-store extension I'm working in WSO2-SI (streaming integrator) and building some siddhi apps. I came to need to use a mongodb-store extension which is available in siddhi store. I installed the extensions and configure the @store with type mongodb. But It seems that, I can't run the app because I'm facing an error com/mongodb/MongoException. Sometime, when I restart the SI, I see com/mongodb/MongoSocketOpenException. I don't why it's happening and how to debug this error. I can see that mongodb jar files in under {WSO2-SI-HOME}/lib/ directory, so extension is installed but not properly working.
Here is the full code of my siddhi app:
@App:name("MongoDB search")
@App:description("desc is here")

define stream SearchID (id string)

-- Exceptions appears here: com/mongodb/MongoException or com/mongodb/MongoSocketOpenException
@store(type="mongodb", mongodb.uri="mongodb://user:password@127.0.0.1:27017/database_name?replicaSet=rs0", collection.name="users")
define table UsersTable (id string, date_of_birth string, gender string, height_cm double, weight_kg double);

@sink(type='log', prefix='Logging')
define stream ListeningLogs(id string, Date_of_Birth string, Gender string, Height double, Original_Weight double)

@info(name='logging')
from SearchID as s join UsersTable as u
    on s.id == u.id
select u.id, u.date_of_birth as Date_of_Birth, u.gender as Gender, u.height_cm as Height, u.weight_kg as Original_Weight
insert into ListeningLogs;

New Lines Added
I tested the app on server and found the following cause:
Caused by: java.lang.NoClassDefFoundError: com/mongodb/MongoSocketOpenException
...
Caused by: java.lang.ClassNotFoundException: com.mongodb.MongoSocketOpenException cannot be found by siddhi-store-mongodb_2.1.1

But I don't know, how to fix it.

A: You need to add mongo-java-driver-3.4.2.jar to {Home}/lib/


text:
Q: Return the list content contained in the given cell I have data like below. I would like to fill Column2 with a value in list column(E) if one of that value is substring of Column1.
I am able to assert that condition and return TRUE or FALSE , but not return the actual string in List column.
Any help?

Update:
I referred here to return TRUE or FALSE based on the condition

A: You can do it combining SUMPRODUCT with INDEX.
I got this:

My formula in E1 and dragged down is:
=IFERROR(INDEX($E$1:$E$4;SUMPRODUCT(--ISNUMBER(SEARCH($E$1:$E$4;A6));ROW($E$1:$E$4)));"Not found")

This is how it works:

*

*Part SUMPRODUCT(--ISNUMBER(SEARCH($E$1:$E$4;A6));ROW($E$1:$E$4))) will return an array of 1 and 0 if the text is found/not found. And we multiply those 1 and 0 by the row number of each option in the list. If nothing is found, it will return 0

*With INDEX and the number returned in step 1, we just list the element.

*We trap INDEX with IFERROR because sometimes step 1 will return 0, raising error on step 2 if nothing is found, so we return text "not found".

Hope you can adapt this to your needs.
IMPORTANT: This formula will work if there is 0 or 1 coincidences. If there are more, the formula won't work, because it will return a sum of 2 or more row numbers, and then INDEX will raise an error. Watch out for that
Example: if you type GRAY DOG, the formula will return 5 (coincidences at row 1 and 4, and summed up). But with INDEX you are looking in a range of only 4 rows, not 5, so it will raise an error.


text:
Q: In flutter how can I go back to previous URL when the back button is pressed? I am completely new to flutter, I am using web view widget , but whenever I am pressing back it exits the app. How can I go back to previous page while the back button is pressed?
Here is my code snippet
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(MyApp());
WebViewController controllerGlobal;

Future<bool> _exitApp(BuildContext context) async {
  if (await controllerGlobal.canGoBack()) {
    print("onwill goback");
    controllerGlobal.goBack();
    return Future.value(true);
  } else {
    Scaffold.of(context).showSnackBar(
      const SnackBar(content: Text("No back history item")),
    );
    return Future.value(false);
  }
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'TRAVMAKS',
      home: WillPopScope(
        onWillPop: () => _exitApp(context),
        child:Scaffold(
              body: Container(
                    margin: const EdgeInsets.only(top: 52.0),
                    child: Container(
                            margin: const EdgeInsets.only(top: 0.0),
                            child: WebView(
                                        initialUrl: 'https://www.google.com',
                                        javascriptMode: JavascriptMode.unrestricted,
                        )
              )
        )
    )
    )
    );

  }
}

A: You are returning true after navigating back in your WebView. If you return true in onWillPop, Flutter pops the route and if it's your root route, the app will exit. You may want to return false there too.
https://api.flutter.dev/flutter/widgets/WillPopScope/onWillPop.html


text:
Q: Android R file not building when declare-styleable of type enum is added Recently my Android workspace isn't compiling correctly anymore (the R file isn't created).
After trying the usual like cleaning i started searching deeper.
I discovered that when i comment out the items int my attrs.xml file of the type declare-styleable with the format="enum" the R file is build but not when they are present (not commented out).
Is there a recent change or something with the way you have the declare enums or something?
Here a piece of the project
working
<?xml version="1.0" encoding="utf-8"?>
<resources>

<declare-styleable name="SwipeListView">
    <attr name="swipeOpenOnLongPress" format="boolean" />
    <attr name="swipeAnimationTime" format="integer" />
    <attr name="swipeOffsetLeft" format="dimension" />
    <attr name="swipeOffsetRight" format="dimension" />
    <attr name="swipeCloseAllItemsWhenMoveList" format="boolean" />
    <attr name="swipeFrontView" format="reference" />
    <attr name="swipeBackView" format="reference" />
<!--         <attr name="swipeMode" format="enum"> -->
<!--             <enum name="none" value="0" /> -->
<!--             <enum name="both" value="1" /> -->
<!--             <enum name="right" value="2" /> -->
<!--             <enum name="left" value="3" /> -->
<!--         </attr> -->
<!--         <attr name="swipeActionLeft" format="enum"> -->
<!--             <enum name="reveal" value="0" /> -->
<!--             <enum name="dismiss" value="1" /> -->
<!--             <enum name="choice" value="2" /> -->
<!--         </attr> -->
<!--         <attr name="swipeActionRight" format="enum"> -->
<!--             <enum name="reveal" value="0" /> -->
<!--             <enum name="dismiss" value="1" /> -->
<!--             <enum name="choice" value="2" /> -->
<!--         </attr> -->
<!--         <attr name="swipeDrawableChecked" format="reference" /> -->
<!--         <attr name="swipeDrawableUnchecked" format="reference" /> -->
</declare-styleable>
</resources>

not working
<?xml version="1.0" encoding="utf-8"?>

<declare-styleable name="SwipeListView">
    <attr name="swipeOpenOnLongPress" format="boolean" />
    <attr name="swipeAnimationTime" format="integer" />
    <attr name="swipeOffsetLeft" format="dimension" />
    <attr name="swipeOffsetRight" format="dimension" />
    <attr name="swipeCloseAllItemsWhenMoveList" format="boolean" />
    <attr name="swipeFrontView" format="reference" />
    <attr name="swipeBackView" format="reference" />
    <attr name="swipeMode" format="enum">
        <enum name="none" value="0" />
        <enum name="both" value="1" />
        <enum name="right" value="2" />
        <enum name="left" value="3" />
    </attr>
    <attr name="swipeActionLeft" format="enum">
        <enum name="reveal" value="0" />
        <enum name="dismiss" value="1" />
        <enum name="choice" value="2" />
    </attr>
    <attr name="swipeActionRight" format="enum">
        <enum name="reveal" value="0" />
        <enum name="dismiss" value="1" />
        <enum name="choice" value="2" />
    </attr>
    <attr name="swipeDrawableChecked" format="reference" />
    <attr name="swipeDrawableUnchecked" format="reference" />

</declare-styleable>

A: Did you try defining the enum outside the declare styleable and then using attr without any format in the declare-styleable


text:
Q: adjust drop down menu height to show more options (AngularJS Material) i'm new to Angularjs Material so maybe this is something obvious yet it seems i can't figure it out.
i have a multiple choice drop down menu which shows only 4 options when initially clicked on and the rest can be viewed/accessed by scrolling down. I'm trying to expand that view to another static number (e.g. to fit 8 options without scroll).
i found very similar question asked before:
Make multiple-select to adjust its height to fit options without scroll bar
however, it seems not to have any effect neither with "size" nor "ng-size"
here is my example:
<md-input-container>
    <label>Providers</label>
    <md-select ng-size="10" ng-model="vm.selectedProviders" ng-change="vm.prov()" multiple>
        <md-optgroup label="Providers">
            <md-option ng-value="provider.namep" ng-repeat="provider in vm.providers">{{provider.namep}}</md-option>
        </md-optgroup>
    </md-select>
</md-input-container>

A: Looking at the documentation of md-select, there doesn't seem to be an attribute that specifies the number of options to show.
So the other possible way is to change the maximum heights set by default in AngularJS Material. They're set like this:
md-select-menu, md-select-menu md-content {
    max-height: 256px;
}

For me, it displays 5 options by default (not 4). So, I added this to my CSS:
md-select-menu, md-select-menu md-content {
    max-height: 385px;
}

And it made all md-select tags fit 8 options instead of 5. The number doesn't have to be the same for you, so play with the height until you're satisfied.
Hope that helps.


text:
Q: How to Combine D3's built in zoom as well as on click zoom for Zoomable Icicle? I am currently using the Zoomable Icicle layout example found here: http://bl.ocks.org/mbostock/1005873 to view a file system.
The example provides a "zoom" on click, but I would also like to incorporate D3's zoom behaviour on the graph as well.
I am worried that these two zoom functions will clash on click, so do I need to reset D3's zoom behaviour on click?
How can I incorporate both these zoom-like functions that they do not conflict and rather provide smooth interaction?
Thanks.

A: Without speculating on the use case for this, I was curious to see how this would pan out (no pun intended). Here is a FIDDLE with the results...not sure what to think, honestly...but my brains get fried on Fridays anyways.
function zoom() {
    d3.selectAll("rect")
        .attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

One thing is true...panning helps :)
UPDATED FIDDLE Per request, this version has a Reset Zoom button that resets the zoom AND the zoomable icicle to its initial display (with transition).


text:
Q: Site usage analytics When trying to understand how site usage analytics work I can see the same document with different extensions. I see the document as a PDF (which it is) and as an aspx. Both have unique visitors. However one and the same document has more visitors as an aspx than it has as the PDF.
Could someone please tell me what the difference is and how many unique visitors the document really had?
Thank you.


text:
Q: How to keep some space between tables in a row in knitr::kable? I use the following code from bookdown package tutorial in R markdown file:
```{r}
d1 <- head(cars, 3)
d2 <- head(mtcars[, 1:3], 5)
knitr::kable(
  list(d1, d2),
  caption = 'Two tables placed side by side.',
  booktabs = TRUE, valign = 't'
)
```

Unlike the book, the code returns the result without space between two tables, like so.

In some questions I see the solutions with cat() function and some html injections.
(Also we need to set the option results = 'asis')
I wonder is there a more elegant and simple way to set some space between tables and preserve default html formatting at the same time?

A: If you're not willing to do some tweaking using HTML/CSS, layout functions such as fluidRow() and column() from the Shiny package might help:
```{r, echo=F}
library(kableExtra)
library(shiny)

d2 <- head(mtcars[, 1:3], 5) %>% kable() %>% kable_styling()

fluidRow(
    column(2, HTML(d2), offset = 2),
    column(2, HTML(d2), offset = 2),
)
fluidRow(align = "center", column(12, "Figure 1: Two tables side by side"))
```