text:
Q: AngularJS Jasmine - Test with different Mock Response in next 'it' block describe('test mock', function () {

    var resource, employeeRoles, provider, mockBaseUrl, mockUser, mockOffices, mockCalendar, $window, $httpBackend, $scope, $serializer;

    beforeEach(angular.mock.module('appointmentManager'));

    beforeEach(inject(function ($injector, $rootScope, $httpParamSerializer) {

        mockCalendar = {
     // sample data
            };

        $window = $injector.get('$window');
        $window.ApiBaseUrl = mockBaseUrl;
        $window.LoggedInUser = mockUser;

        $httpBackend = $injector.get('$httpBackend');
        $httpBackend.expectPOST('api/Calendar/GetCalendar').respond(200, mockCalendar);

        $scope.$apply();

        $httpBackend.flush();
    }));

    it('should be defined in module', function () {
        expect(resource).toBeDefined();
        expect(provider).toBeDefined();
    });

    it('active employees should be true', function () {
        expect(provider.isNoActiveEmployeesAvailable).toBe(false);

        //test with another mockCalendar data
    });

    afterEach(function () {
        $scope.$destroy();
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });
});

I want to test with different Mock Response in Next it block. Here, how can I assign new value in mockCalendar variable before the second it block runs?

A: In your scenario, which is not uncommon, I typically create a function that has code that is going to be common in all my tests, and then call it from your test, after additional arrangements that cannot be performed in the beforeEach. Note this is different than using the beforeEach, because you still need to be able to modify something prior to calling the function.
For instance, your code would be modified to be like the following:
describe('test mock', function () {

    var resource, employeeRoles, provider, mockBaseUrl, mockUser, mockOffices, mockCalendar, $window, $httpBackend, $scope, $serializer;

    var setupTest = function(mockCalendar) {
        $httpBackend.expectPOST('api/Calendar/GetCalendar').respond(200, mockCalendar);
        $scope.$apply();
        $httpBackend.flush();
    };

    beforeEach(angular.mock.module('appointmentManager'));

    beforeEach(inject(function ($injector, $rootScope, $httpParamSerializer) {
        mockCalendar = {
          // sample data
        };

        $window = $injector.get('$window');
        $window.ApiBaseUrl = mockBaseUrl;
        $window.LoggedInUser = mockUser;

        $httpBackend = $injector.get('$httpBackend');
    }));

    it('should be defined in module', function () {
        setupTest(mockCalendar); // not sure if this is needed here.
        expect(resource).toBeDefined();
        expect(provider).toBeDefined();
    });

    it('should set provider.isNoActiveEmployeesAvailable to false when xxx', function () {
        mockCalendar.someField = 'some value';
        setupTest(mockCalendar);
        expect(provider.isNoActiveEmployeesAvailable).toBe(false);
    });

    it('should do something else', function () {
        mockCalendar.someField = 'some other value';
        setupTest(mockCalendar);
        expect(provider.isNoActiveEmployeesAvailable).toBe(true);
    });

    afterEach(function () {
        $scope.$destroy();
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });
});


text:
Q: Удалить неполную строку в SQL Есть вот такой запрос
Нужно вывести только те строки где property_values имеет все три значения
SELECT
title,
stock,
price,
(
    SELECT GROUP_CONCAT(p.title, ': ', pv.value SEPARATOR ', ')
    FROM ( SELECT * FROM product_property_value pv WHERE (pv.property_id,pv.value)=(1,"Красный" ) or (pv.property_id,pv.value)=(2,4 ) or (pv.property_id,pv.value)=(2,5 ) or (pv.property_id,pv.value)=(3,5 )) pv

    INNER JOIN property p on pv.property_id = p.id WHERE pv.product_id = product.id
) property_values

FROM product ORDER BY property_values;
И в картинке результат. КАК мне вывести только те строки где в property_values есть все три значения?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PayPal ExpressCheckout API : Get transaction total in local currency Is there a way of getting the total for the transaction (or better yet, split between shipping, subtotal etc.) in merchant's local currency using the ExpressCheckout API - even though the transaction has been done using different currency code?
Example would be someone who has selected USD on the website to display prices in and paid using USD when redirected to PayPal, but the business (merchange) who receives the funds is based in UK and his default currency is GBP.
Is there a way to get the sub-totals in GBP using ExpressCheckout API? I couldn't find anything within the GetExpressCheckoutDetails and DoExpressCheckoutPayment calls - so not quite sure it's possible at all.

A: To my knowledge, GetExpressCheckoutDetails will not allow you to return specific currencies, but you could use the ConvertCurrency API to convert the value returned by GECD to what you need.


text:
Q: Ammaps legend only appears on window resize I'm using ammaps to create a map and trying to create a legend. I'm running in to a weird problem where the legend doesn't appear on initial load but only appears on window resize. Regardless of the window size, on any resize, the legend becomes visible (VERY WEIRD RIGHT?).
Code:
var icon = "M9.875,0.625C4.697,0.625,0.5,4.822,0.5,10s4.197,9.375,9.375,9.375S19.25,15.178,19.25,10S15.053,0.625,9.875,0.625";
var map = AmCharts.makeChart( "mapdiv", {
    /**
    * this tells amCharts it's a map
    */
    "type": "map",

    /**
    * create data provider object

    */
    "dataProvider": {
      "mapURL": "https://raw.githubusercontent.com/ggwc82/amcharts/master/unitedKingdomLow.svg",
      "getAreasFromMap": false,

      "images": [ {
        "latitude": 51.5074,
        "longitude": 0.1278,
        "svgPath": icon,
        "scale": 0.7,
        "label": "Dagenham Factory",
        "labelBackgroundColor": "#ffffff",
        "labelColor": "#696D6E",
        "labelFontSize": 14,
        "labelShiftY": 00,
        "color": "#D30000",
        "title": "1 Warning",
        "url": "http://www.google.co.uk",
        "description": "DRM with id 09 is offline"
      },
      {
        "latitude": 53.4808,
        "longitude": -2.2426,
        "svgPath": icon,
        "scale": 0.7,
        "label": "Manchester Factory",
        "labelBackgroundColor": "#ffffff",
        "labelColor": "#696D6E",
        "labelFontSize": 14,
        "labelShiftY": 0,
        "color": "#40D300",
        "title": "No Issues",
        "url": "http://www.google.co.uk",
        "description": ""
      },
      {
        "latitude": 54.9783,
        "longitude": -1.6178,
        "svgPath": icon,
        "scale": 0.7,
        "label": "Newcastle Factory",
        "labelBackgroundColor": "#ffffff",
        "labelColor": "#696D6E",
        "labelFontSize": 14,
        "labelShiftY": 0,
        "color": "#D3D000",
        "title": "2 Alerts",
        "url": "http://www.google.co.uk",
        "description": "DRM with id 23 is inactive. DRM with id 25 is inactive."
      }
    ],

  },

  /**
  * create areas settings
  * autoZoom set to true means that the map will zoom-in when clicked on the area
  * selectedColor indicates color of the clicked area.
  */
  "areasSettings": {
    "autoZoom": true,
    "unlistedAreasColor": "#C8E1D6",
    "selectedColor": "#CC0000"

  },
  "zoomControl": {
    "zoomControlEnabled": false,
    "homeButtonEnabled": true,
    },
  "dragMap": false,
  "showDescriptionOnHover": true,
  "allLabels": [
        {
        "text": "Default Factory View - UK Sites",
        "bold": true,
        "size": 20,
        "color": "#696D6E",
        "align": "center",
        "y": 100
        }
    ],

} );

var legend = new AmCharts.AmLegend();
console.log("hello");
map.addLegend(legend,"legenddiv");
legend.data = [{title:"first", color:"#CC0000", markerType: "circle"},
               {title:"second", color:"#00CC00", markerType: "circle"},
              {title:"second", color:"#ffff00", markerType: "circle"}]

A: You're using the makeChart function. This function is an helper which allow you to create in a single call a chart / map, configure it using JSON, display it in the container div passed as first argument and get back the instance previously created.
You're adding the legend to your instance but it's already rendered by the makeChart helper when you're hitting your code adding the legend. So, when adding the legend to an already rendered chart, it'll only be visible when re-rendered which happens when you resize your window.
As specified in the documentation, the AmMap class can not be instantiated explicitly so the use of the makeChart method is mandatory but you can also configure your legend in the JSON config instead of doing it later.
/**
 * Legend
 */
"legend": {
  "width": 400,
  "backgroundAlpha": 1,
  "backgroundColor": "#fff",
  "borderColor": "#000",
  "borderAlpha": 1,
  "bottom": 15,
  "right": 15,
  "horizontalGap": 10,
  "data": [{
    "title": "first",
    "color": "#CC0000",
    "markerType": "circle"
  }, {
    "title": "second",
    "color": "#00CC00",
    "markerType": "circle"
  }, {
    "title": "third",
    "color": "#ffff00",
    "markerType": "circle"
  }]
},

I've put a little fiddle based on your question including a legend configured in JSON. The legend is displayed at the same time of the map, no resize or anything required to show it.


text:
Q: Is ride-hailing the same as hail and ride? I am not a native English speaker. I need some experience straight from the horse's mouth.
Today I read an article with the word 'ride-hailing' (and I posted a quote below this paragraph).
I got curious what ride-hailing is, so I opened my dictionary and tried to translate the word into my language. There have been no answers. There seem to be no equivalents in my language. I decided to add this word to a user-contributed dictionary. But, first, I need to understand the idea behind the word. This might help find a similar word in my language. So, I needed to understand what 'ride-hailing' was, and I googled it.
I have found no reliable sources to explain the word. However, there was a big Wikipedia article on ... hail and ride! The other serious-looking results were mostly about ... 'ride-hailing' and there is even an online dictionary article. Suddenly, I got an idea, an insight. What if both words - hail and ride and  ride-hailing are the same thing simply written in different words?
In this case, if the connotations - the words - are the same, than ride-hailing means hail and ride and, so I can continue with my little research.
THE QUESTION IS: are ride-hailing and hail and ride the same thing?
HERE IS THE QUOTE from TheGuardian with the original words:

"Uber tripled federal lobbying efforts in 2016, spending $1.36m – a
  whopping $890,000 more than in 2015. These efforts focused on
  modernizing existing laws, including pushing to allow federal
  employees to use
  ride-hailing
  services when traveling on official
  business."

So, here they are talking about taxis, and not buses!

But, then, Wiki talks buses:

In public transport in the United Kingdom and Australia, hail and ride
  is boarding or alighting a mode of public transport by signalling the
  driver or conductor that one wishes to board or alight, rather than
  the more conventional system of using a designated stop. Hail and ride
  is used primarily in bus transport.

Please, help me with your expertise. I understand you can speak different versions of English, so, it would be useful if you mentioned your part of the world.
P.S. The images in this article were borrowed from Business Standard and Transport for London. Also, I got puzzled by the Google image search results where ride-hailing was mainly about taxi, while hail and ride was about both buses and taxis.

A: Ride-hailing is the act of stopping a vehicle to ride it. Hail-and-ride is the system (scheme, set of practices and rules) in which buses can be / must be hailed by passengers who want to ride. Hail-and-ride is used to distinguish such systems within modes of transportation (buses) where it is not customary.


text:
Q: Помогите с правилом XSLT Имеется XML.
<file>

    <comment>#   Секция заслешивания путей без слеша в конце</comment>
    <rule typename="RewriteRule" pattern="/([-a-zA-Z]+)" substitution="/$1/" flags="R=301,L" />
    <rule typename="RewriteRule" pattern="/([-a-zA-Z]+)/([-a-zA-Z]+)" substitution="/$1/$2/" flags="R=301,L" />
    <rule typename="RewriteRule" pattern="/([-a-zA-Z]+)/([-a-zA-Z]+)/([-a-zA-Z]+)" substitution="/$1/$2/$3/" flags="R=301,L" />

    <comment>#    Секция преобразования URL в вызов контроллера</comment>

</file>

На выходе после преобразования, получаем следующий текстовый документ.
#   Секция заслешивания путей без слеша в конце

RewriteRule ^/([-a-zA-Z]+)/([-a-zA-Z]+)/([-a-zA-Z]+)$ /$1/$2/$3/ [R=301,L]
RewriteRule ^/([-a-zA-Z]+)/([-a-zA-Z]+)$ /$1/$2/ [R=301,L]
RewriteRule ^/([-a-zA-Z]+)$ /$1/ [R=301,L]

#    Секция преобразования URL в вызов контроллера

Имеем следующий шаблон для работы с узлами rule
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="rule">

        <xsl:if test="@typename != ''">

            <xsl:text>
</xsl:text>

            <xsl:value-of select="@typename"></xsl:value-of>

            <xsl:text> ^</xsl:text>

            <xsl:value-of select="@pattern"></xsl:value-of>

            <xsl:text>$ </xsl:text>

            <xsl:value-of select="@substitution"></xsl:value-of>

            <xsl:if test="@flags != ''">

                <xsl:text> [</xsl:text>

                <xsl:value-of select="@flags"></xsl:value-of>

                <xsl:text>]</xsl:text>
            </xsl:if>

        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Вопрос, как доработать шаблон, что бы он в каждом паттерне, убирал первый слэш из строк типа ^/([-a-zA-Z]+)$ и паттерн выглядел бы так ^([-a-zA-Z]+)$

A: Используя функции для работы с текстом substring() или substring-after(). substring() возвращает подстроку из исходной строки, начиная с указанной позиции, а substring-after() возвращает подстроку после указанного символа
<xsl:value-of select="substring(@pattern, 2)"/>
<xsl:value-of select="substring-after(@pattern, '/')"/>


text:
Q: Generate dynamic buttons in angularJS table I have a dynamic table being populated using ng-repeat=
How can i make the buttons dynamic , as buttons kind of hard code , all the stop timer buttons are getting disables once the starttimer button is clicked once.
And form is getting submitted n number times.

        Name

        Employees

        Head Office

        {{updateLeadEnvir.envirName}}

        {{updateLeadEnvir.envirDesc}}

        <button ng-click="hidetimer = {{updateLeadEnvir.envirName}}; startTimer()" ng-disabled="timerRunning">Start Timer</button>
        <button type="button" ng-click="stopTimer();hideMsg=true" ng-disabled="!timerRunning">Stop Timer</button>

 <timer>{{minutes}} minutes, {{seconds}} seconds.</timer>

A: Everytime you use ng-repeat, it creates a scope for each of the items. Inside this scope, there's a $index variable that can be used. So, you could use this $index value and start the timer related to that $index.

      <button ng-click="startTimer($index)" ng-disabled="timerRunning">Start Timer</button>
      <button type="button" ng-click="stopTimer($index)" ng-disabled="!timerRunning">Stop Timer</button>

 <timer>{{minutes}} minutes, {{seconds}} seconds.</timer>

Another problem that you are issuing is that the form is being submitted whenever you click in any button. Try using type="button" in the buttons so this doesn't happen
<button type="button"></button>


text:
Q: Docker Container won't start with systemctl I have just started checking out coreos
I have tried to setup redis and mysql docker instances, but with little succcess.
I initially expected everything to work on start up out of the box, but it appeared not to be the case.
So based on this documentation on systemd on the coreos site, I decided to try this to start my docker instace
cd /etc/systemd/system

sudo systemctl enable redis.service
$ sudo systemctl start redis.service

This did not work.
I used docker events to track its initialisation
docker event &

I am not sure what I am probably missed out..
Here is my cloud config file
#cloud-config
hostname: user1
# include one or more SSH public keys
ssh_authorized_keys:
  - ssh-rsa....
users:
  - name: user2
    passwd: temp123
    groups:
      - sudo
      - docker
    ssh-authorized-keys:
      - ssh-rsa....
coreos:
  etcd2:
    #generate a new token for each unique cluster from https://discovery.etcd.io/new?size=#{number_instances}
    discovery: https://discovery.etcd.io/fdadfadjskd546887878kfksdjfds
    # multi-region and multi-cloud deployments need to use 1.1.1.1
    advertise-client-urls: http://1.1.1.1:2379
    initial-advertise-peer-urls: http://2.2.2.2:2380
    # listen on both the official ports and the legacy ports
    # legacy ports can be omitted if your application doesn't depend on them
    listen-client-urls: http://0.0.0.0:2379,http://0.0.0.0:4001
    listen-peer-urls: http://2.2.2.2:2380,http://2.2.2.2:7001
  fleet:
    public-ip: 1.1.1.1
  flannel:
    interface: 3.3.3.51/23
  units:
    - name: systemd-networkd
      command: stop
    - name: 00-static.network
      runtime: true
      content:   "[Match]\n\
        Name=ens19\n\
        [Network]\n\
        Address=3.3.3.3/23\n\
        Gateway=3.3.3.255\n\
        DNS=8.8.8.8\n\
        DNS=8.8.4.4  \n"
    - name: systemd-networkd
      command: start
    - name: etcd2.service
      command: start
    - name: fleet.service
      command: start
    - name: redis.service
      command: start
      enable: true
      content: "[Unit]\n\
        Description=Redis Server Docker Container\n\
        After=docker.service\n\
        Requires=docker.service\n\
        [Service]\n\
        TimeoutStartSec=0 \n\
        EnvironmentFile=/etc/environment\n\
        ExecStartPre=-/usr/bin/docker kill %p\n\
        ExecStartPre=-/usr/bin/docker rm %p\n\
        ExecStartPre=/usr/bin/docker pull redis:latest \n\
        ExecStart=/usr/bin/docker run --name=redis --detach=true --publish=6379:6379 redis \n\
        ExecStop=/usr/bin/docker stop redis \n\
        [Install] \n\
        WantedBy=multi-user.target \n"
    - name: mysql.service
      command: start
      enable: true
      content: "[Unit]\n\
        Description=MySQL Server Docker Container\n\
        After=docker.service\n\
        Requires=docker.service\n\
        [Service]\n\
        TimeoutStartSec=0 \n\
        EnvironmentFile=/etc/environment\n\
        ExecStartPre=-/usr/bin/docker kill %p\n\
        ExecStartPre=-/usr/bin/docker rm %p\n\
        ExecStartPre=/usr/bin/docker pull mysql:latest \n\
        ExecStart=/usr/bin/docker run --name=mysql --env MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} --env MYSQL_USER=${MYSQL_USER} --env MYSQL_PASSWORD=${MYSQL_PASSWORD} --env MYSQL_DATABASE=${MYSQL_DATABASE} --detach --publish 3306:3306 --volume=/path/to/dumps/:/dumps/ mysql\n\
        ExecStop=/usr/bin/docker stop mysql\n\
        [Install] \n\
        WantedBy=multi-user.target \n"
write_files:
  - path: /etc/environment
    permissions: 0644
    content: "\nMYSQL_USER='user1'\n\
      MYSQL_DATABASE='db1'\n\
      MYSQL_CONTAINER_NAME='mysql'\n\
      MYSQL_ROOT_PASSWORD=$(cat /dev/urandom | LC_CTYPE=C tr -dc 'a-zA-Z0-9' | fold -w 32 | sed 1q) \n"

A: You are running redis container in detached mode so docker utility starts container and then exits. From systemd point of view this looks like controlled process exited so systemd executes ExecStop script which in your case stops redis container.
You need to keep process running so systemd won't try to stop or restart your container. One way to achieve this is to remove --detach flag. You can also use KillMode=none so systemd won't send SIGTERM to docker utility but will execute only ExecStop instead.
[Unit]
Requires=docker.service
After=docker.service

[Service]
TimeoutStartSec=0
KillMode=none
Restart=always
RestartSec=5s

ExecStartPre=-/usr/bin/docker kill %p
ExecStartPre=-/usr/bin/docker rm -v %p

ExecStart=/usr/bin/docker --name=redis --publish=6379:6379 redis

ExecStop=/usr/bin/docker stop %p
ExecStopPost=-/usr/bin/docker stop %p


text:
Q: Ionic SQLite Android / iOS database backup Im using Ionic Framework to build my native android and ios app. Data is stored via sqlite capacitor plugin. I want to provide a backup solution for my customers.
I'm considering sending a create, update, or delete request to my server after every sqlite operation. Or I could start a backup to my server every time the app starts, because ionic doesn't offer a proper scheduler service when the app is off. How would a professional solve this problem?


text:
Q: Why would my if(-f ) not be working? When initially checking if ARGV[0] is a file or directory, it worked fine with accurate results. Then further down into sub files I try it again and it doesnt return anything. This may seem like a small silly question but Im a student and help on programming on the weekends is scarce. Sometimes a new set of eyes can help.Thanks in advance.
#!/usr/bin/perl -w

my %hash;
my $args = @ARGV;

my $dh = $ARGV[0];

if ( -f $dh ) {
    words($dh);

} elsif ( -d $dh ) {
    files($dh);
}

sub words {
    open( my $file, '<', $_[0] ) or die 'cant open file';
    while ( my $line = <$file> ) {
        chomp $line;
        @words = split( /\s+/, $line );
        foreach $word (@words) {
            $word =~ tr/A-Z/a-z/;
            $hash{$word}++;
        }
    }

    foreach $key ( keys %hash ) {
        print $key. " " . $hash{$key} . "\n";
    }
}

sub files {
    opendir( DH, $_[0] );
    my @paths = grep !/^\./, readdir(DH);
    closedir(DH);
    foreach (@paths) {
        if ( -f $_ ) {
            print $_. "\n";
        }
    }
}

A: You're missing path to your file,
if (-f "$_[0]/$_") ..

or to make it less obscure,
sub files{
  my ($path) = @_;

  opendir(my $DH, $path);
  my @paths = grep !/^\./, readdir($DH);
  closedir($DH);

  foreach (@paths) {
    if (-f "$path/$_") {
       print "$_\n";
    }
  }
}

A: As has already been stated, the return values of readdir contain just the basename.  Therefore, to do file tests, you must either chdir or include the path info explicitly.
if (-f "$_[0]/$_") {

One alternative solution is to use Path::Class or some similar module for doing Cross-platform path specification manipulation.
The following is your script rewritten using this module:
use strict;
use warnings;

use Path::Class;

my $path = shift // die "Usage: $0 <Dir or File>\n";

words($path) if -f $path;
files($path) if -d $path;

sub words {
    my $file = file(shift);

    my %count;
    $count{ lc($_) }++ for split ' ', $file->slurp;

    for my $key ( keys %count ) {
        printf "%s %s\n", $key, $count{$key};
    }
}

sub files {
    my $dir = dir(shift);

    for ( $dir->children ) {
        next if $_->is_dir;
        print "$_\n", $_->basename;
    }
}


text:
Q: Similar venues with location foursquare API I am playing with Foursquare API and I was wondering if theres an endpoint for getting a similar venue in a location given another venue?
All I found is this endpoint:

https://api.foursquare.com/v2/venues/VENUE_ID/similar

Which returns a list of venues similar to a given venue. What I want is, exactly this but I want the returned venues be close to a given location.
For example:
I love a mexican restaurant in London.
I want to find a similar restaurant but in Barcelona.
Is that possible?
Thanks!

A: The venues/similar endpoint will only show similar venues near the desired venue. Your best bet is probably using the query parameter with venues/explore. The query parameter is pretty smart about determining your intent if you know what you're looking for and you can specify any location.
i.e.
https://api.foursquare.com/v2/venues/explore?
query=Mexican food outdoor seating
near=Barcelona


text:
Q: BLDC Isolated sensorless control I've currently developed a BLDC motor controller and it generally works fine. During some events however the microcontroller locks up (e.g. stopping the motor or fast changes of duty cycle). Because of this, I want to isolate the microcontroller from the power side (i.e. isolated supply and optocoupled signals) the issue however is I'm using sensorless control and am wondering what the best way of relaying the phase values back to the microcontroller would be?
I currently detect the zero crossing in software and use this to commutate my phases (as per the Microchip AN970 amongst others). I'd rather not use comparators on the power side and optocouplers to send back a digitized version of the phase voltages as I want to have the ability to change the trigger point.
I've looked at isolation amplifiers but they seem pretty expensive and I was wondering if there were any potentially cheaper solutions.
Thanks

A: Maybe have a look at this document:
https://www.silabs.com/documents/public/application-notes/AN614.pdf.
We use this design, but in a total different application. I dont' really know much about BLDC motors but maybe it helps.
kind regards


text:
Q: Read multiple keys from a JSON file in Python I am a little stuck with the following task that I am trying to sort out as I am just learning Python. I need to sort out "city" from the json file that looks like:
[{
    "city": "Las Vegas",
    "operator": "",
    "browser_name": "chromium",
    "browser_version": "55",
    "country_code": "us",
    "country": "United States",
    "location_code": "2e4efc13-6a6a-45ba-a6aa-ec4eb1f4fb2b|north-america.na.us.west.lasvegas|chromium|55",
    "location_tier": "1"
}, {
    "city": "Las Vegas",
    "operator": "",
    "browser_name": "firefox",
    "browser_version": "46",
    "country_code": "us",
    "country": "United States",
    "location_code": "2e4efc13-6a6a-45ba-a6aa-ec4eb1f4fb2b|north-america.na.us.west.lasvegas|firefox|46",
    "location_tier": "1"
}, ...

I have the code like this:
import json, operator

file_path = './response.json'

with open(file_path) as f:
    data = json.loads(f.read())
    print(data[0]['city'])

The thing is that I need comma separated output to a console like "city, city, city...". Would appreciate any help! Thanks a lot!

A: print(', '.join(item['city'] for item in data))

Also, have a look at this answer, using inflect package that will allow for properly constructed list in English, e.g. city, city, and city

A: You are very close to the result. You can have a list like this.
Code;
import json, operator
file_path = './response.json'
result = []
with open(file_path) as f:
    data = json.loads(f.read())
    for d in data:
        result.append(d['city'])
print(result)

Output; ['Las Vegas', 'Las Vegas']


text:
Q: getting 'Missing calls inside every { ... } block' when using mokk I'm using MockK as mock library for kotlin, for some reason I get an error on the every{} line.
io.mockk.MockKException: Missing calls inside every { ... } block.

this is my test class
internal class TestClass {

  private val service: MyService = mockk(relaxed = true)
  private val dao: MyDao = mockk(relaxed = true)
  private val repository: MyRepository = MyRepositoryImp(
    service = service,
    dao = dao,
  )

  @Test
  fun test() = runBlocking {
    val expected = SOMETHING

    every { repository.getValues() } returns flowOf(SOMETHINGELSE) // crash

    assertEquals(1, 1)
  }
}

MyService is just a retrofit interface
internal interface MyService {

  @GET("123")
  suspend fun getRemoteData(): Response<SOMECLASS>

}

Anyone has any idea? thanks!

A: You've instantiated the repository as a real instance. That means that it'll actually execute the code inside its implementation and that's known as the 'subject under test'.
But every { ... } returns ...  needs a mockk instance.
So in your example, it should be
every { service.getRemoteData() } returns ...
or
every { dao.someMethod() } returns ...


text:
Q: How to return ajax response with error http code from PrestaShop ModuleFrontController? I start working with PrestaShop 1.7.6 (before I worked with Symfony) and I write few custom modules to PrestaShop, but now I want send json data from my front controller module to user. Everything works fine if I send json with http code 200, but now I want send error message with proper http code (e.g 400). In Symfony I can do that by using JsonResponse (I try to do that here but it's not working as expected).I saw in presta controller are just two methods with ajax response (ajaxDie - which is deprecated and ajaxRender), but both of them doesn't takes as parameter http code response and always send 200.
    if (!$product) {
         $json = Tools::jsonEncode(['status' => false]);
         $this->ajaxRender($json);

         //return new JsonResponse($json, Response::HTTP_BAD_REQUEST);// doesn't send proper code
    }

Can anyone tell me how to send error code from module front controller which extends ModuleFrontController?? Now only possible to me action is send error message with http code 200 (but I think it's bad idea to send error with that code). Thanks a lot for any help.

A: The proper way to send and receive data using AJAX is displayed below.
More information can be found at Prestashop Docs
Ajax post
    $.ajax({
        type: 'POST',
        dataType : 'json',
        url: 'linktoyourfile.php',
        data: { action: 'getMyrequest' },
        success: function(data) {
            alert(data.result);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Error: ' + textStatus + ' ' + errorThrown);
        }
    });

Module Front Controler
    class TestModuleFrontController extends ModuleFrontController
    {
        public function init()
        {
            parent::init();
        }

        public function displayAjaxGetMyrequest()
        {
            // ERROR HANDELING
            if ($this->errors) {
                die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
            } else {
                echo Tools::json_encode(array('result' => 'test result'));
            }
        }
    }


text:
Q: Is there an include_partial equivalent in Twig (symfony 2.0)? I really like to use partial templates in my symfony 1.4 projets and I was wondering if there is something like that with Twig in symfony 2.0.
It's way more clear and reusable to have something like that
<?php include_partial('forum/message', array('message'=>$message)); ?>

Rathen than a big portion of php/html code.

A: Yes. It's called include in Twig. Details are in the docs.


text:
Q: The Passive Auxillary

*

*The company is being taxed

*The company has been taxed

*The company has been being taxed

These are three examples listed in a book on syntax.
In the first one, the book suggests that "is" is the progressive auxiliary and "being" is the passive auxiliary.
In the second one, the book suggests that "has" is perfective and "been" is passive.
In the third example, the book suggests that "has" is the perfective, "been" is the progressive and "being" is the passive.
Firstly, I was wondering how does one define what the passive auxiliary actually is? I understand how one forms the passive tense, but I'm unsure what a passive auxiliary actually is.
Secondly, It seems odd to me that in the third example, "been" is noted as the progressive auxiliary, whereas in the second example the word "been" is defined as being the passive auxiliary.
If anyone could clear these issues up for me I would be extremely grateful.
Thank you.

A:
Firstly, I was wondering how does one define what the passive auxiliary actually is

It's always going to be {form of be} + {past participle}.
The form of be can be is, being, or been.  If a past participle follows, it's part of a passive voice expression.

I understand how one forms the passive tense

Passive voice is not a tense.  You can have past (the ball was thrown), present (the ball is thrown), future passive voice (the ball will be thrown).

but I'm unsure what a passive auxiliary actually is.

A passive auxillary will be the first word in the phrase {form of be} + {past participle}.
A progressive auxillary will be the first word in the phrase {form of be} + {present participle}.

The company has been being taxed

Be can be expressed passively or progressively/continuously like any other verb.  So you might have two forms of be next to each other but it's the first one that determines passive or progressive.
And it's possible for passive or progressive be to be perfect as well.

I am being taken for a fool.
I had been being taken for a fool until I had found out his master plan.

Being been is invalid.


text:
Q: Speeding up jQuery empty() or replaceWith() Functions When Dealing with Large DOM Elements Let me start off by apologizing for not giving a code snippet. The project I'm working on is proprietary and I'm afraid I can't show exactly what I'm working on. However, I'll do my best to be descriptive.
Here's a breakdown of what goes on in my application:

*

*User clicks a button

*Server retrieves a list of images in the form of a data-table

*Each row in the table contains 8 data-cells that in turn each contain one hyperlink

*

*Each request by the user can contain up to 50 rows (I can change this number if need be)

*That means the table contains upwards of 800 individual DOM elements

*My analysis shows that jQuery("#dataTable").empty() and jQuery("#dataTable).replaceWith(tableCloneObject) take up 97% of my overall processing time and take on average 4 - 6 seconds to complete.

I'm looking for a way to speed up either of the above mentioned jQuery functions when dealing with massive DOM elements that need to be removed / replaced. I hope my explanation helps.

A: jQuery empty() is taking a long time on your table because it does a truly monumental amount of work with the contents of the emptied element in the interest of preventing memory leaks.  If you can live with that risk, you can skip the logic involved and just do the part that gets rid of the table contents like so:
    while ( table.firstChild )
        table.removeChild( table.firstChild );

or
    table.children().remove();

A: I recently had very large data-tables that would eat up 15 seconds to a minute of processing when making changes due to all the DOM manipulation being performed.  I got it down to <1 second in all browsers but IE (it takes 5-10 seconds in IE8).
The largest speed gain I found was to remove the parent element I was working with from the DOM, performing my changes to it, then reinserting it back into the DOM (in my case the tbody).
Here you can see the two relevant lines of code which gave me huge performance increases (using Mootools, but can be ported to jQuery).
update_table : function(rows) {
    var self = this;
    this.body = this.body.dispose();  //<------REMOVED HERE
    rows.each(function(row) {
        var active = row.retrieve('active');
        self.options.data_classes.each(function(hide, name) {
            if (row.retrieve(name) == true && hide == true) {
                active = false;
            }
        });
        row.setStyle('display', (active ? '' : 'none'));
        row.store('active', active);
        row.inject(self.body);   //<--------CHANGES TO TBODY DONE HERE
    })
    this.body.inject(this.table);  //<-----RE-INSERTED HERE
    this.rows = rows;
    this.zebra();
    this.cells = this._update_cells();
    this.fireEvent('update');
},

A: Do you have to repopulate all at once, or can you do it by chunks on a setTimeout()? I realize it'll probably take even longer in chunks, but it's worth a lot for the user to see something happening rather than an apparent lockup.

A: What worked for me is $("#myTable").detach(). I had to clear a table that has 1000s of rows. I tried $("#myTable").children().remove(). It was an improvement over $("myTable").empty(), but still very slow. $("#myTable").detach() takes 1 second or less.
Works fine in FF and Chrome. IE is still slow.


text:
Q: How to query interval without including the current date? I have this query:
SELECT *
FROM table
WHERE status != 'done'
AND added >= (NOW() - interval '30 days') order by added desc;

However, it includes the current date. How do I query without including results from the current date?

A:
How do I query without including results from the current date?

Just exclude the current date by applying a < condition:
SELECT *
FROM table
WHERE status <> 'done'
  AND added >= (NOW() - interval '30 days')
  AND added < current_date
order by added desc;


text:
Q: Join 2 DataTables into 1 in C# I have two identical DataTables from two different databases (but the ids are unique!).  So now I want to have combine this data into a single DataTable. I have no idea what to do.
I tried the following:
DataTable one = new DataTable();
one = baza_win.pobierz_dane("SELECT...");
DataTable two = new DataTable();
two = baza_win2.pobierz_dane("SELECT...");
//DataTable sum = one + two;
DataTable sum = new DataTable();
sum.Clone(one);
sum.Merge(two,false);

But this doesn't work at sum.Clone(one);
Any ideas?

A: sum = one.Copy();
sum.Merge(two);

A: I think you need Copy instead of Clone:
DataTable one = new DataTable();
one = baza_win.pobierz_dane("SELECT...");
DataTable two = new DataTable();
two = baza_win2.pobierz_dane("SELECT...");
//DataTable sum = one + two;
DataTable sum = new DataTable();
sum.Copy(one);
sum.Merge(two,false);

A: copied from link
http://msdn.microsoft.com/en-us/library/fk68ew7b.aspx
duplicate of
how to join two datatable datas into one datatable to show in one gridview in asp.net
private static void DemonstrateMergeTable()
    {
        DataTable table1 = new DataTable("Items");
    // Add columns
    DataColumn column1 = new DataColumn("id", typeof(System.Int32));
    DataColumn column2 = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(column1);
    table1.Columns.Add(column2);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { column1 };

    // Add RowChanged event handler for the table.
    table1.RowChanged +=
        new System.Data.DataRowChangeEventHandler(Row_Changed);

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

    // Accept changes.
    table1.AcceptChanges();
    PrintValues(table1, "Original values");

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2);
    PrintValues(table1, "Merged With table1");

}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}

A: try the following... CLONE the first table so it has proper structure, THEN merge two into it.
DataTable sum = one.Clone()
sum.Merge(two,false);


text:
Q: View does not update when selection changes, after moving it to separate XIB file My OS X application has an AppDelegate with:
- a managed object context and
- an NSArrayController (from MainMenu.xib)
a MainMenu.xib with:
- an NSArrayController,
- a TableView to display all the objects and
- a bunch of TextFields to display the details of the selected object.
Everything is connected via Bindings and works perfectly well.
I want to add a separate window with a TextView for one of the details (notes).
As long as I add the separate window with the TextView to the MainMenu.xib and connect everything via Bindings, there is no problem, of course.
But I want to make a separate NSWindowController and XIB,
- NotesPanelController and
- NotesPanel.xib.
I added an NSArrayController property (arrayController) to the NotesPanelController and then initialized it with the arrayController from the AppDelegate. Now I bind my TextView in NotesPanel.xib to File's Owner with the following model key path: self.arrayController.selection.notes.
The TextView does no longer update, when the TableView (and by this the ArrayController) selection changes in the main window, though. What is wrong with my setup?
UPDATE:
I found out, the problem is not, that the selection is not observed, but changes to the text view in my notes panel don't get committed. Everything works as it should, when i enable continously update value in the NSTextView's value binding. But would this be an acceptable solution?


text:
Q: PHP - SQL query Syntax Error I'm having a hard time finding the error that exists in my script. Can anyone help me spot it?
        case "process_movie_order":
        // handle POST
        if ($_POST) {
            //Drop "order" column and Re-ADD it to reset ID #'s
            $droppedresult = mysql_query("ALTER TABLE videos DROP COLUMN order");
            $addedresult = mysql_query("ALTER TABLE videos ADD order int NOT NULL");
            $totalMovies = count($_POST['movie']);
            // use $i to increment the order number
            $i=$totalMovies;
            // loop through post array in the order it was submitted
            foreach ($_POST['movie'] as $video_id) {
                // update the row
                $query = sprintf("UPDATE videos SET order='%s' WHERE video_id='%s'",
                    mysql_real_escape_string($i),
                    mysql_real_escape_string($video_id));

                $result = mysql_query($query);

                 if(!$result) {
                     echo mysql_error();
                    echo 'MySQL query failed. Please report this error to the author of this script.

                        Back
';
                    break;
                }
                // decrease order number to make the next movie lower
                $i--;
            }
        }

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order='55' WHERE video_id='video55'' at line 1
Thanks!

A: order is a reserved keyword in MySQL.  You must specify the column name instead.  Put backticks around "order".


text:
Q: Generating URL for Yahoo and Bing Scraping for multiple pages with Python and BeautifulSoup I want to scrape news from different sources. I found a way to generate URL for scraping multiple pages from google, but I think that there is a way to generate much shorter link.
Can you please tell me how to generate the URL for scraping multiple pages for Bing and Yahoo news, and also, is there a way to make google url shorter.
This is the code for google:
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=0

for page in range(1,5):

    page = page*10

    url = 'https://www.google.com/search?q={}&tbm=nws&sxsrf=ACYBGNTx2Ew_5d5HsCvjwDoo5SC4U6JBVg:1574261023484&ei=H1HVXf-fHfiU1fAP65K6uAU&start={}&sa=N&ved=0ahUKEwi_q9qog_nlAhV4ShUIHWuJDlcQ8tMDCF8&biw=1280&bih=561&dpr=1.5'.format(term,page)
    print(url)

    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

These are the URL-s for yahoo and bing, but for 1 page:
yahoo: url = 'https://news.search.yahoo.com/search?q={}'.format(term)
bing: url = 'https://www.bing.com/news/search?q={}'.format(term)

A: I am not sure are you looking after this shorten url for news.
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=0

for page in range(1,5):

    page = page*10

    url = 'https://www.google.com/search?q={}&tbm=nws&start={}'.format(term,page)
    print(url)

    response = requests.get(url, headers=headers,verify=False)
    soup = BeautifulSoup(response.text, 'html.parser')

#Yahoo:
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=1
while True:

    url ='https://news.search.yahoo.com/search?q={}&pz=10&b={}'.format(term,page)
    print(url)
    page = page + 10
    response = requests.get(url, headers=headers,verify=False)
    if response.status_code !=200:
        break
    soup = BeautifulSoup(response.text, 'html.parser')


text:
Q: How to identify about month change in input[type=date] I am using the input field type=date in react component as shown below.
<input
  id="date_export"
  className="date-calender"
  type="date"
  disabled={!this.state.disableCalendar}
  onChange={(event) => this.setState({date: event.target.value})}}
  required={true}
  value={this.state.date} />

Now, when the user clicks on the input field, the calendar pops up and there is an up and down arrow to change the month.

How to identify from the event which arrow gets clicked?

A: Unfortunately, It's VERY hard to have a stable code for your answer, but here is an example:

class DateForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      dateInput: new Date().toISOString().split('T')[0]
    }
  }

  handleChange(e) {
    const { dateInput } = this.state;
    const { value } = e.target;
    this.setState({ dateInput:value });
    const monthInput = new Date(value).getMonth();
    const monthState = new Date(dateInput).getMonth();
    const dateOnInput = new Date(value).getDate();
    const dateState = new Date(dateInput).getDate();
    if(dateOnInput === dateState) {
      if(Math.sign(monthInput - monthState == -1)) {
        console.log('Up arrow');
      } else {
        console.log('Down arrow');
      }
    }
  }

  render() {
    const { dateInput } = this.state;

    return (
      <form>
        <input type="date" value={dateInput} onChange={this.handleChange} />
      </form>
    )
  }
}

ReactDOM.render(<DateForm />, document.getElementById('root'))


text:
Q: vizualisation of package dependencies According to the solution of Heiko
(How to design a command inquiring internally required packages?)
I would like to have one additional file to be written...
It should have the form
Headerlines  > ptree.tex
child -> parent > ptree.tex
Footerlines > ptree.tex
line by line in an tex file
As an example...
The written file should have the form
\begin{dot2tex}
strict digraph G { nodesep=0.01
graph [ overlap = false, fontsize = 10 ];
edge[weight=1.2];
"amstext [2000/06/29 v2.01]" -> "amsmath [2013/01/14 v2.14 AMS math features]";
"amsgen [1999/11/30 v2.0]" -> "amsmath [2013/01/14 v2.14 AMS math features]";
"..." -> "...";
\end{dot2tex}

As a result of this text file it can be displayed via graphViz.... (maybe I have to make an graphviz newline between package and version, so the nodes wont be as width as without newline.
But I am not aware about the newline graphviz code (node).
Is there any way to produce this code additional to the which is written to logfile?
desired output: additional texfile as described above.
Compiling will generate the tex-file.
Compiling a new file will display the graph...


text:
Q: Platform Events and Transaction I want to trigger an Event from Apex Trigger, but since Platform event cannot be rollbacked, is there a way to publish it only when the transaction is successfull?

A: Based on some sleuthing by @danielballinger I believe that becomes an option in Summer 19 (#safeharbor and all that)
PreRelease Orgs are now available if you want to check it out for yourself, or you can wait for Sandbox upgrades to start


text:
Q: Cannot login with requests post import requests

session = requests.Session()

data = "memberNo=&url=&cyberId={}&cyberPass={}"
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7",
    "Cache-Control": "max-age=0",
    "Connection": "keep-alive",
    "Content-Length": "57",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "www.sonofelicecc.com",
    "Origin": "https://www.sonofelicecc.com",
    "Referer": "https://www.sonofelicecc.com/login.dp/dmparse.dm",
    "sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "Windows",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36",
}

main_headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7",
    "Cache-Control": "max-age=0",
    "Connection": "keep-alive",
    "Host": "www.sonofelicecc.com",
    "Referer": "https://www.sonofelicecc.com/login.dp/dmparse.dm",
    "sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "Windows",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36",
}

login_req = session.post("https://www.sonofelicecc.com/doLogin.dp/dmparse.dm", headers=headers, data=data)
main_resp = session.get("https://www.sonofelicecc.com/main.dp/dmparse.dm", headers=main_headers)

if main_resp.text.find(username) != -1:
    print("login success")

I am trying to login with requests without selenium. I've first tried login with selenium; however it was too slow; thus, I saved the selenium's cookie and return it to requests for faster work.
Then, I want to make all working with only requests. I've loaded all the headers correctly, but it doesn't work at all. How can I?


text:
Q: Jquery on select file , submit form I have this html code
    <form method="post" id="upload_video" enctype="multipart/form-data" action="/Home/Save">

                    <input type="text" name="name" id="name" value="" style="color: rgb(0, 0, 0);">

                    <input type="text" name="email" id="email" value="" style="color: rgb(0, 0, 0);">

                    <input type="text" name="mobile" id="mobile" value="Κινητό" style="color: rgb(0, 0, 0);">

                    <input type="checkbox" id="checkbox">

            <input type="file" name="file" id="upload_file" style="position:absolute;top:-100px;">
    </form>

and i want by clicking the #upload div then to automaticallu=y select file, and when i do it then submit my form. So i have this script
            $('#upload').click(function () {
                    $('#upload_file').click();
            });

            $("#upload_file").change(function () {
                $('#upload_video').submit();
            });

The $('#upload_file').click() event works great in all browsers but the $('#upload_file').change() works only in FF and Chrome but not in IE.
So my form is submitted only in FF and Chrome..
Any ideas?

A: From this post: jQuery change method on input type="file"
it looks like you may have to do this:
$("#upload_file").live( 'change', function () {
                $('#upload_video').submit();
            });

A: Just found that this is not possible in IE due to security reasons

A: I'm not sure why Kory Hodgson's answer is marked as the answer since this will not work in chrome or newer versions of IE. This is a security risk since files could be upload without the user's consent.
For those trying to do this, you have a large number of options. There are some very inexpensive options for uploading multiple files (uploadify or plupload are two I have used.)  If you only need to upload one file, then you could use an iframe to upload the image (google upload file using iframe, there are tons of examples.)  In the iframe, you will want to call a javascript function on the "onload" event.  After the image is uploaded, you can return some json to the iframe window that provides the status of the upload (success/fail.)  Depending on what you are trying to accomplish, you could either pass your data back through the json or you could pass the redirect page url in the json.


text:
Q: File couldn't be opened because you don't have permission I keep getting the error:
The file "Blah" couldn't be opened because you do not have permission to view it.

I tried the top 5 answers in this question -
"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4
But they do not work.
Note: I deleted the debug and release from the Test  in the Build Settings and cleared the derived data multiple times.

info.plist

A: Go to Build Settings -> Build Options. Then change the value of the "Compiler for C/C++/Objective-C" to Default Compiler.

A: I've just found another potential cause for this error
Xcode will say "you do not have permission" if the  .app file does not contain a valid binary (you can inspect the .app file by right-clicking on it and selected Show Package Contents -- you're looking for something with an icon of a terminal with the green letters "exec")
The binary may be missing for a number of reasons (failed compilation, failed linking, etc) - but you can usually find a hint by clicking on the "warnings" tab above the file list in Xcode. In my case I was referencing a third-party library but needed to add it to the "Link Binary with Libraries" build phase

A: I faced the same problem today, in my case the application name was containing space like (X Y), In info.plist Xcode converts the name to (X-Y) in the Executable file property, so I changed the application name to be like (XY) without space and the problem disappeared !
hope this will help anybody :)

A: It appears you are getting this error while running your XCTest target.
I've seen cases where the test target has no permission for files belonging to the app target.
This worked for me:

*

*use XCode 7 (makes @testable import easier)

*do NOT compile your app classes into your test target

*instead DO import your app target into your XCTest class

Now you write the code that accesses the file in your app code that is compiled into your app target.
From your XCTest class you call the method in the app target that has the permission to access app files.

A: Please make sure that you have this. If not you can edit that.
1.$(BUILT_PRODUCTS_DIR)/yourappname.app/yourappname
2.In info.plist make sure that Executable file value is this only "$(EXECUTABLE_NAME)"
3.You may be need to give permission to your folder as read & write. For this you need to follow these steps:
a. Right click
b.get info
c. unlock it and give your password
d. then give read & write permission to yourself.
Hope this will help you out. I had the same issue and i solved it by following these steps.


text:
Q: Post URL in php script to move webcam when I call .../axis-cgi/com/ptz.cgi?gotoserverpresetname=Eis_links1&camera=1 the attached webcam is moving to the preset position (i can change the value of gotoserverpresetname and it moves)...
How can I call this script from a php script?
I tried with the code below, but nothing happens..
Best regards
Adriana
    $myvar1="Eis_mitte";
    $myvar2="1";

    $url = '...my url....';
    $myvars = 'gotoserverpresetname='.$myvar1 . '&camera='.$myvar2;

    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_POST, 1);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt( $ch, CURLOPT_HEADER, 0);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec( $ch );

A: You need a GET REQUEST:
$myvar1="Eis_mitte";
$myvar2="1";

$url = '...my url....';
$myvars = '?gotoserverpresetname='.$myvar1 . '&camera='.$myvar2;

$ch = curl_init( $url.$myvars );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

NOTE: Added '?' to myvars and removed CURLOPT_POSTFIELDS


text:
Q: Expressions and for loops in C Is this correct way of assigning an expression to a variable?
int a == ( i<3 );

And I want to use a for loop like this
for(i=0;a; i++)

A: The assignment operator is =. So the correct way to assign an expression to a variable is
int a = i < 3;

More accurately, this assigns the value of the expression to a variable. It does not assign the expression itself to the variable. This means that the expression is evaluated immediately. When you do
for(i=0;a; i++)

The value of a will never change even though i does.
The idiomatic way of writing for loops is to write the boolean expression inline:
for(i=0;i<3; i++)

If you have some more complicated calculation to determine when a loop should end, then you can write a function for the calculation. For example:
int condition(int i) {
    return i < 3;
}

Now you can write the for loop as
for (i = 0; condition(i); i++)

A: You can use macros like following
#include <stdio.h>
#define a(i) i < 3
int main(void) {
    for(int i =0; a(i); i++) {
        printf("%d\n",i);
    }
    return 0;
}
Output
0
1
2

EDIT
As others said macro is not a good idea when the condition is large. In that case you can make a separate function for the complex logic and use that in your for loop condition part. Like following:
int a(i) {
  return i < 3; // Your condition. It may be even more complex as per your requirement.
}

Then you can use that function in your for loop in the following way:
for(int i =0; a(i); i++ ){...}

A: You cannot do that, why would you even want to? Can you give me an example, where this would be useful? Just curious, maybe we find better solution :)
Also, you can read more about loops at http://en.cppreference.com/w/cpp/language/for


text:
Q: Java android EventBus No subscribers registered for event class In activity I do this:
onCreate():
EventBus.getDefault().register(this);

and I override this:
@Override
protected void onStart() {
  super.onStart();
  EventBus.getDefault().register(this);
}

@Override
protected void onStop() {
  EventBus.getDefault().unregister(this);
  super.onStop();
}

And in my service I did this:
Global.getInstance().getGeoLocation().setBestLocation(loc);
EventBus.getDefault().post(new EventLocation(loc));

And in logsd I see this:
10-27 09:15:04.367 5097-5097/komunal W/EventBus: Subscriber to unregister was not registered before: class komunal.activities.PGOListActivity
10-27 09:15:04.458 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:04.458 5097-5097/komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
10-27 09:15:05.425 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:05.425 5097-5097 komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
10-27 09:15:06.458 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:06.459 5097-5097/komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
10-27 09:15:07.435 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:07.436 5097-5097/komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

A: First, you need to only register the subscriber once. So, if you've already registered in onCreate don't register it again in onStart().
Second, whenever your activity is no longer visible, you're activity will be unsubscribed from the event. This is because you have the following:
@Override
protected void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

Instead, you need to move the unregistering to the onDestroy():
@Override
protected void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();
}

Last, you need to subscribe to the Event in your activity with something like this:
// process the event in the Main thread.
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(EventLocation event) {
  // do something with the event.
}


text:
Q: Participle of "center/centre" in UK English — "centring"? Seriously? As an American, I was  never shocked to see the word "center" spelled as "centre." It didn't bother me at all. Honestly.
But then I saw the participle of it spelled as "centring" as opposed to "centering," and it really made me reconsider the whole thing. Do UK (and Australian, New Zealand, etc.) speakers pronounce it similarly to US speakers (three syllables)? Do you guys ever spell it "centering?" Do you find the US spelling as weird as we find the UK spelling? Does it make you uncomfortable in a way you can't fully understand?
Also, I see that my Chrome spell check is equally thrown off by the UK spelling. Is your browser's spell check disgusted by the US spelling?

A: British English doesn't use the spelling centering; it's always centring.
As to pronunciation, it's two syllables, or maybe two-and-a-half with the hint of a schwa, /ˈsɛntriŋ/ /ˈsɛntᵊriŋ/.
Spelling the word with a third syllable looks odd because we don't spell it that way and we don't say it that way either. Spelling and pronunciation are linked, but it's a bit chicken-and-egg. As the "British" spelling comes from French and the American comes from Webster, it's highly likely that the pronunciation of centring/centering follows from the spelling.
My British-dictionary browser objects to centering.

A: I agree that 'centring' sounds weird! I say it as though it's spelled 'centering' and I found myself on this site checking the word as I didn't think it was right. Sometimes the English version is not as good as the American one. And I'm English! I refuse to use 'centring' so am forced to use 'centred on' instead. How annoying.. ;)


text:
Q: JavaScript function not working in Firefox and Safari (just in Chrome) I have a page with already other JavaScripts correctly working... apart from this one:
<script>
function add(numDaysToAdd) {
    var data_in = new Date (document.WADAInsertForm.data_in.value);
    var data_out = data_in.setDate(data_in.getDate()+numDaysToAdd);
    var final_day = data_out.getDate();
    var final_month = data_out.getMonth() + 1;
    var final_year = data_out.getFullYear();

    document.WADAInsertForm.data_out.value = final_year+'-'+final_month+'-'+final_day;

    }
</script>

This script is triggered by an OnChange call on a checkbox together with a OnClick event. To clarify:
<input type="checkbox" name="product" value="Insurance plan: 1 month" id="product" onClick="this.form.price.value='41.40'" onChange="add(+30)">

When I test the page in Chrome it does all the homeworks: insert the price value in the "price" field and update the "data_out" field with the proper value.
When I do the same in Firefox and Safari... it works only the "price" setting.
Any suggestions or help?

A: onChange="add(+30)"

Here +30 doesn't represent any String or any Integer in your script it would through a type error, to add days to the current date you could use this script
<script type="text/javascript" language="javascript">
    function AddDays(toAdd) {
        if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
        var d = new Date();
        d.setDate(d.getDate() + parseInt(toAdd));

        document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
    }
</script>
---------------------- UI ---------------
    <div id="result">
    </div>
    <input type="text" value="0" onkeyup="AddDays(this.value);" />

A: onClick isn't valid. Use onclick.
And I find it strange to have both onclick and onchange on a checkbox. You should include your onclick in the onchange.


text:
Q: PHP, Can't access base class via child properly Base Class:
class A {

    public x;
    public y;

    public function __construct {

        $this->x = new X();
        $this->y = new Y();
    }
}

Class X:
class X extends A {

    public function __construct {}

    public function job() {

        echo 'x working!';
    }
}

Class Y:
class Y extends A {

    public function __construct {}

    public function job() {

        var_dump($this->x);    // NULL, Why???

        $this->x->job();
    }
}

Problem: When I'm calling x->job() from inside of class Y, I have no access to the X already instanced object totally, and var_dump shows it's null.
Any ideas what's wrong with that?
Thanks! :)
Update:
If I use parent::__construct(); in the child class' __construct() method, then it would generates Fatal Error: maximum function nesting level of '100' reached, aborting!. That's why I add those empty __construct() methods. Any idea again how to solve that?
I have this one also on the source code:
$base = new A();

So, the constructor should been run already, right?

A: You must call parent::__construct() in the chil class constructor, otherwise the parent constructor is not called and the property won't recieve its value.

A: In this example case you could also just leave out the constructor of the child class, because it doesn't do anything, else use the suggested method by GolezTrol


text:
Q: At a time only one expander expand on xamarin form On my page there is a 4 expander ,I want to write a code for at a time one expander is expand ,What can I do for this scenario please help me ,For more clarifications I have a add image of expanders ,In this given code there is a one expander show ,but this type of a 4 expander available on my page and i want to expand one at a time
enter image description here
<StackLayout IsVisible="{Binding Synonyms,Converter={x:StaticResource CorrectionTypeVisiableConverter}}" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
                                                <xct:Expander ExpandAnimationEasing="CubicIn"
                                                         ExpandAnimationLength="500"
                                                          CollapseAnimationEasing="CubicOut"
                                                          CollapseAnimationLength="500">
                                                    <xct:Expander.Header>
                                                        <Frame  HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BorderColor="#F0F0F0" HasShadow="False" >
                                                            <StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                                                                <xct:BadgeView Text="{Binding Synonyms,Converter={StaticResource CorrectionCountBadgeConverter}}"  BackgroundColor="#FADBD8" BadgePosition="TopLeft"   TextColor="#E74C3C" HorizontalOptions="Start" FontSize="16"  AutoHide="True"                                                                               VerticalOptions="CenterAndExpand">

                                                                </xct:BadgeView>

                                                                <Image Source="Expand.png"
                                                                         HorizontalOptions="EndAndExpand"
                                                                         VerticalOptions="CenterAndExpand">
                                                                    <Image.Triggers>
                                                                        <DataTrigger TargetType="Image"
                                                                                Binding="{Binding Source={RelativeSource AncestorType={x:Type xct:Expander}},                                                                              Path=IsExpanded,Mode=OneTime}"
                                                                                Value="True">
                                                                            <Setter Property="Source"
                                                                                Value="collapse.png" />
                                                                        </DataTrigger>
                                                                    </Image.Triggers>
                                                                </Image>
                                                            </StackLayout>
                                                        </Frame>
                                                    </xct:Expander.Header>
                                                    <xct:Expander.ContentTemplate>
                                                        <DataTemplate>
                                                            <StackLayout BindableLayout.ItemsSource="{Binding Synonyms}" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
                                                                <BindableLayout.ItemTemplate>
                                                                    <DataTemplate>
                                                                        <Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BorderColor="#F0F0F0" HasShadow="False" >
                                                                            <Grid >
                                                                                <Grid.RowDefinitions>
                                                                                <RowDefinition Height="Auto" />
                                                                                <RowDefinition Height="Auto" />
                                                                                <RowDefinition Height="Auto" />
                                                                                <RowDefinition Height="Auto" />
                                                                                </Grid.RowDefinitions>
                                                                                <StackLayout Grid.Row="0" Orientation="Horizontal">

                                                                                " HorizontalOptions="Start" VerticalOptions="Center">
                                                                                <Grid>
                                                                                <Grid.ColumnDefinitions>
                                                                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                                                                </Grid.ColumnDefinitions>
                                                                                <xct:BadgeView Grid.Column="0" Text=""  BackgroundColor="#FADBD8" BadgePosition="TopRight" TextColor="#E74C3C" FontSize="14"                                                                                HorizontalOptions="CenterAndExpand" AutoHide="True"                                                                                VerticalOptions="Center" Background="#FADBD8" WidthRequest="80" HeightRequest="25">

                                                                                </xct:BadgeView>
                                                                                <ImageButton Grid.Column="0" Source="Storyedit.png"
                                                                                HorizontalOptions="EndAndExpand" VerticalOptions="Center"   WidthRequest="12" HeightRequest="12"/>
                                                                                </Grid>
                                                                                <ImageButton Source="Info.png" Command="{Binding  Path=BindingContext.CorrectionInfoCommand,Source={x:Reference Name=storyView}}"
                                                                                CommandParameter="{Binding .}"  HorizontalOptions="EndAndExpand"/>
                                                                                </StackLayout>
                                                                                <Button Grid.Row="1" Text="{x:Static resources:AppResources.IgnoreButton}"                                                                                Style="{StaticResource CancelButton}" VerticalOptions="EndAndExpand"                                                                                HorizontalOptions="CenterAndExpand" ></Button>
                                                                                <Button Grid.Row="1" Text="{x:Static resources:AppResources.AcceptButton}"                                                                                Style="{StaticResource AcceptButton}" VerticalOptions="EndAndExpand"                                                                                HorizontalOptions="StartAndExpand" ></Button>

                                                                                <FlexLayout  IsVisible="False" Grid.Row="3" HorizontalOptions="FillAndExpand"                                                                                VerticalOptions="FillAndExpand" AlignItems="Start" AlignContent="Center"                                                                                Direction="Row" Wrap="Wrap" JustifyContent="Center">
                                                                                <Button Text="{x:Static resources:AppResources.IgnoreButton}" Padding="5"                                                                                Style="{StaticResource CancelButton}" HorizontalOptions="StartAndExpand"></Button>
                                                                                <Button Text="{x:Static resources:AppResources.IgnoreAllButton}" Style="{StaticResource                                                                        CancelButton}" HorizontalOptions="CenterAndExpand" Padding="5"></Button>
                                                                                <Button Text="{x:Static resources:AppResources.AcceptButton}" Style="{StaticResource                                                                        AcceptButton}" HorizontalOptions="StartAndExpand" Padding="5"></Button>
                                                                                <Button Text="{x:Static resources:AppResources.AcceptAllButton}" Style="{StaticResource                                                                      AcceptButton}" HorizontalOptions="CenterAndExpand" Padding="5"></Button>
                                                                                </FlexLayout>
                                                                            </Grid>
                                                                        </Frame>
                                                                    </DataTemplate>
                                                                </BindableLayout.ItemTemplate>
                                                            </StackLayout>
                                                        </DataTemplate>
                                                    </xct:Expander.ContentTemplate>
                                                </xct:Expander>
                                            </StackLayout>

A: You could binding true or false for the IsExpanded property to indicate that the Expander is expanded or collapsed.
I make a simple example for your reference.
Model:
  public class Model : INotifyPropertyChanged
{
    #region fields
    public string _synonyms;
    public string _s;
    public bool _isexpand;
    #endregion
    public string Synonyms
    {
        get { return _synonyms; }
        set { _synonyms = value; OnPropertyChanged("Synonyms"); }
    }
    public string s
    {
        get { return _s; }
        set { _s = value; OnPropertyChanged("s"); }
    }
    public bool ISexpand
    {
        get { return _isexpand; }
        set { _isexpand = value; OnPropertyChanged("ISexpand"); }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}

ViewModel:
 public class ViewModel1
{
    public ObservableCollection<Model> models { get; set; }
    public ViewModel1()
    {
        CreateCollection();
    }
    public void CreateCollection()
    {
        models = new ObservableCollection<Model>()
        {
            new Model(){ Synonyms="Synonym1", s="A", ISexpand=false},
            new Model(){ Synonyms="Synonym2", s="B",ISexpand=false},
            new Model(){ Synonyms="Synonym3", s="C",ISexpand=false},
            new Model(){ Synonyms="Synonym4", s="D",ISexpand=false},
            new Model(){ Synonyms="Synonym5", s="E",ISexpand=false},
        };
    }

}

Xaml:
 <ContentPage.BindingContext>
    <local:ViewModel1></local:ViewModel1>
</ContentPage.BindingContext>
<ContentPage.Content>
    <StackLayout x:Name="stacklayout"  BindableLayout.ItemsSource="{Binding models}" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
        <BindableLayout.ItemTemplate>
            <DataTemplate>
                <xct:Expander IsExpanded="{Binding ISexpand}"  Tapped="Expander_Tapped" >
                    <xct:Expander.Header>

                    </xct:Expander.Header>
                    <xct:Expander.ContentTemplate>
                        <DataTemplate>

                        </DataTemplate>
                    </xct:Expander.ContentTemplate>
                </xct:Expander>
            </DataTemplate>
        </BindableLayout.ItemTemplate>
    </StackLayout>
</ContentPage.Content>

Code behind:
 public partial class Page10 : ContentPage
{
    ViewModel1 viewModel1=new ViewModel1();
    public Page10()
    {
        InitializeComponent();

    }
    int i = 0;
    private void Expander_Tapped(object sender, EventArgs e)
    {
        var expander = sender as Expander;
        var label = expander.Header as Label;
        var list = viewModel1.models;
        foreach (var item in viewModel1.models)
        {
            if (item.Synonyms == label.Text)
            {
                item.ISexpand = true;

                if (i >= 1)
                {
                    foreach (var item1 in viewModel1.models.ToList())
                    {
                        if (item1.Synonyms!= label.Text)
                        {
                            item1.ISexpand = false;

                        }
                    }
                    BindableLayout.SetItemsSource(stacklayout, viewModel1.models);
                }
            }
        }
        i++;
    }
}

OutPut:
https://imgur.com/4D6x1yB


text:
Q: Where can I get an array of all native node modules? I am looking for a way to get a list of all available node modules. It would be interesting to get this dynamically, because different versions or future versions may add or deprecate modules.

A: If you are using Node version > 8.11.3, the recommended way to achieve that is to use the builtinModules property of the module object, as follows:
const builtins = require('module').builtinModules;

Further details: https://nodejs.org/api/modules.html#modules_module_builtinmodules

A: You can use this code to get the list of all globally installed modules:
function exec(callback) {
  require('child_process').exec('npm ls -g --depth=0 --json', function(err, data, stderr) {
    if (err) return cb(err)
    callback(data);
  });
}

function get_modules(callback) {
    var res = [];
    exec(function(d) {
        d = JSON.parse(d);
        var m = d.dependencies;
        for(key in m) res.push(key);
        callback(res);
    });
}

get_modules(console.log);

If you want built-in modules , use
console.log(require("module").builtinModules)

Refer this doc.

A: Programmatically get the list (only works on node 8 and above)
console.log(require("module").builtinModules)

Latest List:
const builtins = [
  '_http_agent',       '_http_client',        '_http_common',
  '_http_incoming',    '_http_outgoing',      '_http_server',
  '_stream_duplex',    '_stream_passthrough', '_stream_readable',
  '_stream_transform', '_stream_wrap',        '_stream_writable',
  '_tls_common',       '_tls_wrap',           'assert',
  'async_hooks',       'buffer',              'child_process',
  'cluster',           'console',             'constants',
  'crypto',            'dgram',               'dns',
  'domain',            'events',              'fs',
  'fs/promises',       'http',                'http2',
  'https',             'inspector',           'module',
  'net',               'os',                  'path',
  'perf_hooks',        'process',             'punycode',
  'querystring',       'readline',            'repl',
  'stream',            'string_decoder',      'sys',
  'timers',            'tls',                 'trace_events',
  'tty',               'url',                 'util',
  'v8',                'vm',                  'worker_threads',
  'zlib'
]

Here's an older list:
const builtins = [
  'assert',         'buffer',   'child_process',
  'cluster',        'console',  'constants',
  'crypto',         'dgram',    'dns',
  'domain',         'events',   'fs',
  'http',           'https',    'module',
  'net',            'os',       'path',
  'process',        'punycode', 'querystring',
  'readline',       'repl',     'stream',
  'string_decoder', 'sys',      'timers',
  'tls',            'tty',      'url',
  'util',           'vm',       'zlib'
];

Here's a function that attempts to work across all versions of node:
export const builtins = () => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const result = require('module');
    // eslint-disable-next-line node/no-unsupported-features/node-builtins
    return result.builtinModules;
  } catch (e) {
    // prettier-ignore
    return [
      'assert',         'buffer',   'child_process',
      'cluster',        'console',  'constants',
      'crypto',         'dgram',    'dns',
      'domain',         'events',   'fs',
      'http',           'https',    'module',
      'net',            'os',       'path',
      'process',        'punycode', 'querystring',
      'readline',       'repl',     'stream',
      'string_decoder', 'sys',      'timers',
      'tls',            'tty',      'url',
      'util',           'vm',       'zlib'
    ];
  }
};

A: You can get the list of native modules like this:
const repl = require('repl')
console.log(repl._builtinLibs)

This way you get the native modules available in your specific version of Nodejs.


text:
Q: Optimal transport: how is the use of disintegration theorem valid in this construction of $\widetilde{\phi}$? Let $X,Y$ be Polish spaces and $\mathcal P(X)$ the space of all Borel probability measures on $X$.

*

*Fix $\mu\in \mathcal P(X), \nu \in \mathcal P(Y)$. Let $\pi \in \Pi(\mu, \nu)$, i.e., $\pi \in \mathcal P(X \times Y)$ whose marginal on $X$ is $\mu$ and that on $Y$ is $\nu$.

*Let $c:X \times Y \to [0, \infty)$ and $\psi:X \to \mathbb R \cup\{-\infty\}$ be measurable. Let $\phi:Y \to \mathbb R \cup\{-\infty\}$ which is not necessarily measurable.

We assume there is a $\sigma$-compact subset $S$ of $X \times Y$ such that

*

*$\pi (S) = 1$,

*$\psi (x), \phi (y) \neq -\infty$, and

*$\phi (y) - \psi (x)  = c(x, y)$ for all $(x, y) \in S$.

At page 84 of Villani's Optimal Transport: Old and New, the author constructs a measurable $\widetilde \phi: Y \to \mathbb R \cup \{\pm\infty\}$ such that $\widetilde \phi (y) = \phi (y)$ for $\nu$-a.e. $y\in Y$ as follows.

The measurability of $\phi$ is subtle also, and at the present level of generality it is not clear that this function is really Borel measurable. However, it can be modified on a $\nu$-negligible set so as to become measurable. Indeed, $\phi(y)-\psi(x)=c(x, y), \pi(d x d y)$-almost surely, so if one disintegrates $\pi(d x d y)$ as $\pi(d x | y) \nu(d y)$, then $\phi(y)$ will coincide, $\nu(d y)$-almost surely, with the Borel function $\widetilde{\phi}(y) :=$ $\int_{\mathcal{X}}[\psi(x)+c(x, y)] \pi(d x | y)$.

I understand how the disintegration theorem leads to the family $\{\pi(d x | y)  : y \in Y\}$. Let $f(x, y) := c(x, y) - \varphi (x)$. Then $f$ is measurable and finite on $S$. I think the author uses claim 1. of this version of disintegration theorem to show that

*

*$\widetilde{\phi}(y)$ is well-defined, and

*$\widetilde{\phi}$ is measurable.

IMHO, disintegration theorem only applies to extended non-negative measurable and bounded measurable functions. We don't know if $f$ satisfies either conditions.
Could you elaborate on how the construction of $\widetilde{\phi}$ makes sense? Thank you so much.

I posted this question on MSE, but have not received any answer so far. So I post it here.


text:
Q: Get Exact Inner Text of Javascript Result I run this script on a website:
document.forms[0].getElementsByTagName('input')[2]

it's output is:
<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">

It is what I exactly need (or something comma separated). when I try to convert it into a string uaing JSON.stringify, it gives a TypeError: Converting circular structure to JSON error. No problem, I can also convert the circular structure into a string with the help of this: Chrome sendrequest error: TypeError: Converting circular structure to JSON
But it will return so many extra unknown strings! I just only need that inner HTML in a comma-separated format (JSON). what should I do?

A: You can use outerHTML to get the HTML for the element and its descendants:

const input = document.forms[0].getElementsByTagName('input')[2];

console.log(input.outerHTML);
<form>
<input>
<input>
<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">
</form>

I just only need that inner HTML in a comma-separated format (JSON). what should I do?

If you mean you want the above for all of the inputs in the form, you can loop through the result from getElementsByTagName and get the outerHTML of each of them, and join the strings together with join(","). (Though I probably wouldn't use CSV for this.)

const inputs = document.forms[0].getElementsByTagName('input');
const strings = Array.prototype.map.call(
    inputs,
    input => input.outerHTML
);
console.log("Joined with a comma:");
console.log(strings.join(","));
console.log("As JSON:");
console.log(JSON.stringify(strings));
<form>
<input type="text" class="example">
<input type="date" class="blah">
<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">
</form>