text:
Q: Porting zepto plugin to jquery Im using the a framework that relies on jquery. Id like to add the page transition plugin found here: https://github.com/dgileadi/zepto-page-transitions
The plugin is built on zepto and Im trying to port it to run on Jquery 1.9.1, but I cant get it to work. If someone could help me Id be very grateful!
Id thought id be as simple as just replacing Zepto with JQuery but I cant get it to work :)
Thanks.

A: Just change "Zepto" to "jQuery" (that's a small "j") in the file transition.js, that works for me


text: Q: VirtualBox Networking does not work on Linux host? My host OS is Fedora 18 (kernel: 3.11.10) and I am running VirtualBox 4.2.18. The only networking mode which is working is NAT and non of Bridged Adapter, Internal, and Host-Only works! By this, I mean when I start a virtual machine, I can't get an IP and ping my virtual machine. I really have no idea why this behaves like this since it was working previously without any problem. Any idea please?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my raid5 always resyncing ? (device names no persistent?) I have a Intel RST software raid on ubuntu 14.04 with mdadm:
(4 x 6TB drives in Raid 5, created with device names /dev
sudo mdadm -C /dev/md/imsm /dev/sda /dev/sdb /dev/sdh /dev/sdi -n 4 -e imsm
sudo mdadm -C /dev/md/vol0 /dev/md/imsm -n 4 -l 5

the output now (after several restarts looks like)
sudo mdadm --query --detail /dev/md/vol0
/dev/md/vol0:
      Container : /dev/md/imsm0, member 0
     Raid Level : raid5
     Array Size : 17581557760 (16767.08 GiB 18003.52 GB)
  Used Dev Size : -1
   Raid Devices : 4
  Total Devices : 4

          State : clean, resyncing
 Active Devices : 4
Working Devices : 4
 Failed Devices : 0
  Spare Devices : 0

         Layout : left-asymmetric
     Chunk Size : 128K

  Resync Status : 54% complete

           UUID : 9adaf3f8:d899c72b:fdf41fd1:07ee0399
    Number   Major   Minor   RaidDevice State
       3       8      112        0      active sync   /dev/sdh
       2       8       16        1      active sync   /dev/sdb
       1       8        0        2      active sync   /dev/sda
       0       8      144        3      active sync   /dev/sdj

Could the problem of always resyncing be, that the system renames the devices inconsitently (/dev/sda -> becoms suddenly /dev/sdi for example) after boot?
sudo mdadm --detail --scan
ARRAY /dev/md/imsm0 metadata=imsm UUID=e409a30d:353a9b11:1f9a221a:7ed7cd21
ARRAY /dev/md/vol0 container=/dev/md/imsm0 member=0 UUID=9adaf3f8:d899c72b:fdf41fd1:07ee0399

The mdadm tool output:
sudo mdadm --examine /dev/md/imsm0
/dev/md/imsm0:
          Magic : Intel Raid ISM Cfg Sig.
        Version : 1.3.00
    Orig Family : 68028309
         Family : 68028309
     Generation : 00002f29
     Attributes : All supported
           UUID : e409a30d:353a9b11:1f9a221a:7ed7cd21
       Checksum : 85b1b0cb correct
    MPB Sectors : 2
          Disks : 4
   RAID Devices : 1

  Disk00 Serial : WD-WXL1H84E5WHF
          State : active
             Id : 00000002
    Usable Size : 11721038862 (5589.03 GiB 6001.17 GB)

[vol0]:
           UUID : 9adaf3f8:d899c72b:fdf41fd1:07ee0399
     RAID Level : 5 <-- 5
        Members : 4 <-- 4
          Slots : [UUUU] <-- [UUUU]
    Failed disk : none
      This Slot : 0
     Array Size : 35163115520 (16767.08 GiB 18003.52 GB)
   Per Dev Size : 11721038848 (5589.03 GiB 6001.17 GB)
  Sector Offset : 0
    Num Stripes : 45785308
     Chunk Size : 128 KiB <-- 128 KiB
       Reserved : 0
  Migrate State : repair
      Map State : normal <-- normal
     Checkpoint : 5191081 (1024)
    Dirty State : clean

  Disk01 Serial : WD-WX51DA476UL6
          State : active
             Id : 00000001
    Usable Size : 11721038862 (5589.03 GiB 6001.17 GB)

  Disk02 Serial : WD-WX51DA476P65
          State : active
             Id : 00000000
    Usable Size : 11721038862 (5589.03 GiB 6001.17 GB)

  Disk03 Serial : WD-WX51DA476HS5
          State : active
             Id : 00000003
    Usable Size : 11721038862 (5589.03 GiB 6001.17 GB)

So the dirty state says clean? Why is it then resyncing??
Does anybody know where a potential problem could be ?
and my dmesg tail output shows:
I have to say that I don't have a SAS ata7 port (I guess this is the Marvell SAS controller which is switched of in the BIOS), I only have 6 SAT ports, and 2 (turned off) SAS ports)
[ 4064.913017] sr 0:0:0:0: command ffff8802fc4ccc00 timed out
[ 4064.913043] sas: Enter sas_scsi_recover_host busy: 1 failed: 1
[ 4064.913048] sas: ata7: end_device-0:0: cmd error handler
[ 4064.913092] sas: ata7: end_device-0:0: dev error handler
[ 4064.913529] sas: --- Exit sas_scsi_recover_host: busy: 0 failed: 0 tries: 1
[ 4064.913874] sr 0:0:0:0: command ffff8802fb703b00 timed out
[ 4064.913896] sas: Enter sas_scsi_recover_host busy: 1 failed: 1
[ 4064.913900] sas: ata7: end_device-0:0: cmd error handler
[ 4064.913984] sas: ata7: end_device-0:0: dev error handler
[ 4064.914356] sas: --- Exit sas_scsi_recover_host: busy: 0 failed: 0 tries: 1
[ 4064.915269] sr 0:0:0:0: command ffff8802fc4ccc00 timed out
[ 4064.915297] sas: Enter sas_scsi_recover_host busy: 1 failed: 1
[ 4064.915302] sas: ata7: end_device-0:0: cmd error handler
[ 4064.915382] sas: ata7: end_device-0:0: dev error handler
[ 4064.915777] sas: --- Exit sas_scsi_recover_host: busy: 0 failed: 0 tries: 1
[ 4064.923419] md: md127 stopped.
[ 4064.927256] md: bind<sdc>
[ 4064.927350] md: bind<sdb>
[ 4064.927427] md: bind<sda>
[ 4064.927505] md: bind<sdi>
[ 4065.497163] sr 0:0:0:0: command ffff880304de9700 timed out
[ 4065.497181] sas: Enter sas_scsi_recover_host busy: 1 failed: 1
[ 4065.497184] sas: ata7: end_device-0:0: cmd error handler
[ 4065.497255] sas: ata7: end_device-0:0: dev error handler
[ 4065.497650] sas: --- Exit sas_scsi_recover_host: busy: 0 failed: 0 tries: 1
[ 4065.498026] sr 0:0:0:0: command ffff8802fb703e00 timed out
[ 4065.498041] sas: Enter sas_scsi_recover_host busy: 1 failed: 1
[ 4065.498043] sas: ata7: end_device-0:0: cmd error handler
[ 4065.498106] sas: ata7: end_device-0:0: dev error handler
[ 4065.498503] sas: --- Exit sas_scsi_recover_host: busy: 0 failed: 0 tries: 1
[ 4065.499352] sr 0:0:0:0: command ffff880304de9700 timed out
[ 4065.499372] sas: Enter sas_scsi_recover_host busy: 1 failed: 1
[ 4065.499375] sas: ata7: end_device-0:0: cmd error handler
[ 4065.499483] sas: ata7: end_device-0:0: dev error handler
[ 4065.499803] sas: --- Exit sas_scsi_recover_host: busy: 0 failed: 0 tries: 1
[ 4071.294317] md: md126 stopped.
[ 4071.294421] md: bind<sdi>
[ 4071.294481] md: bind<sda>
[ 4071.294533] md: bind<sdb>
[ 4071.294596] md: bind<sdc>
[ 4071.296579] md/raid:md126: not clean -- starting background reconstruction
[ 4071.296595] md/raid:md126: device sdc operational as raid disk 0
[ 4071.296596] md/raid:md126: device sdb operational as raid disk 1
[ 4071.296597] md/raid:md126: device sda operational as raid disk 2
[ 4071.296598] md/raid:md126: device sdi operational as raid disk 3
[ 4071.296900] md/raid:md126: allocated 0kB
[ 4071.296920] md/raid:md126: raid level 5 active with 4 out of 4 devices, algorithm 0
[ 4071.296922] RAID conf printout:
[ 4071.296923]  --- level:5 rd:4 wd:4
[ 4071.296925]  disk 0, o:1, dev:sdc
[ 4071.296926]  disk 1, o:1, dev:sdb
[ 4071.296927]  disk 2, o:1, dev:sda
[ 4071.296929]  disk 3, o:1, dev:sdi
[ 4071.296944] md126: detected capacity change from 0 to 18003515146240
[ 4071.297632]  md126: unknown partition table
[ 4072.773368] md: md126 switched to read-write mode.
[ 4072.773686] md: resync of RAID array md126
[ 4072.773690] md: minimum _guaranteed_  speed: 1000 KB/sec/disk.
[ 4072.773692] md: using maximum available idle IO bandwidth (but not more than 200000 KB/sec) for resync.
[ 4072.773698] md: using 128k window, over a total of 5860519424k.


text:
Q: PHP Laravel custom guard error I'm getting the error:

Auth guard [accountant] is not defined.

This is my config\auth.php file
<?php

 return [

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
     'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
    'accountant' => [
        'driver' => 'session',
        'provider' => 'accountants',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
     'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
    'accountants' => [
        'driver' => 'eloquent',
        'model' => App\Accountant::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],
      'admins' => [
        'provider' => 'admins',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    'accountants' => [
        'provider' => 'accountants',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],

];

The previous guard admin is working fine. But the accountant guard is throwing an error. What have I done incorrectly?
I have added the guard in the model as well

A: You may need to clear the config cache:
php artisan config:clear

Here are the docs on configuration caching: https://laravel.com/docs/5.4/configuration#configuration-caching
You may have previously run the config:cache command on your dev instance


text:
Q: Jquery Modal Login Registration I am working on a jquery modal login and registration. By default the modal window shows the login form. If I click on the show registration button, it switches to the registration form. The jqquery code supposed to execute on the current active (visible) form but it only seems to work with the default form (login). When I switch to the registration form, the code does not do anything and I can't figure out why. None of the jquery seems to work. It seems that once the jquery is loaded on page load, it won't let me redefine the plActiveForm variable which holds the ID of the current form. As you can see in the code, this variable is used throughout.
Any help would be appreciated. Thank you!
I don't know if I'm making much sense, this is difficult to explain. My plugin is shown below:
// -----------------------------------------------
// JQUERY - FOR MODAL LOGIN + REGISTRATION FORM
// -----------------------------------------------
(function ($) {
$.fn.plMlogin = function (options) {

    // -----------------------------------------------
    // DEFAULTS AND OPTIONS
    // -----------------------------------------------
    var defaults = {
        plTooltip: true,
        plResetButton: true,
        plBubbleResponse: true
    };
    var settings = $.extend({}, defaults, options);

    // -----------------------------------------------
    // SHOW MODAL WINDOW ON CLICK
    // -----------------------------------------------
    $('.pl-m-trigger').click(function(e) {
        e.preventDefault();

        // -> append container into body
        $('body').append('
');

        // -> load modal forms into container
        $.ajax({
            url: 'pl-module/public/modal-login-html.php',
            dataType: 'html',
            timeout: 10000, // 10 seconds
            success: function(html) {

                // -----------------------------------------------
                // -> LOAD FORMS INTO CONTAINER
                // -----------------------------------------------
                $(".pl-m-container").html(html);

                // -----------------------------------------------
                // PROPERTIES
                // -----------------------------------------------
                var plMContainer = $('.pl-m-container');
                var plMWrap = $('.pl-m');
                var plMOverlay = $('.pl-m-overlay');
                var plMLoginFrm = $('#pl_frmMlogin');
                var plMRegFrm = $('#pl_frmMRegister');
                var plMLoading = $('.pl-loading');
                var plMCloseBtn = $('.pl-m-close');
                var plMShowRegBtn = $('#pl_showRegForm');
                var plMShowLoginBtn = $('#pl_showLoginForm');
                var plMLoginSubmitUrl = 'pl-module/public/login.php';
                var plMRegisterSubmitUrl = 'pl-module/public/register.php';
                var plActiveForm = plMLoginFrm;
                var plSubmitUrl = plMLoginSubmitUrl;

                // -----------------------------------------------
                // SHOW MODAL WINDOW AND DEFAULT FORM
                // -----------------------------------------------
                $(plMWrap).fadeIn('fast');
                $(plMOverlay).fadeIn('fast');
                $(plActiveForm).fadeIn('fast');

                // -----------------------------------------------
                // CLOSE MODAL WINDOW ON BTN CLICK
                // -----------------------------------------------
                $(plMCloseBtn).click(function(e) {
                    e.preventDefault();
                    $(plMWrap).fadeOut('fast', function() {
                        $(plMOverlay).fadeOut('fast', function() {
                            $(plMContainer).remove();
                        });
                    });
                });

                // -----------------------------------------------
                // CLOSE MODAL WINDOW ON OVERLAY CLICK
                // -----------------------------------------------
                $(plMOverlay).click(function() {
                    $(plMWrap).fadeOut('fast', function() {
                        $(this).fadeOut('fast', function() {
                            $(plMContainer).remove();
                        });
                    });
                });

                // -----------------------------------------------
                // SWITCH TO REGISTRATION FORM
                // -----------------------------------------------
                $(plMShowRegBtn).click(function(e) {
                    e.preventDefault();
                    plResetForm();
                    $(plMLoginFrm).slideUp('fast', function() {
                        $(plMRegFrm).slideDown('fast', function(){
                            // set active form to registration
                            plActiveForm = plMRegFrm;
                            plSubmitUrl = plMRegisterSubmitUrl;
                        });
                    });
                });

                // -----------------------------------------------
                // SWITCH TO LOGIN FORM
                // -----------------------------------------------
                $(plMShowLoginBtn).click(function(e) {
                    e.preventDefault();
                    plResetForm();
                    $(plMRegFrm).slideUp('fast', function() {
                        $(plMLoginFrm).slideDown('fast', function(){
                            // set active form to login
                            plActiveForm = plMLoginFrm;
                            plSubmitUrl = plMLoginSubmitUrl;
                        });
                    });
                });

                // -----------------------------------------------
                // RESPONSE MESSAGES
                // -----------------------------------------------
                function plResponse(plMsg, plShowHide) {
                    var plResponse = $('.pl-response', plActiveForm);
                    if (plShowHide === true) {
                        $(plResponse).fadeIn('slow').html(plMsg);
                    } else if (plShowHide === false) {
                        $(plResponse).fadeOut('slow');
                    }
                }

                // -----------------------------------------------
                // RESET FORM BUTTON CLICK
                // -----------------------------------------------
                if (settings.plResetButton) {
                    var plResetBtn = $('.pl-reset-btn', plActiveForm);

                    $(plResetBtn).click(function (e) {
                        e.preventDefault();
                        plResetForm();
                    });
                }

                // -----------------------------------------------
                // RESET FORM FUNCTION
                // -----------------------------------------------
                function plResetForm() {
                    $('.pl-cust-response', plActiveForm).remove();
                    $('.pl-error', plActiveForm).removeClass('pl-error');
                    plResponse('', false);
                    plResetBtn.hide();
                    $(plActiveForm)[0].reset();
                }

                // -----------------------------------------------
                // FORM VALIDATION
                // -----------------------------------------------
                function plValidate() {
                    // remove custom errors if visible
                    $('.pl-cust-response', plActiveForm).remove();

                    // -----------------------------------------------
                    // CHECK - EMPTY REQUIRED FIELDS
                    // -----------------------------------------------
                    $(plActiveForm).find('.pl-required').each(function () {
                        var plEmptyCheck = $.trim($(this).val());
                        if (plEmptyCheck.length == 0) {
                            plResponse(PLLANG.MSG_03, true);
                            if (settings.plBubbleResponse) {
                                $(this).parent().append('' + PLLANG.MSG_04 + '');
                                $('.pl-cust-response').fadeIn('slow');
                            }
                            $(this).addClass('pl-error');
                        } else {
                            $(this).removeClass('pl-error');
                        }
                    });

                    // -----------------------------------------------
                    // IF ERROR(S) FOUND
                    // -----------------------------------------------
                    var $errors = $('.pl-error', plActiveForm);
                    if ($errors.length > 0) {
                        if (settings.plResetButton) {
                            plResetBtn.show();
                        }
                        return false;
                    } else {
                        plResponse('', false);
                        return true;
                    }
                }

                // -----------------------------------------------
                // FORM SUBMIT
                // -----------------------------------------------
                plActiveForm.submit(function (e) {
                    e.preventDefault();

                    // if validation is ok
                    if (plValidate() === true) {
                        var plFormData = $(this).serialize();
                        plAjaxSubmit(plFormData);
                        $(plMLoading).show();
                    } else {
                        return false;
                    }
                });

                // -----------------------------------------------
                // AJAX SUBMIT FUNCTION
                // -----------------------------------------------
                function plAjaxSubmit(plFormData) {
                    $.ajax({
                        type: 'POST',
                        url: plSubmitUrl,
                        data: plFormData,
                        dataType: 'json',
                        cache: false,
                        timeout: 20000,
                        success: function (data) {
                            $.each(data, function(key, value) {
                                if (value.error == true) {
                                    // hide loading image
                                    $(plMLoading).hide();

                                    plResponse(value.msg, true);

                                    // show reset button
                                    if (settings.plResetButton) {
                                        plResetBtn.show();
                                    }
                                } else if (value.error == false) {
                                    // reset form
                                    plResetForm();

                                    // hide loading image
                                    $(plMLoading).hide();

                                    // display success message
                                    plResponse(value.msg, true);
                                }
                            });
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            plResponse(PLLANG.MSG_06, true);

                            // hide loading image
                            $(plMLoading).hide();
                        },
                        complete: function (XMLHttpRequest, status) {
                            // hide loading image
                            $(plMLoading).hide();
                        }
                    });
                }
            }
        });
    });
};
})(jQuery);

// -----------------------------------------------
// INSTANTIATE MODAL LOGIN
// -----------------------------------------------
$(document).ready(function() {
    $('.pl-m').plMlogin({
        plTooltip : true,
        plResetButton : true,
        plBubbleResponse : true
    });
});

A: Rather than using the .click(function(e){...}) method, use the .on('click', function(e){...}) method. The .on() method works on dynamically modified HTML, while the other event methods only work on the original HTML.

Also, just a suggestion, you can declare multiple variables like this instead:

            var plMContainer = $('.pl-m-container'),
                plMWrap = $('.pl-m'),
                plMOverlay = $('.pl-m-overlay'),
                plMLoginFrm = $('#pl_frmMlogin'),
                plMRegFrm = $('#pl_frmMRegister'),
                plMLoading = $('.pl-loading'),
                plMCloseBtn = $('.pl-m-close'),
                plMShowRegBtn = $('#pl_showRegForm'),
                plMShowLoginBtn = $('#pl_showLoginForm'),
                plMLoginSubmitUrl = 'pl-module/public/login.php',
                plMRegisterSubmitUrl = 'pl-module/public/register.php',
                plActiveForm = plMLoginFrm,
                plSubmitUrl = plMLoginSubmitUrl;

I'm not sure if it's better performance-wise but it looks more organized in my opinion.


text:
Q: python PIL Image open isn't RGB i've been trying to open a .jpg image using
im = Image.open('file.jpg').

my problem is that for some reason the "im" is not an RGB image, i.e the channels are not R,G,B. this also cause the im.convert('L') (rgb2gray) give a very bad result.
channel 0 image,
attemped gray sacale.
Im using: Python 2.7.12 |Anaconda 4.1.1 (64-bit)
I would very much appreciate any help figuring this out.
edit:
it seems the problem is that the matplotlib color map isn't set right. does anyone know why? and how to fix?

A: You can find current mode in im.mode and do convert with im.convert('RGB').


text:
Q: Problems with markers in an AR.js panorama I'm building an AR panorama with AR.js and would like to have markers floating above landmarks. I tried a sample provided in AR.js git but it's always the same bug, the marker is not synchronized with the object/landmark when I'm moving the camera, it doesn't stay at the right place. In the beginning, I thought my coordinates were wrong but they are not, I tried both in GPS mode and in simulated/forced location mode (double-checking my location with a handheld Garmin GPS12) for the user location.
Here is a video of the problem (we see the marker doesn't stay above the obelisk).
Here is my HTML code, which is pretty close to the sample.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>GeoAR.js demo</title>
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
    <script src="https://unpkg.com/aframe-look-at-component@0.8.0/dist/aframe-look-at-component.min.js"></script>
    <script src="https://raw.githack.com/AR-js-org/AR.js/3.3.1/aframe/build/aframe-ar-nft.js"></script>
  </head>

  <body style="margin: 0; overflow: hidden;">
    <a-scene
      vr-mode-ui="enabled: false"
      embedded
      arjs="sourceType: webcam; debugUIEnabled: false;"
    >
      <!-- Obélisque : https://geohack.toolforge.org/geohack.php?language=fr&pagename=Ob%C3%A9lisque%20de%20Louxor&params=48.8655_N_2.3211_E_scale:8000 -->
      <!-- WGS84 48.8655°, 2.3211° -->
      <a-image
        src="location.png"
        look-at="[gps-camera]"
        scale="14 14 14"
        gps-entity-place="latitude: 48.8655; longitude: 2.3211;"
      ></a-image>
      <a-text
        value="Obélisque de Louxor"
        look-at="[gps-camera]"
        scale="14 14 14"
        position="0 40 0"
        align="center"
        gps-entity-place="latitude: 48.8655; longitude: 2.3211;"
      ></a-text>
      <!-- force GPS coordinates -->
      <!-- GPS12: 48.86650 2.32210 80M -->
      <!-- Apple Map: 48.866766 2.322606 -->
      <a-camera gps-camera="simulateLatitude: 48.8665; simulateLongitude: 2.3221; simulateAltitude: 80m;" rotation-reader></a-camera>
      <!-- <a-camera gps-camera rotation-reader></a-camera> -->
    </a-scene>
  </body>
</html>


text:
Q: How can I make tagging work for the concept of "all"? There's an approach to organising information that says that hierarchy is a tool of the devil, or at least is overrated. I've embraced this understanding for a data-driven site I'm working on which has a fixed set of admins who create and tag data and a slightly less fixed group of data consumers. It uses tagging and search to inform the data consumers when a piece of information is related to what they're reading or searching for (as opposed to expecting non-1337 admins to maintain an object-style hierarchy).
I now face the situation of needing some items of information to relate to "all" others in one respect. I cannot expect content creators to tag their "all" entries with every subject in the domain, and if they did the sheer weight of tags in that domain would drown out the information implied by the other tags on the entry. The options I can think of thus far (all unappealing) are:

*

*Create an "all" checkbox, which can
assign an arbitrarily higher score to an entry
when considering relevance

*Make different categories of tags, i.e. one tag field per clearly delineated group of subjects

*Replace tagging with a more traditional hierarchy

*Create magic "all" tags that get handled differently by my code (I can't believe I'm even thinking that out loud)

Are there any other approaches that could work? Is one of these a clear winner?

A: The answer would be to have an inheritance hierachy in your tags (i.e. not the information you are tagging but the tags *themselves*) such that if all of your items require a tag then you would use the parent tag. For example animal is abstract parent of dog, cat, fish, whale.

A: What about an "untagged" tag that you automatically add if the user doesn't define any tags?

A: In your question you imply that the choice is to have either a hierarchy or tagging - yet your own suggestions and the nature of the problem suggest that the requirement may be for both a hierarchy and tagging?

A: Also look at Drupal and its taxonomy features, it includes parent abstract tags functionality and even managing multiple taxonomies and vocabularies. Other interesting features are synonym collapse where similar terms can be purged into one term, e.g. NY and New York.


text:
Q: loop through files and send to web service I need to loop through a directory of files (doc) and send them to a web service, getting back a pdf file (identical name as the doc).
for one file, this works:
$MyInvocation.MyCommand.Path | Split-Path | Push-Location

$uri = "http://someinternalurl"
$doc= "somefilename.doc"
$pdf= "somefilename.pdf"

Invoke-WebRequest -Uri $uri -Method POST -InFile $doc-ContentType "application/octet-stream" -OutFile $pdf

but with a loop I keep messing up, I'm currently trying:
$files = get-childitem c:\in\doc -Filter *.doc
ForEach ($file in $files) {
    $MyInvocation.MyCommand.Path | Split-Path | Push-Location

    $uri = "http://someinternalurl"
    $doc = Get-Content $file.Fullname ## <<-- this is where i'm surely wrong
    $pdf = $file.Basename + '.pdf'

    Invoke-WebRequest -Uri $uri -Method POST -InFile $in -ContentType "application/octet-stream" -OutFile $pdf
}

A: $DocPath = 'c:\in\doc'
$Uri = 'http://someinternalurl'

Get-ChildItem -Path $DocPath -Filter '*.doc' | ForEach-Object {
    $PdfPath = Join-Path -Path $_.Directory.FullName -ChildPath ($_.BaseName + '.pdf')
    Invoke-WebRequest -Uri $Uri -Method POST -InFile $_.FullName -ContentType 'application/octet-stream' -OutFile $PdfPath
}


text:
Q: How to fix ValueError: DataFrame constructor not properly called on flask I want to try to make a dataframe from pdfreader, with the column name is isi1. but why do I get an error ValueError: DataFrame constructor not properly called !. what should i do to fix this error. help from anyone when needed for this problem.
this is my code
 if request.method == 'POST':
        f = request.files['file']
        f.save(f.filename)
        pdfreader = PyPDF2.PdfFileReader(open('C:/Users/Novilia/PycharmProjects/tesaja/' + f.filename, 'rb'))
        from pandas import DataFrame
        df1 = DataFrame(pdfreader, columns=['isi1'])
        #vect = count_vect.transform(['isi1']).toarray()
        df1['label1'] = text_clf.predict(df1['isi1'])
        df1.append(['label1'])
        hasil = (df1.isi1[df1['label1'] == 'positif'])
        len(hasil)
        hasil_list = hasil.values.tolist()
        stringList = ' '.join([str(item) for item in hasil_list])
        hasil_ringkas = stringList

    return render_template('result.html', ringkasan = hasil_ringkas)

the error is
ValueError
ValueError: DataFrame constructor not properly called!

Traceback (most recent call last)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Novilia\PycharmProjects\tesaja\app.py", line 79, in summarize
df1 = DataFrame(pdfreader, columns=['isi1'])
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\pandas\core\frame.py", line 509, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!

A: From my understanding, I guess you need to iterate over the pages and get the text from each page. can you try the following:
import nltk

pdfreader = PyPDF2.PdfFileReader(open('C:/Users/Novilia/PycharmProjects/tesaja/' + f.filename, 'rb'))
page_contents = [sent for page_no in range(pdfreader.getNumPages())
                 for sent in nltk.sent_tokenize(pdfreader.getPage(page_no).extractText())]
df1 = DataFrame(page_contents, columns=['isi1'])

Kindly let me know if you find any problem with the code.


text:
Q: pip install python app from github, with non pypi dependecy We wrote an application for ourselves which calls us on the phone, if our telescope has a problem. One can install this application (without prior cloning) like this:
pip install git+https://github.com/fact-project/shifthelper

and we like that our non-developer friends can install the app without prior cloning it. So far so good.

Now we pulled out part of the app into a little library, which one can install like this:
pip install git+https://github.com/fact-project/smart_fact_crawler

but we seem to be unable to tell pip in the setup.py how to install the required library before installing the app.
We tried using this:
#setup.py
....
dependency_links=[
    "git+http://github.com/fact-project/smart_fact_crawler.git#egg=smart_fact_crawler",
],
....

So how does one specify non pypi dependencies in the setup.py?

A: From Release Notes for pip 1.5 (2014-01-01)

BACKWARD INCOMPATIBLE pip no longer respects dependency links by
  default. Users may opt into respecting them again using
  --process-dependency-links.

A: Your setup is all good and the deprecation of --process-dependency-link has since been (luckily) reverted.
The missing piece here is that pip requires an additional flag to actually use the listed links:
pip install ... --process-dependency-links ...

The Pull Request that was reverted - https://github.com/pypa/pip/pull/1519


text:
Q: Legacy ActiveX Control with .NET 4.0 - Microsoft POS We have an ActiveX Control calling Microsoft Point of Sale for .NET.  However POS doesn't work with .NET 4.0 due to CAS (Code Access Security) which is obsolete for .NET 4.0.
The best resource I've found is on this LavaBlast Blog, however I've been unable to get it to work.
At what point should I be setting this?  I didn't think ActiveX controls had configuration files associated with them for this setting, and wouldn't this be a setting on the user's computer and not on a webserver's web.config file?
Here is the code and the specific error:
PosExplorer explorer = new PosExplorer();

This method explicitly uses CAS policy, which has been obsoleted by
  the .NET Framework. In order to enable CAS policy for compatibility
  reasons, please use the NetFx40_LegacySecurityPolicy configuration
  switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570


text:
Q: How to define an event for features selected in mapcanvas in qgis using python I have created a push button, when it is clicked it calls the function 'selectfeatures'. This function will call the Select feature by free hand tool of QGIS and allows the user to select features in the mapcanvas. What I need is my event to recognize the features selected in mapcanvas and call another function.  How should this be accomplished?

A: If I got you right, you can use the SIGNAL selectionChanged from your vector layer and connect it to your other function (which must accept an argument to receive selected features' ids).
For example, load a vector layer to QGIS, activate it in the ToC and run the following code in the QGIS Python console. You should see the function is running after a new selection, recognizing the selected features' ids.
lyr=iface.activeLayer()
def myFunction(selFeatures):
    print str(len(selFeatures)) + " features were selected: " + str(selFeatures)

lyr.selectionChanged.connect(myFunction)


text:
Q: How to count attributes (columns) from a txt file in Python using pandas? I have a txt file that has rows and columns of data in it. I am trying to figure out how to count the number of columns (attributes) in the whole txt file. Here is my code to read the txt file and to count the columns but it is giving me the wrong answer.
    import pandas as pd

    data_file = pd.read_csv('3human_evolution.txt')
    data_file.columns = data_file.columns.str.strip()
    A=len(data_file.columns)
    print(A)

A: len gives you all elements in the DataFrame (product of rows and columns). The number of rows and columns are accessible with DataFrame.shape. shape gives you a tuple where the first entry is the number of rows and the second the number of columns. So you can print the number of columns with:
print(data_file.shape[1])


text:
Q: Disable Autostart on Login There is an application, zoom, which depends on software known as ibus. After installation, ibus likes to autostart. I don't want ibus to autostart. Ive removed autostart files that start im-daemon from ~/.config/autostart and /etc/xdg/autostart, but the application still starts. Ive searched for systemd services, and there are none which start ibus. If I logout and log back in, the application starts again. How can I find the source and stop this malware-emulating software from autostarting? I'm on Debian 10 Cinnamon
Currently I have deleted the binary for im-daemon, which causes the autostart program to fail. However, I still want to know how and why this software strives to hide its activity from the user.

A: I am assuming you are talking about the Zoom Meeting application.
I ran the command
strace -o debug.txt   -e trace=file  -f ./ZoomLauncher

This showed at one point to run libibusplatforminputcontextplugin.so which is part of the zoom package.  To guess what is happening without a full deep dive into the product I ran:
strings ./platforminputcontexts/libibusplatforminputcontextplugin.so | grep -i ibus

This showed that there are several strings that reference ibus.  So the application likely needs it.
The easier solutions are not using gnome variant or trying to run the application in wine.
If you want to directly want to stop it you could try to stop the changes from happening.  I am not running Cinnanmon so I am guessing at the solution so you may need more research.  The debug file from earlier can show all files accessed.  Running the following can show a cleaned up list of file accesses.
cat debug.txt | grep -v "No such file or directory\|RDONLY\|exited\|unfinished\|\"/dev/" | grep "[0-9]* openat("

Zoom seemed interested in my "/run/user/1000/dconf/user" file.  To be clear (due to recent events in the news) I am not saying this malicious I am saying on my system the modify time changed the same time as when I was running zoom.  My lack of statement is due to my current knowledge of dconf is low and from what I know there are many legitimate reasons to change a field in this field for any friendly application.  If it is modifying dconf settings there could be something in there that is starting ibus.  If that is the solution the I would recommend changing permissions on that file to not allow your user to change it.
chmod 400 /run/user/1000/dconf/user

or the dconf file under your home directory if zoom is modifying it.  This very possibly can cause poor and unexpected behavior, but the question tone seems to indicate that this would be acceptable.  There are also options for locking dconf with the same caveats.  Locking dconf


text:
Q: String Manipulation in UNIX I have a script that after running, will shows:
The square 1 with the name Square with area 10 is created
The square 2 with the name Box with area 20 is created
The circle with the name Spinny with area 22 is not created
The rectangle with the name Tri with area 30 is created.

How can I retrieve all the numbers between area and is created and store it into an array?
stored array will be:
10
20
30

The tricky part is that, I cannot just find the first number, as square (1) will be read,
I cannot also do take the number between "area" and "is" as it might take in shapes that are not created.
any idea how to do this?

A: Using grep:
$ cat testfile
The square 1 with the name Square with area 10 is created
The square 2 with the name Box with area 20 is created
The circle with the name Spinny with area 22 is not created
The rectangle with the name Tri with area 30 is created.
$ grep -Eo 'area [0-9]+ is created' testfile | grep -Eo '[0-9]+'
10
20
30

NOTE POSIX grep doesn't support -o, but this should work on BSD and GNU greps.

A: awk
awk '/area [[:digit:]]+ is created/{ print $(NF-2); }'

Prints the third-to-last field on matching lines.
array=( $(awk '/area [[:digit:]]+ is created/{ print $(NF-2); }' <<< "$input") )
printf '%s\n' "${array[@]}"
10
20
30

pure bash
array=()
while read -a line; do
  if [[ "${line[@]: -2:1}" = is && "${line[@]: -1}" = created ]]; then
    array+=( "${line[@]: -3:1}" )
  fi
done <<< "$input"
printf '%s, ' "${array[@]}" # Will output 10, 20 if there's a period on the last line...

A: array=( $(sed -n 's/.*with area \([0-9][0-9]*\) is created.*/\1/p' data) )

The array=( ... ) notation is an array assignment in bash.  The $(...) is command substitution.  The sed command does not print by default, but when a line matches 'with area XX is created' (where XX is a number of one or more digits), then the line is replaced with the value of XX and printed.

A: Using gnu grep (Lookahead and Lookbehind Zero-Length Assertions)
grep -Po '(?<=area )[0-9]* (?=is created)' file

Using sed
sed -n 's/.* area \([0-9]*\) is created.*/\1/p' file


text:
Q: What equation precisely defines the epoch of recombination? I understand that a very rough first estimate would be to assume this happens when the mean photon energy drops below the value required to photoionise hydrogen, namely when
\begin{equation} \label{eq1}
\begin{split}
T_{rec} & \approx \frac{Q}{2.7k}
\end{split}
\end{equation}
but this is a very crude estimate. What formula do I need to find the precise epoch?


text:
Q: How to handle unsent messages in a concurrent queue in a web api I am using a concurrent queue in my Web API as mentioned in thread
How to maintain state or queue of requests in Web API
But I am running into an issue where if the application pool is stopped or recycled it looses all the data in the memory.
Can someone help me as to how I can handle the same?
My use case requires accepting messages from different origins and putting in the queue and after every 5 seconds interval i am writing those messages to an input .txt file.


text:
Q: Send array from php to js with ajax and json I am trying to send an array from php (that I have taken from a mysql table to js). Although there a lot of examples out there I can't seem to make any of them work. The code that I have reached so far is:
php_side.php
<!DOCTYPE html>

<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");

$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);

/*while($row = mysqli_fetch_array($result)) {
     echo $row['User1_number'];
     echo "
";
     echo $row['User2_number'];
         echo "
";
     echo $row['canvas_channel'];
         echo "
";
}*/
echo json_encode($result);

    mysqli_close($con);
    ?>

test_ajax.html
    $(document).ready(function(){
      $.getJSON('php_side.php', function(data) {
        $(data).each(function(key, value) {
            // Will alert 1, 2 and 3
            alert(value);
        });
     });
   });

This is my first app that I use something like this, so please be a little patient.

A: Right now you're sending the complete page markup mixed with your json response, which of course will not work.
For example imagine that you have the following php script which suppose to return a json response:

<?php print json_encode(array('domain' => 'example.com')); ?>

The response from this page would not be json since it also will return the wrapping div element.
You can move your php code to the top of the page or simply remove all the html:
<?php
 // uncomment the following two lines to get see any errors
 // ini_set('display_errors', 1);
 // error_reporting(E_ALL);

 // header can not be called after any output has been done
 // notice that you also should use 'application/json' in this case
 header("Content-type: application/json");

 $con = mysqli_connect("localhost","root","","Tileiatriki");
 if (!$con) {
   die('Could not connect: ' . mysqli_error($con));
 }

 $sql="SELECT * FROM users_in_calls";
 $result = mysqli_query($con,$sql);

 // fetch all rows from the result set
 $data = array();
 while($row = mysqli_fetch_array($result)) {
   $data[] = $row;
 }
 mysqli_close($con);

 echo json_encode($data);

 // terminate the script
 exit;
?>


text:
Q: Correct way of declaring arrays using the Array() constructor? I know that the Array() constructor takes in two arguments: the size of the array and a function which receives the index of an array and returns the value for that index.
I've written some example programs in the kotlinlang.org online IDE, and have declared & initialised my arrays as such:
var array = Array(9, {i -> ' '})

A "blank" char array of size 9, completely filled with whitespaces. This works fine in the kotlinlang.org compiler, and runs well too; however, when I try to import the same code to IntelliJ-IDEA, I get the following warning:

Warning: Kotlin: Parameter 'i' is never used, could be renamed to _

What does the underscore character mean? How does it act as an index? Renaming i to _ does remove the warning, but what does it do, exactly?
How should I correctly use the Array() constructor to initialise a an array using a lambda expression? Bear in mind, I know that the lambda expression can be written outside the brackets, but I chose to include it anyway because it is pretty simple.
Thanks in advance.

A: It says "Warning" not "error".
Warning: Kotlin: Parameter 'i' is never used, could be renamed to _
The code is compiling fine, it's just informing you that the unused lambda parameter can be renamed to _ to make it more obvious that the lambda parameter is unused.
So, to answer you question, you have constructed the array correctly. However, if for some reason you wanted to use the index to construct the array, you can leave it named and use it for calculations inside the lambda that is executed for constructing each element of the array. For instance:
val array = Array(10, { i -> i * 10  })

Which would result in an array like:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Also, something to note, you have used var, this means your variable array is mutable (i.e. the whole variable can be re-assigned). This is probably not what you want, so you should favour val unless you specifically want a mutable variable.

A: It is just a warning.
In Kotlin if you do not use parameter you can rename it to _. It is more readable.
In your case you do not use i on the right side of your lambda function. So you can rename it to _

A: As other answers have said, your code is correct, but since you're not using the parameter i, there's no need to give it a name.  You can instead use _, which is simply a placeholder: it indicates to Kotlin that the lambda takes a parameter, but you don't care about it.
(The underscore might not seem very useful here, but it can help in more complex cases.  For example, if you had a big Person class with many fields, you could use just a couple of them with e.g. for ((name, _, _, age) in persons)…)
In fact, you can simplify the expression even further!  Unlike more traditional block-structured languages, in Kotlin braces usually indicate a lambda (except in cases such as function bodies, and if and when branches), even without a ->.  And here Kotlin can infer the number as well as the type of parameters.  So you can drop the parameter and arrow entirely, and simply use:
var array = Array(9, {' '})

A: All of the definitions below create the same array. Kotlin (and IntelliJ) discourage redundant code, so _ is "better" then i (as i is not used) and "nothing" is better then _. Finally, IntelliJ encourages last parameter lambda to be in a separate block - as per the fourth example:
Array(9, { i -> ' ' })
Array(9, { _ -> ' ' })
Array(9, { ' ' })
Array(9) { ' ' }


text:
Q: Boto3 API RDS: get list of params accepted by function I am using the boto3 API, particularly the RDS client, to modify an RDS instance based on a list of parameters and their associated values. Prior to calling the modify_db_instance() function, I want to validate the user-provided parameters to ensure that they can be passed to the modify function (the parameters will also be used elsewhere; thus, they may be accepted by some boto functions but not others).
If I were to execure the modify function and provide an invalid parameter, I would receive a ParamValidationError from boto, as well as a list of all of the acceptable parameters. I would like to retrieve this list programmatically. Boto3 docs suggest I use the describe_valid_db_instance_modifications() function - the response I get is indeed similar to what is described in the docs here, but I'm explicitly looking for a list of params, which I don't get from that function. I cannot figure out a way to programmatically do this.
Thanks!

A: The valid arguments for these boto3 functions are not hardcoded into the function signature itself, so this is a little trickier than using something like inspect.getargspec. This is certainly a little convoluted, but works:
import urllib3
import json

url = 'https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/rds/2014-10-31/service-2.json'

http = urllib3.PoolManager()
r = http.request('GET', url)
data = json.loads(r.data)
print(data['shapes']['ModifyDBInstanceMessage']['members'].keys())

A: boto3 does expose the models for you, but you have to dig deep:
allowed_keys = dict(client.meta.service_model
  .operation_model("ModifyDBInstanceMessage").input_shape.members).keys()

This works for any model for the client type, but you do have to find the service-2.json to figure out the name.


text:
Q: Best way to open m3u8 stream in PhoneGap What is the best way to open m3u8 video streaming in a PhoneGap application on Android? I already accomplished it on iphone using html5 video tag but it's not working on android as expected.
I'm using build.phonegap.com so I can't use native plugins. When using the  tag with width=100% and height=100% the video gets skewed in portrait. I need a way to open it in the native media player if possible.

A: I ended up creating my own plugin.


text:
Q: iOS build error: Error - Unable to import Certificate iOS build error: Error - Unable to import Certificate
We have try phonegap build for iphone. But error occur.
Error - Unable to import Certificate - You can fix this here

A: This has happened to me as well. Try removing your key, generating the .p12 and provisioning profile again, and adding them back to your Phonegap build.


text:
Q: Displaying images and navbar on certain urls react Im using a react app and have done the login and signup forms and have private routes in app.js. Everyone has access to login and sign up. The rest of the pages are protected. I have the landing signup page rendering a background image using HTML tag in css but I cant get it to switch to another image in another component. Also I dont want the navbar to show up on login and Signup pages.
      <main>
        <Switch>
          <PrivateRoute path="/user/home" component={Home} />
          <PrivateRoute path="/user/resources" component={Resources} />
          <PrivateRoute path="/user/about" component={About} />
          <PrivateRoute path="/user/mealplan" component={MealPlan} />

          <Route exact path="/" component={SignUp} />
          <Route path="/login" component={Login} />
        </Switch>
      </main>
    </div>

A: Create a new Navbar component named something like NavBarController. While calling the navbar controller component pass in the "Type" as prop. Type should be a state and should change depending on the page the user is on.
<NavBarController type={1}></NavBarController>

You would just create a few different NavBars and then NavBarController will handle whichever navbar you want to display out of your multiple navbars.
Your NavBarController will return something like this:
return (props.type===1?<NavBarHome/>
:props.type===2?<NavBarResources/>
:props.type===3?<NavBarAbout/>
:props.type===4?<NavBarMealPlan/>)

A: If the current pathname is the pathname , you want to hide your nav or other component , follow the below code :
import { useLocation } from 'react-router-dom';

// custom hook to get the current pathname in React

  const location = useLocation();

      <main>
        <Switch>
          <PrivateRoute path="/user/home" component={Home} />
          <PrivateRoute path="/user/resources" component={Resources} />
          <PrivateRoute path="/user/about" component={About} />
          <PrivateRoute path="/user/mealplan" component={MealPlan} />

          {location.pathname!=="some pathname"&& <Route exact path="/" component={SignUp} /> }
          {location.pathname!=="some pathname"&& <Route path="/login" component={Login} /> }
        </Switch>
      </main>
    </div>


text:
Q: How to bundle manually lazy loaded modules with angular4 and webpack ngtools/webpack I have multiple modules in app . i made few of modules are lazy loaded manually as follows
 this.moduleLoader.load('Infor.MinglePortal/tsScripts/usersettings/usersettings.module#UserSettingsModule')
        .then((moduleFactory: NgModuleFactory<any>) => {
            const vcRef = this.vcRef;
            const ngModuleRef = moduleFactory.create(vcRef.parentInjector);
            const comp = ngModuleRef.injector.get(LazyLoadConfig).component;
            const compFactory = ngModuleRef.componentFactoryResolver.resolveComponentFactory(comp);
            this.compRef = vcRef.createComponent(compFactory, 0, ngModuleRef.injector);
            let info = {
                componentRef: this.compRef,
                factory: compFactory,
                moduleRef: ngModuleRef
            };

        });

I am not able to bundle this with webpack3 , ngtools/webpack and aot.
here is my tsconfig and webpack.config.js
enter code{
"compilerOptions": {
  "module": "es2015",
  "moduleResolution": "node",
  "target": "es5",
  "noImplicitAny": false,
  "sourceMap": true,
  "mapRoot": "",
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "lib": [
    "es2015",
    "dom"
  ],
  "outDir": "lib",
  "skipLibCheck": true,
  "baseUrl": ".",

},
"exclude":["./Abc.AbcPortal/tsScripts/abc-aot.ts", "./build/*", "./dist/*","node_modules"],
"angularCompilerOptions": {
  "debug": true,
  "entryModule":"./Infor.AbcPortal/tsScripts/abc/abc.module#abcModule"
}

}
webpack.config.js
const ngToolsWebpack = require("@ngtools/webpack");
const path = require("path");

module.exports = {
  resolve: {
    extensions: [".ts", ".js"]
  },
  node: {
    net: "empty",
    tls: "empty"
  },
  entry: "./abc.abcPortal/tsScripts/main.ts",
  output: {
    path: path.resolve(__dirname, "./build/"),
    publicPath: "/build/",
    filename: "[name].bundle.js",
    chunkFilename: "[id].chunk.js"
  },
  plugins: [
    new ngToolsWebpack.AotPlugin({
      tsConfigPath: "./tsconfig-web3.json"
    })
  ],
  module: {
    loaders: [
      { test: /\.css$/, loader: "raw-loader" },
      { test: /\.html$/, loader: "raw-loader" },
      { test: /\.ts$/, loader: ["@ngtools/webpack"] }
    ]
  }

My Problem is i am unable to load the lazy loaded modules with webpack + aot + ngtools/webpack .
I am getting the following error when i load lazy loaded module.
main.bundle.js:2387 ERROR Error: Uncaught (in promise): Error: Cannot find module 'abc.MinglePortal/tsScripts/usersettings/usersettings.module.ngfactory'.
Error: Cannot find module 'abc.MinglePortal/tsScripts/usersettings/usersettings.module.ngfactory'.
Please help me out.


text:
Q: Directory structure (file system design) I was looking at how file systems are designed and noticed that most places say that the directory hierarchy can be implemented using a hash table.
Could someone please explain me how using a hash table to store a directory structure works?
For example, what would happen if I add a file/ directory or move a directory, how does that affect the hash table?
Also, how are paths involved?

A: The easiest is to have a hash table per directory.  To follow a pathname, just get the root hash table, query it for the first directory in the path.  Then, if it's a directory, get the next hash table and query it with the next part, and so on until the last part.
Since hash tables are unordered structures, you would typically sort them in memory to list a whole directory.  Also, the hash wouldn't help to match wildcards; you have to do a whole directory scan to see which names match a given pattern.  Of course, an ordered structure (like a sorted list or a B*tree) only help if there's a constant prefix.
A different way (used by Mac's HFS system) is to use an ordered structure (a B*tree in HFS case) and index by directory/name.  In HFS, there was a dirID/filename structure that served as the main key for a single B*tree.  Once you had this file handle, a single query returned the directory entry, without having to traverse the whole pathname.  To get a directory list, just read the range [dirID, dirID+1), the resulting interval comprised all the filenames stored in that directory, in binary lexicographical order.


text:
Q: PrerenderIO not working on my MeteorApp I have an Issue with making PrerenderIO work on my app.
I am running meteor@1.3.5.1 and prerender-node and I have set up this code in my server/prerenderio.js like this
Meteor.startup( function(){
const prerenderio = Npm.require('prerender-node');
const settings = Meteor.settings.PrerenderIO;

console.log(settings);

if (settings && settings.token && settings.host) {
    console.log('This is true');
    prerenderio.set('prerenderToken', settings.token);
    prerenderio.set('host', settings.host);
    prerenderio.set('protocol', 'http');
    WebApp.rawConnectHandlers.use(prerenderio);
   }
});

And my settings.json liiks like this
{
"PrerenderIO": {
    "token": "wi7DqaiBlaBlaBlaqTGmT",
    "host": "http://locallhost:3000/"
},
"public":{
    "ga": {
        "id": "UA-XXXXXXXXX-1"
    }
}
}

When I start the server on my localhost, I get this on the log
Prerender Token: wi7DqaiBlaBlaBlaqTGmT

So, I have PrerenderIO's local server running on port:3033 and when I run http://localhost:3000/?_escaped_fragment_=, it takes long and then returns "localhost not found" and logs some error on my meteor server logs.
Also, when I deploy the app to my host, and the visit my prerender.io dashboard I still see the warning that i have not installed my prerender token.
when I visit http://localhost:3033/http://localhost:3000 I get the cached page without the images
Please NOTE i have tried the following packages dfischer:prerenderio and dferber:prerenderbut the same thing.

A: Somewhere in your server, you need to import Meteor to fetch your private settings, you need to import prerenderIO from your node modules and WebApp from meteor/webapp. Setup your config file for prerender like this:
import prerenderIO from 'prerender-node';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';

Meteor.startup(() => {
    const settings = Meteor.settings.private.PrerenderIO;

    if (settings && settings.token && settings.host) {
        prerenderIO.set('prerenderToken', settings.token);
        prerenderIO.set('host', settings.host);
        prerenderIO.set('protocol', 'http');
        WebApp.rawConnectHandlers.use(prerenderIO);
    }
});

Also, in your settings, you don't need to include http in your domain string, as you're setting it in the server by calling the protocol method. your host url should just be: localhost:3000


text:
Q: Django i18n Javascript Problem I have this problem: When i set a language (it or en)in my django app, with this form,
the javascript strings are converted always in English.
My base Language is Italian.
This is my configuration:
urls.py:

js_info_dict = {
      'domain': 'djangojs',
      'packages': ('myproject',),
  }
urlpatterns += patterns('',
      (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
  )

I have run this command:

django-admin.py makemessages -d djangojs -l en

To generating the djangojs.mo/po files.
I Have translated the string from it to en in that file.
and i've run:

django-admin.py compilemessages

Now when I go on the page that contains this JS:

document.write(gettext('Questa stringa è da tradurre'));

the strings return always 'This string is to be translated',
(That is the translation of 'Questa stringa è da tradurre')
I have included this js in my html file:

<script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>

Where am i wrong? Any Ideas? Thanks in advance.

A: you should run
django-admin.py makemessages -d djangojs -l en
django-admin.py compilemessages

for each language you have :)

A: In your file base.html  add the following lines to the beginning
{% load static from staticfiles %}
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}


text:
Q: Git works using Git bash in terminal, but not in VS code Working in Visual Studio Code I'm using Git to manage my files. I use SSH to have a secure connection. When working with files in file explorer and using the git bash terminal everything works fine. However, when I use git with Visual Studio Code I get the following error:
> git pull --tags origin master
  git@bitbucket.org: Permission denied (publickey).
  fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.

Using the Git bash terminal (thus without VS Code) everything works smoothly. What am I doing wrong?


text:
Q: How to trim down a URL using regex in PHP? I am struggling to finish this regex code in PHP.  I want to trim down the following url which is held in variable $text so that it goes from:
 http://www.site.net/showthread.php?tid=324&pid=...

to:
 showthread.php?tid=324

Thank you kindly!

A: Why use a regex? The parse_url method should give you all you want: http://php.net/manual/en/function.parse-url.php
Edit: working example
$someurl = 'http://www.site.net/showthread.php?tid=324&pid=...';
$urlParts = parse_url($someurl, PHP_URL_PATH | PHP_URL_QUERY);
$params = parse_str($urlParts['query']);
unset($params['pid']);
$queryString = http_build_query($params);
$newUrl = $urlParts['path'] . '?' . $queryString;

Since $urlParts['path'] start with a / and you didn't want that, you could even use
$newUrl = substr($newUrl, 1);

and be done :) Does that help at all?

A: This should do it:
$url = 'http://www.site.net/showthread.php?tid=324&pid=...';
$pattern = "/showthread.php\?tid=[0-9]+/";

if (preg_match($pattern, $url, $match))
    print_r($match);


text:
Q: Azure function accessible locally only I have an Azure static web app with a svelte front end and azure server less functions for backend. When developing locally I can connect to the functions perfectly with fetch('https://localhost:7071/api/test') But when I replace it with fetch('/api/test') it won't work locally or on the deployed site.

A: Yes! As Lokanath Das said, Root URL + Route makes an API URL.
In The Azure Functions Scenario:
When you run locally, the root URL is combination of localhost, port number and the route (api/function_name).

When you run in the Cloud, then the URL will be: "https://<azurefunctionappname>.azurewebsites.net/api/<FunctionName>" .
We can customize the Azure Function URL Route using HTTP Route Trigger Parameters and can make them optional or we can define the route in the Azure Function Header. Refer here for more information


text:
Q: Putting two colours in listview I have created a list view in JQuery mobile with 2 grids. And I need to set background color to only 1 grid (block-a) but doing so, the padding of the list view is being displayed as white. I need to set color for the padding also. I need the first half to have one colour and second half to have different colour.
Thanks in advance.

Page One

Distance

Places

A: You need to customize css in jQuery.
Like for example
.ui-grid-a .ui-block-a { customization goes here }

.ui-grid-a .ui-block-b { customization goes here }

I have set up a sample jsFiddle, it will get you started.
http://jsfiddle.net/Akki619/z3BQ2/
The fiddle may not provide the exact solution you are looking for but you can always play along for desired results.
In your case: You need to customize data-theme a/c to your need.
It might be a tricky to get the desired result as you want.

A: Your padding is already colorized so far, but the margin isn't.
You need to remove the margin and set a padding:
ul li {
    padding-left: 10px;
    margin-left: 0px;
}

Then your background color will be set with the space before your items content.


text:
Q: How do a date range validation with vue/Quasar I try to create a date range with controls in a compoment
Vue.component('FraisHebergement', {
template: '

\
            <template>\
                    <q-input filled v-model="model.date" :rules="ConfirmDateRange" label="Date début" class="td25pc q-pr-xs" ref="dtedeb">\
                        <template v-slot:append>\
                            <q-icon name="event" class="cursor-pointer">\
                                <q-popup-proxy ref="qDateProxy" transition-show="scale" transition-hide="scale">\
                                    <q-date v-model="model.date" mask="DD/MM/YYYY" @input="() => $refs.qDateProxy.hide()" :locale="myLocale"/>\
                                </q-popup-proxy>\
                            </q-icon>\
                        </template>\
                    </q-input >\
                </template ><template>\
                    <q-input filled v-model="model.dateFin" :rules="ConfirmDateRange" label="Date Fin" class="td25pc" ref="dtefin">\
                        <template v-slot:append>\
                            <q-icon name="event" class="cursor-pointer">\
                                <q-popup-proxy ref="qDateProxyf" transition-show="scale" transition-hide="scale">\
                                    <q-date v-model="model.dateFin" mask="DD/MM/YYYY" @input="() => $refs.qDateProxyf.hide()" :locale="myLocale"/>\
                                </q-popup-proxy>\
                            </q-icon>\
                        </template>\
                    </q-input >\
                </template>\
                <q-input input-class="text-right" filled ></q-input >\
\
             <q-btn class="q-mt-sm" label="Reset Validation" @click="reset" color="primary"/>
   \

',
computed: {
    ConfirmDateRange() {
        return [
            (v) => !!v || "Saisissez quelque chose :-)",
            (v) => regex.test(v) || "Format de date à utiliser: JJ/MM/AAAA",
            (v) => this.model.dateFin > this.model.date || "Date incohérente"
        ]
    }
},
 data: function () {
    return {
        model: {
           date: Quasar.utils.date.formatDate(Date.now(), 'DD/MM/YYYY'), dateFin: ''
        },
        myLocale: {
            days: 'Dimanche_Lundi_Mardi_Mercredi_Jeudi_Vendredi_Samedi'.split('_'),
            daysShort: 'Dim_Lun_Mar_Mer_Jeu_Ven_Sam'.split('_'),
            months: 'Janvier_Fevrier_Mars_Avril_Mai_Juin_Juillet_Aout_Septembre_Octobre_Novembre_Decembre'.split('_'),
            monthsShort: 'Janv_Fevr_Mars_Avr_Mai_Juin_Juil_Aout_Sept_Oct_Nov_Dec'.split('_'),
            firstDayOfWeek: 1
        },
        natures: [],
    }
},
methods: {
    reset() {
        this.$refs.dtedeb.resetValidation(); this.$refs.dtefin.resetValidation()
    }
}
});

All controls are ok, but I want use resetValidation function of q-input to reset errors on 2 dates and after apply rules. Cause I put startdate bigger than enddate : error appear on startdate. But If I change enddate, my old error stay on startdate.
I put a button to reset... but I would like an automatical system
Thanks for your help

A: I think that by using watch properties, your problem can be solved
watch: {
   model: {
      handler() {
         this.reset();
      },
      deep: true,
   }
}

I do not know if it's ok, can be adapted according to your data
deep: true allows you to inherit from the method on other properties of your object
https://v2.vuejs.org/v2/guide/computed.html#Watchers
see you
edit 11/12
here is an example of watch properties
https://jsfiddle.net/alexisgt01/nhatL8cv/15/

A: Thanks, I didn't understand watch clearly. I just begin with Vue.
I find another and simplier way. Use the rule.
resetValidation is a function return void then I just call it in first like that
 ConfirmDateRange() {
        return [
            (v) => (this.$refs.dtedeb.resetValidation()|| this.$refs.dtefin.resetValidation() || !!v) || "Saisissez quelque chose :-)",
            (v) => regex.test(v) || "Format de date à utiliser: JJ/MM/AAAA",
            (v) => this.model.dateFin > this.model.date || "Date incohérente"
        ]
    }

It's ok now
Hope that can help others :-)

A: Currently, there is a big issue open, for now I recommend use vcalendar.io


text:
Q: Birkhoff-Grothendieck confusion I encountered what looks like a contradiction to the Birkhoff-Grothendieck theorem, so I am hoping somebody can point out where I am confused.
Let $\ell \subset V \subset \mathbb{P}^n$ be a line contained in a hypersurface of degree $d$. In $\mathbb{P}^n$, $\ell$ is the transverse intersection of $n-1$ hyperplanes, so its normal bundle is
$$N_{\mathbb{P}^n/\ell} \cong (n-1)[H]\big|_\ell = \mathcal{O}(1)^{\oplus n-1}.$$
But we also have
$$N_{\mathbb{P}^n/\ell} \cong N_{V/\ell} \oplus N_{\mathbb{P}^n/V} = N_{V/\ell} \oplus d[H]\big|_\ell = N_{V/\ell} \oplus \mathcal{O}(d).$$
By Birkhoff-Grothendieck, $N_{V/\ell}$ factors as a sum of line bundles, giving a factorization of $N_{\mathbb{P}^n/\ell}$, and further that factorization is supposed to be unique up to reordering. How does one factorization have an $\mathcal{O}(d)$ summand while the other does not?

A: Let me explain the error in the arguments above. The normal bundle to $\ell$ is not a direct sum$$N_{\ell/V} \oplus N_{V/\mathbb{P}^n}.$$For this to be true the line should be a section of $V$ by a some linear $2$-space, which is possible only if$$\deg V = 1.$$


text:
Q: Classifying Singular Points as Regular/Irregular for Differential Equation The question asks to find the singular points of the Differential Equation and to classify each of them as regular/irregular:
$x(x^2+1)^2y''+y=0$
Edit: I gave it another shot and I ended up with 3 singular points:
$x=0$ (regular singular point)
$x=+i$ (irregular singular point)
$x=-i$ (irregular singular point)
Could you kindly let me know if I found the correct solution? Thank you for your time.


text:
Q: Ansible loop over a list to define a dynamic dictionary I am trying to define a dictionary FACTS_VAR in which the key must contain the word SUB. Argument_value and the value is true but when I loop over the variable Argument
hosts: all
gather_facts: true

vars:

  Argument:
    - value1
    - value2

tasks:

- name: DEFINING A variable
  set_fact:
    FACTS_VAR: {'SUB..item': true}
  loop: "{{Argument}}"

- debug:
    var: FACTS_VAR

I got this result so I don't know what is missing there. I am expecting to get a dictionary like this
FACTS_ENTRY:
   SUB.value1: true
   SUB.value2: true

TASK [debug] *****************************************************************************************************************
ok: [control] => {
    "FACTS_ENTRY": {
        "SUB..item": true
    }
}
ok: [ansible4] => {
    "FACTS_ENTRY": {
        "SUB..item": true
    }

A: Create the keys
facts_entry_keys: "{{ ['sub']|product(argument)|map('join','.')|list }}"

gives
facts_entry_keys:
  - sub.value1
  - sub.value2

Create the dictionary
facts_entry: "{{ dict(facts_entry_keys|product([true])) }}"

gives
facts_entry:
  sub.value1: true
  sub.value2: true

Example of a complete playbook
- hosts: localhost
  vars:
    argument:
      - value1
      - value2
    facts_entry_keys: "{{ ['sub']|product(argument)|map('join','.')|list }}"
    facts_entry: "{{ dict(facts_entry_keys|product([true])) }}"
  tasks:
    - debug:
        var: facts_entry

A: From your current description I understand only that you probably like to define variables somehow dynamically.
The following example could give some guidance.
---
- hosts: test
  become: false
  gather_facts: false

  vars:

    ARG:
      - val1
      - val2

  tasks:

  - name: Dynamically define variable
    set_fact:
      FACTS_VAR: "{ 'SUB_{{ item }}': true }"
    loop: "{{ ARG }}"

  - debug:
      var: FACTS_VAR

resulting into an output of
TASK [Dynamically define variable] **
ok: [test.example.com] => (item=val1)
ok: [test.example.com] => (item=val2)

TASK [debug] ************************
ok: [test.example.com] =>
  FACTS_VAR:
    SUB_val2: true

Please take note that according your current description there can be only one value as result.
Further Q&A

*

*Build variable name at play level


text:
Q: Umbraco 7 in Azure cloud as web roles I have been trying to get Umbraco working in a web role environment (web services) in Azure, but the site errors when you try and access it, saying that config/trees.config is not accessible.
These are the steps i carried out:

*

*Create a new empty MVC4 project in Visual Studio 2013

*Install Umbraco v7.1.8 from nuget

*Run up and configure using a new azure SQL database.

*Added in the umbraco folders to the solution.

*Added an azure web services project to the solution.

*Added the existing MVC umbraco project to the azure role profiles.

*Published to Azure staging area.

The site starts up with the usual 'Looks like there is still work to do' screen in the full Azure emulator in visual studio with multiple role instances. However fails to run up when hosted in Azure.
I am currently assuming that the issue is that the site root does not have write access when hosted in Azure, so the IIS worker process cannot write to the trees.config file.
I found an article where you can add a 'startup.bat' file, with the following:
echo "starting startup task" >> log.txt
%windir%\system32\Icacls.exe .. \* /T /grant "Network Service":(F) > log.txt

But this stops the role instances for starting up at all in both the emulator and when hosting in azure.
Any suggestions would be gratefully appreciated

A: I would suggest using a VM instead of a web role for hosting Umbraco in Azure, particularly since Umbraco is needing local write access to persist.
Web roles expect your application to be stateless, meaning no writing or persisting anything to the actual file system.  This guarantee allows Azure to make certain assumptions so that it can load balance and scale the application correctly (it basically saves a master copy and then re-deploys it fresh as it scales up or makes updates, etc.  This works great for web apps that were created with this in mind, but if not, then a VMs allows you to scale UP without worrying about your app needing to work a certain way to properly scale OUT under a load balancer (which is what web roles are made to help you do).
So, basically I would suggest installing to a Virtual Machine.  It's still in the cloud, and you get all the cloud benefits of on-demand scaling of the infrastructure.  In addition, I would expect Virtual Machines to be a supported install of Umbraco, where a web role install would not.  Hope that helps!


text:
Q: How does a defect rate scale with the area of a wafer? this is my first time posting here so hopefully I'm not breaking any rules. I have a fairly simple question but I can't seem to wrap my head around it. I'm currently reading "Computer architecture: A quantitative approach" and in chapter 1 the writers mention defect rates in integrated circuit wafers. A 28nm process will have "0.016-0.047 defects per square centimeter". I'm somehow not sure if this represents a percentage or simply a quantity, but I'm guessing it's not a percentage because percentages scale with any area, i.e. they wouldn't mention an area. I want to know how this would scale to square meters. I understand that cm^2 scales to m^2 by a factor of 10^4, so does this mean that the defects per square meters is 160-470? Or are there other factors to take into account when scaling areas like this?

A: Yes, that's correct.
'$0.016 - 0.047$ defects per square centimeter' means for $1$ square centimeter, there will be between $0.016$ and $0.047$ defects.
Therefore, for $1$ square meter $=$ $10^4$ square centimeters, there will be between $0.016 \cdot 10^4 = 160$ and $0.047 \cdot 10^4 = 470$ defects.


text:
Q: Semicontinuity and cohomological flatness for algebraic spaces Let $f \colon X \to S$ be a proper morphism form a seperated algebraic space $X$ to an affine noetherian scheme $S$.
Given a coherent sheaf $F$ on $X$, we know from Knutson's book, that the finiteness theorem holds: The $R^qf_*F$ are finite $\mathcal O_S$-modules. For complete $S$, we also have the theorem of formal functions.
Now, let us assume that $F$ is flat over $S$. If $X$ were a scheme, we would know that the function on $S$, given by the dimension of the cohomology of $F$ restricted to fibers, is upper semicontinous. Is the same also true for $X$ an algebraic space?
Moreover, if we knew that for some $i \ge 0$ the function $s \mapsto h^i(X_s, F_s)$ is constant, than for $X$ a scheme, it would follow that the base change map $R^i f_* (F) \otimes k(s) \to H^i(X_s, F_s)$ is an isomorphisms. What about algebraic spaces?
many thanks in advance.

A: This is definitely true and there ought to (but may not)  exist a reference. One
way to prove it is just to check that the usual proof for schemes extends. If we
follow Hartshorne for instance the crucial part is Proposition III:12.2 which
can be proven using an étale affine cover instead of an open affine one.


text:
Q: OSX 10.9.5 upgrade causes apache/php downgrade Today I installed the OSX 10.9.5 upgrade and it appears to have downgraded my Apache and PHP version.
Is there an easy way to reverse this unwanted downgrade?
Or do I have to reinstall apache via homebrew again?

A: I replaced the following line in httpd.conf:
LoadModule php5_module libexec/apache2/libphp5.so
With:
LoadModule php5_module /usr/local/Cellar/php55/5.5.12/libexec/apache2/libphp5.so
This seems to have restored a lot of my old setup and I can work again.


text:
Q: Simulating the range-based for loop's begin/end behavior Consider the specification of the range-based for loop's begin-expr and end-expr (N4140 [stmt.ranged]/p1). Given a range __range of type _RangeT,

begin-expr and end-expr are determined as follows:

*

*if _RangeT is an array type, begin-expr and end-expr are __range and __range + __bound, respectively, where __bound is
  the array bound. If _RangeT is an array of unknown size or an array
  of incomplete type, the program is ill-formed;

*if _RangeT is a class type, the unqualified-ids begin and end are looked up in the scope of class _RangeT as if by class member access
  lookup (3.4.5), and if either (or both) finds at least one
  declaration, begin-expr and end-expr are __range.begin() and
  __range.end(), respectively;

*otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin and end are looked up in
  the associated namespaces (3.4.2). [ Note: Ordinary unqualified
  lookup (3.4.1) is not performed. —end note ]

Is it possible to simulate this exact behavior in ordinary C++ code? i.e., can we write a magic_begin and a magic_end function template such that
for(auto&& p : range_init) { /* statements */ }

and
{
    auto&& my_range = range_init;
    for(auto b = magic_begin(my_range), e = magic_end(my_range); b != e; ++b){
        auto&& p = *b;
        /* statements */
    }
}

always have the exact same behavior?
Non-answers include qualified calls to std::begin/std::end (doesn't handle the third bullet, among other things) and using std::begin; begin(range); because, among other things, that is ambiguous if ADL for begin finds an overload that's equally good as std::begin.

For illustration, given
namespace foo {
    struct A { int begin; };
    struct B { using end = int; };
    class C { int* begin(); int *end(); }; // inaccessible
    struct D { int* begin(int); int* end();};
    struct E {};

    template<class T> int* begin(T&) { return nullptr; }
    template<class T> int* end(T&) { return nullptr; }
}

foo::A a; foo::B b; foo::C c; foo::D d; foo::E e;

I want magic_begin(a)/magic_begin(b)/magic_begin(c)/magic_begin(d) to be a compile error, and magic_begin(e) to return (int*)nullptr.

A: The following SFINAE-friendly approach seems to work as desired (see below for exceptions):
#include <type_traits>

namespace detail {
    struct empty {};
    template <typename T>
    using base = std::conditional_t<std::is_class<T>{} && not std::is_final<T>{},
                                    T, empty>;

    struct P1 {typedef int begin, end;};
    template <typename U>
    struct TestMemType : base<U>, P1 {
        template <typename T=TestMemType, typename=typename T::begin>
        static std::true_type test_begin(int);
        template <typename T=TestMemType, typename=typename T::end>
        static std::true_type test_end(int);

        static std::false_type test_begin(float), test_end(float);
    };

    template <typename T>
    constexpr bool hasMember = !decltype(TestMemType<T>::test_begin(0)){}
                            || !decltype(TestMemType<T>::test_end(0)){};

    //! Step 1
    template <typename T, std::size_t N>
    constexpr auto begin(int, T(&a)[N]) {return a;}
    template <typename T, std::size_t N>
    constexpr auto end(int, T(&a)[N]) {return a+N;}

    //! Step 2 - this overload is less specialized than the above.
    template <typename T>
    constexpr auto begin(int, T& a) -> decltype(a.begin()) {return a.begin();}
    template <typename T>
    constexpr auto end(int, T& a) -> decltype(a.end()) {return a.end();}

    //! Step 3
    namespace nested_detail {
        void begin(), end();
        template <typename T>
        constexpr auto begin_(T& a) -> decltype(begin(a)) {return begin(a);}
        template <typename T>
        constexpr auto end_(T& a) -> decltype(end(a)) {return end(a);}
    }
    template <typename T, typename=std::enable_if_t<not hasMember<std::decay_t<T>>>>
    constexpr auto begin(float, T& a) -> decltype(nested_detail::begin_(a))
    {return nested_detail::begin_(a);}
    template <typename T, typename=std::enable_if_t<not hasMember<std::decay_t<T>>>>
    constexpr auto end(float, T& a) -> decltype(nested_detail::end_(a))
    {return nested_detail::end_(a);}
}

template <typename T>
constexpr auto magic_begin(T& a) -> decltype(detail::begin(0, a))
{return detail::begin(0, a);}
template <typename T>
constexpr auto magic_end  (T& a) -> decltype(detail::end  (0, a))
{return detail::  end(0, a);}

Demo. Note that GCCs lookup is broken as it doesn't consider non-type names for typename T::begin in TestMemType::test_end/begin. A workaround sketch can be found here.
The check in step 2 requires that the class type be derivable, which implies that this method doesn't properly work with final classes or unions - if those have an inaccessible member with name begin/end.

A: Almost.
Doing #1 if it works, and if not #2 if it works, and if not #3 is a pretty basic tag dispatching/sfinae exercise.
For #3:
Create a namespace that is used nowhere else.  Nest it in another.
In the outer, put a =delete begin function that takes anything.
Put a helper function that calls begin in it.
That will find the adl begin, and otherwise the deleted begin.
The failure mode is that the namespaces could be used somewhere else; there is no way to prevent it.


text:
Q: Функция Random.Range() выдает ошибку Код:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = System.Random;

public class MeteorSpawn : MonoBehaviour
{
    public GameObject mateorPrefab;
    public float maxSpawnDelay = 3f;
    public float minSpawnDelay = 1f;

    public float spawnXLimit = 6f;

    private void Start()
    {
        Spawn();
    }

    private void Spawn()
    {
        float random = Random.Range(-spawnXLimit, spawnXLimit);
    }
}

Unity выдает ошибку:

Random does not contain a definition for Range()

A: Всё правильно, вы пытаетесь использовать Random  непосредственно от C#, а надо от Unity.
Удалите строку using Random = System.Random;


text:
Q: Question about a definition in topology If $X$ is a continuum (a compact connected metric space), then $$\text{Span}(X) =\sup
_{Z}
\inf_{(x,y)∈Z}d(x, y)$$
where $Z$ ranges over all (non-empty) continua $Z \subseteq X × X$ with $π_1(Z) = π_2(Z)$.
That is the definition.
My question: Is $\text{Span}(X)=0$ equivalent to $Z\cap \Delta\neq\varnothing$ for every (non-empty) continuum $Z \subseteq X × X$ with $π_1(Z) = π_2(Z)$?
($\Delta$ is the diagonal in $X\times X$)

A: I think you are right. $Z$ is compact and $d$ is continuous, so it attains its minimum. Hence, the infimum is $0$ iff $Z$ intersects the diagonal. And so the span is $0$ iff every admissible $Z$ intersects the diagonal.


text:
Q: MVC client-side validation for multiple models I have three models: VehicleType, VehicleModel, and VehicleManufacturer.
Both VehicleType and VehicleManufacturer point to VehicleModel in the model, like so:
public class VehicleModel
{
    [Key]
    public int ModelId { get; set; }

    [Required(ErrorMessage = "Field is Required")]
    public int TypeId { get; set; }

    [Required(ErrorMessage = "Field is Required")]
    public int ManufacturerId { get; set; }
    public string ModelName { get; set; }

    public VehicleType VehicleType { get; set; }
    public VehicleManufacturer Manufacturer { get; set; }

}

From there, VehicleModel points to the InventoryModel:
 public class Inventory
{
    [Key]
    public int InventoryId { get; set; }
    public int Price { get; set; }
    public int Mileage { get; set; }
    public int Year { get; set; }

    public int ModelId { get; set; }
    public VehicleModel VehicleModel { get; set; }
}

My problem is when I try to get client-side validation working on all three dropdownlists (VehicleType, VehicleManufacturer, VehicleModel), it only works with VehicleModel.
What needs to be done to validate these two dropdownlists using these models?
Here is my controller (fyi):
 // GET: /Inventory/Create
    public ActionResult Create()
    {
        ViewBag.TypeId = new SelectList(db.Types, "TypeId", "TypeName"); //(Object List, Value Field (usually Id), Column)
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName"); //(Object List, Value Field (usually Id), Column)
        ViewBag.ManufacturerId = new SelectList(db.Manufacturers, "ManufacturerId", "ManufacturerName"); //(Object List, Value Field (usually Id), Column)

        return View();
    }

    // POST: /Inventory/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Inventory inventory, VehicleManufacturer VehicleManufacturer, VehicleType VehicleType)
    {
        if (ModelState.IsValid)
        {
            db.Inventorys.Add(inventory);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.TypeId = new SelectList(db.Types, "TypeId", "TypeName");
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName");
        ViewBag.ManufacturerId = new SelectList(db.Manufacturers, "ManufacturerId",     "ManufacturerName");

        return View(inventory);
    }

View:

        @Html.LabelFor(model => model.VehicleModel.TypeId, "Some name for column")

        @Html.DropDownList("TypeId", String.Empty)

        @Html.ValidationMessageFor(model => model.VehicleModel.TypeId)

        @Html.LabelFor(model => model.ModelId, "Some name for column")

        @Html.DropDownList("ModelId", String.Empty)
        @Html.ValidationMessageFor(model => model.ModelId)

        @Html.LabelFor(model => model.VehicleModel.ManufacturerId, "Some name for column")

        @Html.DropDownList("ManufacturerId", String.Empty)
        @Html.ValidationMessageFor(model => model.VehicleModel.ManufacturerId)

Please someone help. I've been on this for many, many hours!

A: There are actually two problems That I see above
1) That you're not mapping the DropDownList and the ValidationMessageFor to the same model attribute.
@Html.ValidationMessageFor(model => model.VehicleModel.ManufacturerId)

The above is binding it to VehicleModel_ManufacturerId where as:
@Html.DropDownList("ManufacturerId", String.Empty)

the above is mapping the DropDown to just ManufacturerId
You need to change one or the other to match each other.
2) In the above code, I don't see any Validation Attributes. did you forgot them when you copied the code over here?
Hope this helps, Let me know if you needed more details.


text:
Q: Error: ASSERTION ERROR: Type passed in is not NgModuleType, it does not have 'ɵmod' property If i remove @NgModule i get this error.
Can anyone tell me what is an emod property.I googled a lot but couldnt find any information on this.Additionally can anyone give me resources which tell what all are injected by angular at run time.Actually i am afraid to ask this.I know this is a stupid question but still in a terrian where angular seems to me a blackbox.


text:
Q: How can I identify a ROI that is formed by many contours (canny image)? (OpenCV and Python) I'm newbie with OpenCV, but I'm tring to do a solution to identify flaws in a machining process in a specific Region of Interrest (ROI).
I wrote a code that can 'identify' this ROI and ignores the rest of the part, however I don't know how to create a filter in that region, because my Canny image is formed by a lot of small areas, and not by a single area.
What I want to do, is find a way to get ROI's bounding box (x,y,w,h) coordinates for after filter my input (webcam) image with this ROI and apply again the Canny method to identify this machining flaws
I put my code and a image from the metal part and the Canny image showing the ROI.  I've never use computer vision so I'd be very grateful if someone helps me.
def getContours(img):
contours, Hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for i in contours:
    area = cv2.contourArea(i)
    # print(area)
    if area>500:
        cv2.drawContours(img, i, -1, (255, 0, 0), 3)

return img

def empty(a):
    pass

def detect_cont(img, pos_min, pos_max):
    imgGray = convert_gray(img)
    imgBlur = cv2.GaussianBlur(imgGray,(7,7),1)
    imgContours = img.copy()
    imgCanny = cv2.Canny(imgBlur, pos_min, pos_max)  # 200,0

imgContours = getContours(imgCanny)

return imgCanny, imgContours

#cv2.imshow("Image", imgBlur)
#cv2.imshow("ImageCanny", imgCanny)
#cv2.waitKey(0)

if __name__ == '__main__':

#use_webcam()
#img = reading_image("Bad1.jpg")
#reading_video("")

#detect_cont(img)
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars", 640, 240)
cv2.createTrackbar("Min", "TrackBars", 50, 300, empty)
cv2.createTrackbar("Max", "TrackBars", 50, 300, empty)

cv2.namedWindow("preview")
vc = cv2.VideoCapture(cv2.CAP_DSHOW)
vc.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
vc.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
vc.set(cv2.CAP_PROP_FOURCC, 0x32595559)
vc.set(10, 150)
vc.set(cv2.CAP_PROP_FPS, 20)

if vc.isOpened():  # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

running, frame = vc.read()

good = 1
bad = 1

while rval:
    cv2.imshow("preview", frame)

    pos_min = cv2.getTrackbarPos("Min", "TrackBars")
    pos_max = cv2.getTrackbarPos("Max", "TrackBars")

    img_final, imgContours = detect_cont(frame, pos_min, pos_max)
    #cv2.imshow("Tons de Cinza", img_final)
    cv2.imshow("Densenhado", imgContours)

    rval, frame = vc.read()
    key = cv2.waitKey(20)

    if key == 27:  # exit on ESC
        break

    if key & 0xFF == ord("q"):
        running = False

vc.release()
cv2.destroyWindow("preview")


text:
Q: Sending Email with attachments which are > 4MB Retrieving the token from the below code
var token = await GetAccessToken();
GraphServiceClient graphServiceClient =
  new GraphServiceClient($"{graphApi}/v1.0",
    new DelegateAuthenticationProvider(async(requestMessage) =>
    {
      requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", token);
    })
  );

sending Email using App permission using
graphServiceClient.Users[fromAddress]
  .SendMail(message, false)
  .Request()
  .PostAsync().Wait();

And attachments are been attached when created dynamically
attachments.Add(new FileAttachment
{
  ODataType = "#microsoft.graph.fileAttachment",
    ContentBytes = System.IO.File.ReadAllBytes(getAttachmentLocation() + attach.Name),
    ContentId = attach.Name,
    ContentType = "csv/html",
    Name = attach.Name,
    IsInline = false
});

Now the issue is email is not been triggered when the attachment size is more than 4MB.
Could someone help me understand how to fix this issue?
Do we have anything which actually increases the threshold of this 4MB or a newer version of Graph that supports attachments > 4 MB?

A: To send larger messages you have to create a draft message, and then add attachments.
If the attachment is larger than 3MB, you cannot send it with one request. Use UploadSession instead as described here: https://learn.microsoft.com/en-us/graph/sdks/large-file-upload?tabs=csharp


text:
Q: App that launches prefpane app I've been working on a .prefpane app and it's almost ready for the mac app store. The problem is that the product created from this app is a .prefpane file and not a .app file so as I see it I need to create an app that launches this .prefpane file so I was wondering how to do that?
Hope this makes sense!
Thank you in advance!

A: Per the Mac App Store Review Guidelines sections 2.15, 2.30, and probably some others, .prefpanes aren't allowed in the App Store.


text:
Q: Trying to drop database only if it does not exist by using the db_id function fails When the database foo is not yet created and I I run this
IF db_id(N'foo') IS NOT NULL
BEGIN
  ALTER DATABASE [foo] SET OFFLINE
  GO

  DROP DATABASE [foo]
  GO
END

I get a message

Cannot drop the database 'foo' becuase it does not exist or you do not
  have permission.

Why?
I have confirmed that the sql statement select db_id(N'foo') returns NULL.

A: This is a parsing error, not a runtime error. You can avoid this by removing the GO commands (these can't exist inside an IF block anyway) and using dynamic SQL.
Why IF DB_ID() instead of just putting the DROP inside TRY/CATCH (or letting it error)?
You may want WITH ROLLBACK IMMEDIATE on the ALTER.
BEGIN TRY
  ALTER DATABASE foo SET OFFLINE WITH ROLLBACK IMMEDIATE;
  DROP DATABASE foo;
END TRY
BEGIN CATCH
  PRINT 'Failure or database does not exist.';
END CATCH

Or
IF DB_ID(N'foo') IS NOT NULL
BEGIN
  EXEC sys.sp_executesql N'ALTER DATABASE foo SET OFFLINE WITH ROLLBACK IMMEDIATE;
    DROP DATABASE foo;';
END

Of course this approach (OFFLINE first) will leave the data and log files intact, which means that if they were created in the default location, if you try to create the same database again, you'll first need to move or rename those files, or manually specify different names in the new file specification.

A: Below should work
If exists (select 1 from master.sys.databases where name ='db you want to check')
  Begin
    Alter database db-name set restricted user with rollback immediate ;
    Drop database db-name;
  End
Else
  Print 'db does not exist '

Note: If you offline the database and drop the database, the mdf and ldf files will still remain on disk and you have to manually delete them.


text:
Q: Do I need to use a broadcast variable when using variable in foreachRDD? In my code, I subscribe to a Kafka stream and process each RDD in a function:
  val myStream = KafkaUtils.createDirectStream[K, V](
      streamingContext,
      PreferConsistent,
      Subscribe[K, V](topics, consumerConfig)
    )

  val myMap: Map[ObjA, ObjB] = getMyMap() // This is the variable I want to access in 'process'

  def process(record: (RDD[ConsumerRecord[String, String]], Time)): Unit = record match {

     // Code that uses myMap.get("key")

  }

  myStream.foreachRDD((x, y) => process((x, y)))

I read this post about Spark and Kafka integration patterns. As far as I understood, foreachRDD is executed locally on the driver, but then any inner loops are distributed to cluster nodes. Does that mean that I should broadcast myMap for performance reasons?

A:
Does that mean that I should broadcast myMap for performance reasons?

Well:

*

*If you don't The data broadcasted this way is cached in serialized form and deserialized before running each task.

*If you do, Spark will keep a copy on each executor, and reuse when needed.

Because variable is reused across multiple tasks, there is a value in broadcasting, especially if data is large enough to add significant overhead.
If not, it might be preferebale to stick with closure serialization for better readability (I acknowledge this is a matter of preference).

A:
but then any inner loops are distributed to cluster nodes

It isn't "any inner loops" which are distributed, but operations on RDD.
So it depends on how exactly myMap.get("key") is used inside process. E.g. here is an example where broadcasting is completely pointless:
def process(record: (RDD[ConsumerRecord[String, String]], Time)): Unit = record match {
  case (rdd, _) => rdd.take(10).filter(/* do something using myMap */)
}