text:
Q: If a node version is beyond LTS support will it stop building on Heroku? I have a Node 12 app and am trying to assess when i should migrate up to a newer version of Node. Even though it is no longer officialy suppported the app builds today on v12.  I read in heroku's documentation (https://devcenter.heroku.com/articles/nodejs-support) that I can install "most node versions". That seems to explain why the app is still building, but then I also read that official buildpack support is given to active or LTS node versions.
Given the above, what is the implication for older apps? That it will build until a breaking change in the buildpack stops it from building? Is there a buildpack per node version which, if true, would mean that the build will work but without benefit of updates or bugfixes?


text:
Q: ActiveMQ broker redelivery vs consumer redelivery I'm trying to understand the difference between ActiveMQ redeliveryPlugin and consumer's attempt to recieve messages before it marks it as a poison pill. What's the difference. In the documentation there'is an example:
<broker xmlns="http://activemq.apache.org/schema/core"    schedulerSupport="true" >
        ....
        <plugins>
            <redeliveryPlugin fallbackToDeadLetter="true" sendToDlqIfMaxRetriesExceeded="true">
                <redeliveryPolicyMap>
                    <redeliveryPolicyMap>
                        <redeliveryPolicyEntries>
                            <!-- a destination specific policy -->
                            <redeliveryPolicy queue="SpecialQueue" maximumRedeliveries="4"
redeliveryDelay="10000" />
                        </redeliveryPolicyEntries>
                        <!-- the fallback policy for all other destinations -->
                        <defaultEntry>
                            <redeliveryPolicy maximumRedeliveries="4" initialRedeliveryDelay="5000"
redeliveryDelay="10000" />
                        </defaultEntry>
                    </redeliveryPolicyMap>
                </redeliveryPolicyMap>
            </redeliveryPlugin>
        </plugins>

Now, I uderstand the broker's redelivery system as a separate to the client's one. For instance, after making 6 attempts (by default) to acknowledge a message (CLIENT_ACKNOWLDGMENT mode) the consumer send a poison pill. So, is it true that after receiving the poison pill, broker will try to resend the message to the consumer which will make another 6 attempt.
So, in total we may have 4 x 6 = 24 attempts before the message will send to a DLQ.
Is my understading correct?

A: Yes. The broker is not aware of any client redelivery. That happens in "the driver" - in memory. The broker won't consider if the client has already retried or not. The result is nested retries which is good to be aware of.

redpajama_set_name: RedPajamaStackExchange


text:
Q: After replacing Rmagick with Minimagick, gets 'identify.im6: no decode delegate for this image format' error In my Rails app, I just removed Rmagick and added Minimagick. Rmagick was too heavy. Things worked fine with Rmagick but in minimagick I get the following error :
MiniMagick::Invalid: `identify /tmp/mini_magick20150518-10411-1qz42x8` failed with error:
identify.im6: no decode delegate for this image format `/tmp/mini_magick20150518-10411-1qz42x8' @ error/constitute.c/ReadImage/544.
from /home/pubudu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/mini_magick-4.2.4/lib/mini_magick/image.rb:200:in `rescue in validate!'

The file url :
[8] pry(main)> file.file.file
=> "/home/pubudu/Projects/istockseller/public/store/photos/thpubs/istockseller-13642162-wallhaven-61582.jpg"

The code im trying to run :
MiniMagick::Image.read(file.file.file).first

A: Try to reinstall ImageMagick and add --with-jpeg=yes to the configuration.
Run convert -list configure, and see if you have jpeg under DELEGATES. If not, reinstall ImageMagick and add params to ./configure:
1. wget http://www.imagemagick.org/download/ImageMagick.tar.gz
2. tar xvfz ImageMagick.tar.gz
3. cd ImageMagick
4. ./configure --with-bzlib=yes --with-fontconfig=yes --with-freetype=yes --with-gslib=yes --with-gvc=yes --with-jpeg=yes --with-jp2=yes --with-png=yes --with-tiff=yes --disable-shared
5. make
6. sudo make install
7. sudo ldconfig /usr/local/lib
8. run again "convert -list configure" and look at changes

for more information: Carrierwave Error Msg: Failed to manipulate with MiniMagick, maybe it is not an image?

A: I experienced the same thing on my Ubuntu server. However, I solved it by adding ghostscript and libgs-dev to my Dockerfile apt-get lines
FROM ruby:2.5.3

RUN apt-get update -qq && apt-get install -y \
  ghostscript libgs-dev imagemagick


text:
Q: Model Builder is not intersecting erased and selected files I'm having trouble debugging my model that I'm creating in ArcMap 10.1 ModelBuilder.
The model is just a simple string of geoprocesses, but there's a point at which the model isn't exporting the expected features. Specifically, I've narrowed it down to a point at which the model takes a polyline file which had been erased (interim_erased) and intersects it with a selected polygon file (Inactive_ESA), and at this point the output file (interim_intersect) is empty.
The only thing I see that could be happening is that the "ESA" isn't getting selected at the "Select by Attributes" step (The output being "Inactive_ESA"), because the erased file "interim_erased" has the expected features in its table.
Also, I've double-checked the selection expression - it's correct and works fine outside of ModelBuilder. I also have the license to execute Erase.
Maybe, if someone knows how to look into ModelBuilder at what's actually getting selected at the "Select Layer By Attributes" point in the model?

++++++++++++ ADDED 2014-07-31 +++++++++++++++
The ESA polygons are broken down by active(green) and inactive(red), the polylines as well, active(green) and inactive(red). I'm selecting the green polygons in the ESA, and selecting the red polylines. Then I'm Erasing the red polylines with the green ESA. (This part works, and my intermediate data for this process outputs the expected result - red polylines only on the red ESA with no red polylines overlapping onto green ESA).
However, when this erased file of red polylines is intersected with my selected Inactive_ESA (which is where I'm selecting the red polygons), the table is empty. So this suggests to me that the ESA isn't actually getting selected by the "Select Layer By Attribute (9)" process. How might I see what's actually getting selected at this step? (because I've double checked my expression and it's correct and works fine outside of the model)

A: Right click on Active_ESA, select Add to Display and rerun entire model

A: So you've confirmed that the select layer by attribute is definitely selecting your polylines.
Well here is a list of potential problems:

*

*Your polyline and erase layers are different coordinate systems

*The erase layer has a selection on it so it never clips the area you expect?

*The erase layer must be a polyline or polygon layer (i.e. higher geometry dimension)

*The select by attribute (9) in your model is not selecting what you expect

Finally would it be the correct understanding of you model is that you have your ESA layer, select the active polyines, erase some of these, reselect the inactive polylines and then attempt an intersection of inactive lines in an area of nothing which should produce nothing...
So if I have understood your description and if everything was running as expected the black line that I have identified below based on image above would be what the intersect is returning?

A: Problem "solved". I just deleted the Select Layer By Attribute (9) and re-replaced it with a new Select Layer By Attribute process. When I revalidated and ran the model, the intersect worked, and everything looks like it's supposed to.
Maybe I don't get some fundamental thing about ModelBuilder, but it looks like the order you place tools on the whiteboard of ModelBuilder actually matters. Even though the connections were correct (and has exactly the same parameter as before I replaced the Select By Attribute tool), removing the Select by Attribute tool and replacing it worked for some reason.


text:
Q: I need to know about faster cpu processors I want to know more about the technology and what is the "best" regarding CPU-GPU one can use for video editing, photo and 3D graphics.
Note: please keep answers to factual data and not solely opinion.  If you have used the technology please talk about it, but NO '[Blank] is the best' and that's it.  Talk about the technology and why it is useful for video, photo, and 3D graphics

A: Basically you want the fastest one you can afford.
You also need to consider the graphics card memory and GPU speed - and get the best one you can afford here too.
Programs increasingly off-load a lot of processing to the GPU so having a good CPU isn't necessary enough.
Also as Xantec points out the amount of memory you have will affect performance too, so again you need to buy the fastest RAM and as much as you can afford.
Even then, your system will be out of date within 6 months and feel like it's running really slowly as you try to edit that 3 hour video and tweak those 20 mega pixel images you've just created ;)

A: It's not a great idea to buy the very fastest CPU or graphics card, as you do not get that much more power for the money.  One can generalise it this way: you can usually get 80% of the performance for 20% of the price of the fastest components.
I once spent £1,800 (around $3,600 USD at the time) building the most powerful CAD workstation I could afford, only to see machines costing half as much beating its performance within a few months.
It's a better idea to buy a CPU or graphics card that is one or two levels from the top spec, and with the saved money you can replace it in a year or two.

A: Moab is right.  However, what your are probably looking for is not a fast CPU but a fast graphics card.  Once again this comes down to price.  You really can spend as much as you want on a graphic card.  If price is not an issue, then go ahead and look at this guy: http://www.newegg.com/Product/Product.aspx?Item=N82E16814102909.  Thats a Radeon HD 6870.  Its what can be considered top of the line.  It will definitely be able to handle any graphic intensive applications you have to throw at it.

A: Right now its this one,,http://www.technize.com/the-worlds-fastest-processor-on-the-planet-intel-core-i7-980x-review/


text:
Q: "Save failed with the following error:" after overriding SAVE() - Joomla 2.5 I have overridden the Joomla save() function for some reason.
Last statement of the function is return $data->player_id; which get to the same form loaded with data from DB (That's good!)
Problem is that It shows
Save failed with the following error:

Message even every data field is saved correctly.
Here is the snippet
public function save($data) {

    $table_one = $this->getTable('Player', 'footballTable', array());
    // Bind the data.
    $table_one->bind($data);
    // Store the data.
    $table_one->save($data);

    // Some code here...

    return $data->player_id;
}

A: at the end of file write this one line:
return true;

for more information follow this link.


text:
Q: "Chromium didn't shut down correctly" message after almost every snap update since Ubuntu 19.10, 20.04 Almost every time my Chromium browser on Ubuntu 20.04 gets an update, next time I start Chromium I will get this annoying message "Chromium didn't shut down correctly" and the option to restore tabs. Also, the Chromium icon wich I have locked to the Unity launcher is removed so I have to lock it again.
I presume this has to do with the way the updates are installed as snaps and without asking me to close Chromium before. So usually it seems to happen that the updates are installed while Chromium is running, causing it to not being able to close properly, thus the error message at next start after update.
The updates are installed via snapcraft.io it says in Gnome Software info and not through repositories. Can I change to the traditional repository installation for Chromium? That way, I would see the updates coming and simply close Chromium before starting a Chromium update.


text:
Q: How do I randomly generate a variable name? In python, I need to know how to randomly generate a variable name for a list, but I am unsure how to go about doing this.
Right now, I have something like this written.
name = random.randint(0,9)
name = [a,b,c,d]

I know this will just change the 'name' variable to be the list.
What I want to do is get my randomly generated number to be assigned as a variable to the list. How do I do this?
I'm fairly new to python as well, so if there is a better way of doing this, I would be open to suggestions.

A: Generate variables :
You can create variables from a list of strings with the following code, but I don't think this is common practice.
name = ['a','b','c','d']
values = [random.randint(1, 10) for i in range(len(name))]

for var_value, var_name in zip(values,name):
    locals()[var_name] = var_value

name = [a,d,c,b]

#[8, 8, 6, 4]

Better to make a dictionary:
You can do what you want to by creating a dictionary.
names = ['a','b','c','d']
values = [random.randint(1, 10) for i in range(len(name))]

# make a list of tuples that become the dictionary
names_and_values = []
    for var_value, var_name in zip(values,name):
    names_and_values.append((var_value, var_name))

# create a dictionary with defined vairables
names = {name: value for name, value in names_and_values}

#{1: 'c', 2: 'd', 3: 'a', 5: 'b'}


text: Q: how to move unused css rules to new file in grunt uncss task Grunt uncss remove the unused css rules. My question is that is there a way by which instead of removing unused css rules, it will put them in a separate file


text:
Q: initial videos lag on WebRTC connection what is the correct peer connection setting in android?
I have recently developed an app that establishes a connection to another device using WebRTC.
I have managed to receive four video streams through four tracks.
videos start with lags and after 4/5 minutes it continues correctly.
how can I solve this lag at beginning of my videos?
my peer connection config:
    private void createPeerConnection() {
        PeerConnection.RTCConfiguration rtcConfig =
                new PeerConnection.RTCConfiguration(peerIceServers);
        // TCP candidates are only useful when connecting to a server that supports
        // ICE-TCP.
        rtcConfig.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED;
        rtcConfig.bundlePolicy = PeerConnection.BundlePolicy.BALANCED;
        rtcConfig.bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE;
        rtcConfig.rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE;
        rtcConfig.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY;
        rtcConfig.enableCpuOveruseDetection = false;
        rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        rtcConfig.iceTransportsType = PeerConnection.IceTransportsType.ALL;
        //Use ECDSA encryption.
        rtcConfig.keyType = PeerConnection.KeyType.ECDSA;

        localPeer = peerConnectionFactory.createPeerConnection(rtcConfig, new CustomPeerConnectionObserver() {
            @Override
            public void onIceCandidate(IceCandidate iceCandidate) {
                super.onIceCandidate(iceCandidate);
                onIceCandidateReceived(iceCandidate);
            }

            @Override
            public void onAddStream(MediaStream mediaStream) {
                super.onAddStream(mediaStream);
                gotRemoteStream(mediaStream);
            }
            @Override
            public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
                super.onAddTrack(rtpReceiver, mediaStreams);
            }
        });
    }

    private void startWebrtc() {
        initVideos();
        getIceServers();
        //Initialize PeerConnectionFactory globals.
        PeerConnectionFactory.InitializationOptions initializationOptions =
                PeerConnectionFactory.InitializationOptions.builder(this)
                        .setEnableInternalTracer(true)
                        //H.264 video provides better picture quality
                        .setFieldTrials("WebRTC-H264HighProfile/Enabled/")
                        .createInitializationOptions();
        PeerConnectionFactory.initialize(initializationOptions);
        //Create a new PeerConnectionFactory instance - using Hardware encoder and decoder.
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        DefaultVideoEncoderFactory defaultVideoEncoderFactory = new DefaultVideoEncoderFactory(
                rootEglBase.getEglBaseContext(),  /* enableIntelVp8Encoder */true,  /* enableH264HighProfile */true);
        DefaultVideoDecoderFactory defaultVideoDecoderFactory = new DefaultVideoDecoderFactory(rootEglBase.getEglBaseContext());
        peerConnectionFactory = PeerConnectionFactory.builder()
                .setOptions(options)
                .setVideoEncoderFactory(defaultVideoEncoderFactory)
                .setVideoDecoderFactory(defaultVideoDecoderFactory)
                .createPeerConnectionFactory();
        //remoteVideoView.setMirror(true);
        gotUserMedia = true;
        onTryToStart();

    }


text:
Q: User interface flash AS 3.0 since the Site seems to be pretty buggy i have to post my question below. Sorry for the inconvenience.
Hi guys
I'm new to flash and i want to create a GUI for my little game.
How can i create a start window where I can select stuff like how many objects to spawn or move speed of my character.
My first idea was to hide everything else on the stage until I click start.
Would that be right. Is the a better way. how to do this anyway.
And where do i put my GUI script. Stage or extern class.

A: Place your start button in the first frame and put your other elements in second frame. On click of the start button gotoAndPlay to next frame.


text:
Q: ERROR 1728 (HY000): Cannot load from mysql.user. The table is probably corrupted symptom: I just tried to create a user, as I have done many times in the past, only to receive this error:

ERROR 1728 (HY000): Cannot load from mysql.user. The table is probably
  corrupted

cause:
The only things I've done that I can think of since I last created a user through phpMyAdmin that may have caused this would be apt-get upgrades.  As far as I can tell all user accounts work fine (testing all would be a long process) and other databases are able to read/write/etc fine
troubleshooting:
upgrade:
I've already tried mysql_upgrade which both reports that table (and all others) as OK, and required the --force option. I've done a full apt-get upgrade dist and rebooted (followed by another mysql_upgrade - hey why not) and the issue persists.
permissions:
I've verified the permissions in all files south of /var/lib/mysql are mysql:root rw:rw:--  (which were originally mysql group too but only visible by user) including /var/lib/mysql-files (empty) /var/lib/mysql-keyring (one file) and /var/lib/mysql-upgrade (one file)
users:
I have two root users (different name, nearly identical privileges) and both show up with full access to mysql.user (which shows and is able to quickedit fine - though the full edit is missing the BLOB files, could this be the problem?) through phpMyAdmin.
create user methods:
I get the same error when using CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'; as when trying through phpMyAdmin - through both my root accounts
At this point I'm stack-overflow shy of re-installing MySQL or perhaps even Ubuntu, and the closest articles I see are for mysql.proc (which haven't worked)
update logs show:

[Warning] Incorrect definition of table mysql.user: expected column
  'password_expired' at position 41, found 'password_last_changed'.
[ERROR] /usr/sbin/mysqld: Cannot load from mysql.user. The table is
  probably corrupted

A: Even after re-running mysql_upgrade, the columns of user are still in the wrong order.
My (inelegant) solution was to:

*

*Export users

*Rearrange the table column definitions (swap password_expired with password_last_changed)

*Import as user2 (just to be sure)

*DROP TABLE user; (oh my!)

*Copy user2 to user (thankfully it worked!)


text:
Q: Set default avatar network-wide I've seen plugins and snippets on how to set a new default avatar for a site.  I'm wondering if this can be done network-wide, such that every new site on the network will have the network's avatar as its primary default. from there the plugin's that allow the user to upload a new avatar will be sufficient to let each site define it's own.  But until they do I'd prefer they have my avatar than the mystery man or some of the others which are downright ugly.

A: The avatar_default is the better option.
add_filter('pre_option_avatar_default', 'se72578_avatar_default');
function se72578_avatar_default( $option ){
   return 'http://example.com/your/default/here.jpg';
}

Simple. Stick that in a mu-plugin and you're good to go.
Edit: If you want to still allow site owners to change the default avatar, use the default_option_avatar_default hook instead.

A: Must Use Plugins will anable functionality global. And actualy functionality is pretty simple... only prefiltring default_avatar value.
Use this code as plugin which you can install to anable default avatar.
<?php
    /*
    Plugin Name: Network Default Avatar
    Description:  This Plugin Used to be the General Framework
    Author:
    Version:
    Author URI:
    */

    add_filter('pre_option_avatar_default', 'pre_option_avatar_default');
    function pre_option_avatar_default(){
        return 'mystery';
    }

Update  New code

*

*Using get_avatar filter hook you can replace the original avatar
add_filter('get_avatar', 'get_avatar_custom',10,5);
function get_avatar_custom($avatar, $id_or_email, $size, $default, $alt){
   // your code here...
      /*
      ** Example code will check if current avatar string is contain "mystery" avatar if yes, it will
      ** try to get site_default_avatar property from options table (you can create a UI for entering this value)
      ** if system_default_avatar exists - filter will repalce default value (first argument of this filter callback)
      ** and return new value
      ** if (strpos($avatar, '561e2e7a9910204ba43fa4097e45c5e9') !== false
      **    && get_option('site_default_avatar', false) != ''){
      **    $avatar =  "<img alt='".esc_attr($alt)."' src='".get_option('site_default_avatar', false)."'
      **        class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
      ** }
      **
      */
    return $avatar;
}

*Using a... get_avatar function. get avatar is plugable function, which mean you can ovveride it in any plugin, theme or in our case in mu-plugin
function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false {
   // your code here
   return $some_html_with_avatar_picture;
}

A: In my mu-plugins folder I now have the following code, which adds a custom avatar as the default network wide, but allows each individual site to change it thereafter.
<?php
  /*
    Plugin Name: Network Default Avatar
    Description:  This Plugin sets the default avatar network-wide
    */

    class Network_Default_Avatars {

    // configure these two variables
    static $name = "Network Default";  // text description of avatar... ie "Mystery Man"
    static $avatar = "http://example.com/default-avatar.png";  // URL of avatar

    function __construct() {

        // default avatar
        add_filter( 'avatar_defaults', array( $this, 'default_avatar' ) );
        add_action( 'wpmu_new_blog', array( $this, 'new_blog_default_avatar' ) );

    }
    // add to list of default avatars
    function default_avatar ($avatar_defaults) {
        $ib_avatar[self::$avatar] = self::$name;
        return array_merge( $ib_avatar,$avatar_defaults ); // Put our custom avatar on top
    }

    // set a new blog to have the default avatar
    function new_blog_default_avatar( $blog_id ){
        switch_to_blog($blog_id);
        update_option( 'avatar_default', esc_url( self::$avatar ) );
        restore_current_blog();
    }

}

new Network_Default_Avatars();

EDIT #1
Per @Otto's comment about the default_option_avatar_default_filter I've changed the new blog update_option action to use the default filter instead.
<?php
  /*
    Plugin Name: Network Default Avatar
    Description:  This Plugin sets the default avatar network-wide
    */

    class Network_Default_Avatars {

    // configure these two variables
    static $name = "Network Default";  // text description of avatar... ie "Mystery Man"
    static $avatar = "http://example.com/default-avatar.png";  // URL of avatar

    function __construct() {

        // default avatar
        add_filter( 'avatar_defaults', array( $this, 'avatar_defaults' ) );
        add_filter( 'default_option_avatar_default', array( $this, 'default_avatar' ) );

    }

    // add to list of default avatars
    function avatar_defaults ($avatar_defaults) {
        $ib_avatar[self::$avatar] = self::$name;
        return array_merge( $ib_avatar,$avatar_defaults ); // Put our custom avatars on top
    }

    function default_avatar () {
        return self::$avatar;
    }

}

new Network_Default_Avatars();


text:
Q: Make KML LineString follow roads I am working on a KML file with two co ordinates that I use to draw line strings. It works fine when the roads are straight, but whenever the road curves the lines do not curve. Here is the KML code I use
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
  <Document>
    <open>1</open>
    <Style id="s_ylw-pushpin_hl">
      <IconStyle>
        <color>ffff5500</color>
        <scale>0.583333</scale>
        <Icon>
          <href>http://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href>
        </Icon>
      </IconStyle>
      <LabelStyle>
        <color>00ffffff</color>
      </LabelStyle>
      <ListStyle />
      <LineStyle>
        <color>ff0000ff</color>
        <width>3.6</width>
      </LineStyle>
      <PolyStyle>
        <fill>0</fill>
      </PolyStyle>
    </Style>
    <StyleMap id="m_pushpin">
      <Pair>
        <key>normal</key>
        <styleUrl>#s_ylw-pushpin</styleUrl>
      </Pair>
      <Pair>
        <key>highlight</key>
        <styleUrl>#s_ylw-pushpin_hl</styleUrl>
      </Pair>
    </StyleMap>
    <Style id="s_ylw-pushpin">
      <IconStyle>
        <color>ffff5500</color>
        <scale>0.5</scale>
        <Icon>
          <href>http://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href>
        </Icon>
      </IconStyle>
      <LabelStyle>
        <color>00ffffff</color>
      </LabelStyle>
      <ListStyle />
      <LineStyle>
        <color>ff0000ff</color>
        <width>3.6</width>
      </LineStyle>
      <PolyStyle>
        <fill>0</fill>
      </PolyStyle>
    </Style>
    <Placemark>
      <name>Test Fac 10-26-2020</name>
      <description>Sidewalk</description>
      <sidewalk_missing>No</sidewalk_missing>
      <LineString>
        <extrude>1</extrude>
        <tessellate>1</tessellate>
        <coordinates>-104.818968772888,39.710975093838,0 -104.810267686844,39.708465999778,0</coordinates>
      </LineString>
      <Style>
        <LineStyle>
          <color>ffff0000</color>
          <width>5</width>
        </LineStyle>
      </Style>
    </Placemark>
    <Placemark>
      <name>Test Fac 10-26-2020</name>
      <description>Sidewalk 1</description>
      <sidewalk_missing>No</sidewalk_missing>
      <LineString>
        <extrude>1</extrude>
        <tessellate>1</tessellate>
        <coordinates>-104.819033145905,39.707747919881,0 -104.814473390579,39.70400883137,0</coordinates>
      </LineString>
      <Style>
        <LineStyle>
          <color>ffff0000</color>
          <width>5</width>
        </LineStyle>
      </Style>
    </Placemark>
  </Document>
</kml>

I would like the LineString to follow similar to the yellow lines on the road. I looked into Directions API, but can't figure out a better way.

A: I was able to query Google Roads API as below and parse the json response and add multi geometry to KML file with the resulting co-ordinates
        string url = @"https://roads.googleapis.com/v1/snapToRoads?path=" + beginLat + "," + beginLon + "|" + endLat + "," + endLon + "&interpolate=true&key=";
        System.Net.WebRequest request = System.Net.WebRequest.Create(url);
        System.Net.WebResponse response = request.GetResponse();
        System.IO.Stream data = response.GetResponseStream();
        System.IO.StreamReader reader = new System.IO.StreamReader(data);
        string responseFromServer = reader.ReadToEnd();
        response.Close();

Here is the json parser code. The co-ordinates are inside the "locations" table inside the dataset.
            jsonString = $"{{ \"snappedPoints\": {{{jsonString.Trim().TrimStart('{').TrimEnd('}')}}} }}";
            var xd = JsonConvert.DeserializeXmlNode(jsonString);
            var result = new DataSet();
            result.ReadXml(new XmlNodeReader(xd), mode);
            return result;

Thank you all for the help and pointing me towards the right direction.


text:
Q: Rotating and Scaling about centroid.
rotating
$x' = x\cos(\text{angle}) - y\sin(\text{angle})$
$y' = x\sin(\text{angle}) + y\cos(\text{angle})$
Scaling
$x' = x\cdot sx$
$y' = y\cdot sy$

but all formulas will doing about origin point. If i want to do about Centroid point.
(I have $(Cx,Cy)$ ). What the formulas will be.
Sorry, about english, I will practice more.
Thanks.

A: $$
x' = C_x + (x - C_x) \cos(\theta) - (y - C_x) \sin(\theta)\\
y' = C_y + (x - C_x) \sin(\theta) + (y - C_x) \cos(\theta)
$$


text:
Q: Random variable probabilities with a weighted coin Suppose a coin is tossed $n$ times, with a random variable $X = X_H - X_T$ denoting the difference between the number of heads and number of tails.
I know that $X$ can take on every other integer value between $-n$ and $n$. Now, I am interested in probabilities. Say, $n=5$ and the probability of getting a heads is $2/3$. I want to find the associated probabilities that $X$ can assume. I am wondering if I am doing this correctly: let's say $X = 1$. This means that there were 3 heads and 2 tails. Then $P(X) = {5 \choose 3}(\frac{2}{3})^3 \times {5 \choose 2} (\frac{1}{3})^2$. Alternatively, let's say $X=3$. Then $P(X) = {5 \choose 4}(\frac{2}{3})^4 \times {5 \choose 1} (\frac{1}{3})$. Or if X=5, then $P(X) = (\frac{2}{3})^5$. Am I calculating these probabilities correctly, or are some of these wrong?
Lastly, for general $n$ and general probability of heads $p$, I am interested in the general probability for each value of that $X$ can take. I am unsure of how to do this.

A: Suppose the are $n$ coin tosses with probability of having head to be $p$. First, note that the probability of $X = k$ is zero if $n+k$ is an odd number. Now, assume $n+k$ is even. The event $X = k$ means that there are $(n+k)/2$ heads and $(n-k)/2$ tails (note that $k$ can be negative). Following the comment of @saulspatz the probability can be written as
$$Pr(X=k) = {n \choose (n+k)/2} p^{(n+k)/2} (1-p)^{(n-k)/2}.$$


text:
Q: ECR Lifecycle Policy to exclude certain tags Is there a way to exclude certain tags/images from a cleanup policy?
E.g. say I have a repository with images and the related SHAs for the Pull Request which triggered their creation.  When these are approved for deployment to an environment the image is tagged with that environment's name, resulting in something like this:
+---------------------------------------------------------------------------+
| Image Tags      | Image URI                                               |
+---------------------------------------------------------------------------+
| sha923456       | 000000.dkr.ecr.eu-west-1.amazonaws.com/myrepo:sha923456 |
+-----------------+---------------------------------------------------------+
| sha823456, test | 000000.dkr.ecr.eu-west-1.amazonaws.com/myrepo:test      |
+-----------------+---------------------------------------------------------+
| sha723456       | 000000.dkr.ecr.eu-west-1.amazonaws.com/myrepo:sha723456 |
+-----------------+---------------------------------------------------------+
| sha623456, prod | 000000.dkr.ecr.eu-west-1.amazonaws.com/myrepo:prod      |
+-----------------+---------------------------------------------------------+
| sha523456       | 000000.dkr.ecr.eu-west-1.amazonaws.com/myrepo:sha523456 |
+-----------------+---------------------------------------------------------+

I want to ensure that what's currently deployed to any environment doesn't get deleted; so those images tagged test or prod should be kept.  In addition, the SHA tags against their images should be kept.
Beyond that, I want to keep all images created in the last 90 days with an SHA tag.
I'm happy for anything untagged to be removed.
Applying the below rules almost works; only it seems that because there's a match on the sha tag, the prod and test images would be expired.
{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Remove untagged images",
      "selection": {
        "tagStatus": "untagged",
        "countType": "imageCountMoreThan",
        "countNumber": 1
      },
      "action": {
        "type": "expire"
      }
    },
    {
      "rulePriority": 100,
      "description": "Purge non-deployed images over 90 days old",
      "selection": {
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 90,
        "tagStatus": "tagged",
        "tagPrefixList": [
          "sha"
        ]
      },
      "action": {
        "type": "expire"
      }
    }
  ]
}

I can't find any documentation on adding a "NOT" rule, and trying an exclamation doesn't work.
    {
      "rulePriority": 100,
      "description": "Purge non-deployed images over 90 days old",
      "selection": {
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 90,
        "tagStatus": "tagged",
        "tagPrefixList": [
          "!test", "!prod"
        ]
      },
      "action": {
        "type": "expire"
      }
    }


text:
Q: In BigQuery, is there any way to avoid query processing costs? I'm trying to avoid the processing cost in BigQuery when creating a table from a query result e.g:
select *  from xxx where ....

...and write into a destination table.
Is there a way to do it using one of the BigQuery tools?

A: No.
Whenever you query, you will be pay for how much data you are touching in the query no matter what.
Remember, your first 1TB p/m is free in BigQuery. So maybe this is not really a problem for you.


text:
Q: regex to allow atleast one special character, one uppercase, one lowercase(in any order) Can anyone help me with a regex to allow  atleast one special character, one uppercase, one lowercase.
This is what I have so far:
 ^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

but it seems to match the characters only in the order "special character", "uppercase", "lowercase".
Any help is greatly appreciated

A: Here is a function you can use.
function checkRegex(string) {
    var checkSpecial = /[*@!#%&()^~{}]+/.test(string),
        checkUpper = /[A-Z]+/.test(string),
        checkLower = /[a-z]+/.test(string),
        r = false;

        if (checkUpper && checkLower && checkSpecial) {
            r = true;
        }

        return r;

        }

and then check if it's true or false.
var thisVal = document.getElementById('password').value;
var regex = checkRegex(thisVal);

If var regex is true then the condition satisfied.

A: It can be done quickly by 3 regular expression.
function check($string){
   return    preg_match("/[`!%$&^*()]+/", $string)
          && preg_match("/[a-z]+/", $string)
          && preg_match("/[A-Z]+/", $string) ;
}

Dont forget to tweak the list of special characters. Because I dont know what characters you think are special.
I believe wasting a lot of time on a single line regex while you are not expert will not increase your productivity. This 3 regex solution will do just fine. It saves time.

A: If you want the output like the image below :

You can use the dynamic custom component below :
import { Component, Input, OnInit, EventEmitter, Output, OnChanges } from '@angular/core';
import { RegExpValidator } from '../../classes/reg-exp-validator';

@Component({
  selector: 'app-reg-exp-validator',
  template: `
       <div *ngFor="let regExp of regExps" style='text-align: left'>
          <div>
            <i *ngIf="!regExp.isOptional" [ngStyle]="{'color': isValidExp(regExp) ? 'green' : 'red'}"
               [className]="isValidExp(regExp)? 'pi pi-check-circle' : 'pi pi-times-circle'">
              </i>
            <i *ngIf="regExp.isOptional" [ngStyle]="{'color': isValidExp(regExp) ? 'green' : 'orange'}"
               [className]="isValidExp(regExp)? 'pi pi-check-circle' : 'pi pi-times-circle'">
              </i>
            {{regExp.message}}
          </div>
       </div> `
})
export class RegExpValidatorComponent implements OnInit, OnChanges {

  @Input() value: string;
  @Input() regExps: Array<RegExpValidator>;

  @Output() onChange: EventEmitter<boolean> = new EventEmitter();

  constructor() { }

  ngOnChanges(): void {
    this.validateExpressions();
  }

  ngOnInit() {
  }

  isValidExp(regExp) {
    if (regExp.isValid)
      return regExp.isValid;
  }

  initiValue() {
    this.value = this.value == undefined ? "" : this.value;
  }

  validateExpressions() {
    this.initiValue();
    let isInVlaidExpression = false;
    this.regExps.forEach((regExp) => {
      regExp.isValid = this.testRegExpression(regExp.regExpression);
      if (!regExp.isValid && !regExp.isOptional) {
        isInVlaidExpression = true;
      }
    });

    this.onChange.emit(isInVlaidExpression);
  }

  testRegExpression(regExpression: RegExp) {
    return regExpression.test(this.value);
  }
}

where

regExps

input array class is
export class RegExpValidator {
 regExpression: RegExp;
 message: string;
 ordinal: number;
 isValid: boolean = false;
 isOptional: boolean; }

*

*After you define it, you can use it in your target component by following the two steps below :
1- Define the first input parameters which is array of regular expressions itself , validation message and if it is optional or not as below :
DefineRegExpressions(){
let minPasswordLengthSixCharacters = new RegExpValidator();
minPasswordLengthSixCharacters.message = " The password should be at least 6 charcters";
minPasswordLengthSixCharacters.regExpression = /^.{6,}$/;
minPasswordLengthSixCharacters.isOptional = false;

let containsDigit = new RegExpValidator();
containsDigit.message = "The password should contains at least 1 digit";
containsDigit.regExpression = /\d/;
containsDigit.isOptional = false;

let containsLowerCharacter = new RegExpValidator();
containsLowerCharacter.message = "The password should contains at least 1 lower charcter";
containsLowerCharacter.regExpression = /.*[a-z].*/;
containsLowerCharacter.isOptional = false;

let containsUpperCharacter = new RegExpValidator();
containsUpperCharacter.message = "The password should contains at least 1 upper charcter";
containsUpperCharacter.regExpression = /.*[A-Z].*/;
containsUpperCharacter.isOptional = false;

let containsSymbol  = new RegExpValidator();
containsSymbol.message = "The password contains at least 1 symbol @!#%&()^~{}";
containsSymbol.regExpression = /[*@!#%&()^~{}]+/;
containsSymbol.isOptional = true; }

then define the first input and add all the defined expressions declaration above to it:
  regExps = Array<RegExpValidator>();
    this.regExps.push(minPasswordLengthSixCharacters);
    this.regExps.push(containsDigit);
    this.regExps.push(containsLowerCharacter);
    this.regExps.push(containsUpperCharacter);
    this.regExps.push(optional);

2- Finally add to your target component HTML the below code :
  <app-reg-exp-validator [value]="password"
                                   [regExps]="regExps"
                                   (onChange)="onChangeRegExpValidator($event)">
            </app-reg-exp-validator>

the value input refer to the target input to validate in our case it is the password and
  the onChange is output from custom componet that you can use to know if all validation
  is valid or not.

A: Your regex
^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

should actually work just fine, but you can make it a lot better by removing the first .*:
^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

will match any string of at least 8 characters that contains at least one lowercase and one uppercase ASCII character and also at least one character from the set @#$%^&+= (in any order).

A: A more generic password/text validation where you can choose the number for characters to be allowed in each category.
var regularExpression = new RegExp("^^(?=.*[A-Z]{"+minUpperCase+",})" +
    "(?=.*[a-z]{"+minLowerCase+",})(?=.*[0-9]{"+minNumerics+",})" +
    "(?=.*[!@#$\-_?.:{]{"+minSpecialChars+",})" +
    "[a-zA-Z0-9!@#$\-_?.:{]{"+minLength+","+maxLength+"}$");
if (pswd.match(regularExpression)) {
    //Success
}


text:
Q: User ID Clearing This is not SEO related but somewhat merely client related.
There is a website in particular that uses Google Analytics tracking to uniquely identify each one of their users.
This website has a blocking system that is preventing me from viewing some of their content, which I'd like to view.
I figured out that the website uses the Google Analytics cookie to somehow identify me.
Is there a way I can somehow spoof the client-ID from Google Analytics to basically make a new identity for myself? Thanks community.

A: GA has two ids that could identify a user, clientId and userId. The client id is set by the javascript tracking code. To delete that you would simply have to delete the _ga cookie. You will get a new ID randomly generated that does not identify you other than in the sense that multiple pageviews with that clientId will be treated as coming from the same user.
The userId is set by the server when a user logs in (to connect all sessions of that user, however it must not personally identify the user in question), so at that point the website already has to know you to set a userid.
It seems more than unlikely (and technologically not even feasible) to use Google Analytics to limit access to a website. For starters, Google provides an opt-out plugin for Analytics that would make such a system rather ineffectual, and I'm not quite sure how such a system would work.
To yet answer your question, you can change the clientId by manipulating the _ga cookie and replace the value therein, and you could spoof the userID e.g. by using a browser plugin that allows you to manipulate http requests. However I don't think this will let you bypass any access protection.


text:
Q: Conditional required-field validation in Serde Can I specify that a field must be present (not null) if (and only if) another field has a certain value?
Here is an example (see the comment):
#[derive(Serialize, Deserialize, Debug)]
pub struct Params {
    pub id: i32,
    pub foo: i32,
    pub bar: Option<i32>, // this must be Some if "foo == 5"
}

I'm also interested in cases where foo is an enum.

A: You can only perform validation by manually implementing Deserialize. You can still use the derive to perform the heavy lifting:
#[derive(Deserialize, Debug)]
#[serde(remote = "Self")]
pub struct Params {
    pub id: i32,
    pub foo: i32,
    pub bar: Option<i32>, // this must be Some if "foo == 5"
}

impl<'de> Deserialize<'de> for Params {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let this = Self::deserialize(deserializer)?;

        if this.foo == 5 && this.bar.is_none() {
            return Err(D::Error::custom("bar should be set when foo equals '5'"));
        }

        Ok(this)
    }
}

Another option is to have two structs, one to deserialize (ParamsUnchecked) and a second which is checked that all constraints hold (Params). You can then use TryFrom to convert between them.
#[derive(Deserialize, Debug)]
#[serde(try_from = "ParamsUnchecked")]
pub struct Params {
    pub id: i32,
    pub foo: i32,
    pub bar: Option<i32>, // this must be Some if "foo == 5"
}

#[derive(Deserialize, Debug)]
pub struct ParamsUnchecked {
    pub id: i32,
    pub foo: i32,
    pub bar: Option<i32>,
}

impl TryFrom<ParamsUnchecked> for Params {
    type Error = String;

    fn try_from(pu: ParamsUnchecked) -> Result<Self, Self::Error> {
        if pu.foo == 5 && pu.bar.is_none() {
            return Err("bar should be set when foo equals '5'".to_string());
        }
        Ok(Self {
            id: pu.id,
            foo: pu.foo,
            bar: pu.bar,
        })
    }
}

A: You can do this by writing your own deserializer.
This is how the code works in a few bullet points:

*

*Use a struct InnerParams with all the same fields like Params and make it derive Deserialize, so you don't have to write that by hand.

*Deserialize using the code generated for InnerParams

*Do your custom validation on the deserialzied InnerParams, when they're invalid return a custom error

*If valid map to Params
Code:
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize};

#[derive(Serialize, Debug)]
pub struct Params {
    pub id: i32,
    pub foo: i32,
    pub bar: Option<i32>, // this must be Some if "foo == 5"
}

impl<'de> Deserialize<'de> for Params {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        // Create our contract for internal use
        #[derive(Deserialize)]
        struct InnerParams {
            id: i32,
            foo: i32,
            bar: Option<i32>,
        }

        // Deserialize the contract
        let inner = InnerParams::deserialize(deserializer)?;

        // Do the additional validation, if it fails return an error
        if inner.foo == 5 && inner.bar.is_none() {
            return Err(D::Error::custom("bar should be set when foo equals '5'"));
        }

        // Return the actual contract
        Ok(Params {
            id: inner.id,
            foo: inner.foo,
            bar: inner.bar,
        })
    }
}


text:
Q: how to pass data to children ? reactjs Here the simple code I am using to pass through children with a verification of authentication:
export default function PrivateRoute({ children }) {
  const [BodyContent, setBodyContent] = useState("...");
  const [User, setUser] = useState({});
  const getBodyContent = async ({ children }) => {
    const auth = await getInLocalStorage("auth");
    if (auth !== "true") {
      window.location.href = "/";
    } else {
      setBodyContent(children);
      const user = await read("/auth/" + (await getInLocalStorage("userId")));
      if (user.status === 200) {
        setUser(user.message);
      }
    }
  };
  useEffect(() => {
    getBodyContent({ children });
  }, [children]);

  return <Layout user={User}>{BodyContent}</Layout>;
}

How can i add the information of which user is it ? Which role he has ?


text:
Q: CFDIRECTORY blocked by hosting provider. Any alternatives? I am working on an intranet enhancement that will allow the user to open the latest instance(most recently modified or created) of a file within a given directory.
Unfortunately, the cfdirectory tag (and a few others) are blocked by the hosting provider.  I essentially need to mimic the functionality of this piece of code without using cfdirectory:
<cfdirectory action="list" directory="\\SERVERABC\FILEDIR"   name="myDirectory">
<cfloop query="mydirectory">
<cfoutput>
     <cfif mydirectory.dateLastModified EQ DateFormat(Now(),'mm/dd/yy')>
        <!--- ..display link to file for user to download --->
     </cfif>
</cfoutput>
</cfloop>

The FileExists() function is available. But the default ColdFusion user would not have access to all the network locations that might be available to the actual user within the application itself.

A: You need to ask your host to give you a security sandbox so you can use those tags. The only reason they couldn't do this is if they are running the CF Standard Edition, and not Enterprise. If that is the case, case you are out of luck as all file i/o tags will be unavailable. No professional CF host runs the Standard Edition.


text:
Q: Combinatorics problems that can be solved more easily using probability I'm looking for examples of combinatorics problems which would be very difficult to solve by direct enumeration, but can be easily solved using ideas from probability, like independence, commuting sums and expectations, etc.  I know I have seen such problems before, especially in the HMMT combinatorics subject tests, but I can't now recall any good examples.
I am NOT looking for probabilistic existence proofs (the so-called "probabilistic method" introduced by Erdos).  The sort of problems I'm interested in are enumerative.

A: This might be a good example. Prove that for any positive integers $m,n$ with $m< n$,
$$
\sum_{k=0}^n \frac{\binom{m}{k}}{\binom{n}k}=\frac{n+1}{n-m+1}.
$$
Solution: Imagine you have a deck of $n$ cards, $m$ of which are black, the rest of which are red. You shuffle the deck, and deal from the top until you deal a red card. What is the expected number of cards dealt?
Letting $X$ be the number of cards dealt, you have $P(X>k)=\binom{m}{k}/\binom{n}{k}$, since $X>k$ occurs if and only if the first $k$ cards are all black. Therefore,
$$
E[X]=\sum_{k=0}^nP(X>k)=\sum_{k=0}^n \frac{\binom{m}{k}}{\binom{n}k}
$$
On the other hand, the $n-m$ red cards divide the deck into $n-m+1$ sections of black cards. Each black card is equally likely to fall in each section. In particular, there is a probability of $1/(n-m+1)$ of it falling in the top section. By linearity of expectation, the expected number of black cards in the top section is $m/(n-m+1)$. Therefore, the expected number of cards dealt is
$$
1+\frac{m}{n-m+1}=\frac{n+1}{n-m+1}
$$

I think there are a lot of complicated combinatorial sums which can be made easy using linearity of expectation. For example,
$$
\sum_{k=0}^nk\binom{n}kp^k(1-p)^{n-k}=np
$$
is best understood by realizing the sum is the expected value of a binomial random variable with parameters $n$ and $p$, whose value is obviously $np$ by linearity of expectation. There, the sum is not hard, but there are probability examples in a similar vein.

A: Graph enumeration problems are often solved using the theory of random graphs. For example, if you want to asymptotically count the number of (labeled) connected graphs on $n$ vertices, it is easiest to estimate the probability that the Erdős–Rényi graph $\mathcal G_{n,1/2}$ is connected, then multiply by $2^{\binom n2}$, the total number of labeled graphs on $n$ vertices.
For a fancier example, the asymptotic number of labeled $d$-regular $n$-vertex graphs can be counted by a similar probabilistic strategy. If $d$ is sufficiently small as $n \to \infty$, we analyze the configuration model (which generates a random $d$-regular multigraph by picking a random matching between the $dn$ half-edges) and estimate the probability that the graph is simple. For an example of the newest and fanciest results in this vein, see this paper by Liebenau and Wormald.
The fundamental ideas in such cases are often about proving asymptotic independence between many very unlikely events, which lets us make Poisson or Gaussian approximations to random variables that approach the truth as $n \to \infty$. This would be difficult to recast in a purely deterministic form, and the result would be very hard to understand.
By contrast, in a problem where the "trick" was independence or commuting sums and expectations, the probability is essentially flavor and you could recast such a proof as taking a sum in two ways or something similar.

A: Here are some problems:

*

*Find the sum of the number of all continuous runs of all possible sequences with $2019$ ones and $2019$ zeros

*https://artofproblemsolving.com/community/c6h366278p2018435

*https://artofproblemsolving.com/community/c6h60752p366512

*https://artofproblemsolving.com/community/q2h1151650p5452212

*http://artofproblemsolving.com/community/c6h1170845p5622460

*https://artofproblemsolving.com/community/q4h1497881p9354029

*https://artofproblemsolving.com/community/q1h79679p10589332


text:
Q: concatenate activerecord relations using "or" condition I have two queries
urgent = MassScanTask.joins(:mass_scan_list).where("mass_scan_lists.urgent = ? AND mass_scan_lists.enabled = ?", true, true).order("updated_at DESC")
not_urgent = MassScanTask.joins(:mass_scan_list).where("mass_scan_lists.urgent = ? AND mass_scan_lists.enabled = ? ", false, true).order("updated_at ASC")

how can I get them all together urgent + not_urgent using single query? Or maybe there is some method to add one to another. I have already tried concat but it returns array and I need activerecord relations, I have also tried merge but it returns nothing.

A: So, looking at these queries, it seems that you want all enabled rows from the mass_scan_lists table, but the only difference is the ordering. You want all urgent to come first, ordered byupdated_at descand then havenon-urgentordered byupdated_at`.
So, I would just use some custom SQL in the order statement. You don't specify what RDBMS you are using, but if it is PostgreSQL, it would look like:

tasks = MassScanTask \
  .joins(:mass_scan_list) \
  .where(mass_scan_lists: { enabled: true }) \
  .order('case urgent when true then -1 * extract(epoch from updated_at) else extract(epoch from updated_at) end')

This order clause uses a CASE statement, which is not supported in all DBs, but whatever you are using likely has a similar clause.


text:
Q: Bootstrap - form-Inline element wrong space btn-group I have a question about Bootstrap components.
I have tried to do some number input, that's ok if I do not put into a form-inline or a navbar.
Here is the fiddle:
http://fiddle.jshell.net/6Lrhcezb/

First input are Ok... Now, if I focused in the other input, this doesn't get the right size.

Can I fix it with bootstrap or I need to do my own div control?
Thanks!
--
Guys this occour with the 3.5.5 bootstrap version.
I have updated in Fiddle, and now I can show you my problem...
http://fiddle.jshell.net/6Lrhcezb/4/

A: Guys this occour with the 3.5.5 bootstrap version.
I have updated in Fiddle, and now I can show you my problem...
http://fiddle.jshell.net/6Lrhcezb/4/


text:
Q: Occur "OSError: Could not write record batch to stream" when write table using flight I got a OSError when using flight to send data, and I got nothing useful information.
The basic info is:
python version 3.7.9
pyarrow version 0.17.1

The code is :
writer, reader = client.do_put(FlightDescriptor.for_path(*paths), schema)
writer.write_table(table)
result: Buffer = reader.read()
writer.close()

The error is:
Traceback (most recent call last):
  File "pyarrow/ipc.pxi", line 240, in pyarrow.lib._CRecordBatchWriter.write_table
  File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status
OSError: Could not write record batch to stream:


text:
Q: Spectral decomposition for higher-rank antisymmertric real tensors For any arbitrary anti-symmetric matrix $M_{n\times n}$, there always exists orthogonal matrix $O$ that $M = O\Sigma O^T$, with
$$
\Sigma = \left( \bigoplus_{i=1}^m \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \right) \oplus 0_{(n-2m) \times (n-2m)}
$$
Now, for any arbitrary anti-symmetric rank-$r$ tensor $T_{(i_1,\cdots,i_n)}$, which satisfies $T_{I'} = -T_I$, where $I$ is a $r$-tuple of indices, and $I'$ is $I$ with two of the indices swapped, does a similar theorem for decomposition of such tensor exists?


text:
Q: Linux - Logging process list during high memory usage I'm trying to diagnose occasional spikes in memory usage on a Linux server. If the spikes are high enough the OOM Killer kicks in, which results in /var/log/messages containing a useful dump of the process list at the time.
However, I'm also experiencing spikes that aren't severe enough to cause the OOM Killer to kick in, but are still enough to cause heavy swap usage. Any way to automatically log the process table during such periods?

A: You could use the smem utility to gather information about our systems memory usage and collect it for later analysis. I have used it to find out what processes are using swap by taking a snapshot of the system swap usage at one time and then taking other snapshots later and comparing them.

A: Montoring tools like nagios or ganglia can collect system metrics and build graphs. More simple solution is to use one-liner and put it in infinite loop, cron etc...
free |awk '/Swap:/ {if(int($3/$2*100) > 50)system("echo Swap usage is over 50% && top -abn 1 > process_dump_`date +%Y-%m-%d_%H:%M`.txt")}'


text:
Q: Binary addition algorithm using quotient and reminder I'm trying to implement the binary addition algorithm  using javascript ,
the problem is when i console.log the function it returns nothing
here is my code:
function max(a,b)
  {
    if(a>b)
       return a;
    return b;
   }

function addb(A,B)
{
    var result=[]
    var l=max(A.length,B.length)
    var carry=0
    var sum=0;
    for(var i=l.length-1;i>=0;i--)
      {
        sum=A[i]+B[i]+carry;
        carry=Math.floor(sum/2);
        result[i]=sum%2;
       }
     return result;
    }
 var a=[1,1,0];
 var b=[1,1,1];
 console.log(addb(a,b));

A: You're passing ints into the max function and then treating it like it's an array
e.g
var l=max(A.length,B.length)
....
for(var i=*l.length-1*;i>=0;i--)
just put the arrays in and it works.
var l=max(A,B)

A: You need the length l without length property and a final check of carry and unshift the array with this value.

function max(a, b) {
    return a > b ? a: b;
}

function addb(A, B) {
  var result = [],
      l = max(A.length, B.length),
      carry = 0,
      sum = 0;

  for (var i = l - 1; i >= 0; i--) {
      sum = A[i] + B[i] + carry;
      carry = Math.floor(sum / 2);
      result[i] = sum % 2;
  }

  if (carry) result.unshift(carry); // the most left value!
  return result;
}

var a = [1, 1, 0];
var b = [1, 1, 1];

console.log(addb(a, b));

A: l variable is a number already not an array hence just use that number inside the for loop as the starting case

function max(a, b) {
  if (a > b)
    return a;
  return b;
}

function addb(A, B) {
  var result = []
  var l = max(A.length, B.length)
  var carry = 0
  var sum = 0;
  for (var i = l- 1; i >= 0; i--) {
    sum = A[i] + B[i] + carry;
    carry = Math.floor(sum / 2);
    result[i] = sum % 2;
  }
  return result;
}
var a = [1, 1, 0];
var b = [1, 1, 1];
console.log(addb(a, b))


text:
Q: Http authorization with node.js My former server.js is like:
After running the server I could see my index.html
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(5000, '192.168.xx.xx', function(){
    console.log('Server running on 5000');
});

I want to create http login and password to secure the website, so I found online the information of http module: if I put right login and password, I could see congratulations message:
var http = require('http');

var server = http.createServer(function(req, res) {
        // console.log(req);   // debug dump the request

        // If they pass in a basic auth credential it'll be in a header called "Authorization" (note NodeJS lowercases the names of headers in its request object)

        var auth = req.headers['authorization'];  // auth is in base64(username:password)  so we need to decode the base64
        console.log("Authorization Header is: ", auth);

        if(!auth) {     // No Authorization header was passed in so it's the first time the browser hit us

                // Sending a 401 will require authentication, we need to send the 'WWW-Authenticate' to tell them the sort of authentication to use
                // Basic auth is quite literally the easiest and least secure, it simply gives back  base64( username + ":" + password ) from the browser
                res.statusCode = 401;
                res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');

                res.end('Need authorization');
        }

        else if(auth) {    // The Authorization was passed in so now we validate it

                var tmp = auth.split(' ');   // Split on a space, the original auth looks like  "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part

                var buf = new Buffer(tmp[1], 'base64'); // create a buffer and tell it the data coming in is base64
                var plain_auth = buf.toString();        // read it back out as a string

                console.log("Decoded Authorization ", plain_auth);

                // At this point plain_auth = "username:password"

                var creds = plain_auth.split(':');      // split on a ':'
                var username = creds[0];
                var password = creds[1];

                if((username == 'admin') && (password == 'admin')) {   // Is the username/password correct?

                        res.statusCode = 200;  // OK
                        res.end('Congratulations, feel free to explre!');
                }
                else {
                        res.statusCode = 401; // Force them to retry authentication
                        res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');

                        // res.statusCode = 403;   // or alternatively just reject them altogether with a 403 Forbidden

                        res.end('You shall not pass');
                }
        }
});

server.listen(5000, function() { console.log("Server Listening on http://localhost:5000/"); });

I am new to nodejs, I want to know how to combine this 2 js? In order to realize my function of adding authorization to my web.
Could I do something to show my index instead of showing congratulation message after putting the login and password?
Thanks a lot.

A: In order to show HTML page instead of congratulation message, you can follow these steps:

*

*Get request path by req.url, such as / or /introduction.html.

*According to the above path, read the corresponding HTML file in server disk, using fs.readFile().

*Return HTML file content to browser if the read is successful. Otherwise, return 404 error page.

Here is some example code for above steps:
if((username == 'admin') && (password == 'admin')) {   // Is the username/password correct?

  res.statusCode = 200;  // OK
  // res.end('Congratulations, feel free to explre!');
  var requestURL = req.url; // e.g. / or /a or /a.html
  var requestFilePath = getFilePathFromRequestURL(requestURL); // you need to implement this logic yourself, such as "/" mapping to "./index.html"
  fs.readFile(requestFilePath, function(error, data) {
    if (error) {
      res.statusCode = 404;
      res.write('File not found.');
    } else {
      res.statusCode = 200;
      res.write(data);
    }
    res.end();
  });
}

However, unless you want to write some low-level node.js code to better understand this language, I highly recommend using node.js web framework such as Express. Serve HTTP request using low-level node.js would be tedious, especially in production code.
Also, please note that using WWW-Authenticate Basic for authentication is neither secure nor user-friendly. You need some other way to implement authentication, such as JSON Web Tokens


text:
Q: How does Heroku dyno caching works with Play framework I have a Play application hosted by Heroku with 5 dynos. Its seems like my dynos were been restarted randomly in different time period. For example, three of them were restarted by itself 22 hours ago, and two of them were restarted 10 hours ago (not sure if this time was triggered by clearing the cache). It seems like that cached data isn't persistent between dynos. My problem is when I sent same request to my Heroku application multiple times, I get different cached response, in the response, some are most up to date data, others were old data. I assume this is because my request was processed by different dyno. After restart all my dyno fixed the problem(I assume this also clear cache in all dynos).
So I want to know what triggered the random dyno restart, and why it does that?
How to solve cached data inconsistency in this case?
Thanks

A: I think you should use mutualised cache in order to avoid this kind of problem when you scale horizontally.
Couchbase is a good solution to do it. We use this internally at Clever Cloud (http://www.clever-cloud.com/en/), that is the reason why we released a Couchbase as a service.

A: As for dyno restarts, did you try the documentation?  Dyno's are cycled at least once per day


text:
Q: Ошибка в Remote SSH Всем привет! Выводит ошибку в консоль "Couldnt establish connection to ip adress"
лог консоли :

[19:00:31.751] Log Level: 2
[19:00:31.762] SSH Resolver called for "ssh-remote+80.87.202.7", attempt 1
[19:00:31.763] "remote.SSH.useLocalServer": false
[19:00:31.763] "remote.SSH.showLoginTerminal": false
[19:00:31.763] "remote.SSH.remotePlatform": {}
[19:00:31.764] "remote.SSH.path": undefined
[19:00:31.764] "remote.SSH.configFile": C:\Users\uukeyi\.ssh\config
[19:00:31.764] "remote.SSH.useFlock": true
[19:00:31.764] "remote.SSH.lockfilesInTmp": false
[19:00:31.764] "remote.SSH.localServerDownload": auto
[19:00:31.764] "remote.SSH.remoteServerListenOnSocket": false
[19:00:31.764] "remote.SSH.showLoginTerminal": false
[19:00:31.765] "remote.SSH.defaultExtensions": []
[19:00:31.765] "remote.SSH.loglevel": 2
[19:00:31.765] "remote.SSH.enableDynamicForwarding": true
[19:00:31.765] "remote.SSH.enableRemoteCommand": false
[19:00:31.765] "remote.SSH.serverPickPortsFromRange": {}
[19:00:31.766] "remote.SSH.serverInstallPath": {}
[19:00:31.772] VS Code version: 1.75.1
[19:00:31.772] Remote-SSH version: remote-ssh@0.96.0
[19:00:31.772] win32 x64
[19:00:31.774] SSH Resolver called for host: 80.87.202.7
[19:00:31.774] Setting up SSH remote "80.87.202.7"
[19:00:31.778] Using commit id "441438abd1ac652551dbe4d408dfcec8a499b8bf" and quality "stable" for server
[19:00:31.782] Install and start server if needed
[19:00:33.118] Checking ssh with "ssh -V"
[19:00:33.162] > OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2

[19:00:33.166] Using SSH config file "C:\Users\uukeyi\.ssh\config"
[19:00:33.166] Remote command length: 6211/8192 characters
[19:00:33.166] Running script with connection command: ssh -T -D 49156 -F "C:\Users\uukeyi\.ssh\config" "80.87.202.7" powershell
[19:00:33.169] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[19:00:33.388] > ]0;C:\WINDOWS\System32\cmd.exe
[19:00:33.388] Got some output, clearing connection timeout
[19:00:54.419] > ssh: connect to host 80.87.202.7 port 22: Connection timed out
[19:00:54.435] > Попытка записи в несуществующий канал.
[19:00:55.700] "install" terminal command done
[19:00:55.701] Install terminal quit with output: Попытка записи в несуществующий канал.
[19:00:55.701] Received install output: Попытка записи в несуществующий канал.
[19:00:55.701] Failed to parse remote port from server output
[19:00:55.703] Resolver error: Error:
    at g.Create (c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:584147)
    at t.handleInstallOutput (c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:582761)
    at t.tryInstall (c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:680758)
    at async c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:643114
    at async t.withShowDetailsEvent (c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:646432)
    at async t.resolve (c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:644164)
    at async c:\Users\uukeyi\.vscode\extensions\ms-vscode-remote.remote-ssh-0.96.0\out\extension.js:1:721750
[19:00:55.711] ------

``
Просит три раза пароль и потом не подключает. Пытался поменять в конфигурации плагинов корневой путь к config ssh не получилось тоже.
Конфиг ssh :
Host 80.87.202.7
HostName 80.87.202.7
User root
Путь к папке к конфигу : C:\Users\uukeyi.ssh\config


text:
Q: HTML forms - nested dropdowns? I don't know what this is called, so here's an image of what I want to do in an HTML form:

I want to select from a dropdown.  As I scroll down the list, I want to show subordinate selections, like you do in this example from Windows.  And use that final selection as the input to the form.
Can this be done?

A: It can be done but most likely you'll have to use a third party library.
This menu is called context menu.
Checkout the library below
http://swisnl.github.io/jQuery-contextMenu/index.html
If you just want to put input in a form then probably it's better to use a simple dropdown.

A: I guess you want to implement something like this. You will get many codes in google if you simply search for a multilevel drop down navigation menu.

ul
{
 list-style:none;
 position:relative;
 float:left;
 margin:0;
 padding:0
}

ul a
{
 display:block;
 color:#333;
 text-decoration:none;
 font-weight:700;
 font-size:12px;
 line-height:32px;
 padding:0 15px;
}

ul li
{
 position:relative;
 float:left;
 margin:0;
 padding:0
}

ul li.active
{
 background:#ddd
}

ul li:hover
{
 background:#f6f6f6
}

ul ul
{
 display:none;
 position:absolute;
 top:100%;
 left:0;
 background:#fff;
 padding:0
}

ul ul li
{
 float:none;
 width:200px
}

ul ul a
{
 line-height:120%;
 padding:10px 15px
}

ul ul ul
{
 top:0;
 left:100%
}

ul li:hover > ul
{
 display:block
}

Home

Menu 1 ►

Sub Menu 1

Sub Menu 2 ►

Sub Sub Menu 1

Sub Sub Menu 2

Sub Menu 3

Menu 2 ►

Sub Menu 1

Sub Menu 2

Sub Menu 3

Menu 3

A: Fair enough, the suggestion to use the jQuery contextMenu plugin really is not bad. It can handle submenu's for you without a problem and really makes defining the command's quite a lot easier than writing it yourself.
http://swisnl.github.io/jQuery-contextMenu/demo/sub-menus.html


text:
Q: Angular img source within ng-repeat I have a ROR application and I'm integrating a small angularJS on the client side (using HAML for the templates).
I have two issues I'm not sure how to address:

*

*I'm placing my images under "app/assets/javascripts/images/" is it the right place to keep my images? (please keep in mind that I'm using assets pipeline)

Here's my code:
.box{ "ng-repeat" => "s in treatments.services", "ng-show" => "true"}
  .category-title
    {{ s.category }}
  %img{"src" => "/assets/images/icon_{{ s.category }}.png"}

*I have 4 services, and everything looks visually good, the thing is that I'm getting a 404 (Not Found) JS error, looking at the 'network' tab in the developers tool (I'm using chrome) I can see all the expected Get requests foreach service's category I have and one EXTRA request (the false one that caused the js not found error) to http://localhost:3001/assets/images/icon_%7B%7B%20category%20%7D%7D**.png**
Here's a valid request that I can also see going through:
http://localhost:3001/assets/images/icon_xray.png
Any idea why this extra get request happens?

Thanks !

A: Angular markup in a src attribute doesn't work, the markup will be used as it is in the source link. You should instead use ng-src :
.box{ "ng-repeat" => "s in treatments.services", "ng-show" => "true"}
  .category-title
    {{ s.category }}
  %img{"ng-src" => "/assets/images/icon_{{ s.category }}.png"}

More info here : AngularJS: API: ngSrc
About the images, it should normally be placed under 'app/assets/images', and then from the client side you access it with '/assets/img.png'.


text:
Q: How to run async code inside each() function? I need to be able to run async code inside the each loop, and not iterate until the async code has finished .
$("#items").children(".block-option-small").each(function(item) {
    request(newurl,function(err, resp, body) {  $ = cheerio.load(body);});
});

A: Try using async's whilst function:
var async = require("async"),
    request = require("request");

var items, count;

items = $("#items").children(".block-option-small");
count = 0;

async.whilst(
    function() {
        return count < items.length;
    },
    function(whilstCallback) {
        var item;

        item = items[count];
        count++;

        // build request url...

        request(newurl, function(err, resp, body) {
            $ = cheerio.load(body);

            // more processing...

            // process the next item
            whilstCallback();
        });
    },
    function(err) {
        // called when all items have been processed
    }
);

A: You don't have to use the module just for this. You could also write it like this;
var items = $("#items").children(".block-option-small");
var count = items.length;

(function iterate(i) {
  if (i === count) {
    // iterations complete
    // do what you want to once iterations are complete
    process.exit(1);
  }

  var item = items[i];

  // async code
  request(newurl, function (err, resp, body) {
    $ = cheerio.load(body);
    iterate(i+1);
  });
})(0);

Hope this helps.


text:
Q: laravel create omits/skips fields I'm trying to seed a couple of databases with laravel seeder, but it seems that it skips some fields..
I'm doing it this way:
Item::create(array(
    'name' => 'Category 2',
    'photo' => 'Description of category 2',
    'order' => 1
    'price' => 2.30
    'category_id' => 1,
));

The fields 'category_id' and order are not setup in the database..
I'm calling the seeder this way
Artisan::call('db:seed',array('--database' => 'tenant_'.$user, '--class' => 'TenantSeeder'));

Any idea why does it happen?
If I use the standard
$item = new Item;
$item->allfields = "its_value";
$item->save();

It works perfectly
UPDATE
Here comes the model:
<?php
class Item extends Model {

    //============================================================================
    // PARENT VARIABLES
    //============================================================================
    protected $table = "items";

    protected $softDelete = true;

    protected $hidden = ['created_at','updated_at'];
    protected $fillable = ['name','price','description','photo'];   //Items that can be mass assigned
    protected $guarded = array('id');

    protected static $rules = [
        'name'          => 'required|min:3',
        'price'         => '',
        'description'   => '',
    ];

    //============================================================================
    // METHODS
    //============================================================================
    public function getId()         {   return $this->getKey();  }
    public function getName()       {   return $this->name;      }
    public function getPhotoSrc()   {   return $this->photo;     }

    public function item_category(){
        return $this->belongsTo('Items_category');
    }

    public function scopeActive($query)
    {
        return $query->where('active', '=', true);
    }
}

And the Scheme
Schema::create('items', function(Blueprint $table)
        {
            // auto increment id (primary key)
            $table->increments('id');

            $table->string('name')->default('New Item');
            $table->float('price')->default(0);
            $table->string('photo')->nullable();
            $table->integer('order')->unsigned();
            $table->boolean('active')->default(true);
            $table->string('description')->nullable();

            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')->references('id')->on('items_categories')->onDelete('cascade');

            // created_at, updated_at DATETIME
            $table->timestamps();
            $table->softDeletes(); //It is not really deleted, just marked as deleted
        });

Any idea?

A: As User2094178 said,
I didn't have the fields in the $fillable


text:
Q: Calculate direction of rotation after object collision in three.js I'm detecting collision in my three.js demo using a Raycaster which points out the front of my camera (which can only move in the direction it's facing - though the mouse steers the camera in any direction):
var ray = new THREE.Raycaster( camera.position, cameraDirectionVector );
var collisionResults = ray.intersectObjects( scene.children  );
if ( collisionResults.length > 0 )
    {
        if (collisionResults[0].distance < 0.15) {
            var crossAxis = new THREE.Vector3( 0, 0, 1 );
            crossAxis.crossVectors(cameraDirectionVector, collisionResults[0].face.normal)
            camera.rotateOnAxis( crossAxis, 0.2); // this second parameter is the number I'd like to calculate correctly
    }
}

So when there's a collision, I'm using the cross product of the collision face normal and the camera's direction of travel as the axis of rotation, with the aim of effectively spinning the camera away from the collision.
I'd like to know how to correctly calculate the direction of the rotation around that axis; Depending on the direction of crossAxis Vector3 relative to the face normal and direction of travel, the value might either need to be positive or negative.
I should point out this collision detection is aiming only to be very rudimentary - and limited by the fact that the player can only move forward.
How would I figure out if the camera needs to rotate clockwise or anticlockwise around that cross product axis? (Once I know how this number can be calculated I can have the collision expressed more 'realistically'; eg, by having the rotation value decrease over a set amount of frames).
Any help, much appreciated!

A: Maybe I missunderstood your question, but depending on what direction the camera is approaching the collision face normal, the cross product will be facing in different direction, and thereby changing the rotation direction.
In the example below, the blue arrow would be your collision face normal, the red arrow is your cameras direction, and the green arrow is the cross product betweeen the two (red X blue). The cameras direction is coming in towards the face normal in different directions, thus creating a different cross product each time.
You'll notice that each time the angle between the red and blue arrow passes 180 degrees of eachother, the rotation direction of the white sphere changes. This is because I am using the green arrow (the cross product of red and blue arrow) as the axis of rotation, and when the axis of rotation changes side, the rotation direction changes aswell due to the right hand rule.
Because of this, you should not have to put any sign infront of the second parameter, the direction of rotation is already given in the (cross product) vector that you use as rotation axis.
But since your asking this question, and you are providing some example code, I assume that the solution you have provided is not what you want. Maybe you mean that you always want the camera to rotate away from the collision normal, have you tried simply to put a negative value as the second parameter?

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75,     window.innerWidth/window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var origin = new THREE.Vector3(0, 0, 0)

var a = new THREE.Vector3(1, 0, 0);
var arrowHelperA = new THREE.ArrowHelper( a, origin, 1, 0xff0000 );
scene.add( arrowHelperA );

var b = new THREE.Vector3(0, 1, 0);
var arrowHelperB = new THREE.ArrowHelper( b, origin, 1, 0x0000ff );
scene.add( arrowHelperB );

var crossAB = new THREE.Vector3().crossVectors(a, b);
var arrowHelperCrossAB = new THREE.ArrowHelper( crossAB, origin, 1, 0x00ff00 );
scene.add( arrowHelperCrossAB );

var geometry = new THREE.SphereGeometry( 0.02, 32, 32 );
var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
var sphere = new THREE.Mesh( geometry, material );
scene.add( sphere );
sphere.position.copy(crossAB);
sphere.position.x = 0.3;

camera.position.z = 2;
camera.position.x = 2;
camera.position.y = 2;

camera.lookAt(origin);

var animate = function () {
  requestAnimationFrame( animate );

  a.applyAxisAngle(new THREE.Vector3(0, 0, 1), 0.01);
  arrowHelperA.setDirection(a);

  crossAB = new THREE.Vector3().crossVectors(a, b);
  arrowHelperCrossAB.setDirection(crossAB);
  arrowHelperCrossAB.setLength(crossAB.length())

  sphere.position.z = crossAB.z;
  sphere.position.applyAxisAngle(crossAB.normalize(), .1);

  renderer.render(scene, camera);
};

animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/86/three.min.js"></script>


text:
Q: jQuerys $(e.target) returns different things in Chrome and IE11 I've made a codepen for you to see the misbehaving IE11:
http://codepen.io/timkley/pen/rjamgP
Basic setup is a form with a select field and a button. I want to catch the click on the form and only fire the submit button if the select button was NOT clicked.
<form class="form">
  <select class="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <button class="button" type="submit">Hello</button>
</form>

And the Javascript:
$(document).on('click', '.form', function(e) {
  console.log($(e.target));

  e.preventDefault();
});

Basically all I did was check for $(e.target).hasClass('select') to return false. But this doesn't work in IE11 because not only doesn't it return the DOM Element but also fires 2 click events. One for the clicking on the select element and one for selecting an option.
How can I ensure the same behavior in both browsers?

A: Not sure why you're going this route but you can detect the tag type of the target and branch from there.

    $(document).on('click', '.form', function(e) {
      var $target = $(e.target);
      var tag = $target[0].tagName.toLowerCase();

      if(tag !== "select" && tag !== "option"){
        console.log(tag + " isn't a select or an option");
      } else {
        console.warn(tag + " was clicked");
      }
      e.preventDefault();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
  <select class="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <button class="button" type="submit">Hello</button>
</form>

A: You can bind another click handler with select and use event.stopPropagation()
$(document).on('click', '.form', function (e) {
    e.preventDefault();
    console.log(e.target.tagName + ' is clicked.');
}).on('click', '.form select', function (e) {
    e.stopPropagation();
});

$(document).on('click', '.form', function(e) {
  e.preventDefault();
  console.log(e.target.tagName + ' is clicked.');
}).on('click', '.form select', function(e) {
  e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
  <select class="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <button class="button" type="submit">Hello</button>
</form>

Or, You can use .closest() to test whether e.target is select or its child element.
$(document).on('click', '.form', function (e) {
    e.preventDefault();
    if ($(e.target).closest('select').length) {
        console.log('Select is clicked do nothing.');
    } else {
        console.log(e.target.tagName + ' is clicked.');
    }
});

$(document).on('click', '.form', function(e) {
  e.preventDefault();
  if ($(e.target).closest('select').length) {
    console.log('Select is clicked do nothing.');
  } else {
    console.log(e.target.tagName + ' is clicked.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
  <select class="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <button class="button" type="submit">Hello</button>
</form>


text:
Q: Using insert() on empty std::vector when sorting I know ideally to add to a std::vector without worry I should use push_back(). However my problem set is that I need a clean code to check if the value I am entering is already in the std::vector and if not, I have to put in sequential, ascending order. To do that I am doing:
vector<Book>::iterator it;
it = std::find(books.begin(), books.end(), b);
if (it != books.end()) {
    *it = b; // if b exists in books, overwrite the iterator
}
else {
    vector<Book>::iterator _it;
    _it = lower_bound(books.begin(), books.end(), b);
    books.insert(_it, b); // here on an empty vector, _it has no values
}

The else will only run if the value b doesnt already exist in the std::vector. If this is the first value being checked against it, the else runs (since its empty) and the std::iterator is at books[0](?).
What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to. Now the program functions and yields anticipated results, but is it erroneously?

A: What you are doing works fine. However it is not the most efficient way. Using std::find doesn't take advantage of the fact that the data in the vector is sorted, it visits every element until if finds the correct one.
Instead of std::find you can use std::lower_bound from the beginning because that will find your element if it exists and if not, it will find the correct place to insert a new one.
Also it will use a binary search so it will be leaps and bounds faster than std::find. Also you don't end up finding the insertion/replacemt point twice.
Something like this should do:
void insert_or_replace(std::vector<Book>& books, Book const& b)
{
    std::vector<Book>::iterator it;

    it = std::lower_bound(books.begin(), books.end(), b);

    if(it != books.end() && *it == b)
        *it = b;
    else
        books.insert(it, b);
}

A: It is all well defined behavior.
lower_bound will return the end iterator (books.end() in your case) for an empty range or if b should come after the last element.  insert will add the new element before the iterator passed to it, so this will be before end.  In an empty vector, this will have the effect of adding the element to the vector.

A: The code is pretty fine. For an empty vector lower_bound(books.begin(), books.end(), b) will return end() iterator. Passing it to std::vector::insert will work fine.

pos -   iterator before which the content will be inserted. pos may be the end() iterator

and about your worry:

What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to.

That's because the end() iterator points to the position following the last element, so it's invalid to deference on it (to get a nonexistent element).


text:
Q: Indenting / Spaces layout after a label in Intellij with groovy Intellij Seems to have a default layout like this
def foo(int arg) {
    label1:
    for (i in 1..10) {
        label2:
        foo(i)
    }
}

How do i change it to
def foo(int arg) {
    label1:
        for (i in 1..10) {
            label2:
            foo(i)
        }
}

This is required since we want out test layouts to look like this:
def 'my test'() {
   given:
       ...
   when:
       ...
   then:
       ...
}

ANSWER:
As given below in the answer, I can confirm this works in intellij 13

A: In Idea Intellij 13+
Settings -> Editor -> Code Style -> Groovy -> Tabs and Indents

*

*Label indent: 4

*Label indent style: Indent statement after label


text:
Q: Creating Text Elements using ArcPy? From what I can tell python at ArcGIS Desktop 10.0 cannot create new textElements nor GraphicElements. Yet, 10.1 seems to support the ability to at least create a clone, of a existing GraphicElements, but not create one from scratch.
Can someone confirm this?
Does anyone know of any workaround to create a textElement from scratch?

A: This is true.
ArcPy at ArcGIS Desktop 10.0 cannot create or copy/clone graphic or text elements using the arcpy.mapping module.
ArcPy from ArcGIS 10.1 for Desktop has a clone option is available, but it is still not possible to create a graphic or text element from scratch.
This software behaviour is the same in ArcPy from ArcGIS 10.2 for Desktop where the TextElement (arcpy.mapping) help says:

The TextElement object provides access to properties that enable its
  repositioning on the page layout as well as modifying the text string
  and font size.
...
Existing text elements can be cloned and deleted. This capability was
  initially added to support the creation of dynamic graphic tables. To
  accomplish this, a map document must be authored with the text
  elements having the appropriate symbology.


text:
Q: How do you balance the conflicting needs of backwards compatibility and innovation? I work on an application that has a both a GUI (graphical) and API (scripting) interface.  Our product has a very large installed base.  Many customers have invested a lot of time and effort into writing scripts that use our product.
In all of our designs and implementation, we (understandably) have a very strict requirement to maintain 100% backwards compatibility.  A script which ran before must continue to run in exactly the same way, without any modification, when we introduce a new software version.
Unfortunately, this requirement sometimes ties our hands behind our back, as it really restricts our ability to innovate and come up with new and better ways of doing things.
For example, we might come up with a better (and more usable) way of achieving a task which is already possible.  It would be desirable to make this better way the default way, but we can't do this as it may have backwards compatibility implications.  So we are stuck with leaving the new (better) way as a mode, that the user must "turn on" before it becomes available to them.  Unless they read the documentation or online help (which many customers don't do), this new functionality will remain hidden forever.
I know that Windows Vista annoyed a lot of people when it first came out, because of all the software and peripherals which didn't work on it, even when they worked on XP.  It received a pretty bad reception because of this.  But you can see that Microsoft have also succeeded in making some great innovations in Vista, at the expense of backwards compatibility for a lot of users.  They took a risk.  Did it pay off?  Did they make the right decision?  I guess only time will tell.
Do you find yourself balancing the conflicting needs of innovation and backwards compatibility?  How do you handle the juggling act?

A: As far is my programming experience is concerned, if I'm going to fundamentally change something that will prevent past incoming data to be used correctly, I need to create an abstraction layer for the old data where it can be converted for use in the new format.
Basically I set the "improved" way as default and make sure through a converter it can read data of the old format, but save or store data as the new format.
I think the big thing here is test, test, test.  Backwards compatibility shouldn't hinder forward progress.

A: Split development into two branches, one that maintains backwards compatibility and one for a new major release, where you make it clear that backwards compatibility is being broken.

A: The critical question that you need to ask is wether the customers want/need this "improvement" even if you perceive it as one your customers might not. Once a certain way of doing things has been established changing the workflow is a very "expensive" operation. Depending on the computer savyness of your users it might take some a long time to adjust to the change in the UI.
If you are dealing with clients innovation for innovation's sake is not always a good thing as fun as it might be for you to develop these improvements.

A: You could alawys look for innovative ways to maintain backwards compatibilty.


text:
Q: What is the right way variables initialize in stateless widget? I am initializes in constructor but I am not sure it is the right way?
class PlaceDialogWidget extends StatelessWidget {
  final NearbyPlace currentPlace;
  final SizeHelper sizeHelper;

  PlaceDialogWidget(
      {Key? key, required this.currentPlace, required this.sizeHelper})
      : dialogWidth = sizeHelper.width! * 0.7,
        dialogHeight = sizeHelper.height! * 0.5,
        super(key: key);

  late final double dialogWidth;
  late final double dialogHeight;
}

A: Yes, this is one way of initializing variables in Dart.
Dart as a language has many interesting features around constructors. Please see Using constructors for more info
flutter is a framework build with dart, so the constructor rules of dart apply to flutter as well and so a StatelessWidget class is like any other dart class.


text:
Q: Get all folders from Composite I'm creating a tree structure of a given folder (only folders no files)
also i return the security permission of each folder and add it to a list
Now how can i Loop through this composite and get all items and sub items
 public abstract class FolderComponent:IEnumerable
{
    public string FullName { get; set; }
    public string Name { get; set; }
    public List<string[]> Rules { get; set; }
    public abstract void AddFolder(FolderComponent folderComponent);
    public abstract IEnumerator GetEnumerator();
    public abstract void AssignRules();
}

public class Folder : FolderComponent
{
    public IList<FolderComponent> FolderComponents { get; set; }

    public Folder(string path)
    {
        FullName = path;
        FolderComponents = new List<FolderComponent>();
        Rules = new List<string[]>();
    }

    public override void AddFolder(FolderComponent folderComponent)
    {
        FolderComponents.Add(folderComponent);
    }

    public override IEnumerator GetEnumerator()
    {
        return FolderComponents.GetEnumerator();
    }

    public override void AssignRules()
    {
        // some code
        string[] rules = new string[]{"Read","Write","Execute"};
        Rules.Add(rules);
    }

}

public class Program
{
    private static FolderComponent GetFolders(string path)
    {
        FolderComponent folder = new Folder(path);
        folder.AssignRules();
        foreach (var directory in Directory.GetDirectories(path))
        {
            folder.AddFolder(GetFolders(directory));
        }
        return folder;
    }

    public static void Main()
    {

        FolderComponent folder = GetFolders(@"C\:Test");
        // How can i loop though all folder structure inside folder?

    }
}

A: If you want to do something like this with your Folder class:
FolderComponent folders = GetFolders(@"C\:Test");
foreach (var folder in folders) { Console.WriteLine(folder.FullName); }

and get the full directory tree printed, then the GetEnumerator method needs to have logic to traverse the tree.  For example
    public override IEnumerator<FolderComponent> GetEnumerator()
    {
        // Return the current element
        yield return this;

        // Work through the collection of components in this folder ...
        foreach (var component in FolderComponents)
        {
            // ... and traverse all the subfolders in each component.
            // Note that this recursively calls this GetEnumerator
            // method on the subfolders to work down the tree.
            foreach (var subfolder in component)
            {
                yield return subfolder;
            }
        }
    }

A: I added a method to your FolderComponent class and implement that
see if that can do the thing:
 public abstract class FolderComponent : IEnumerable
{
    public string FullName { get; set; }
    public string Name { get; set; }
    public List<string[]> Rules { get; set; }
    public abstract void AddFolder(FolderComponent folderComponent);
    public abstract IEnumerator GetEnumerator();
    public abstract void AssignRules();
    public abstract List<FolderComponent> GetAllItems();
}

public class Folder : FolderComponent
{
    public IList<FolderComponent> FolderComponents { get; set; }

    public Folder(string path)
    {
        FullName = path;
        FolderComponents = new List<FolderComponent>();
        Rules = new List<string[]>();
    }

    public override void AddFolder(FolderComponent folderComponent)
    {
        FolderComponents.Add(folderComponent);
    }

    public override IEnumerator GetEnumerator()
    {
        return FolderComponents.GetEnumerator();
    }

    public override void AssignRules()
    {
        // some code
        string[] rules = new string[] { "Read", "Write", "Execute" };
        Rules.Add(rules);
    }

    public override List<FolderComponent> GetAllItems()
    {
        var resultItems = new List<FolderComponent> {this};
        foreach (var folderComponent in FolderComponents)
        {
            resultItems.AddRange(folderComponent.GetAllItems());
        }
        return resultItems;
    }
}

public class Program
{
    private static FolderComponent GetFolders(string path)
    {
        FolderComponent folder = new Folder(path);
        folder.AssignRules();
        foreach (var directory in Directory.GetDirectories(path))
        {
            folder.AddFolder(GetFolders(directory));
        }
        return folder;
    }

    public static void Main()
    {

        FolderComponent rootfolder = GetFolders(@"D:\4Share");
        var allItems = rootfolder.GetAllItems();
        foreach (var folderComponent in allItems)
        {
            Console.WriteLine(folderComponent.FullName);
        }
        Console.ReadLine();

    }

A: you should add a list of folder type (children).
FolderComponent Parent;
List<FolderComponent> children;

And add a child when u find a folder inside specific folder. You can add parent for backward processing as well.
var directoryInfo = new DirectoryInfo(folderPath);
foreach (var directory in directoryInfo)
{
    FolderComponent newSubFolder = new FolderComponent();
    newSubFolder.Parent = this;
    // get whatever you want like name, permissions etc.
    children.Add(newSubFolder);
}

You need something like this in your code (depends on implementation)
PrintFolders()
{
    foreach(var child in children)
         child.PrintFolders();

    Console.WriteLine(FolderName);
}