text:
Q: JavaScript inheritance extend function I'm having some trouble understanding the IF clause at the end of this function from Pro JavaScript Design Patterns:
function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;

    subClass.superclass = superClass.prototype;
    if(superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

The book explains that these lines ensure that the superclass's constructor attribute is correctly set, even if the superclass is the Object class itself.  Yet, if I omit those three lines and do the following:
function SubClass() {};
extend(SubClass, Object);

alert(Object.prototype.constructor == Object);

The alert says 'true', which means the superclass's constructor is set correctly even without those last three lines.  Under what conditions, then, does this IF statement do something useful?
Thanks.

A: The problem that those two lines try to avoid, is generally produced when you replace the prototype property of a Constructor Function, for example:
function Foo () {};
Foo.prototype = {
  bar: 'baz'
};

var foo = new Foo();
foo.constructor === Object; // true, but `constructor` should refer to Foo

When functions objects are created, the prototype property is initialized with a new object, which contains a constructor property that refers to the function itself, e.g.:
function Bar () {};
var bar = new Bar();
bar.constructor === Bar; // true

When you replace the prototype property with another object, this object has it's own constructor property, generally inherited from other constructor, or from Object.prototype.
var newObj = {};
newObj.constructor === Object;

Recommended articles:

*

*Constructors considered mildly confusing

*JavaScript Prototypal Inheritance


text:
Q: socket.io terminating on second http request I have a little node.js app that uses subdomains to shorten links which are submitted in the site's path (i.e. requesting http://a.example.com/google.com makes it so a.example.com redirects to google.com in the future).
I wanted to use socket.io to make it so the subdomain was parked only as long as a user had the redirection page (store.html) open. Using the open connection, I could also send the user a notification that the page was accessed by someone else, etc.  I am tracking the status of this store.html connection by watching for the socket.io disconnection event.
server:
var app = require('express')()
, fs = require ('fs')
, http = require('http').createServer(app)
, io = require('socket.io')(http)
, links = {};

app.get('/favicon.ico',function(r,s){});
app.get('/',function(req,res) {
  var subd=req.subdomains[0];
  if (!subd) {
    res.sendfile(__dirname + '/public/index.html');
  } else {
    if (link[subd]) {
      res.redirect(link[subd].URL);
    } else {
      res.send('nothing saved here');
    }
  }
});
app.get('*',function(req,res) {
  var subd=req.subdomains[0];
  if (!subd) {
    res.send('invalid URL');
  } else  if (link[subd]) {
    res.send('subdomain in use');
  } else {
    var URL=req.originalUrl.substring(1);
    link[subd]={ URL: (/^\w+:\/\//.test(URL) ? URL : (/^\w+\.\w+/.test(URL) ?  http://'+URL : 'http://google.com')) };
    res.sendfile(__dirname+'/public/store.html');
  }
});

io.on('connection', function(socket) {
  socket.on('subd',function(subd) {
    socket.subd=subd;
    link[subd].socket=socket;
    socket.emit('content',link[subd].URL);
  });
  socket.on('disconnect',function() {
    delete link[socket.subd];
  });
});

store.html:

  HTML / Link

The problem I'm running into is that if I connect to the subdomain within the same browser, I get a "transport error" and disconnection event, closing the socket and triggering the deletion of the subdomain from the link object.  How can I keep the socket open when I access the same page in a new tab? How are the two linked?
restated, this is how the problem happens:

*

*visit http://link.example.com/google.com

*visit link.example.com , redirects to google

*socket closes unexpectedly

*visit link.example.com, receive response indicating emptiness

redpajama_set_name: RedPajamaStackExchange


text:
Q: Printing out file/folder permissions I need a solution how to print out file permissions in a python script. The idea is to pass shell command $: ls -l to a python script, from where I'll print out the lines with "additional explanation". For example
-rwxrwxr-x
The additional explanation would be:
Owner of the file has reading rights, writing right, but doesn't have execution rights.
Group has reading rights, writing right and execution rights.
So, instead of covering all the possible cases of who has what rights, is there any easier way to do this besides checking each case with an if conditional?

A: Here's some code to get you started.
We first create a list named modes containing all the combinations of who has the permission and the kind of permission they have. Then we loop over the mode string and our modes list in parallel, grabbing the associated combination from modes if the mode string doesn't have a - in that position.
modes = [(who, kind) for who in ('user', 'group', 'others')
    for kind in ('read', 'write', 'execute')]

def explain_modestring(modestring):
    return ', '.join([' can '.join(t)
        for c, t in zip(modestring[1:], modes) if c != '-'])

for s in ('-rwxrwxrwx', '-rwxr-xr--', '-r--------'):
    print(s, explain_modestring(s))

output
-rwxrwxrwx user can read, user can write, user can execute, group can read, group can write, group can execute, others can read, others can write, others can execute
-rwxr-xr-- user can read, user can write, user can execute, group can read, group can execute, others can read
-r-------- user can read


text:
Q: Custom options in Joomla! component help I am building a module, or component not sure yet, but I need to have a some options that depend on another option. For example, if you choose "A" then options 1, 2 and 3 appear. If you choose "B" then 4,5 and 6 appear.
I can make everything appear at once just sending in the  but can I make some params only appear after another is chosen?
Thank you.

A: This should be reasonably simple to achieve using javascript (i.e. it will run on the user's PC without a round-trip back to the server).
Put all the controls on the form, but for the ones that you do not wish to display initially use the CSS attribute {display:none} and they won't show.
Then use the onclick() event of the control which will determine whether other controls are made visible to show / hide controls as you wish.
There is an example of something similar to this (not within Joomla, but there is no reason (that I can think of) why this won't also work fine within a Joomla module / component) here: http://www.java2s.com/Code/JavaScript/Development/Makebuttoncontrolvisibleorinvisible.htm


text:
Q: Converting Makefile to CMakeLists.txt I'm using a developement board that has its own libraries. I have installed ROS on it and now I need to use publish/subscribe by including its libraries to the CMakeLists.txt of the package. I have to also note that I use Eclipse for compilation, so the CMakeLists.txt is in that form. Here is the Makefile of hardware library that I want to use in CMakeLists.txt:
DIR=$(shell pwd)/../

INCS = -I.\
        -I$(DIR) \
        -I$(DIR)/hardware \
        -I$(DIR)/hardware/environment \
        -I$(DIR)/hardware/environment/cores \
        -I$(DIR)/hardware/environment/cores/environment \
        -I$(DIR)/hardware/environment/variants \
        -I$(DIR)/hardware/environment/variants/sunxi \
        -I$(DIR)/libraries \
        -I$(DIR)/libraries/Serial \
        -I$(DIR)/libraries/SPI \
    -I$(DIR)/libraries/Wire \
    -I$(DIR)/libraries/LiquidCrystal \
    -I$(DIR)/Basibos/include LIBS=../libenvironment.a TARGET=../output/test

OBJS = BasibosAnaProgram

all:
    @mkdir -p $(TARGET)
    for i in $(OBJS); do echo "$(CXX) $(INCS) $$i.cpp -o $(TARGET)/$$i $(LIBS)"; done
    @for i in $(OBJS); do $(CXX) $(INCS) $$i.cpp -o $(TARGET)/$$i $(LIBS); done

clean:
    @for i in $(OBJS); do rm -f $(TARGET)/$$i; done

And here is the example CMakeLists.txt that Makefile should be included:
cmake_minimum_required(VERSION 2.4.6)
include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake)

rosbuild_init()

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)

rosbuild_add_library(${PROJECT_NAME} src/Basibos.cpp)
rosbuild_add_library(${PROJECT_NAME} src/HedefeGitme.cpp)
rosbuild_add_library(${PROJECT_NAME} src/Konum.cpp)
rosbuild_add_library(${PROJECT_NAME} src/Robot.cpp)
rosbuild_add_library(${PROJECT_NAME} src/Sonar.cpp)
rosbuild_add_library(${PROJECT_NAME} src/Zaman.cpp)
rosbuild_add_library(${PROJECT_NAME} src/XMLAyiklayici.cpp)

rosbuild_add_executable(srctest RobotKontrol.cpp)

target_link_libraries(srctest ${PROJECT_NAME})

I'm stuck and can't go forward without help. Any help will be greately appreciated. Thanks in advance

A: Source: http://www.ros.org/wiki/rosbuild/CMakeLists
You have to add the source files in following fashion:
rosbuild_add_library(XmlRpc src/XmlRpcClient.cpp
                   src/XmlRpcDispatch.cpp
                   src/XmlRpcServer.cpp
                   src/XmlRpcServerConnection.cpp
                   src/XmlRpcServerMethod.cpp
                   src/XmlRpcSocket.cpp
                   src/XmlRpcSource.cpp
                   src/XmlRpcUtil.cpp
                   src/XmlRpcValue.cpp)


text:
Q: Siri Shortcuts: How to require unlocking the phone Siri Intent: Is it possible to require that the user to unlock the iPhone before the execution take place? I don't want the Intent to cause the corresponding iOS app to be launched.
If I uncheck the "Supports background execution" box (shown below), Siri requires the devices to be unlocked but it also launches the app and I don't want that.

A: Found the answer. See the screenshot. In the Intent definition file, set the "authentication" to "Restricted While Locked"


text:
Q: Check if Clipboard.GetImage() is transparent in C# I think I have a simple problem that seems very hard for me to figure out - how to check if an image I get from Clipboard.GetImage() uses transparency. If it does then I will show it in a PictureBox with the transparent background.
I copy the picture directly from the application - e.g. the browser or one of the Windows image viewers. Pasting the picture to e.g. Word will get the transparent background.
I am using this code:
// Check if the picture in clipboard has any transparency (alpha channel != 255)
Bitmap img = new Bitmap(Clipboard.GetImage());
for (int y = 0; y < img.Height; ++y)
{
    for (int x = 0; x < img.Width; ++x)
    {
        if (img.GetPixel(x, y).A != 255)
        {
            Debug.WriteLine("Picture is transparent - set breakpoint here");
        }
    }
}
...

// Show the picture with transparent background - this works fine
img.MakeTransparent(img.GetPixel(0,0));
myPictureBox.Image = (Image)img;

I am trying with various pictures found on the net and I can copy/paste those pictures with the transparent background so I know they are transparent but no pictures will trigger the Debug.WriteLine and all values equals 255?
Though I recognize this has been asked before then I must be doing something wrong since this simple example does not work? Also they are old so maybe there is a new and better way? I have tried to find other solutions besides these:

*

*Detecting if a PNG image file is a Transparent image?

*Check to see if image is transparent
.. and more also not from StackOverflow. I have seen both really simple solutions and horrofying complex ones - but still none of them seems to work.
is this because the clipboard object cannot see the transparency or .. ?

A: I ended up this solution, based on the comment from @Jeff, CopyTransparentImages. This will get the (real?) image from the clipboard (which will also include the alpha channel) and then I will check if the image contains any transparency afterwards. If it does then I will make the image background color transparent, according to my original question, before I show it in a PictureBox.
// Get the image formats from clipboard and check if it is transparent
Image imgCopy = GetImageFromClipboard();
bool isClipboardImageTransparent = IsImageTransparent(imgCopy);
if (isClipboardImageTransparent)
{
    ...
}

// Get the real image from clipboard (this supports the alpha channel)
private Image GetImageFromClipboard()
{
    if (Clipboard.GetDataObject() == null) return null;
    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Dib))
    {

        // Sometimes getting the image data fails and results in a "System.NullReferenceException" error - probably because clipboard handling also can be messy and complex
        byte[] dib;
        try
        {
            dib = ((System.IO.MemoryStream)Clipboard.GetData(DataFormats.Dib)).ToArray();
        }
        catch (Exception ex)
        {
            return Clipboard.ContainsImage() ? Clipboard.GetImage() : null;
        }

        var width = BitConverter.ToInt32(dib, 4);
        var height = BitConverter.ToInt32(dib, 8);
        var bpp = BitConverter.ToInt16(dib, 14);
        if (bpp == 32)
        {
            var gch = GCHandle.Alloc(dib, GCHandleType.Pinned);
            Bitmap bmp = null;
            try
            {
                var ptr = new IntPtr((long)gch.AddrOfPinnedObject() + 40);
                bmp = new Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, ptr);
                return new Bitmap(bmp);
            }
            finally
            {
                gch.Free();
                if (bmp != null) bmp.Dispose();
            }
        }
    }
    return Clipboard.ContainsImage() ? Clipboard.GetImage() : null;
}

// Check if the image contains any transparency
private static bool IsImageTransparent(Image image)
{
    Bitmap img = new Bitmap(image);
    for (int y = 0; y < img.Height; ++y)
    {
        for (int x = 0; x < img.Width; ++x)
        {
            if (img.GetPixel(x, y).A != 255)
            {
                return true;
            }
        }
    }
    return false;
}

At least this is working for me :-)


text:
Q: CraueFormBundle : create a form flow from several entities I'm trying to make a multi-step form with CraueFormFlow. The CraueForm need a class to hydrate but I have several entities so I dit a addChildWizard class where all I have my needed entities as properties like this :
    <?php

    namespace VS\CrmBundle\Entity;

    use Doctrine\Common\Collections\ArrayCollection;
    use VS\CrmBundle\Entity\MedicalRecord;
    use VS\CrmBundle\Entity\Person;
    use VS\CrmBundle\Entity\Relationship;
    use Doctrine\ORM\Mapping as ORM;

    /**
     *
     * Class AddChildWizard
     * @package VS\CrmBundle\Entity
     */
    class AddChildWizard
    {
        /**
         * Step 1
         *
         * @var Relationship
         */
        protected $currenUserChildRelationship;

        /**
         * Step 1
         *
         * @var Person
         */
        protected $child;

        /**
         * Step 2
         *
         * @var MedicalRecord
         */
        protected $childsMedicalRecord;

        /**
         * Step 3
         *
         * This is a collection of Relationship entities
         *
         * @var ArrayCollection
         */
        protected $childsFamily;

        public function __construct()
        {
            $this->childsFamily = new ArrayCollection();
        }
+ getters and setters

Then I have my flow class :
<?php

namespace VS\CrmBundle\Form\Wizard\AddChild;

use Craue\FormFlowBundle\Form\FormFlow;
use Craue\FormFlowBundle\Form\FormFlowInterface;

class AddChildFlow extends FormFlow {
    protected function loadStepsConfig()
    {
        return array(
            array(
                'label' => 'ChildData',
                'form_type' => 'VS\CrmBundle\Form\Wizard\AddChild\AddChildStep1'
            ),
            array(
                'label' => 'ChildMedicalRecord',
                'form_type' => 'VS\CrmBundle\Form\Wizard\AddChild\AddChildStep2'
            ),
            array(
                'label' => 'ChildFamily',
                'form_type' => 'VS\CrmBundle\Form\Wizard\AddChild\AddChildStep3'
            ),
            array(
                'label' => 'confirmation',
            ),
        );
    }
}

With one form for each step. For example step 1 is :
<?php

namespace VS\CrmBundle\Form\Wizard\AddChild;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use VS\CrmBundle\Entity\Person;
use VS\CrmBundle\Entity\Relationship;
use VS\CrmBundle\Form\PersonChildType;
use VS\CrmBundle\Form\RelationshipFromCurrentUserType;

class AddChildStep1 extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('currenUserChildRelationship', RelationshipFromCurrentUserType::class, array(
                'data_class' => Relationship::class
            ))
            ->add('child', PersonChildType::class, array(
                'data_class' => Person::class
            ));
    }

    public function getBlockPrefix()
    {
        return 'AddChildStep1';
    }
}

And the action is :
 public function addChildAction()
    {

        // Our form data class
        $formData = new AddChildWizard();

        // We call service (craue form flow)
        $flow = $this->get('vs_crm.form.flow.add_child');
        $flow->bind($formData);

        $form = $flow->createForm();

        if($flow->isValid($form))
        {
            $flow->saveCurrentStepData($form);

            if($flow->nextStep())
            {
                $form = $flow->createForm();
            }
            else
            {
                $child = $formData->getChild();
                $curentUserRel = $formData->getCurrenUserChildRelationship();
                $currentUser = $this->get('security.token_storage')->getToken()->getUser();
                $medicalRecord = $formData->getChildsMedicalRecord();
                $family = $formData->getChildsFamily();

                $curentUserRel->setSourceId($child);
                $curentUserRel->setDestinationId($currentUser);
                $medicalRecord->setPerson($child);

                foreach($family as $member)
                {
                    $member->setSourceId($child);
                }

                //return new JsonResponse(array($formData->getId()));

                // flow finished

                $em = $this->getDoctrine()->getManager();
                $em->persist($formData);
                $em->flush();

                $flow->reset();

                $this->addFlash('success', 'Your child has been saved.');
                return $this->redirectToRoute('vs_crm_parent_dashboard');

            }
        }

        return $this->render('VSCrmBundle:Parent:add-child.html.twig', array(
            'form' => $form->createView(),
            'flow' => $flow
        ));
    }

This works perfectly, but at the end I have this error :

Class "VS\CrmBundle\Entity\AddChildWizard" is not a valid entity or
  mapped super class.

So doctrine wants an entity with the @Entity annotation and a Identifier and our friend Doctrine want to save the identifier in the Database ....
Is there an other way to do this stuff without saving the id in the database or I should listen to our friend Doctrine ?

A: Ok, If it can help someone...
At the end I had $em->persist($formData);and this is why Doctrine wanted my class addChildWizard ($formData = new AddChildWizard();) to be an entity. What I did is :
 $em->persist($child);
 $em->persist($curentUserRel);
 $em->persist($medicalRecord);

 foreach($family as $familyMember)
 {
     $em->persist($familyMember);
 }

And now this multi-step form works perfectly !


text:
Q: using sql count in a case statement I have a table and i need to present the output in the following fashion.
tb_a:

col1  |  reg_id | rsp_ind

Count of rows with rsp_ind = 0 as 'New' and 1 as 'Accepted'
The output should be
NEW | Accepted
9   | 10

I tried using the following query.
select
  case when rsp_ind = 0 then count(reg_id)end as 'New',
  case when rsp_ind = 1 then count(reg_id)end as 'Accepted'
from tb_a

and i m getting output as
NEW | Accepted
NULL| 10
9   | NULL

Could someone help to me tweak the query to achieve the output.
Note : I cannot add a sum surrounding this. Its part of a bigger program and so i cannot add a super-query to this.

A: Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.
For example, here's a simple table Grades:
| Letters |
|---------|
| A       |
| A       |
| B       |
| C       |
We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):
SELECT
    COUNT(CASE WHEN Letter = 'A' THEN 1 END)           AS [Count - End],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)    AS [Count - Else Zero],
    SUM(CASE WHEN Letter = 'A' THEN 1 END)             AS [Sum - End],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END)   AS [Sum - Else Null],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)      AS [Sum - Else Zero]
FROM Grades

And here are the results (unpivoted for readability):
|    Description    | Counts |
|-------------------|--------|
| Count - End       |    2   |
| Count - Else Null |    2   |
| Count - Else Zero |    4   | *Note: Will include count of zero values
| Sum - End         |    2   |
| Sum - Else Null   |    2   |
| Sum - Else Zero   |    2   |
Which lines up with the docs for Aggregate Functions in SQL
Docs for COUNT:

COUNT(*) - returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression) - evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression) - evaluates expression for each row in a group, and returns the number of unique, nonnull values.

Docs for SUM:

ALL - Applies the aggregate function to all values. ALL is the default.
DISTINCT - Specifies that SUM return the sum of unique values.

A: The reason you're getting two rows instead of one is that you are grouping by rsp_ind in the outer query (which you did not, to my disappointment, share with us). There is nothing you can do to force one row instead of two without dealing with that GROUP BY item.

A: If you want to group the results based on a column and take the count based on the same, you can run the query as :
$sql = "SELECT COLUMNNAME,

COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'New',

COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'ACCPTED'

FROM TABLENAME

GROUP BY COLUMNANME";

A: CREATE TABLE #CountMe (Col1 char(1));

INSERT INTO #CountMe VALUES ('A');
INSERT INTO #CountMe VALUES ('B');
INSERT INTO #CountMe VALUES ('A');
INSERT INTO #CountMe VALUES ('B');

SELECT
    COUNT(CASE WHEN Col1 = 'A' THEN 1 END) AS CountWithoutElse,
    COUNT(CASE WHEN Col1 = 'A' THEN 1 ELSE NULL END) AS CountWithElseNull,
    COUNT(CASE WHEN Col1 = 'A' THEN 1 ELSE 0 END) AS CountWithElseZero
FROM #CountMe;

A: SELECT
    COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New",
    COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted"
from tb_a

You can see the output for this request HERE

A: Close... try:
select
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

A: select sum(rsp_ind = 0) as `New`,
       sum(rsp_ind = 1) as `Accepted`
from tb_a

A: ok. I solved it
SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
 `page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct (CASE WHEN page_pages.funnel_id != 0 then  page_pages.funnel_id ELSE NULL END ) ) as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE  smart_projects.status !=  0
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
GROUP BY `smart_projects`.`project_id`
ORDER BY `title` DESC


text:
Q: run mount as root inside udev rule A while ago I got an udev script to run when an usb-stick is inserted into Ubuntu 16.04 (server) machine. (I've been using that to mount stick to virtualbox guest.)
Now I want to do something different in that script (mount it in the host).
I've got an udev rule:
#/etc/udev/rules.d/10-usbmount.rules
KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/bin/su <username> -c /home/<username>/automount"

It calls the automount script which is currently:
LOG_FILE=/home/<username>/usb_log
echo "New usb device detected at $DEVNAM doing stuff
mount $DEVNAME /home/<username>/flashes_folder &>> $LOG_FILE
#mount /dev/sdb1 /home/<username>/flashes_folder &>> $LOG_FILE
ret=$?
echo "$ret" >> $LOG_FILE

(taken from here)
The log file contains the following output:
New usb device detected at /dev/sdb doing stuff
mount: only root can do that
1

Explicitly entering the disk path /dev/sdb1 (commented line) does result in the same error (the disk indeed is /dev/sdb1).
Apparently, /bin/su <admin_username> has not enough privileges. How do I fix that?

A: For an ordinary user to mount a volume (even if he has complete access to the device file) an entry in /etc/fstab is necessary. This obviously does not work well with dynamic device names.
udev can only add symlinks but not change the name of a block device. But the fstab entry needs the real name.
But instead of using the device name you could use the filesystem UUID. udev can make the device readable for your user and set a symlink so that your user script can determine the UUID.
fstab entry
UUID=8186709a-ab1f-4d18-80bb-b219cb126398 /mnt/tmp   ext4       defaults,noauto,user,nofail 0 0

mount script
current_uuid=$(blkid --output export /dev/myusb | grep ^UUID=)
mount "$current_uuid"

device mapper
A different approach would be to put a device mapper device on top of the USB device (man dmsetup). The advantage is that you get a static name that way, e.g. /dev/mapper/myusb. But I do not know how the DM device reacts if you pull the USB stick. You may need udev unplug rules to handle that. This seems much more complicated and is probably not worth the static name.

A: I've solved my problem without touching /etc/fstab by using pmount program. This program seems to be available in package repositories of multiple linux distributions.
On ubuntu automatically creates folders inside /media and mounts the disks to those. There seems to be no way to mount disks outside the /media but I personally have come to terms with that.
Program takes partition identifier (e.g. sdb1) as an argument. $DEVNAME available in udev script provides a disk identifier (e.g. sdb). With flash sticks it is reasonable to expect a disk to have only firs partition (sdb1).
So the working version of the script in the question would be:
LOG_FILE=/home/<username>/usb_log
echo "New usb device detected at $DEVNAM doing stuff
pmount "{$DEVNAME}1" &>> $LOG_FILE
ret=$?
echo "$ret" >> $LOG_FILE

As a final note: the script is run as root user and the script file must belong to the root. (on ubuntu)


text:
Q: php function always returns null I've got this php function:
function JobPollAsync(&$fp)
{
if (($fp === false) or ($fp==null)) {
        return false;
    }

if (feof($fp)) {
    fclose($fp);
    $fp = false;
    return false;
}

return fgets($fp, 1000);
}

The problem is that always return NULL. At first time, I thought that the $fp variable was null, but when I put a loop to print whatever was on the variable like this:
function JobPollAsync(&$fp)
{
if (($fp === false) or ($fp==null)) {
        return false;
    }

if (feof($fp)) {
    fclose($fp);
    $fp = false;
    return false;
}

    while (!feof($fp)) {
       echo fgets($fp, 128);
    }

}
The printed text was correct. So I don't know what is the reason that forces the null value on the return.
I call to this function from another PHP file. The calling is as simple as JobPollAsync($fp1); so this can't be the problem.
Anyone who can give me a trace.


text:
Q: Retrieving the latest emails with MailCore2 I'm loading my latest emails and I'm saving the latest UID because later if the user reload the list of emails I want to get all the emails from that UID to now...  for this, I'm using
UInt64 start = lUid;
UInt64 end = UINT64_MAX;

MCOIMAPMessagesRequestKind requestKind = MCOIMAPMessagesRequestKindHeaders;
MCOIndexSet *uids = [MCOIndexSet indexSetWithRange:MCORangeMake(start, end)];

MCOIMAPFetchMessagesOperation *fetchOperation = [imapSession fetchMessagesOperationWithFolder:@"INBOX"
                                                                                requestKind:requestKind
                                                                                uids:uids];

this action always return the results but I'm getting the latest email... So I tried to make
UInt64 start = lUid + 1;

but it is exactly the same.
EDIT
I'm looking the logger and the last UID is 34038 so when i made the call the start parameter was 34039... so why im getting the email with id 34038?
2015-01-20 18:33:06.852 App[25022:730644] mailcore - IMAP: 8 UID FETCH 34039:* (UID ENVELOPE BODY.PEEK[HEADER.FIELDS (References)])

Anyone know whats going on?
EDIT 2:
So this is my code
UInt64 start = lUid + 1;
UInt64 end = UINT64_MAX;

MCOIMAPMessagesRequestKind requestKind = MCOIMAPMessagesRequestKindHeaders;
MCOIndexSet *uids = [MCOIndexSet indexSetWithRange:MCORangeMake(start, end)];

MCOIMAPFetchMessagesOperation *fetchOperation = [imapSession fetchMessagesOperationWithFolder:@"INBOX"
                                                                                requestKind:requestKind
                                                                                uids:uids];

void(^fetchHandler)(NSError *, NSArray *, MCOIndexSet *) = ^(NSError *error, NSArray *fetchedMessages, MCOIndexSet *vanishedMessages) {

    if( error ) {
        completionHandler(UIBackgroundFetchResultFailed);

        NSLog(@"Error downloading message headers:%@", error);
    }

    NSMutableArray *currentMessages = [NSMutableArray arrayWithArray:fetchedMessages];

    if( [currentMessages count] > 0 ) {

        MCOIMAPMessage *lastMessage = [fetchedMessages lastObject];
        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
        [defaults setObject:@(lastMessage.uid) forKey:@"lastUID"];
        [defaults synchronize];

        completionHandler(UIBackgroundFetchResultNewData);

    }
    else {
        completionHandler(UIBackgroundFetchResultNoData);
    }

};

[fetchOperation start:fetchHandler];

and this is the logger when i execute that call
2015-01-21 18:02:46.723 App[5021:473470] mailcore - IMAP: * OK Gimap     ready for requests from 181.167.207.42 b69mb75112208qhb
2015-01-21 18:02:46.725 App[5021:473470] mailcore - IMAP: 1 CAPABILITY
2015-01-21 18:02:46.955 App[5021:473470] mailcore - IMAP: * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN
1 OK Thats all she wrote! b69mb75112208qhb
2015-01-21 18:02:46.955 App[5021:473470] mailcore - IMAP: 2     AUTHENTICATE XOAUTH2     dXNlcj1zYW50b21lZ29uemFsb0BnbWFpbC5jb20BYXV0aD1CZWFyZXIgeWEyOS5BZ0VQNnBQNFRJN1ZEMHlwempRNm01bTMwS2J0b0F6VzN6REdBbXc2dmh0VEF1TUJISVVaN3BobEtwY0M4dDlQRVFHcVhETHRlMU5VaFEBAQ==
2015-01-21 18:02:47.267 App[5021:473470] mailcore - IMAP: * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT
2 OK santomegonzalo@gmail.com authenticated (Success)
2015-01-21 18:02:47.267 App[5021:473470] mailcore - IMAP: 3 COMPRESS DEFLATE
2015-01-21 18:02:47.518 App[5021:473470] mailcore - IMAP: 3 OK Success
2015-01-21 18:02:47.518 App[5021:473470] mailcore - IMAP: 4 ENABLE CONDSTORE
2015-01-21 18:02:47.767 App[5021:473470] mailcore - IMAP: * ENABLED CONDSTORE
4 OK Success
2015-01-21 18:02:47.767 App[5021:473470] mailcore - IMAP: 5 NAMESPACE
2015-01-21 18:02:48.016 App[5021:473470] mailcore - IMAP: * NAMESPACE (("" "/")) NIL NIL
5 OK Success
2015-01-21 18:02:48.017 App[5021:473470] mailcore - IMAP: 6 ID NIL
2015-01-21 18:02:48.267 App[5021:473470] mailcore - IMAP: * ID ("name"     "GImap" "vendor" "Google, Inc." "support-url"     "http://support.google.com/mail" "version" "gmail_imap_150113.07_p0"     "remote-host" "181.167.207.42")
6 OK Success
2015-01-21 18:02:48.268 App[5021:473470] mailcore - IMAP: 7 SELECT INBOX
2015-01-21 18:02:48.770 App[5021:473470] mailcore - IMAP: * FLAGS     (\Answered \Flagged \Draft \Deleted \Seen $MailFlagBit1 $MailFlagBit0     $Phishing $Forwarded $MailFlagBit2 JunkRecorded $NotJunk NotJunk     $NotPhishing $Junk)
* OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen     $MailFlagBit1 $MailFlagBit0 $Phishing $Forwarded $MailFlagBit2 JunkRecorded $NotJunk NotJunk $NotPhishing $Junk \*)] Flags permitted.
* OK [UIDVALIDITY 617846230] UIDs valid.
* 20472 EXISTS
* 0 RECENT
* OK [UIDNEXT 34091] Predicted next UID.
* OK [HIGHESTMODSEQ 4668463]
7 OK [READ-WRITE] INBO
2015-01-21 18:02:48.771 App[5021:473470] mailcore - IMAP: X selected.     (Success)
2015-01-21 18:02:48.771 App[5021:473470] mailcore - IMAP: 8 UID FETCH     34092:* (UID ENVELOPE BODY.PEEK[HEADER.FIELDS (References)])
2015-01-21 18:02:49.405 App[5021:473470] mailcore - IMAP: * 20472 FETCH     (UID 34090 MODSEQ (4668387) ENVELOPE ("Wed, 21 Jan 2015 20:31:46 -0000"     "Subject" (("User" NIL "pullrequests-reply" "company.org")) (("User" NIL     "toreply" "company.org")) (("User" NIL "toreply" "company.org")) ((NIL NIL     "santomegonzalo" "gmail.com")) NIL NIL "<toreply@company.com>" "    <toreply@company.com>") BODY[HEADER.FIELDS (References)] {52}
References: <toreply@company.com

)
8 OK Success


text:
Q: Remover uma linha específica em todos arquivos de um diretório usando PHP Tenho um diretório com 5500 arquivos nomeados de forma aleatória sem extensão, por exemplo:

*

*4as6d4ad

*4asd564ad

*1mi3jh

*019i43nmasf

Preciso remover a última linha de todos arquivos neste diretório. Encontrei este código mas não consegui adaptá-lo:
<?php

// load the data and delete the line from the array
$lines = file('filename.txt');
$last = sizeof($lines) - 1 ;
unset($lines[$last]);

// write the new data to the file
$fp = fopen('filename.txt', 'w');
fwrite($fp, implode('', $lines));
fclose($fp);

?>

O código acima funciona, mas tenho que especificar arquivo por arquivo.
Edit: Com a ajuda do nos comentários, consegui resolver o problema utilizando:
<?php
if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

// load the data and delete the line from the array
$lines = file($entry);
$last = sizeof($lines) - 1 ;
unset($lines[$last]);

// write the new data to the file
$fp = fopen($entry, 'w');
fwrite($fp, implode('', $lines));
fclose($fp);

        }
    }

    closedir($handle);
}

?>

A: <?php
if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

// load the data and delete the line from the array
$lines = file($entry);
$last = sizeof($lines) - 1 ;
unset($lines[$last]);

// write the new data to the file
$fp = fopen($entry, 'w');
fwrite($fp, implode('', $lines));
fclose($fp);

        }
    }

    closedir($handle);
}

?>


text:
Q: How to get the cursor position (not row or column) in Ace Editor? Is there a way to get the cursor position (not the row and column) in Ace Editor.
For example, if the contents of the Ace Editor are the following:
Hello
World

And the cursor was after the "Wo" in "World". The position or index would be 7 or 8 (if you count newline).
Is there a method to get the position?

A: Ace calls {row, column} objects position, and the number of characters since the document start index.
You can convert position to index using editor.session.doc.positionToIndex method https://github.com/ajaxorg/ace/blob/v1.2.6/lib/ace/document.js#L678, but note that this method is not very fast since it has to iterate over the whole document, so use it and indexToPosition as sparingly as possible.


text:
Q: Load entire json file into single column of BigQuery Table I am trying to load json file with more then 100 columns into Bigquery. Some of these columns has special character within their name i.e. dollar sign($) and period(.)  Rows/Records content also varies - meaning not all columns may be present in each row/record which is totally acceptable json format.
I have search similar posts
How to manage/handle schema changes while loading JSON file into BigQuery table
BigQuery: Create column of JSON datatype
which suggest to load the data into single "STRING" column as CSV format first and parse out columns using JSON_EXTRACT() function to target table. Hence I have created a BigQuery table with following schema definition:
[
  {
    "name": "data",
    "type": "STRING"
  }
    ]
then I have ran following CLI command:
bq load --source_format=CSV test.bq_load_test ./data_file.json ./bq_load_test_schema.json
which result into following error:
Error Message:
BigQuery error in load operation: Error processing job : Error
while reading data, error message: CSV table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the
errors[] collection for more details.
Failure details:
- Error while reading data, error message: Too many values in row
starting at position: 0.
Here's the data file layout:
root
|-- $insert_id: string (nullable = true)
|-- $schema: long (nullable = true)
|-- adid: string (nullable = true)
|-- vendor_attribution_ids: array (nullable = true)
|    |-- element: string (containsNull = true)
|-- vendor_event_type: string (nullable = true)
|-- vendor_id: long (nullable = true)
|-- app: long (nullable = true)
|-- city: string (nullable = true)
|-- client_event_time: string (nullable = true)
|-- client_upload_time: string (nullable = true)
|-- country: string (nullable = true)
|-- data: struct (nullable = true)
|    |-- first_event: boolean (nullable = true)
|-- device_brand: string (nullable = true)
|-- device_carrier: string (nullable = true)
|-- device_family: string (nullable = true)
|-- device_id: string (nullable = true)
|-- device_manufacturer: string (nullable = true)
|-- device_model: string (nullable = true)
|-- device_type: string (nullable = true)
|-- dma: string (nullable = true)
|-- event_id: long (nullable = true)
|-- event_properties: struct (nullable = true)
|    |-- U.vf: string (nullable = true)
|    |-- app.name: string (nullable = true)
|    |-- app.pillar: string (nullable = true)
|    |-- app.version: string (nullable = true)
|    |-- categories: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- cmfAppId: string (nullable = true)
|    |-- content.area: string (nullable = true)
|    |-- content.authenticated: boolean (nullable = true)
|    |-- content.authors: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.cms: string (nullable = true)
|    |-- content.id: string (nullable = true)
|    |-- content.keywords.collections: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.keywords.company: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.keywords.location: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.keywords.organization: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.keywords.person: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.keywords.subject: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.keywords.tag: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- content.media.audiovideo: string (nullable = true)
|    |-- content.media.contentarea: string (nullable = true)
|    |-- content.media.duration: long (nullable = true)
|    |-- content.media.episodenumber: string (nullable = true)
|    |-- content.media.genre: string (nullable = true)
|    |-- content.media.length: double (nullable = true)
|    |-- content.media.liveondemand: string (nullable = true)
|    |-- content.media.region: string (nullable = true)
|    |-- content.media.seasonnumber: string (nullable = true)
|    |-- content.media.show: string (nullable = true)
|    |-- content.media.sport: string (nullable = true)
|    |-- content.media.streamtitle: string (nullable = true)
|    |-- content.media.type: string (nullable = true)
|    |-- content.originaltitle: string (nullable = true)
|    |-- content.pubdate: long (nullable = true)
|    |-- content.publishedtime: string (nullable = true)
|    |-- content.subsection1: string (nullable = true)
|    |-- content.subsection2: string (nullable = true)
|    |-- content.subsection3: string (nullable = true)
|    |-- content.subsection4: string (nullable = true)
|    |-- content.tier: string (nullable = true)
|    |-- content.title: string (nullable = true)
|    |-- content.type: string (nullable = true)
|    |-- content.updatedtime: string (nullable = true)
|    |-- content.url: string (nullable = true)
|    |-- custom.DNT: boolean (nullable = true)
|    |-- custom.cookiesenabled: boolean (nullable = true)
|    |-- custom.engine: string (nullable = true)
|    |-- feature.name: string (nullable = true)
|    |-- feature.position: string (nullable = true)
|    |-- lastupdate: string (nullable = true)
|    |-- pubdate: string (nullable = true)
|    |-- referrer.campaign: string (nullable = true)
|    |-- referrer.url: string (nullable = true)
|    |-- syndicate: string (nullable = true)
|    |-- user.interests.explicit.no: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- user.interests.explicit.yes: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- user.tier: string (nullable = true)
|    |-- userTier: string (nullable = true)
|-- event_time: string (nullable = true)
|-- event_type: string (nullable = true)
|-- idfa: string (nullable = true)
|-- ip_address: string (nullable = true)
|-- is_attribution_event: boolean (nullable = true)
|-- language: string (nullable = true)
|-- library: string (nullable = true)
|-- location_lat: double (nullable = true)
|-- location_lng: double (nullable = true)
|-- os_name: string (nullable = true)
|-- os_version: string (nullable = true)
|-- paying: string (nullable = true)
|-- platform: string (nullable = true)
|-- processed_time: string (nullable = true)
|-- region: string (nullable = true)
|-- sample_rate: string (nullable = true)
|-- server_received_time: string (nullable = true)
|-- server_upload_time: string (nullable = true)
|-- session_id: long (nullable = true)
|-- start_version: string (nullable = true)
|-- user_creation_time: string (nullable = true)
|-- user_id: string (nullable = true)
|-- user_properties: struct (nullable = true)
|    |-- internal.userID: string (nullable = true)
|    |-- internal.userTier: string (nullable = true)
|    |-- experiment.id: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- experiment.variant: array (nullable = true)
|    |    |-- element: string (containsNull = true)
|    |-- location.news: string (nullable = true)
|    |-- location.radio: string (nullable = true)
|    |-- location.region: string (nullable = true)
|    |-- location.tv: string (nullable = true)
|    |-- location.weather: string (nullable = true)
|    |-- referrer.campaign: string (nullable = true)
|    |-- user.id: string (nullable = true)
|    |-- user.id.internalvisitor: string (nullable = true)
|    |-- user.tier: string (nullable = true)
|-- uuid: string (nullable = true)
|-- version_name: string (nullable = true)
|-- feature_origin: string (nullable = true)

Here's the snippet of the data file:
{"server_received_time":"2019-01-17 15:00:00.482000","app":161,"device_carrier":null,"$schema":12,"city":"Caro","user_id":null,"uuid":"9018","event_time":"2019-01-17 15:00:00.045000","platform":"Web","os_version":"49","vendor_id":711,"processed_time":"2019-01-17 15:00:00.817195","user_creation_time":"2018-11-01 19:16:34.971000","version_name":null,"ip_address":null,"paying":null,"dma":null,"group_properties":{},"user_properties":{"location.radio":"ca","vendor.userTier":"free","vendor.userID":"a989","user.id":"a989","user.tier":"free","location.region":"ca"},"client_upload_time":"2019-01-17 15:00:00.424000","$insert_id":"e8410","event_type":"LOADED","library":"amp\/4.5.2","vendor_attribution_ids":null,"device_type":"Mac","device_manufacturer":null,"start_version":null,"location_lng":null,"server_upload_time":"2019-01-17 15:00:00.493000","event_id":64,"location_lat":null,"os_name":"Chrome","vendor_event_type":null,"device_brand":null,"groups":{},"event_properties":{"content.authenticated":false,"content.subsection1":"regions","custom.DNT":true,"content.subsection2":"ca","referrer.url":"","content.url":"","content.type":"index","content.title":"","custom.cookiesenabled":true,"app.pillar":"feed","content.area":"news","app.name":"oc"},"data":{},"device_id":"","language":"English","device_model":"Mac","country":"","region":"","is_attribution_event":false,"adid":null,"session_id":15,"device_family":"Mac","sample_rate":null,"idfa":null,"client_event_time":"2019-01-17 14:59:59.987000"}
{"server_received_time":"2019-01-17 15:00:00.913000","app":161,"device_carrier":null,"$schema":12,"city":"Fo","user_id":null,"uuid":"9052","event_time":"2019-01-17 15:00:00.566000","platform":"Web","os_version":"71","vendor_id":797,"processed_time":"2019-01-17 15:00:01.301936","user_creation_time":"2019-01-17 15:00:00.566000","version_name":null,"ip_address":null,"paying":null,"dma":"CO","group_properties":{},"user_properties":{"user.tier":"free"},"client_upload_time":"2019-01-17 15:00:00.157000","$insert_id":"69ae","event_type":"START WEB SESSION","library":"amp\/4.5.2","vendor_attribution_ids":null,"device_type":"Android","device_manufacturer":null,"start_version":null,"location_lng":null,"server_upload_time":"2019-01-17 15:00:00.925000","event_id":1,"location_lat":null,"os_name":"Chrome Mobile","vendor_event_type":null,"device_brand":null,"groups":{},"event_properties":{"content.subsection3":"home","content.subsection2":"archives","content.title":"","content.keywords.subject":["Lifestyle\/Recreation and leisure\/Outdoor recreation\/Boating","Lifestyle\/Relationships\/Couples","General news\/Weather","Oddities"],"content.publishedtime":154687,"app.name":"oc","referrer.url":"","content.subsection1":"archives","content.url":"","content.authenticated":false,"content.keywords.location":["Ot"],"content.originaltitle":"","content.type":"story","content.authors":["Archives"],"app.pillar":"feed","content.area":"news","content.id":"1.49","content.updatedtime":1546878600538,"content.keywords.tag":["24 1","boat house","Ot","Rockcliffe","River","m"],"content.keywords.person":["Ber","Shi","Jea","Jean\u00e9tien"]},"data":{"first_event":true},"device_id":"","language":"English","device_model":"Android","country":"","region":"","is_attribution_event":false,"adid":null,"session_id":15477,"device_family":"Android","sample_rate":null,"idfa":null,"client_event_time":"2019-01-17 14:59:59.810000"}
{"server_received_time":"2019-01-17 15:00:00.913000","app":16,"device_carrier":null,"$schema":12,"city":"","user_id":null,"uuid":"905","event_time":"2019-01-17 15:00:00.574000","platform":"Web","os_version":"71","vendor_id":7973,"processed_time":"2019-01-17 15:00:01.301957","user_creation_time":"2019-01-17 15:00:00.566000","version_name":null,"ip_address":null,"paying":null,"dma":"DCO","group_properties":{},"user_properties":{"user.tier":"free"},"client_upload_time":"2019-01-17 15:00:00.157000","$insert_id":"d045","event_type":"LOADED","library":"am-js\/4.5.2","vendor_attribution_ids":null,"device_type":"Android","device_manufacturer":null,"start_version":null,"location_lng":null,"server_upload_time":"2019-01-17 15:00:00.925000","event_id":2,"location_lat":null,"os_name":"Chrome Mobile","vendor_event_type":null,"device_brand":null,"groups":{},"event_properties":{"content.subsection3":"home","content.subsection2":"archives","content.subsection1":"archives","content.keywords.subject":["Lifestyle\/Recreation and leisure\/Outdoor recreation\/Boating","Lifestyle\/Relationships\/Couples","General news\/Weather","Oddities"],"content.type":"story","content.keywords.location":["Ot"],"app.pillar":"feed","app.name":"oc","content.authenticated":false,"custom.DNT":false,"content.id":"1.4","content.keywords.person":["Ber","Shi","Jea","Je\u00e9tien"],"content.title":"","content.url":"","content.originaltitle":"","custom.cookiesenabled":true,"content.authors":["Archives"],"content.publishedtime":1546878600538,"referrer.url":"","content.area":"news","content.updatedtime":1546878600538,"content.keywords.tag":["24 1","boat house","O","Rockcliffe","River","pr"]},"data":{},"device_id":"","language":"English","device_model":"Android","country":"","region":"","is_attribution_event":false,"adid":null,"session_id":1547737199081,"device_family":"Android","sample_rate":null,"idfa":null,"client_event_time":"2019-01-17 14:59:59.818000"}

Any input? What am I missing here?

A: You have to specify the right delimiter for CSV file. Notice that the default value for this flag is ',' and your data has ',', therefore, every row is interpreted as multiple fields. I tested with your data and this worked for me:
bq load --source_format=CSV -F ';' test.bq_load_test ./data_file.json

Notice that ';' worked because the snippet data does not contain ';'


text:
Q: How to log user into my service with Facebook login? I want users to log into my application (which has its own server side) using Facebook login.
I thought about loging the user in, and then send the access token to my server (using SSL of course)
and then my server will check the user id of that access token in front of Facebook (and this way I know it's a valid access token).
Is this the right way to do such thing?
Thank you.

A: Here are the instructions from facebook itself.
https://developers.facebook.com/docs/howtos/login/server-side-login/


text:
Q: Sending an event when window.location.href changes My setup:
I have a LWC which is placed in Shared Footer, so I don't have to add it manually on every page. This component is responsible only for sending events.
What problems do I have:
I need to do this so that every time window.location.href changes, this event is sent. Before, I was sending event on connectedCallback, but sometimes connectedCallback doesn't trigger, I also tried renderedCallback, but also it didn't work.

A: So i found the solution, creating a wired method on CurrentPageReference worked like a charm.
import { CurrentPageReference } from 'lightning/navigation';

@wire(CurrentPageReference)
method(data) {
  doSomethingWithData(data)
};


text:
Q: How to convert mongo shell code to java code using document and mongo aggregation How can I convert this code to java? How to use aggregation framework in java ? Can anyone please help me out...
My java code:
Document update = new Document("$project",new Document("TOTAL_EMPLOYEE_SALARY",new Document("$sum","$employees.EMP_SALARY")));
 AggregationOutput output = coll.aggregate(update); // throwing some error in eclipse

My mongo shell code :
db.collection.aggregate([
    { "$project": {
        "TOTAL_EMPLOYEE_SALARY": {
           "$sum": "$employees.EMP_SALARY"
        }
    }}
])

A: So use a List:
List<Document> pipeline = Arrays.<Document>asList(
    new Document("$project",
        new Document("TOTAL_EMPLOYEE_SALARY",new Document("$sum","$employees.EMP_SALARY"))
    )
);

AggregationOutput output = coll.aggregate(pipeline);


text:
Q: Samsung's multi window support - Screen size I'm currently developping my app to be compatible with the samsung multi window feature introduced with the galaxy note 2 and soon the galaxy s3. If you don't know what I'm talking about :

(source: androidheadlines.com)

If you are interested, here is a link to know how to do it :  here
My problem is that I need to know the height/width that my app uses.
I'm doing this :
displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
heightScreen = displaymetrics.heightPixels;
widthScreen = displaymetrics.widthPixels;

But this returns the size of the entire screen, not just the part that my app uses. My activity is  only compose by a Panel which take the entire space, but the panel.getHeight() or getWidth() return 0.
How can I get the real height/width ?
Thanks in advance.

A:
My activity is only compose by a Panel which take the entire space, but the panel.getHeight() or getWidth() return 0.

Try checking later. You are probably checking for this in onCreate(), which is too soon AFAIK.


text:
Q: Find all datetimepicker controls in a page I am using several datetimepicker control in a page. All of the are serves different functionalities. So i have created individual class for each of them. I have to change the datetime format dynamically for all those controls. also, i need to change the datetime string which is already populated by my back end code. backend code is updating textbox with mm/dd/yyyy format but i need to change it dynamically.How can i achieve these ?
I saw after rendering all controls has "hasdatepicker" class. But i am unable to access the control.
$('.hasdatepicker').datetimepicker({ dateFormat: localStorage.serverDateTimeFormat }).val();

Should be able to change the pre populated text with new date time format and all datetimepicker should be able to change the datepicker format.

A: You can set the value and format like this:
$('.yourDateTimePickerIdentifier').datetimepicker({value:'14.04.2018',  format:'d.m.Y'});

Ensure you have a indentifier for all of the datetimepickers. Use a class rather than an ID


text:
Q: Group and gave ranks based on certain conditions I want to give rank to below data based on time (if the timestamp difference is less the 15 mins then same rank else rank +1 )
E.g

*

*time : 06:10:32 and 06:12:38 should get rank 1

*time : 13:36:44 and 13:40:41 and 13:44:47 should get rank 2

*and last 4 rows should get rank 3

user_id ride_id      createdat_local
2681233 96783742    2017-10-04 06:10:32
2681233 96784171    2017-10-04 06:12:38
2681233 96924751    2017-10-04 13:36:44
2681233 96925561    2017-10-04 13:40:41
2681233 96926560    2017-10-04 13:44:47
2681233 96994651    2017-10-04 18:12:29
2681233 96995953    2017-10-04 18:18:16
2681233 96996937    2017-10-04 18:22:15
2681233 96997195    2017-10-04 18:24:00

A: In SQL Server 2012+:
Using the window function lag() in a common table expression to get the datediff() compared to the previous row value for createdat_local, and then sum() over() with conditional aggregation to generate the rank:
;with cte as (
select *
  , datediff(minute,lag(createdat_local) over (
      partition by user_id
      order by createdat_local
      ),createdat_local) as prev_dat
from t
)
select user_id, ride_id, createdat_local
  , sum(case when coalesce(prev_dat,16)>15 then 1 else 0 end) over (
    partition by user_id
    order by createdat_local
    ) as rank
from cte

rextester demo: http://rextester.com/EQUC48356
returns:
+---------+----------+---------------------+------+
| user_id | ride_id  |   createdat_local   | rank |
+---------+----------+---------------------+------+
| 2681233 | 96783742 | 2017-10-04 06:10:32 |    1 |
| 2681233 | 96784171 | 2017-10-04 06:12:38 |    1 |
| 2681233 | 96924751 | 2017-10-04 13:36:44 |    2 |
| 2681233 | 96925561 | 2017-10-04 13:40:41 |    2 |
| 2681233 | 96926560 | 2017-10-04 13:44:47 |    2 |
| 2681233 | 96994651 | 2017-10-04 18:12:29 |    3 |
| 2681233 | 96995953 | 2017-10-04 18:18:16 |    3 |
| 2681233 | 96996937 | 2017-10-04 18:22:15 |    3 |
| 2681233 | 96997195 | 2017-10-04 18:24:00 |    3 |
+---------+----------+---------------------+------+

A: Able to achieve the required result in redshift(psql)
Query:
with cte as (
select *,
(DATEPART('hour',createdat_local) * 60 + DATEPART('minute',createdat_local)) -
lag(DATEPART('hour',createdat_local) * 60 + DATEPART('minute',createdat_local)
) over(partition by user_id order by createdat_local)  as diff_in_minutes
from t
)
select user_id, ride_id, createdat_local
  , sum(case when coalesce(diff_in_minutes,16)>15 then 1 else 0 end) over (
    partition by user_id
    order by createdat_local rows between unbounded preceding and current row
    ) as rank
from cte;


text:
Q: Using net user with a system account with a backslash Entering:
net user "IIS APPPOOL\DefaultAppPool"
Results in:
The syntax of this command is:

NET USER
[username [password | *] [options]] [/DOMAIN]
         username {password | *} /ADD [options] [/DOMAIN]
         username [/DELETE] [/DOMAIN]
         username [/TIMES:{times | ALL}]

Why? Do I have to escape the backslash character? If so, how?


text:
Q: OSCollector Cannot run program "python": error=13, Permission denied When I tend to install and use the tool named benchmarksql-5.0, I found this problem below
[oracle@db01 run]$ ./runBenchmark.sh props.ora
09:43:33,081 [main] INFO   jTPCC : Term-00,
09:43:33,083 [main] INFO   jTPCC : Term-00, +-------------------------------------------------------------+
09:43:33,083 [main] INFO   jTPCC : Term-00,      BenchmarkSQL v5.0
09:43:33,083 [main] INFO   jTPCC : Term-00, +-------------------------------------------------------------+
09:43:33,083 [main] INFO   jTPCC : Term-00,  (c) 2003, Raul Barbosa
09:43:33,084 [main] INFO   jTPCC : Term-00,  (c) 2004-2016, Denis Lussier
09:43:33,086 [main] INFO   jTPCC : Term-00,  (c) 2016, Jan Wieck
09:43:33,086 [main] INFO   jTPCC : Term-00, +-------------------------------------------------------------+
09:43:33,086 [main] INFO   jTPCC : Term-00,
09:43:33,086 [main] INFO   jTPCC : Term-00, db=oracle
09:43:33,086 [main] INFO   jTPCC : Term-00, driver=oracle.jdbc.driver.OracleDriver
09:43:33,086 [main] INFO   jTPCC : Term-00, conn=jdbc:oracle:thin:@localhost:1521:cc
09:43:33,086 [main] INFO   jTPCC : Term-00, user=benchmarksql
09:43:33,086 [main] INFO   jTPCC : Term-00,
09:43:33,086 [main] INFO   jTPCC : Term-00, warehouses=1
09:43:33,086 [main] INFO   jTPCC : Term-00, terminals=1
09:43:33,088 [main] INFO   jTPCC : Term-00, runTxnsPerTerminal=10
09:43:33,088 [main] INFO   jTPCC : Term-00, limitTxnsPerMin=300
09:43:33,088 [main] INFO   jTPCC : Term-00, terminalWarehouseFixed=true
09:43:33,088 [main] INFO   jTPCC : Term-00,
09:43:33,088 [main] INFO   jTPCC : Term-00, newOrderWeight=45
09:43:33,088 [main] INFO   jTPCC : Term-00, paymentWeight=43
09:43:33,088 [main] INFO   jTPCC : Term-00, orderStatusWeight=4
09:43:33,088 [main] INFO   jTPCC : Term-00, deliveryWeight=4
09:43:33,088 [main] INFO   jTPCC : Term-00, stockLevelWeight=4
09:43:33,089 [main] INFO   jTPCC : Term-00,
09:43:33,089 [main] INFO   jTPCC : Term-00, resultDirectory=my_result_%tY-%tm-%td_%tH%tM%tS
09:43:33,089 [main] INFO   jTPCC : Term-00, osCollectorScript=./misc/os_collector_linux.py
09:43:33,089 [main] INFO   jTPCC : Term-00,
09:43:33,235 [main] INFO   jTPCC : Term-00, copied props.ora to my_result_2021-12-30_094333/run.properties
09:43:33,235 [main] INFO   jTPCC : Term-00, created my_result_2021-12-30_094333/data/runInfo.csv for runID 8
09:43:33,235 [main] INFO   jTPCC : Term-00, writing per transaction results to my_result_2021-12-30_094333/data/result.csv
09:43:33,236 [main] INFO   jTPCC : Term-00, osCollectorScript=./misc/os_collector_linux.py
09:43:33,236 [main] INFO   jTPCC : Term-00, osCollectorInterval=1
09:43:33,236 [main] INFO   jTPCC : Term-00, osCollectorSSHAddr=null
09:43:33,236 [main] INFO   jTPCC : Term-00, osCollectorDevices=net_eth0 blk_sda
09:43:33,243 [main] ERROR  OSCollector : OSCollector Cannot run program "python": error=13, Permission denied
java.io.IOException: Cannot run program "python": error=13, Permission denied
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at OSCollector.<init>(OSCollector.java:83)
        at jTPCC.<init>(jTPCC.java:256)
        at jTPCC.main(jTPCC.java:53)
Caused by: java.io.IOException: error=13, Permission denied
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
        at java.lang.ProcessImpl.start(ProcessImpl.java:134)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 3 more

I first seized that the solution of installing python36 and python2 by yum, but it does not help. So what should be done when occuring this error? Thanks for your comments.
For completion, when I use command sh -x runBenchmark.sh props.ora, the error occurred on the following command:
java -cp '.:../lib/oracle/*:/oracle/product/122/lib/*:../lib/*:../dist/*' -Dprop=props.ora -DrunID=19 jTPCC
The total process exhibits here
[oracle@db01 run]$ sh -x runBenchmark.sh props.ora
+ '[' 1 -ne 1 ']'
+ SEQ_FILE=./.jTPCC_run_seq.dat
+ '[' '!' -f ./.jTPCC_run_seq.dat ']'
+++ cat ./.jTPCC_run_seq.dat
++ expr 18 + 1
+ SEQ=19
+ echo 19
+ source funcs.sh props.ora
++ PROPS=props.ora
++ '[' '!' -f props.ora ']'
++ case "$(getProp db)" in
+++ getProp db
+++ grep '^db=' props.ora
+++ sed -e 's/^db=//'
+ setCP
+ case "$(getProp db)" in
++ getProp db
++ grep '^db=' props.ora
++ sed -e 's/^db=//'
+ cp='../lib/oracle/*'
+ '[' '!' -z /oracle/product/122 -a -d /oracle/product/122/lib ']'
+ cp='../lib/oracle/*:/oracle/product/122/lib/*'
+ cp='../lib/oracle/*:/oracle/product/122/lib/*:../lib/*'
+ myCP='.:../lib/oracle/*:/oracle/product/122/lib/*:../lib/*:../dist/*'
+ export myCP
+ myOPTS='-Dprop=props.ora -DrunID=19'
+ java -cp '.:../lib/oracle/*:/oracle/product/122/lib/*:../lib/*:../dist/*' -Dprop=props.ora -DrunID=19 jTPCC
13:38:18,427 [main] INFO   jTPCC : Term-00,
13:38:18,429 [main] INFO   jTPCC : Term-00, +-------------------------------------------------------------+
13:38:18,429 [main] INFO   jTPCC : Term-00,      BenchmarkSQL v5.0
13:38:18,429 [main] INFO   jTPCC : Term-00, +-------------------------------------------------------------+
13:38:18,430 [main] INFO   jTPCC : Term-00,  (c) 2003, Raul Barbosa
13:38:18,430 [main] INFO   jTPCC : Term-00,  (c) 2004-2016, Denis Lussier
13:38:18,432 [main] INFO   jTPCC : Term-00,  (c) 2016, Jan Wieck
13:38:18,432 [main] INFO   jTPCC : Term-00, +-------------------------------------------------------------+
13:38:18,432 [main] INFO   jTPCC : Term-00,
13:38:18,432 [main] INFO   jTPCC : Term-00, db=oracle
13:38:18,432 [main] INFO   jTPCC : Term-00, driver=oracle.jdbc.driver.OracleDriver
13:38:18,432 [main] INFO   jTPCC : Term-00, conn=jdbc:oracle:thin:@localhost:1521:cc
13:38:18,433 [main] INFO   jTPCC : Term-00, user=benchmarksql
13:38:18,433 [main] INFO   jTPCC : Term-00,
13:38:18,433 [main] INFO   jTPCC : Term-00, warehouses=1
13:38:18,433 [main] INFO   jTPCC : Term-00, terminals=1
13:38:18,435 [main] INFO   jTPCC : Term-00, runTxnsPerTerminal=10
13:38:18,435 [main] INFO   jTPCC : Term-00, limitTxnsPerMin=300
13:38:18,435 [main] INFO   jTPCC : Term-00, terminalWarehouseFixed=true
13:38:18,435 [main] INFO   jTPCC : Term-00,
13:38:18,435 [main] INFO   jTPCC : Term-00, newOrderWeight=45
13:38:18,435 [main] INFO   jTPCC : Term-00, paymentWeight=43
13:38:18,435 [main] INFO   jTPCC : Term-00, orderStatusWeight=4
13:38:18,435 [main] INFO   jTPCC : Term-00, deliveryWeight=4
13:38:18,435 [main] INFO   jTPCC : Term-00, stockLevelWeight=4
13:38:18,435 [main] INFO   jTPCC : Term-00,
13:38:18,436 [main] INFO   jTPCC : Term-00, resultDirectory=my_result_%tY-%tm-%td_%tH%tM%tS
13:38:18,436 [main] INFO   jTPCC : Term-00, osCollectorScript=./misc/os_collector_linux.py
13:38:18,436 [main] INFO   jTPCC : Term-00,
13:38:18,605 [main] INFO   jTPCC : Term-00, copied props.ora to my_result_2021-12-30_133818/run.properties
13:38:18,606 [main] INFO   jTPCC : Term-00, created my_result_2021-12-30_133818/data/runInfo.csv for runID 19
13:38:18,606 [main] INFO   jTPCC : Term-00, writing per transaction results to my_result_2021-12-30_133818/data/result.csv
13:38:18,606 [main] INFO   jTPCC : Term-00, osCollectorScript=./misc/os_collector_linux.py
13:38:18,607 [main] INFO   jTPCC : Term-00, osCollectorInterval=1
13:38:18,607 [main] INFO   jTPCC : Term-00, osCollectorSSHAddr=null
13:38:18,607 [main] INFO   jTPCC : Term-00, osCollectorDevices=net_eth0 blk_sda
13:38:18,614 [main] ERROR  OSCollector : OSCollector Cannot run program "python": error=13, Permission denied
java.io.IOException: Cannot run program "python": error=13, Permission denied
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at OSCollector.<init>(OSCollector.java:83)
        at jTPCC.<init>(jTPCC.java:256)
        at jTPCC.main(jTPCC.java:53)
Caused by: java.io.IOException: error=13, Permission denied
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
        at java.lang.ProcessImpl.start(ProcessImpl.java:134)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 3 more

By the way, I have tried using chmod command and sudo command to permission denied issue, but it does not help either.


text:
Q: AFHTTPClient putpath method I have problem with my below funct:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                       sportid, @"sport",
                        country,  SC_PAIS,
                        team,     SC_TEAM,
                        token,    SC_TOKEN,nil];

    [[SCHTTPClientServer sharedClient] setParameterEncoding:AFJSONParameterEncoding];
       [[SCHTTPClientServer sharedClient] putPath:@"calendarelemfilters/teams" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"RESPonsee %@",responseObject);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERROR %@",[error localizedDescription]);

        }];

this is my code. I have below error- How can i fix it?
Thanks
"""RESPONSE STRING: <>Apache Tomcat/7.0.26 - Error report HTTP Status 400 - Required String parameter 'token' is not presenttype Status reportmessage Required String parameter 'token' is not presentdescription The request sent by the client was syntactically incorrect (Required String parameter 'token' is not present).Apache Tomcat/7.0.26
2013-09-19 13:10:24.254 ISportsCal[834:907] ERROR Expected status code in (200-299), got 400"""

A: It's all there in the error message. The server is expecting a parameter called token and you aren't passing one in the expected format.

*

*What is SC_TOKEN? Possibly a capitalization error?

*Are you sure the server is expecting JSON?

*Is the server expecting any additional headers?

You may want to download https://github.com/AFNetworking/AFHTTPRequestOperationLogger to take a look at your requests. You can download a tool like Postman REST Client, get the put request working there, and then make sure your AFNetworking request matches this.

A: I have fixed it with postPath. and also i setted  "setparameter encoding"  as below.
[[SCHTTPClientServer sharedClient] setParameterEncoding:AFFormURLParameterEncoding];

Thanks


text:
Q: Unify classifiers based on their predictions I am working on classifying texts and images of scientific articles. From the texts I use title and abstract. So far I have achieved good results using an SVM for the texts and not that good using a CNN for the images. I still did a multimodal classification, which did not show any classification improvement.
What I would like to do now is to use the svm and cnn predictions to classify, something like a vote ensemble. However the VotingClassifier from sklearn does not accept mixed inputs. You would have some idea of how I could implement or some guide line.
Thank you!

A: One simple thing you can do is take the outputs from both your models and just use them as inputs to third linear regression model. This effectively "mixes" your 2 learners into a small ensemble. Of course this is a very simple strategy but it might give you a slight boost over using each model separately.


text:
Q: Angular Material: Check if User clicked outside Datepicker without Making Any Selection What's the Output Event to see if user clicked outside Material Angular datepicker?

*

*Want to know specifically when user clicked on Datepicker,

*Then Did not make any new selection, or did not reselect the date already entered

*and clicked out? (hence closing it).

Closed Stream event is not the exact answer, since user could have clicked on date selection.
https://material.angular.io/components/datepicker/api

A: you can store in a variable
waitClose:boolean

Then, you can use the events (dateChange) to set the variable to false and (opened) to set the variable to true.
(closed)="waitClose && close()" make that the function close() only happens when you click outside
<mat-form-field>
  <mat-label>Choose a date</mat-label>
    <input matInput [matDatepicker]="picker"
                            (dateChange)="waitClose=false" >
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker (closed)="waitClose && close()"
                            (opened)="waitClose=true">
  </mat-datepicker>
</mat-form-field>

see stackblitz


text:
Q: Mocha.js: how to test consequent save and delete with mongoose Testing framework: mocha
I want to test saving and then deleting created document in mongodb (with mongoose)
Code that actually do this :
item = new Item()
item.save(function(err, data){
   // if no errors test passed, then I need to test removing that item
   Item.remove({_id: data.id})
})

How should I describe the test?
I want to have separate tests results for save and remove in output.
Thanks.

A: var User = require('../../models/user');

describe('User', function(){
  describe('#save()', function(){
    it('should save without error', function(done){
      var user = new User({        username    : 'Luna'
        , email     : 'luna@me.name'
        , password  : 'asdf123'
      });
      user.save(function(err){
        if (err) throw err;
        done();
      });
    })
  })
})


text:
Q: App engine SDK not accessible in Gradle app engine project My build.gradle:
buildscript {    // Configuration for building
  repositories {
    jcenter()    // Bintray's repository - a fast Maven Central mirror & more
    mavenCentral()
  }
  dependencies {
    classpath 'com.google.cloud.tools:appengine-gradle-plugin:+'    // latest App Engine Gradle tasks
  }
}

repositories {   // repositories for Jar's you access in your code
  maven {
    url 'https://maven-central.storage.googleapis.com'             // Google's mirror of Maven Central
//   url 'https://oss.sonatype.org/content/repositories/snapshots' // SNAPSHOT Repository (if needed)
  }
  jcenter()
  mavenCentral()
   maven {
        url "s3://my.private.repo.com/maven/releases"
        credentials(AwsCredentials) {
            accessKey AWS_ACCESS_KEY
            secretKey AWS_SECRET_KEY
        }
    }
}

apply plugin: 'java'                              // standard Java tasks
apply plugin: 'war'                               // standard Web Archive plugin
apply plugin: 'com.google.cloud.tools.appengine'  // App Engine tasks

dependencies {
  providedCompile group: 'javax.servlet', name: 'servlet-api', version:'2.5'
  compile 'com.google.appengine:appengine:+'

    compile 'com.stripe:stripe-java:3.6.0'
    compile 'javax.mail:mailapi:1.4.3'
}

appengine {  // App Engine tasks configuration
  run {      // local (dev_appserver) configuration (standard environments only)
    port = 8080                 // default
  }

  deploy {   // deploy configuration
    stopPreviousVersion = true  // default - stop the current version
    promote = true              // default - & make this the current version
  }
}

group = 'com.example.appengine'   // Generated output GroupId
version = '1.0-SNAPSHOT'          // Version in generated output

sourceCompatibility = 1.7  // App Engine Standard uses Java 7
targetCompatibility = 1.7  // App Engine Standard uses Java 7

The Stripe and JavaMail JARs appear to be downloaded just fine. But when I run compileJava I get other errors:
/path/to/eclipse-workspaces/google-eclipse-projects/myproject/src/main/java/com/package/ChargeStripeServlet.java:3: error: package com.google.appengine.api.taskqueue.TaskOptions does not exist
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
...

It appears that the App Engine SDK is not being downloaded, but I don't see any error message. I have installed the SDK locally, if that helps (although I suspect the JARS will just be downloaded anyway).

A: What you need to do is to add the following dependency:
compile 'com.google.appengine:appengine-api-1.0-sdk:+'

As you can see here 'com.google.appengine:appengine:+' is of type POM, hence does not carry any java classes, it's only a parent.


text:
Q: node typescript : regex to allow whitespace with at least one alphanum caracter with joi validation I am using joi and regex to validate user input, I would like to accept only alpha num caracters where whitespace can be allowed. I've done the following :
const schema = Joi.object({
  value: Joi.string()
    .regex(
      /^[a-zA-Z0-9 ]*$/,
      'message',
    )
    .max(100)
    .required()
...

The problem is that now I allow user to fill a full string composed only of whitespaces, and that's not what I want, I accept whitespaces, only if they are between alphanum caracters. I am using this to test : https://www.regextester.com/104025

A: Try this one:
/^[a-zA-Z0-9]+[a-zA-Z0-9 ]*[a-zA-Z0-9]+$/

I dont know if this is the easiest or most elegant way but [a-zA-Z0-9]+  matches one or more of [a-zA-Z0-9] using the +
I added this to the front and end of your regex.
Test and explanation:
https://regex101.com/r/79uEWb/2/

A: Specify at the beginning that space is not allowed [^ ]

const withSpaceInFront = " hello";
const text = "hello there"
const textAndNumbers = "hello 5"
const textWithSpecialChars = "hello#"
const numeric = 123

const textWithSpecialCharsAllowed = "general Kenobi..?"

const regexNoSpace = /^[^ ][a-zA-Z0-9 ]*$/;

console.log("no space in front")
console.log(regexNoSpace.test(withSpaceInFront));
console.log(regexNoSpace.test(text));
console.log(regexNoSpace.test(textAndNumbers));
console.log(regexNoSpace.test(textWithSpecialChars));
console.log(regexNoSpace.test(numeric));

//if you want to accept special chars like ? or . just add them in your list of accepted chars

const regexAllowedSpecialChars = /^[^ ][a-zA-Z0-9 ?.]*$/;

console.log("no space in front & specific chars allowed")
console.log(regexAllowedSpecialChars.test(textWithSpecialCharsAllowed));

Regex tests:  https://regex101.com/r/8Ulpu9/1/


text:
Q: Cannot remove EventListener when 'mouseout' occurs I don't know why I can't remove EventListener when mouseout event occurs.
I want to activate EventListener('keydown'), when one table row is hovered. The reason is I want to use "delete" key, to remove hovered row, when it's hovered.
I assume problem can be caused by the fact, that keydown event is attached to document not certain element on which it's done. However isn't it impossible to add it to certain element?
    var table = document.querySelector('tbody');
    var rows = table.querySelectorAll('tr');

    for (i = 0; i < rows.length; i++)
    {
        var currentRow = table.rows[i];
        var createClickHandler =
            function(row, showHide)
            {
                return function()
                {
                    console.log('showHide ',showHide);
                    if (showHide === 'hover' )
                    {
                        document.addEventListener('keydown' ,function(ev)
                        {
                            if (showHide == 'hover')
                            {
                                console.log('hover target ', ev.target);
                            }
                        },false);
                        return;
                    }

                    else if (showHide === 'leave')
                    {
                        document.removeEventListener('keydown' ,function(ev)
                        {
                            if (ev.target && showHide === 'leave')
                            {
                                console.log('out ',ev);
                            }

                        },false);
                        console.log('left');
                    }
                 };
            };
        currentRow.addEventListener('mouseover', createClickHandler(currentRow, 'hover'), false);
        currentRow.addEventListener('mouseout', createClickHandler(currentRow, 'leave'), false);
    }

_______________________________________
[EDIT]
I think i solved my problem, but code seems too long and little bit too many those EventListener's as for kind of simple solution.
Can somebody tell me how to make this code shorter, please...?
var table = document.querySelector('tbody');
        var rows = table.querySelectorAll('tr');

    for (i = 0; i < rows.length; i++)
    {
        var currentRow = table.rows[i];
        var createClickHandler =
            function(row, showHide)
            {
                return function()
                {
                    var delKey = function(ev)
                    {
                        console.log('hover target ', ev.target);
                    };

                    console.log('showHide ',showHide);
                    if (showHide === 'hover' )
                    {
                        //console.log('hovered ',row);

                        document.addEventListener('keydown' ,delKey,false);
                        document.addEventListener('keyup' ,function(){
                            document.removeEventListener('keydown',delKey,false);
                            console.log('removed event ');
                        },false);

                        document.body.addEventListener('click', function()
                        {
                            document.removeEventListener('keydown', delKey, false);
                        },false);
                    }

                    else if (showHide === 'leave')
                    {
                        console.log('hidden ');
                    }
                };
            };
        currentRow.addEventListener('mouseover', createClickHandler(currentRow, 'hover'), false);
        currentRow.addEventListener('mouseout', createClickHandler(currentRow, 'leave'), false);
    }

A: EventTarget.removeEventListener should be called with the listener added with addEventListener, not with a new function. You're essentially telling document to remove a listener that has never been added.
Do it this way:
var listener = document.addEventListener('keydown', function(e) { ... });
document.removeEventListener('keydown', listener);

Edit: working example

var table = document.querySelector('tbody');
var rows = table.querySelectorAll('tr');
var log = document.getElementById('log');

for (i = 0; i < rows.length; i++) {
  var currentRow = table.rows[i];
  var createClickHandler = function(row, showHide) {
    return function() {
      var listener;

      console.log('showHide ',showHide);
      if (showHide === 'hover') {
        listener = document.addEventListener('keydown', function(ev) {
          if (showHide == 'hover') {
            console.log('hover target ', ev.target);
          }
        }, false);
        return;
      } else if (showHide === 'leave') {
        document.removeEventListener('keydown', listener, false);
        console.log('left');
      }
    };
  };
  currentRow.addEventListener('mouseover', createClickHandler(currentRow, 'hover'), false);
  currentRow.addEventListener('mouseout', createClickHandler(currentRow, 'leave'), false);
}

// don't do that -- only for demo purposes
console.log = function() { log.innerHTML = log.innerHTML + '
' + [].slice.call(arguments).join(' '); };

row 1

row 2

row 3


text:
Q: How can I make Emacs visualize only indentation whitespace? I've been looking at whitespace-mode, but I'm not sure it can do what I want here. Here is an example:
(defn foo []
..(let [x 1]
....(+ x 2)))

How can I do something like that in Emacs? In words, I'd like it to only visualize the leading (indentation) whitespace, but not all spaces in general. Just the spaces at the beginning of the lines.

A: The answer is to customize the whitespace-style variable and to remove the trailing keyword.  Check out the wiki for whitespace mode.

A: I don't think it can.  If you want it highlighted via font-lock you can add the following to an appropriate place (e.g. a mode hook) changing of course the face from trailing-whitespace to whatever you want.
(font-lock-add-keywords
 nil ;;current buffer instead of a particular mode
 '(("^ +" . 'trailing-whitespace)))

If you want it to be displayed with a visible mark then I don't think that can be done (easily) since whitespace-mode sets buffer-display-table which does a "global replacement" i.e., it doesn't take into account syntax or anything.


text:
Q: Benefits of using Weak variable instead of strong Can anyone provide me link or information about :
why weak variable is beneficial as compared to strong variable?
and IBOutlets in ARC, that should be weak or strong? Why delegate is also defined as weak property?
Thanks in advance.

A: The weak like the world is weak retain to object, when it dealloc that will be nil, and we can avoid the retain cycle. IBOutlets property because the view had retain it so that needn't strong retain it again.

A: strong: assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable
weak: will assign the incoming value to it without retaining it.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW3

A: The current recommended best practice from Apple is for IBOutlets to be strong unless weak is specifically needed to avoid a retain cycle.
In general you should make your outlet strong, especially if you are connecting an outlet to a subview or to a constraint that's not always going to be retained by the view hierarchy. The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended.


text:
Q: (MSAL) Issue with spanish characters getting name from social provider I'm having an issue using msal.js. I have a b2c tenant and when the user is logged I'm showing the user name, but if the name on the social provider(facebook or twitter) have an spanish character (ñ or accent) the name will be show with a strange character(for example ñ will be shown as ñ) I debugged the call to getUser() on msal method and the name is with the strange characters.
var user = this.clientApplication.getUser(); //Msal.UserAgentApplication; object
user.name//this has the  ñ character

Is this a bug on the js library or I'm missing something on b2c configuration?


text:
Q: How to set checked Checkbox based on database record? I would like to raise a question about JSP checkbox
I want to loop the subscription list from the database.
At the same time, I loop the specific user's subscription request.
For example, in the subscription list, there are several items, says
System Analyst
System Developer
System Manager
System Tester

In the subscription list, the user subscribed 2 of them, says
System Manager
System Tester

In the looping, I will loop a table with a checkbox column to show all the subscription value.
I encounter a problem here.
I want to make the checkbox "checked" while the user has subscribed the item.
For example, the result of table should have "checked" 2 of the checkbox.
However, I don't know the algorithm to implement my logic.
Can anyone kindly provide some hints for me to realize this?
Thanks.
siris
Coding-

    Subscription:

    <select name="subscription">

//read the subscription List
ResultSet rs=statement.executeQuery("select * from subsrciption");

//read the user has subscipted what item(s)
ResultSet rs2=statement.executeQuery("select * from request where userid='testing' ");
//in this SQL, for userid-testing, we find 2 records that he subscribed 2 items

//loop the subscription list from database
while ( rs.next() ) {
  String subscription = rs.getString("subscription");
  //after read the subscription table, how to loop the request table
  //while ( rs2.next() ) {

%>
  <option value="<%=subscription%>"><%=subscription%></option>
<%
  //}
} //end loop subscription list

%>
    </select>

A: You have asked about checkbox in the question and writing for Select in code.
Please edit your post.
Use
<INPUT TYPE=CHECKBOX NAME="<%=subscription%>"><%=subscription%>

Secondly,
Get subscription value from rs2 and compare it with rs


text:
Q: How to use variadic macros with Microsoft VS2010? I was trying to use the variadic macros with Microsoft visual studio 2010 and I faced a problem in the preprocessing phase , the complier couldn't translate the expressions correctly.
I searched on the internet for a solution for this problem and I found out that there is some bug in MSV2010 which cause this problem, some programmers suggested  workaround methods to solve this problem and actually they solved it
 but I am still facing small problem.
Here you are the code I am using.
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>

#define VA_NUM_ARGS(…) VA_NUM_ARGS_IMPL_((__VA_ARGS__, 5,4,3,2,1))
#define VA_NUM_ARGS_IMPL_(tuple) VA_NUM_ARGS_IMPL tuple
#define VA_NUM_ARGS_IMPL(_1,_2,_3,_4,_5,N,…) N

#define macro_dispatcher(func, ...)   macro_dispatcher_(func, VA_NUM_ARGS(__VA_ARGS__))

#define macro_dispatcher_(func, nargs)           macro_dispatcher__(func, nargs)
#define macro_dispatcher__(func, nargs)          func ## nargs

// to verify, run the preprocessor alone (g++ -E):
//VA_NUM_ARGS(x,y,z)

#define max(...)     macro_dispatcher(max, __VA_ARGS__)(__VA_ARGS__)

#define max1(a)      a
#define max2(a,b)    ((a)>(b)?(a):(b))
#define max3(a,b,c)  max2(max2(a,b),c)
int main(void)
{
    int a,b,c,d,z;
    a=10;
    b=6;
    c=5;

    d=VA_NUM_ARGS(a,b,c);
    z=max(a,b,c);
    printf("Number of Arguments=%d and the max number=%d",d,z);

}

d=VA_NUM_ARGS(a,b,c) ... Here the code will work correctly and gives the expected data which is d=3;
but for z=max(a,b,c); .... the macros will not be translated correctly and the program will show an error
I have run the preprocessor operation and this is what I got as translation for

z=max(a,b,c)"before preprocessor"
  z=maxVA_NUM_ARGS_IMPL (a,b,c, 5,4,3,2,1) (a,b,c); "after preprocessor" which isn't the expected as the expcted is
  z=max3(a,b,c);

How can I get the correct answer?
Thanks for you help.


text:
Q: I need to create a new column that enumerates each row with respect to two other column values I am attempting to create a row that just enumerates each row value and resets anytime a threshold is met.
date           id    x   x2  x3   new_col
1/1/2018    1   0   x   x   1
1/2/2018    1   1   x   x   1
1/3/2018    1   0   x   x   2
1/4/2018    2   0   x   x   1
1/5/2018    2   0   x   x   2
1/6/2018    2   1   x   x   1
1/7/2018    2   0   x   x   1
1/8/2018    2   0   x   x   2
1/9/2018    3   0   x   x   1
1/10/2018   3   0   x   x   2
1/11/2018   3   0   x   x   3
1/12/2018   3   1   x   x   1
1/13/2018   3   0   x   x   1
1/14/2018   3   0   x   x   2

In this example, the new column need to start over anytime the id value changes OR anytime x1  == 1.

A: Seems like a cumcount problem
s=df.groupby([df.id,df.x.eq(1).cumsum()]).cumcount()+1
s
Out[410]:
0     1
1     1
2     2
3     1
4     2
5     1
6     2
7     3
8     1
9     2
10    3
11    1
12    2
13    3
dtype: int64
df['New']=s


text:
Q: How to put restrictions in textbox using inputmask in html I have a textbox which has a format using inputmask, I also added maxlength which should be seven numbers. But whenever I try to submit the input with incomplete details, the output would be 00-0_-_ _ _ or whatever the user inputs. How can I add retstrictions like the input limit, input numerics only, input/fill im values using the correct format and prompt an error when the user inputs an incomplete value. And also how can I have it in a javascript format

  $(window).load(function(){
    $("#EWR").inputmask("99-99-999");
  });

   CARD N (yy-ww-xxx):
    <input size= "50" type = "Text" name = "EWR" style= "margin-left: -5px" id="EWR" maxlength="7" required>

A: For digits only you could use :
$("#EWR").keypress(function(e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                $("#errmsg").html("Digits Only").show().fadeOut("slow");
                return false
            }
});

Add this right after the label close tag to display a warning :


text:
Q: How would you add an image (watermark) while capturing a video [directshow.net]? I've been working with the DxLogo project from the DirectShowNET samples. This will add an image to video but when moved it distorts the images color and it also doesn't handle transparent backgrounds. So in order for it to handle those factors...
Some how I need to convert the frame to a bitmap:
Bitmap v = new Bitmap(m_videoWidth, m_videoHeight, m_stride, PixelFormat.Format32bppArgb, pBuffer);

Then add the watermark to the new bitmap:
Graphics g = Graphics.FromImage(v);
g.DrawImage(m_Bitmap, 0, 0, m_Bitmap.Width, m_Bitmap.Height);
v = new Bitmap(v.Width, v.Height, g);

Then have the BufferCB take the new bitmap as the frame, and that's where I'm stuck. How would you do that?
Original DxLogo BufferCB method:
int ISampleGrabberCB.BufferCB( double SampleTime, IntPtr pBuffer, int BufferLen )
{
    // Avoid the possibility that someone is calling SetLogo() at this instant
    lock (this)
    {
        if (m_bmdLogo != null)
        {
            for (int x = 0; x < m_bmdLogo.Height; x++)
            {
                CopyMemory(ipDest, ipSource, (uint)m_bmdLogo.Stride);
                ipSource = (IntPtr)(ipSource.ToInt32() + m_bmdLogo.Stride);
                ipDest = (IntPtr)(ipDest.ToInt32() + m_stride);
            }
        }
    }

    return 0;
}

Thanks!

A: Found the issue in case anyone else runs into the problem. I was using the wrong PixelFormat when creating the bitmat from the pBuffer. Instead of PixelFormat.Format32bppArgb use PixelFormat.Format24bppRgb.
Here's my working BufferCB for the DxLogo sample:
int ISampleGrabberCB.BufferCB( double SampleTime, IntPtr pBuffer, int BufferLen )
{
    // Avoid the possibility that someone is calling SetLogo() at this instant
    lock (this)
    {
        if (m_Bitmap != null)
        {
            Bitmap v;
            v = new Bitmap(m_videoWidth, m_videoHeight, m_stride, PixelFormat.Format24bppRgb, pBuffer);

            Graphics g = Graphics.FromImage(v);
            g.DrawImage(m_Bitmap, 100, 100, m_Bitmap.Width, m_Bitmap.Height);
        }
    }

This solves the issue where the images colors would distort if repositioned and transparent backgrounds now work.


text:
Q: Armazenar valor de um atributo em uma variável em jquery Eu tenho esse seguinte menu:

    Inicial

    Perfil

    Calendário

    Material Didático

    Frequencias

    Notas

    Financeiro

    Biblioteca

    Configurações

e tenho esse código jQuery:
$(document).ready(function(){
     $("a#nav").click(function(){

     });
});

o que eu preciso é quando eu clicar por exemplo no menu eu pegar o valor do class e colocar em uma variável, por exemplo se eu clicasse no primeiro "Inicial" eu pegasse o valor da class, que no caso seria o a.

A: Tente isso:
$(function(){
    $('a.nav').click(function(){
        var classes = $(this).find('i').attr('class');
        var classe = classes.charAt(0);
    });
});

Contudo, isso não resolve se o nome da classe que quer pegar tenha mais do que um caractere e se ela não estiver no começo da declaração.
E de acordo com comentário de @DanielAlves na pergunta não duplique um id utilize classes para identificar seus links e é interessante o href ter um #! porque assim a página não dá "scroll":

    Inicial

A: Eu achei estranho você colocar na #nav do html, não seria somente id="nav"?
Também foi relatado que não é uma boa prática id com mesmo nome, então verifique esse html porque realmente tem imperfeições.!
Mas existe uma forma que pode funcionar para o seu caso em especifico, exemplo:

$(document).ready(function() {
  $("li a").click(function() {
      var value = $(this)
        .find('i')
        .attr('class')
        .charAt(0);
      console.log(value);
  });
});

    Inicial

    Perfil

    Calendário

    Material Didático

    Frequencias

    Notas

    Financeiro

    Biblioteca

    Configurações

A: Você pode criar um atributo nas tag de link  e recuperar este dado no jquery.
o código abaixo está bem simples mas fornece a resposta para a solução.

$("li a").click(function(){
      var variavel = $(this).attr('data-link');
      console.log('o link selecionado foi '+variavel);
     });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    Inicial

    Perfil

    Calendário

    Material Didático

    Frequencias

    Notas

    Financeiro

    Biblioteca

    Configurações


text:
Q: python capitalize() on a string starting with space I was using the capitalize method on some strings in Python and one of strings starts with a space:
phrase = ' Lexical Semantics'

phrase.capitalize() returns ' lexical semantics' all in lower case. Why is that?

A: This is the listed behaviour:

Return a copy of the string with its first character capitalized and the rest lowercased.

The first character is a space, the space is unchanged, the rest lowercased.
If you want to make it all uppercase, see str.upper(), or str.title() for the first letter of every word.
>>> phrase = 'lexical semantics'
>>> phrase.capitalize()
'Lexical semantics'
>>> phrase.upper()
'LEXICAL SEMANTICS'
>>> phrase.title()
'Lexical Semantics'

Or, if it's just a problem with the space:
>>> phrase = ' lexical semantics'
>>> phrase.strip().capitalize()
'Lexical semantics'

A: .capitalize() capitalises the first character ... which is a space :) Every other character gets lowercased.

A: It is because the first character is a space, not a letter.


text:
Q: The best way to implement different behaviour's using the same abstraction actually i'm developing a weapon system on unity where you can mount a weapon with three different kind of bullets and i have same structure for bullet prefab but the movement logic should be different for each one. I'm having problems with GetComponent to find abstracted scripts and interfaces, i'm searching for a good solution to implement this architecture. Thanks!
public class BaseBullet : MonoBehaviour, IBullet { .... }
interface IBullet { .. void shoot(vector2 direction); }
public class BaseWeapon : MonoBehaviour, IWeapon
{ ... BaseBullet bullet1; BaseBullet bullet2; BaseBullet bullet3 }


text:
Q: Composition of some linear differential operators $(D-A_n)...(D-A_1)$ Let $D=x\frac{d}{dx}$ and $A_i\in\mathbb{R}[[x]]$ for $i=1,...,n$. Let $B_i\in\mathbb{R}[[x]]$ for $i=1,...,n$ such that $$(D-A_n)...(D-A_1)=D^n+\sum_{i=1}^nB_iD^{n-i}.$$
Is there a well-known formula for $B_i$?
Also, suggestions for the resources for the factorization of linear differential operators are appreciated.


text:
Q: How to find if a GeoCoordinate point is within boundaries I have a list of points (actually shops coordinates) and I need to determine if they lay within certain boundaries.
In C# I know how to create a point from lat&lng
var point = new GeoCoordinate(latitude, longitude);

But how can I check if that point is contained in the rectangle defined by those other two points:
    var swPoint = new GeoCoordinate(bounds.swlat, bounds.swlng);
    var nePoint = new GeoCoordinate(bounds.nelat, bounds.nelng);

Is there any class method I can use?

A: If you are using
http://msdn.microsoft.com/en-us/library/system.device.location.geocoordinate.aspx
You will have to write your own method to make this check.  You may want to make it an extension method (Lot's of resources available on Extension Methods online.)
Then it is almost as simple as
public static Boolean isWithin(this GeoCoordinate pt, GeoCoordinate sw, GeoCoordinate ne)
{
   return pt.Latitude >= sw.Latitude &&
          pt.Latitude <= ne.Latitude &&
          pt.Longitude >= sw.Longitude &&
          pt.Longitude <= ne.Longitude
}

There is one corner case to consider.  The above method will fail if the box defined by sw, ne crosses the 180-degree Longitude.  So additional code will have to be written to cover that case, thus slowing the performance of the method.