Q:

How to scroll page with selenium

I am using FirefoxDriver webdriver. The page that loads in Firefox window is a large page and I want to scroll that page using selenium.
I want to know how this can be done.

A:

If you want to scroll on the firefox window using selenium webdriver, one of the way is to use javaScript in the java code, The javeScript code to scroll down is as follows:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight," + "document.body.scrollHeight,document.documentElement.clientHeight));");

A:

I think you should do something like
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Good Luck.


Q:

Installing EPSON L355 on Ubuntu 14.04

I have recently installed ubuntu 14.04. I have downloaded the driver of my printer from here because in the "printers" drivers menu the driver for EPSON L355 does not appear.
When I try to install the drivers I get this error
vladimir@qubit:~/Documents/Programs/epson_printer_drivers$ sudo dpkg -i epson-inkjet-printer-201207w_1.0.0-1lsb3.2_i386.deb
Selecting previously unselected package epson-inkjet-printer-201207w.
(Reading database ... 215943 files and directories currently installed.)
Preparing to unpack epson-inkjet-printer-201207w_1.0.0-1lsb3.2_i386.deb ...
Unpacking epson-inkjet-printer-201207w (1.0.0-1lsb3.2) ...
dpkg: dependency problems prevent configuration of epson-inkjet-printer-201207w:
 epson-inkjet-printer-201207w depends on lsb (>= 3.2).

dpkg: error processing package epson-inkjet-printer-201207w (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 epson-inkjet-printer-201207w

I have no idea how to fix this. I've tried some solutions involving the package alien, as well as gdebi, but I can't succeed. I'm a bit desperate by now, so any help is very much appreciated.
Also, checking my lsb gives:
vladimir@qubit:~/Documents/Programs/epson_printer_drivers$ lsb_release -a
LSB Version:    core-2.0-amd64:core-2.0-noarch:core-3.0-amd64:core-3.0-noarch:core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noarch:core-4.0-amd64:core-4.0-noarch:core-4.1-amd64:core-4.1-noarch:cxx-3.0-amd64:cxx-3.0-noarch:cxx-3.1-amd64:cxx-3.1-noarch:cxx-3.2-amd64:cxx-3.2-noarch:cxx-4.0-amd64:cxx-4.0-noarch:cxx-4.1-amd64:cxx-4.1-noarch:desktop-3.1-amd64:desktop-3.1-noarch:desktop-3.2-amd64:desktop-3.2-noarch:desktop-4.0-amd64:desktop-4.0-noarch:desktop-4.1-amd64:desktop-4.1-noarch:graphics-2.0-amd64:graphics-2.0-noarch:graphics-3.0-amd64:graphics-3.0-noarch:graphics-3.1-amd64:graphics-3.1-noarch:graphics-3.2-amd64:graphics-3.2-noarch:graphics-4.0-amd64:graphics-4.0-noarch:graphics-4.1-amd64:graphics-4.1-noarch:languages-3.2-amd64:languages-3.2-noarch:languages-4.0-amd64:languages-4.0-noarch:languages-4.1-amd64:languages-4.1-noarch:multimedia-3.2-amd64:multimedia-3.2-noarch:multimedia-4.0-amd64:multimedia-4.0-noarch:multimedia-4.1-amd64:multimedia-4.1-noarch:printing-3.2-amd64:printing-3.2-noarch:printing-4.0-amd64:printing-4.0-noarch:printing-4.1-amd64:printing-4.1-noarch:qt4-3.1-amd64:qt4-3.1-noarch:security-4.0-amd64:security-4.0-noarch:security-4.1-amd64:security-4.1-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

A:

OP accidentally tried to install 32bit driver, while using a 64bit OS.

32bit driver
64bit driver

OP installed the 64bit driver, and all was resolved.


Q:

Android emulator, network state and internet access

I was trying to test the network state of my emulator using following code and allowing it android.permission.ACCESS_NETWORK_STATE:
public class Main extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean wified = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
        TextView textView = (TextView) findViewById(R.id.textView1);
        if (wified) {
            textView.setText("Wified");
        } else {
            textView.setText("Not connected to wifi");
        }
    }
    //..
}

When I run it as Android Application I get Not connected to wifi TextView message displayed on the emulator but when I use emulator to connect to google.com or yahoo.com, it works just fine.
Could someone help me understand why am I getting Not connected to wifi message?
Thanks.

A:

Try adding <uses-permission android:name="android.permission.INTERNET" />
In permission section in your Android manifest file.
Edit:-
Try this..
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo Info = cm.getActiveNetworkInfo();
        if (Info == null || !Info.isConnectedOrConnecting()) {
            Log.i(TAG, "No connection");
        } else {
            int netType = Info.getType();
            int netSubtype = Info.getSubtype();

            if (netType == ConnectivityManager.TYPE_WIFI) {
                Log.i(TAG, "Wifi connection");
             wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                 int linkSpeed = wifiManager.getConnectionInfo().getLinkSpeed();
            //Need to get wifi strength
        } else if (netType == ConnectivityManager.TYPE_MOBILE) {
          Log.i(TAG, "GPRS/3G connection");
           //Need to get differentiate between 3G/GPRS
        }
    }

Ofcourse, check this on real device :)
Hope this helps.


Q:

Why can't I access req.body with multer?

My app (using vue) allows users to upload files with some info about the data to my node backend.  When the user submits the form, this function is triggered:
methods: {
      buttonOK () {
        const formData = new FormData()

        formData.append('name', this.detailFirm.name)
        formData.append('description', this.detailFirm.description)
        formData.append('version', this.detailFirm.version)
        formData.append('date', this.detailFirm.date)
        formData.append('file', this.file)

        for (var [key, value] of formData.entries()) {
          console.log(key, value)
        }

        let headers = {
          'Content-Type': 'multipart/form-data',
          'Accept': 'multipart/form-data'
        }

        this.$http.put('/firmware', formData, {headers: headers})
        this.visible = false
      }

The log statement shows everything that it ought to, and when this request is made, the network tab in the chrome dev tools shows the post data going through, and it has all the values it should:
name: test
description: test
version: 1
date: 0555-05-05
file: (binary)

My multer middleware looks like this:
const multer = require('multer')
const mult = multer({
  dest: '/firmware'
})

module.exports = function (req, res, next) {
  /* --Convert multipart/form-data to useable format within express-- */
  if (req.path === '/firmware') {
    mult.single('file')
    console.log('MULTER MIDDLEWARE')
  }
  next()
}

The log statement there works, leading me to believe that multer is working.
I can't seem to access this information in back end though.  Here I have tried both file and formData as the file name in mult.single('').
Here is my controller function:
let firmware = {
    name: req.body.name,
    version: req.body.version,
    description: req.body.description,
    date: req.body.date,
    file: req.body.file
  }
  firmwareRepo.create(firmware, (err, create) => {
                   .............

I've read some other questions, and have made a few adjustments, but I always get an empty object when I log req.body in the controller.  Please advise.

A:

I don't know why this worked, but everything started functioning as it should when I stopped using multer as an imported middleware, like this:
module.exports = function (req, res, next) {
  /* --Convert multipart/form-data to useable format within express-- */
  if (req.path === '/firmware') {
    mult.single('formData')
    console.log('MULTER MIDDLEWARE')
  }
  next()
}

and instead applied it directly to the route function, like this:
router.put('/firmware', upload.single('formData'), firmware.create) // doesn't work as standalone middleware

If anyone knows why that would be the case, please let me know.


Q:

Show that these circles are linked (their linking number is $\pm 1$)

There are two circles given in 3 dimensions:
$$c_0(\phi) = (\cos(\phi), \sin(\phi),0)\ \ \ \phi \in [0,2\pi[$$
$$c_1(\phi) = \frac{1}{\sqrt{2}-\sin(\phi)}(\cos(\phi), \sin(\phi), \cos(\phi))\ \ \ \phi \in [0,2\pi[$$
Show that their linking number is $\pm 1$, where the linking number is defined by:
$$L(c_0,c_1) = \frac{1}{4\pi}\int_0^{2\pi}\int_0^{2\pi}\frac{(c_0(t)-c_1(s),\dot c_0(t),\dot c_1(s))}{|c_0(t)-c_1(s)|^3}\,dt\ ds$$
Where
$$\text{if } \ a,b,c:\Bbb{R} \to \Bbb{R}^3$$
$$\text{then } \ (a(t),b(t),c(t)) =
\begin{align}\begin{vmatrix}
a_1(t) & b_1(t) & c_1(t) \\
a_2(t) & b_2(t) & c_2(t) \\
a_3(t) & b_3(t) & c_3(t) \\
\end{vmatrix}
\end{align}$$
And
$$\text{if } \ c: \Bbb{R} \to \Bbb{R}^3, \ c(t) = (c_1(t),c_2(t),c_3(t))$$
$$\text{then } \ \dot c(t) = (c_1'(t),c_2'(t),c_3'(t))$$
Usually the integral for the linking number is very difficult to calculate, so there are other options too. For example, since we know that our curves are circles, their linking number can only be $L(c_0,c_1) \in \{-1,0,+1\}$. Showing that an integral is equal to a specific value can be done with this following technique:
$$L(c_0,c_1) \stackrel{?}{=} a \in \{-1,0,+1\} \iff \\
\iff \forall \varepsilon \in \Bbb{R}^+: a - \varepsilon \stackrel{?}{\le} L(c_0,c_1) \stackrel{?}{\le} a + \varepsilon $$
So far I've shown that the circles don't intersect, meaning that there are no $\phi \in \ [0,2\pi[$ values for which $|c_0(\phi)-c_1(\phi)| = 0$. That was relatively easy to show. But the big question is:
$$L(c_0,c_1) \stackrel{?}{=} \pm 1$$
I would appreciate any insight on how I could possibly show this.
In other words, how can we show that the above integral is approximately equal to $1$, with perhaps numerical methods?

A:

Mathematica cannot solve your integral exactly, but it can numerically integrate it. The output of the numerical integration is 1. See the Mathematica code below.

Also, you can use Mathematica to plot the two curves, yielding the following picture.

The linking number of two components of a link can be computed from a diagram of the link. Each crossing is either a positive (or $+1$) crossing or a negative (or $-1$) crossing, as below.

The linking number of the two components is
$$\frac{1}{2}(\#\text{positive crossings} - \#\text{negative crossings})$$
where we only count the crossings between the two components. See the wikipedia page for linking number. If you look in the picture produced by Mathematica above, you can tell that the two circles are linked (and thus have linking number $\pm 1$). By looking at the parameterizations, it shouldn't be too hard to find the orientation of each curve, and then to compute the linking number from the diagram. Both crossings in the above diagram turn out to be positive, and so the linking number is 1.


Q:

Run a shell command with arguments from powershell script

I need to extract and save a some tables from a remote SQL database using bcp. I would like to write a powershell script to invoke bcp for each table and save the data. So far I have this script that creates the necessary args for bcp. However I can not figure out how to pass the args to bcp. Every time I run the script it just shows the bcp help instead. This must be something really easy that I am not getting.
#commands bcp database.dbo.tablename out c:\temp\users.txt -N -t, -U uname -P pwd -S <servername>
$bcp_path = "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe"
$serverinfo =@{}
$serverinfo.add('table','database.dbo.tablename')
$serverinfo.add('uid','uname')
$serverinfo.add('pwd','pwd')
$serverinfo.add('server','servername')
$out_path= "c:\Temp\db\"
$args = "$($serverinfo['table']) out $($out_path)test.dat -N -t, -U $($serverinfo['uid']) -P $($serverinfo['pwd']) -S $($serverinfo['server'])"

#this is the part I can't figure out
& $bcp_path $args

A:

First of all, $args is an automatic variable; you can't set it, so any line like $args = foo will do nothing (even with strict mode on; though a complaint would have been nice).
Then you are only passing a single argument (the string) to the program. I contains spaces, but they are properly escaped or enclosed in parentheses, so the program only sees a single argument.
You'll need to use an array for arguments to a program, instead of a single string, if you want to store it in a variable beforehand. And you need to name it something different than $args:
$arguments = "$($serverinfo['table'])",
             'out',"$($out_path)test.dat",
             '-N','-t,',
             '-U',"$($serverinfo['uid'])",
             '-P',"$($serverinfo['pwd'])",
             '-S',"$($serverinfo['server'])"

& $bcp_path $arguments

Or, what I would prefer, actually, you can simply write it out in a single line which gets rid of most of the ugliness here:
$out_path = 'c:\Temp\db'
& $bcp_path $serverinfo['table'] out $out_path\test.dat -N '-t,' -U $serverinfo['uid'] -P $serverinfo['pwd'] -S $serverinfo['server']


Q:

User input to be separated with semicolon

Can you suggest a short way on how to separate the user input with a semicolon, and the store it into an array.
The line when a user is entering words should look like this.
First;Second;Third;Forth

A:

Assuming the user input is placed in raw_input variable
string[] input = raw_input.Split(';');


Q:

Capturing HTML to String in MVC2.0

I am new to MVC2.0. I use the below code to capture HTML and return it as a string. But this works fine in MVC1.0 and .NET 3.5 framework. Recently I upgraded the code to .NET 4.0 and MVC 2.0. Now this is no longer working and the context returns null. when I explore I saw two errors
1."This operation requires IIS integrated pipeline mode."
2.OutputStream = 'response.OutputStream' threw an exception of type system.Web.HttpException'
Here is the calling function
var htmlstring = this.CaptureActionHtml(new PdfController(_paService, _configService), c => (ViewResult)paController.GetHTML(p));

//and the capture method.
  /// <summary>
    /// Captures the HTML output by a controller action that returns a ViewResult
    /// </summary>
    /// <typeparam name="TController">The type of controller to execute the action on</typeparam>
    /// <param name="controller">The current controller</param>
    /// <param name="targetController">The controller which has the action to execute</param>
    /// <param name="action">The action to execute</param>
    /// <returns>The HTML output from the view</returns>
    public static string CaptureActionHtml<TController>(
        this Controller controller,
        TController targetController,
        Func<TController, ViewResult> action)
        where TController : Controller
    {
        return controller.CaptureActionHtml(targetController, null, action);
    }
        /// <summary>
        /// Captures the HTML output by a controller action that returns a ViewResult
        /// </summary>
        /// <typeparam name="TController">The type of controller to execute the action on</typeparam>
        /// <param name="controller">The current controller</param>
        /// <param name="targetController">The controller which has the action to execute</param>
        /// <param name="masterPageName">The name of the master page for the view</param>
        /// <param name="action">The action to execute</param>
        /// <returns>The HTML output from the view</returns>
         public static string CaptureActionHtml<TController>(
            this Controller controller,
            TController targetController,
            string masterPageName,
            Func<TController, ViewResult> action)
            where TController : Controller
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }
            if (targetController == null)
            {
                throw new ArgumentNullException("targetController");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            // pass the current controller context to orderController
            var controllerContext = controller.ControllerContext;
            targetController.ControllerContext = controllerContext;

            // replace the current context with a new context that writes to a string writer
            var existingContext = System.Web.HttpContext.Current;
            var writer = new StringWriter();
            var response = new HttpResponse(writer);
            var context = new HttpContext(existingContext.Request, response) {User = existingContext.User};
            System.Web.HttpContext.Current = context;

            // execute the action
            var viewResult = action(targetController);

            // change the master page name
            if (masterPageName != null)
            {
                viewResult.MasterName = masterPageName;
            }

            // we have to set the controller route value to the name of the controller we want to execute
            // because the ViewLocator class uses this to find the correct view
            var oldController = controllerContext.RouteData.Values["controller"];
            controllerContext.RouteData.Values["controller"] = typeof(TController).Name.Replace("Controller", "");

            // execute the result
            viewResult.ExecuteResult(controllerContext);

            // restore the old route data
            controllerContext.RouteData.Values["controller"] = oldController;

            // restore the old context
            System.Web.HttpContext.Current = existingContext;

            return writer.ToString();
        }

I found a work around.. but struck in another problem.. The model was not passing through the view..Here is the updated code
public static string CaptureActionHtml<TController>(this Controller controller, TController targetController, string masterPageName, Func<TController, ViewResult>  action) where TController : Controller

       {
    if (controller == null)
    {
    throw new ArgumentNullException("controller");
    }
    if (targetController == null)
    {
    throw new ArgumentNullException("targetController");
    }
    if (action == null)
    {
    throw new ArgumentNullException("action");
    }
    // pass the current controller context to orderController
    var controllerContext = controller.ControllerContext;
    targetController.ControllerContext = controllerContext;

    // replace the current context with a new context that writes to a string writer
    var existingContext = HttpContext.Current;
    var writer = new StringWriter();
    var response = new HttpResponse(writer);
    var context = new HttpContext(existingContext.Request, response) { User = existingContext.User };
    HttpContext.Current = context;

    // execute the action
    var viewResult = action(targetController);

    // change the master page name
    if (masterPageName != null)
    {
    viewResult.MasterName = masterPageName;
    }

    // we have to set the controller route value to the name of the controller we want to execute
    // because the ViewLocator class uses this to find the correct view
    var oldController = controllerContext.RouteData.Values["controller"];
    controllerContext.RouteData.Values["controller"] = typeof(TController).Name.Replace("Controller", "");

    // execute the result
    viewResult.ExecuteResult(controllerContext);

    StringWriter sw = new StringWriter();
    //var viewContext = new ViewContext(controllerContext, viewResult.View, new ViewDataDictionary(controllerContext.Controller.ViewData.Model), new TempDataDictionary(), sw);
    var viewContext = new ViewContext(controllerContext, viewResult.View, targetController.ViewData, new TempDataDictionary(), sw);
    viewResult.View.Render(viewContext, HttpContext.Current.Response.Output);
    response.Flush();

    // restore the old route data
    controllerContext.RouteData.Values["controller"] = oldController;

    // restore the old context
    HttpContext.Current = existingContext;

    return sw.ToString();
    }

any suggestions will be really helpful..

A:

Thanks for reviewing.. I found it myself.. silly me!! its just simple thing.. Here is the full code..
public static string CaptureActionHtml<TController>(this Controller controller, TController targetController, string masterPageName, Func<TController, ViewResult>  action) where TController : Controller

       {
    if (controller == null)
    {
    throw new ArgumentNullException("controller");
    }
    if (targetController == null)
    {
    throw new ArgumentNullException("targetController");
    }
    if (action == null)
    {
    throw new ArgumentNullException("action");
    }
    // pass the current controller context to orderController
    var controllerContext = controller.ControllerContext;
    targetController.ControllerContext = controllerContext;

    // replace the current context with a new context that writes to a string writer
    var existingContext = HttpContext.Current;
    var writer = new StringWriter();
    var response = new HttpResponse(writer);
    var context = new HttpContext(existingContext.Request, response) { User = existingContext.User };
    HttpContext.Current = context;

    // execute the action
    var viewResult = action(targetController);

    // change the master page name
    if (masterPageName != null)
    {
    viewResult.MasterName = masterPageName;
    }

    // we have to set the controller route value to the name of the controller we want to execute
    // because the ViewLocator class uses this to find the correct view
    var oldController = controllerContext.RouteData.Values["controller"];
    controllerContext.RouteData.Values["controller"] = typeof(TController).Name.Replace("Controller", "");

    // execute the result
    viewResult.ExecuteResult(controllerContext);

    StringWriter sw = new StringWriter();
    var xx = targetController.TempData["pdf"];
    //var viewContext = new ViewContext(controllerContext, viewResult.View, new ViewDataDictionary(targetController.ViewData.Model), new TempDataDictionary(), sw);
    var viewContext = new ViewContext(controllerContext, viewResult.View, viewResult.ViewData, new TempDataDictionary(), sw);
    viewResult.View.Render(viewContext, HttpContext.Current.Response.Output);
    response.Flush();

    // restore the old route data
    controllerContext.RouteData.Values["controller"] = oldController;

    // restore the old context
    HttpContext.Current = existingContext;

    return sw.ToString();
    }

I just replaced this line of code
var viewContext = new ViewContext(controllerContext, viewResult.View, new ViewDataDictionary(targetController.ViewData.Model), new TempDataDictionary(), sw);

with
var viewContext = new ViewContext(controllerContext, viewResult.View, viewResult.ViewData, new TempDataDictionary(), sw);

It works fine.. Cheers!!


Q:

Joomla file with classic cronjob don't work?

I have in root folder of my joomla website a php where i load joomla framework and create a xml output file, the first lines before i do a db request are:
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', realpath(dirname(__FILE__)));

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

If i run this file i get a well generated xml file, that's ok. but i need to set a cronjob for it, if i try to run cron job, i get this error message:
/PATH/my_file.php: line 1: ?php: No such file or directory
/PATH/my_file.php: line 2: syntax error near unexpected token `'_JEXEC','
/PATH/my_file.php: line 2: `    define( '_JEXEC', 1 );'

What i need to fix to get a correct cron job?

A:

You will need to define the path, starting from the very root of your server.
Try changing the command to the following:
php /home/XXXX/public_html/my_file.php


Q:

Tips for golfing in Keg

What general tips do you have for golfing in Keg? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Keg (e.g. "remove comments" is not an answer).
Please post one tip per answer.

A:

Brackets autocomplete
This is my biggest tip for anyone golfing in Keg: when writing programs, brackets used in loops or if-statements are automatically balanced if there are unclosed brackets.
For example:
(9|0.)

Can be shortened to:
(9|0.

And:
{:1=[1.]}

Can be shortened to:
{:1=[1.


Q:

incident ticket priority classification in R

I am new to R and machine learning. Here I tried to build a random forest classification model to predict the priority of a incident ticket from its description. The below steps I followed.
1) Input <- description using CSV file
library(tm)
library(SnowballC)
library(caTools)
library(randomForest)
incidents = read.csv("incident.csv", stringsAsFactors = FALSE)

> str(incidents) 'data.frame':  4265 obs. of  7 variables:  $ number                : chr  "INC0031193" "INC0037867" "INC0159979" "INC0031446" ...  $
> u_detailed_description: chr  "Close & Ignore new Ticket New-Production
> SNOW Auto Routing test for XYZ SNOW ticketing in uat"  "" "" ""...  $
> priority              : chr  "3 - Moderate" "2 - High" "4 - Low" "3 -
> Moderate" ...  $ state                 : chr  "Canceled" "Canceled"
> "Canceled" "Canceled" ...  $ category              : chr  "Server"
> "Tools" "Server" "Server" ...  $ assignment_group      : chr
> "Windows" "Tools" "SNOC Support" "Windows" ...

2) Data cleaning, creating DocumenTermMatrix and convert to DataFrame.
incidentCorpus <- Corpus(VectorSource(incidents$u_detailed_description))
incidentCorpus <- tm_map(incidentCorpus, tolower)
incidentCorpus <- tm_map(incidentCorpus, removePunctuation)
incidentCorpus <- tm_map(incidentCorpus, removeWords, stopwords("english"))
incidentCorpus <- tm_map(incidentCorpus, stemDocument)
incidentDTM <- DocumentTermMatrix(incidentCorpus)

3) Splitting data into train and test set using caTools.
set.seed(123)
split <- sample.split(incidentSparse$priority,SplitRatio = 0.7)
train <- subset(incidentSparse, split == TRUE)
test  <- subset(incidentSparse, split == FALSE)
train$priority <- as.character(train$priority)
train$priority <- as.factor(train$priority
test$priority  <- as.character(testSet1$priority)
test$priority  <- as.factor(testSet1$priority)

4) Apply the randomforest() function to create my model and used predict function to classify my test set as well.
incidentRandomF <- randomForest(priority ~ ., data = train, ntree = 200, mtry = 50, importance = TRUE, proximity = TRUE)

5) the overall accuracy of the model is around 90%.
baselineAccuracy <- sum(diag(table(predict(incidentRandomF, type="class"), train$priority)))/nrow(train)

> baselineAccuracy
[1] 0.8392498

predFinalTestSet_RF <- predict(incidentRandomF, newdata = test,  type="class")
FinalTestSetAccuracy <- sum(diag(table(test$priority,predFinalTestSet_RF)))/nrow(test)

> FinalTestSetAccuracy
[1] 0.8828125

As of now my classification model is ready and now I need to execute this model to predict the priority based on a given description, where the description would be provided by the user.
How to provide user input to the R script to make it functional properly?
Your help would be highly appreciated.
Thanks in advance.

A:

So without writing the entire page (or testing the code I wrote here), but hopefully enough to show how to get started (let me know if you have any more questions), here's how the Shiny app will basically look:
In a file called ui.R:
fluidPage(

  # Copy the line below to make a text input box
  textInput("u_detailed_description", label = h3("Text input"), value = "Enter text..."),
  #Additional inputs for other fields here

  hr(),
  fluidRow(column(3, verbatimTextOutput("prediction")))

)

Then in server.R:
function(input, output) {

  # You can access the value of the widget with input$u_detailed_description, e.g.
  output$value <- renderPrint({ predict(incidentRandomF, newdata = input,  type="class") })

}

Tons of great information and documentation, including very many examples over at the Shiny site
While looking something else up, I stumbled on this repo that shows someone displaying predictions from a model in a Shiny app, it might help clarify how to do things like save your model and reload it and that sort of thing.


Q:

MS Chart, add triangles to an existing chart at specific points

Im wondering if its possible to add colored triangles (pointing up or down) at specific points (x,y) on an existing chart, such that they will update their positions if the chart is scrolled/zoomed.
Ive had a google around but havent stumbled across anything which seems to meet those requirements.
Any pointers would be appreciated.

A:

Draw a point chart with markers.
Create your own image and use MarkerImage property to load custom image
Answer Explaining how to get your inverted triangles
Custom MarkerStyles possible in Microsoft Chart Controls?


Q:

Handling parallel ftp download errors

I am downloading multiple files from a ftp server simultaneously using multiple sessions of Python.  At some point one session (I suspect) reads a file that is being accessed by another process and throws the following error:
Traceback (most recent call last):   File
"F:\utilities\python\downloadFTP_NV.py", line 66, in <module>
     os.unlink(FILE) WindowsError: [Error 32] The process cannot access the file because it is being used by another process:
u'm_4011851_ne_11_1_20100620.tif'

This is the block of code where I cannot seem to find the best way to handle the errors and move to the next file to download:
        # Set logic so that already downloaded or partially
        # downloaded files will not be downloaded again
        if os.path.exists(fileCheck): # "fileCheck" is a file prior to renaming
            print 'File "%s" exists already' % name
            pass

        elif os.path.exists(fileCheck2): # "fileCheck2 is a file after renaming
            print 'File "%s" exists already' % FILE
            pass

        else:
            try:
                f.cwd(DIRN + folder)
                start = time.clock()
                f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
                end = time.clock()
                arcpy.Rename_management(os.path.join(workspace, FILE), os.path.join(workspace, name))
            except ftplib.error_perm:
                print 'ERROR: cannot read file "%s"' % FILE
                os.unlink(FILE)

I have thought about adding another except statement with a time.sleep(5) to help reduce overlapping processes.  Or perhaps simply removing the os.unlink(FILE) line.  What is the best method to handle errors such as this one?

A:

I know that this post is 3 years old, but for other users sake that could maybe have the same issue, i will give a possible solution
In your code i don't see that you close your file after the operation, so i think that is where the issue is. As a best practice it is always good to use the with statement as it gives a context manager and a better error handling.
so your part of code where you retrieve a file should be like this
with open(FILE, 'wb') as fhandle:
      ftp.retrbinary('RETR ' + FILE, fhandle.write)

That should fix your problem. And you don't need the os.unlink(FILE)
If you need some background infos about the with statement, this is the place to visit PEP 343 -- The "with" Statement


Q:

How to append a third column in a dataframe using conditions from 2 other columns in a dataframe

I have the following data frame,
uuid    variable    value
AAS Highly_Active   False
AAS Highly_Active   True
SAP Highly_Active   False
SAP Multiple_days   True
YAS Highly_Active   False
YAS Highly_Active   False
YAS Busi_weekday    False

And I need to use the values from the column variable and value to define third column Activity and I have following classic python code doing it but my primary data frame is 121Mb in size and so its taking long time. Any pandas solutions would be great
def activity(row):
    if row['variable'] == "Highly_Active" and row['value'] ==True:
        val = "Highly_Active"
    else:
        val = "NO"
    if row['variable'] == "Multiple_days" and row['value']==True:
        val = "Multiple_days"
    else:
        val = "NO"
    if row['variable'] == "Busi_weekday" and row['value']==True:
        val = "Busi_weekday"
    else:
        val="NO"
    return val

A:

KIS, np.where -
status = ["Highly_Active", "Multiple_days", "Busi_weekday"]

df['Activity'] = np.where(
  df['variable'].isin(status) & df['value'],
  df['variable'],
  'NO'
)

df

  uuid       variable  value       Activity
0  AAS  Highly_Active  False             NO
1  AAS  Highly_Active   True  Highly_Active
2  SAP  Highly_Active  False             NO
3  SAP  Multiple_days   True  Multiple_days
4  YAS  Highly_Active  False             NO
5  YAS  Highly_Active  False             NO
6  YAS   Busi_weekday  False             NO

If @Paul H is right and isin is redundant in the solution above, then you can just use pd.Series.where/pd.Series.mask -
df['variable'].where(df['value'], 'NO')

Or,
df['variable'].mask(~df['value'], 'NO')

df

  uuid       variable  value       Activity
0  AAS  Highly_Active  False             NO
1  AAS  Highly_Active   True  Highly_Active
2  SAP  Highly_Active  False             NO
3  SAP  Multiple_days   True  Multiple_days
4  YAS  Highly_Active  False             NO
5  YAS  Highly_Active  False             NO
6  YAS   Busi_weekday  False             NO

A:

IIUC
df['Active']=(df.variable*df.value).replace('','No')
df
Out[653]:
  uuid       variable  value         Active
0  AAS  Highly_Active  False             No
1  AAS  Highly_Active   True  Highly_Active
2  SAP  Highly_Active  False             No
3  SAP  Multiple_days   True  Multiple_days
4  YAS  Highly_Active  False             No
5  YAS  Highly_Active  False             No
6  YAS   Busi_weekday  False             No


Q:

Rest APIs - mobile specific challenges

I'm working on a new iOS app project, on the mobile side. Some architecture changes are happening and it turns out we will have to rely on a custom built private API that will be used by the app we are building and also by other clients such as a website.
The API being designed follows the Rest style of resources-centric URI and CRUD operations mapped to HTTP verbs. things like:
GET www.example.com/books
DELETE www.example.com/books/482094
POST www.example.com/users/6793

The problem is that this style often leads to the need for the mobile client to do many requests for loading a single app screen or managing a single user UI action. This leads to the app being in loading mode for 8 seconds till it has everything needed. A slow and unresponsive app.
Mobile clients have serious limitations when it comes to connectivity and so ideally, we should follow that sort of rule:
1 screen == 1 API call
1 save == 1 API call.
There are many situations where this puts you on a collision course with the REST design principles, for examples:

let's say your app has been offline for a day and you need to sync
with four tables of the back-end databases and you need a call like
www.example.com/sync_everything?since=2015-07-24
let's say there is a screen where the user can edit many of his
objects, for example ticking tasks in his todo list. There should be
a way to edit all those tasks records in one single batch API call
rather than one API call per edit.
let's say there is a screen that
mixes information from the ORDER, SALESMEN and PRODUCT db tables, I
should get that data in one call instead of three.

the risk is that we might end up with the most Restful API there is and also the most useless unresponsive mobile app there is.
The thing is I'm only a new contractor there and what I need is something that help me makes those points, some articles from well respected  sources or something like that. Major players compromising with the REST style for their mobile client (e.g.: by using composite aggregate API end points).
Or any solution for this general problem. Thanks!

A:

The API being designed follows the Rest style of resources-centric URI and CRUD operations mapped to HTTP verbs.

This is your problem right here.
You have limited your resources to (I'm assuming) the models in your database. As such it is taking ages to load all these resources because your server has no concept of resources that don't have a representation in the database.
For example might have
www.example.com/books/482094
www.example.com/books/582045
www.example.com/books/427454
www.example.com/books/319343

that all have to be loaded to get my library
This isn't a problem with RESTful design, this is actual a REST anti-pattern. There is absolutely nothing in REST that says our resources must have a one to one mapping with anything else in your system, including database models.
The solution is to create more resources that better match what you want to load. If you have 5 resources that always end up together create a new resource that contains the info for those 5 resources.
What you should have is something like this
www.example.com/users/334/my_library

which just loads all the books for that user. "my_library" isn't a model in your database, but it is a resource. The server creates it based on models in the database but there is no 1-to-1 mapping and the server has flexibility to create this resource without changing your DB model.
You might also have
www.example.com/users/334/favioured_books
www.example.com/users/334/books_ordered_last_week
www.example.com/users/334/wishlist

none of which have to exist as model in your database or domain space.
There is a wide spread misconception that this is the wrong thing to do because frameworks like Rails taught people to map resources in a 1-to-1 fashion to models in the domain space which map again 1-to-1 with database rows. This is not necessary nor is it recommended.
Resources should be numerous, cheap and lightweight. It should be easy to create them, and they should be abstracted from your domain model. If you find you need a new one you just make a new one. If you have problems doing that it is your frameworks fault not a fault with REST.
Now the big caveat with that of course is whether your framework allows you to do this. Frameworks like Rails and Django which have taken the course to map 1-to-1 in order to "save you time" make it hard to do this. But that is a flaw with the frameworks, not with RESTful design.
Here is Jim Webber discussing this is more detail (including a few digs at Rails as well!)
https://yow.eventer.com/yow-2011-1004/domain-driven-design-for-restful-systems-by-jim-webber-1047


Q:

Can a 38kHz IR receiver module (TSOP38238) decode 870Hz pulse modulation IR?

I'm trying to reverse engineer my A/C remote controller IR.
I've decoded the IR signal as a NEC code with the PJRC IRremote library.
My attempt to retransmit the same code to A/C unit was unsuccessful.
Having a look at the IR code with a logic analyser (with an IR sensor rather than the TSOP38238) revealed the remote uses 870Hz pulse modulation.
How could the TSOP38238 decode that signal? is the decoding reliable?
Is this really a NEC variant with a different modulation?
EDIT: The module isn't a TSOP38238, but something that looks like it with the same pinout (should be compatible). The caption says 084ST

A:

I think you worry too much about (in)compatibilities. My guess is that you can just use that TSOP38238 and that it will receive the 870 Hz pulses flawlessly.
To make sending and receiving IR codes more reliable, the sender does not send 870 Hz pulses. Instead when a "1" needs to be sent it sends a 38 kHz signal, when a "0" needs to be sent it sends nothing. This is simple amplitude modulation and the TSOP38238 can decode that, the 870 Hz pulses will reappear at it's output.
Just feed those to your Arduino so that it can decode the 870 Hz pulses into codes.
So no worries, just try it and it will work !


Q:

How Post the list of items from PartialView to controller?

This is quite simple situation actually, but I can't get how to make this work. So, there is list of checkboxes rendered in PartialView. Data passed from parent ViewModel to child ViewModel in PartialView. All these wrapped by form, unfortunately I can't get the data from PartialView.
Parent ViewModel:
public class UserProgramsViewModel
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "Введите название")]
        [DisplayName("Название")]
        public string ProgramName { get; set; }
        [DisplayName("Пользователь")]
        public string UserName { get; set; }
        [DisplayName("Пользователь")]
        public int UserId { get; set; }
        [DisplayName("Дни Программы")]
        public ICollection<ProgramDaysDTO> ProgramDays { get; set; }
        public IEnumerable<DaysViewModel> Days { get;  set;} //Passed to Partial
    }

Child ViewModel:
public class DaysViewModel
    {
        public int Id { get; set; }
        public string DayName { get; set; }
    }

Parent View:
@Html.Partial("Days", Model.Days)

PartialView (here we are using attribute name 'Days' to bind it to Parent model)
@model IEnumerable<BBN.Admin.ViewModels.DaysViewModel>

    @foreach (var item in Model)
    {

<input type="checkbox" name="Days" value="@item.Id" /> @item.DayName

    }

Controller:
        [HttpPost]
        [RBAC]
        public async Task<ActionResult> Create(UserProgramsViewModel model)
        {
            var groups = await _us.GetAll();
            ViewBag.Users = groups.Select(x => new SelectListItem
            {
                Text = x.Login,
                Value = x.Id.ToString()
            });
            var dto = new UserProgramsDTO
            {
                ProgramName = model.ProgramName,
                UserId = model.UserId,
                Days = model.Days
            };
            var result = await _ps.Create(dto);
            if (result.IsSuccess == (BLL.Utilities.Enums.IsSuccess)Enums.IsSuccess.Success) return RedirectToAction("Index");
            else return View("Create");
        }

A:

You can use FormCollection. Assign item.DayName to input's name attribute:
PartialView(fragment):

      <input type="checkbox" name="@(item.DayName)Days" @if (item.Id > 0) { <text>checked</text> } /> @item.DayName

Then process FormCollection parameter and fill model's Days property with it's help:
Controller:
[HttpPost]
[RBAC]
public async Task<ActionResult> Create(UserProgramsViewModel model, FormCollection formCollection)
{
    model.Days = new List<DaysViewModel>();
    foreach(var key in formCollection.AllKeys.Where(x => x.Contains("Days")))
        model.Days.Add(new DaysViewModel { Id = formCollection[key] == "on" ? 1 : 0, DayName = key.Replace("Days", "")} );

     //other stuff...
}


Q:

ASP.NET DataGrid is empty

I have a ASP.NET datagrid which is on a user control. I have a main page which adds the user control ( sometimes multiple copies of the user control ) and restores them when a post back occurs.
The dataGrid has insert / edit / delete links. I can add multiple copies of the user control to the page and the insert / edit delete functionality works perfectly for each separate control.
Yesterday I added some property binding to the main page to which are unrelated to the user control using the format Text='<%# DocumentTitle %>'. Initially I couldn't get this to work until I added Page.DataBind(); to the main page's Page_Load method. At this point the property binding started working correctly but then I noticed the insert functionality had stopped working in the datagrid within each user control....I debugged and found that when the following line executes it finds the text fields in the controls within the dataGrid to be empty or "":
eInfo.Ref = ((TextBox)gvEG.FooterRow.FindControl("txtEmployeeName")).Text;

If I remove the page.DataBind() method from the main page then the property binding stops working but the dataGrid(s) in the userControl start working.
My question is two fold i) Why does the seemingly unrelated change effect the dataGrid and ii) what do I do to get this working?
I've added the relevant sections of my code below...or at least what I think are the relevant sections.
Default.aspx
    <div class="general">
    <asp:TextBox Width="488" runat="server" placeholder="Document Title"  Text='<%# DocumentTitle %>'></asp:TextBox>
    </div>

Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Create an empty user control for the first requirements section.
            EmployeeSectionUserControl myUserControl1 = (EmployeeSectionUserControl )LoadControl("~/EmployeeSectionUserControl .ascx");

            // Add it to the panel control holding all the user controls.
            MainPanel.Controls.Add(myUserControl1);

            DocumentTitle = "I am the default document title and I'm bound.";
        }
        else
        {
            // Do nothing
        }
        Page.DataBind();
    }

EmployeeSectionUserControl.ascx
<asp:GridView ID="gvEG" runat="server" AutoGenerateColumns="False" CssClass="grid"
AlternatingRowStyle-CssClass="gridAltRow" RowStyle-CssClass="gridRow" ShowFooter="True"
EditRowStyle-CssClass="gridEditRow" FooterStyle-CssClass="gridFooterRow" OnRowCancelingEdit="gvEG_RowCancelingEdit"
OnRowCommand="gvEG_RowCommand" OnRowDataBound="gvEG_RowDataBound" OnRowDeleting="gvEG_RowDeleting"
OnRowEditing="gvEG_RowEditing" OnRowUpdating="gvEG_RowUpdating" DataKeyNames="Id" ShowHeaderWhenEmpty="true">
<Columns>
    <asp:TemplateField HeaderText="Id" HeaderStyle-HorizontalAlign="Left" ControlStyle-Width="50px">
        <ItemTemplate>
            <%# Eval("Id")%>
        </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Ref" HeaderStyle-HorizontalAlign="Left" ControlStyle-Width="90px">
        <EditItemTemplate>
            <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Ref") %>'
                Width="90px"></asp:TextBox>
        </EditItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtEmployeeName" runat="server" Width="90px"></asp:TextBox>
        </FooterTemplate>

EmployeeSectionUserControl.ascx.cs
protected void gvEG_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            employeeInfo eInfo = new employeeInfo();
            eInfo.Id = 999;// Convert.ToInt32(((TextBox)gvEG.FooterRow.FindControl("Id")).Text);

            // If we're inserting from the EmptyDataTemplate( ie an empty table ) of the gridview then we need to retreive the data differently.
            // So we perform a check on the gridView FooterRow and if it's null then we can assume it's an empty table.
            if (gvEG.FooterRow == null)
            {
                TextBox referenceTxtBox = (((Control)e.CommandSource).NamingContainer).FindControl("txtEmployeeName") as TextBox;
                eInfo.Ref = referenceTxtBox.Text;
            }
            else
            {
                eInfo.Ref = ((TextBox)gvEG.FooterRow.FindControl("txtEmployeeName")).Text;
                eInfo.Need =
            }

            // Store Update and Re-bind data to grid.
        }
    }

A:

Page.DataBind() calls DataBind on it's children, so it updates DocumentTitle in the text box but it also DataBinds your grid. I didn't see a DataSource set in your grid, like an EntityDataSource, so I am assuming you are doing the smart retrieving (and preparation) of the data yourself in code and set the DataSource yourself:
gvEg.DataSource = someCollection;
gvEg.DataBind();

On the get your are loading the user-control and probably call this DataBind with specifying the DataSource. It binds and then you call Page.DataBind() which probably also triggers another DataBind for gvEg but since DataSource is set it shows the same.
On the post back you shouldn't do a DataBind() before handling events. Your call of Page.DataBind() does that. It triggers a DataBind() without a DataSource. Then the rowCommand comes and checks for the TextBox in the Footer which is cleared due to a DataBind with no elements.
What you should do is:
You shouldn't use Page.DataBind(). If you do so, you need todo it at a moment when all DataSources are set correctly and it shouldn't be kicked of during a post back. In general, I would not recommend using it because it makes it more complex and it's probably only helping a bit if you haven't set up your application correctly.
In your case it's definitely not necessary. Your textBox is a server control that's not part of any binding (GridView, Repeater, ListView). So your textBox is immediately available in your code behind.
So you should:

Give the textBox an ID you can use like txtDocumentTitle
 <asp:TextBox Width="488" ID="txtDocumentTitle" runat="server" placeholder="Document Title"></asp:TextBox>

Replace setting DocumentTitle (unless you need it for something else too) with:
 txtDocumentTitle.Text = "I am the default document title and I'm bound.";

Remove Page.DataBind();

So access server controls you have access immediately since they are also properties in your page or control.


Q:

lodash to find common values from array of objects

Find common values from Array of Objects and Transom them
tried using lodash groupBy
var data =[
  {
    "dc": 1,
    "effDate": "1/2/2019",
    "expDate": "1/2/2019",
    "rate": 1,
    "minCharge": 2
  },
  {
    "dc": 1,
    "effDate": "1/2/2019",
    "expDate": "1/2/2019",
    "rate": 2,
    "minCharge": 6
  },
  {
    "dc": 1,
    "effDate": "1/2/2019",
    "expDate": "1/2/2019",
    "rate": 4,
    "minCharge": 7
  }
]

var expectedResult=[
  {
    "dc": 1,
    "effDate": "1/2/2019",
    "expDate": "1/2/2019",
    "rateCharge": [
      {
        "rate": 1,
        "minCharge": 2
      },
      {
        "rate": 2,
        "minCharge": 6
      },
      {
        "rate": 4,
        "minCharge": 7
      }
    ]
  }
]

in data dc,effDate,expDate are same, so i need to keep common things as flat structure and move repeating items into rateCharge.
var expectedResult=uniqBy(data,(val1.rate,val2.rate) => {
  val1.rate!=val2.rate;
});

I have tried using lodash uniqBy property but i am not getting expected result.

A:

You need to group the items by the effDate, and then map the groups to the required form using _.pick() / _.omit() , _.map(), and using _.uniqBy() with the rate as the unique identifier.
Typescript example (open the browsers console)

const { flow, partialRight: pr, groupBy, map, head, pick, omit, uniqBy } = _

const EFF_DATA = 'effDate'
const baseProps = ['dc', EFF_DATA, 'expDate']

const fn = flow(
  pr(groupBy, EFF_DATA),
  pr(map, g => ({
    ...pick(head(g), baseProps),
    rateCharge: uniqBy(map(g, pr(omit, baseProps)), 'rate')
  }))
)

const data = [{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":1,"minCharge":2},{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":2,"minCharge":6},{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":4,"minCharge":7}]

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

If you already import the entire lodash packages, you can use chaining:

const { flow, partialRight: pr, groupBy, map, head, pick, omit, uniqBy } = _

const EFF_DATA = 'effDate'
const baseProps = ['dc', EFF_DATA, 'expDate']

const data = [{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":1,"minCharge":2},{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":2,"minCharge":6},{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":4,"minCharge":7}]

const result = _(data)
  .groupBy(EFF_DATA)
  .map(g => ({
    ...pick(head(g), baseProps),
    rateCharge: uniqBy(map(g, pr(omit, baseProps)), 'rate')
  }));

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

And the lodash/fp version:

const { flow, groupBy, map, head, pick, omit, uniqBy, assoc } = _;

const EFF_DATA = 'effDate'
const baseProps = ['dc', EFF_DATA, 'expDate'];

const fn = flow(
  groupBy(EFF_DATA),
  map(g => assoc(
    'rateCharge',
    flow(map(omit(baseProps)), uniqBy('rate'))(g),
    pick(baseProps, head(g))
  ))
)

const data = [{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":1,"minCharge":2},{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":2,"minCharge":6},{"dc":1,"effDate":"1/2/2019","expDate":"1/2/2019","rate":4,"minCharge":7}]

const result = fn(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>


Q:

How can I convert MultiMap to Map> using Guava?

I'm using MultiMap from Google Guava 12 like this:
Multimap<Integer, OccupancyType> pkgPOP = HashMultimap.create();

after inserting values into this multimap, I need to return:
Map<Integer, Set<OccupancyType>>

However, when I do:
return pkgPOP.asMap();

It returns me
Map<Integer, Collection<OccupancyType>>

How can I return Map<Integer, Set<OccupancyType>> instead ?

A:

Look at this issue and comment #2 by Kevin Bourrillion, head Guava dev:

You can double-cast the Map<K, Collection<V>> first to a raw Map and
  then to the Map<K, Set<V>> that you want. You'll have to suppress an
  unchecked warning and you should comment at that point, "Safe because
  SetMultimap guarantees this." I may even update the SetMultimap
  javadoc to mention this trick.

So do unchecked cast:
@SuppressWarnings("unchecked") // Safe because SetMultimap guarantees this.
final Map<Integer, Set<OccupancyType>> mapOfSets =
    (Map<Integer, Set<OccupancyType>>) (Map<?, ?>) pkgPOP.asMap();

EDIT:
Since Guava 15.0 you can use helper method to do this in more elegant way:
Map<Integer, Set<OccupancyType>> mapOfSets = Multimaps.asMap(pkgPOP);

A:

Guava contributor here:
Do the unsafe cast.  It'll be safe.
It can't return a Map<K, Set<V>> because of the way Java inheritance works.  Essentially, the Multimap supertype has to return a Map<K, Collection<V>>, and because Map<K, Set<V>> isn't a subtype of Map<K, Collection<V>>, you can't override asMap() to return a Map<K, Set<V>>.


Q:

foreach loop create a duplicated of last iteration

So I have a php foreach loop which inserts however many images you upload in to a directory and creates a row in your DB for it. it works great except it is duplicating the last iteration.
I have tried doing an array_splice but that didn't work.
I know the query is subject to sql injections and will fix this once I get the iteration duplication sorted.
$errors= array();
foreach($_FILES['userfile']['tmp_name'] as $key => $tmp_name ){
    $file_name = time().$_FILES['userfile']['name'][$key];
    $file_size =$_FILES['userfile']['size'][$key];
    $file_tmp =$_FILES['userfile']['tmp_name'][$key];
    $file_type=$_FILES['userfile']['type'][$key];
    if($file_size > 2097152){
        $errors[]='File size must be less than 2 MB';
    }
    $query="INSERT INTO table (user_id, filename) VALUES ('$user_id', '$file_name')";
    $desired_dir="/items/";
    if(empty($errors)==true){
        if(is_dir($desired_dir)==false){
            mkdir("$desired_dir", 0700);        // Create directory if it does not exist
        }
        if(is_dir("$desired_dir/".$file_name)==false){
            move_uploaded_file($file_tmp,"/items/".$file_name);
        }else{                                  //rename the file if another one exist
            $new_dir="/items/".$file_name.time();
             rename($file_tmp,$new_dir) ;
        }
        mysql_query($query);
    }else{
            print_r($errors);
    }
}
if(empty($error)){
    echo "Success";
}
if ($conn->query($query) === TRUE) {
echo "done";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}

any ideas as to why its doing this?
thanks in advance!

A:

Inside the last if.. else.. section you're calling $conn->query($query). This will run whatever is in $query - in this case it will be the last value set inside your foreach loop. That's what's causing you to duplicate the last entry.


Q:

T-SQL: checking for email format

I have this scenario where I need data integrity in the physical database. For example, I have a variable of @email_address VARCHAR(200) and I want to check if the value of @email_address is of email format. Anyone has any idea how to check format in T-SQL?
Many thanks!

A:

I tested the following query with many different wrong and valid email addresses. It should do the job.
IF (
     CHARINDEX(' ',LTRIM(RTRIM(@email_address))) = 0
AND  LEFT(LTRIM(@email_address),1) <> '@'
AND  RIGHT(RTRIM(@email_address),1) <> '.'
AND  CHARINDEX('.',@email_address ,CHARINDEX('@',@email_address)) - CHARINDEX('@',@email_address ) > 1
AND  LEN(LTRIM(RTRIM(@email_address ))) - LEN(REPLACE(LTRIM(RTRIM(@email_address)),'@','')) = 1
AND  CHARINDEX('.',REVERSE(LTRIM(RTRIM(@email_address)))) >= 3
AND  (CHARINDEX('.@',@email_address ) = 0 AND CHARINDEX('..',@email_address ) = 0)
)
   print 'valid email address'
ELSE
   print 'not valid'

It checks these conditions:

No embedded spaces
'@' can't be the first character of an email address
'.' can't be the last character of an email address
There must be a '.' somewhere after '@'
the '@' sign is allowed
Domain name should end with at least 2 character extension
can't have patterns like '.@' and '..'

A:

AFAIK there is no good way to do this.
The email format standard is so complex parsers have been known to run to thousands of lines of code, but even if you were to use a simpler form which would fail some obscure but valid addresses you'd have to do it without regular expressions which are not natively supported by T-SQL (again, I'm not 100% on that), leaving you with a simple fallback of somethign like:
LIKE '%_@_%_.__%'
..or similar.
My feeling is generally that you shouln't be doing this at the last possible moment though (as you insert into a DB) you should be doing it at the first opportunity and/or a common gateway (the controller which actually makes the SQL insert request), where incidentally you would have the advantage of regex, and possibly even a library which does the "real" validation for you.


Q:

why this frequency response is added to the power of e?

From where did this ${\angle}H{(\Omega)}$ came into power of $e$ ?

A:

$H(\Omega)$ is a complex number. $Ae^{j(\Omega t + \phi)}$ is another complex number, expressed in polar format by its magnitude $A$ and phase $\Omega t + \phi$. When you multiply complex numbers in this format, you simply multiply their magnitudes and sum their phases. Thus:
$$
H(\Omega)Ae^{j(\Omega t + \phi)} = |H(\Omega)| Ae^{j(\Omega t + \phi \angle H(\Omega))}
$$


Q:

Querying associated classes

If I have a class called Group, and in that class I have a
has_many :users
I want to add a method to the Group class to see if a specific user is in that group.  If I'm using the Devise authentication I can call the current_user.
So I guess my first question would be can I call that current_user from the model, or do I need to pass it to the method?
My second question is I should be able to do something like the following?
  def has_access?
    !current_user.nil && users.where(:id == current_user.id).count(:id) > 0
  end

A:

You can't call current_user in models - it's only available within the scope of controllers and views.
Which means your method's going to look a little different - perhaps try the following:
def has_access?(user)
  user.present? && users.where(:id => user.id).any?
end


Q:

Which data type to use to store fractions?

I have some values like 3/5, 90/100 etc.
I have to store these values in separate columns in my database.
I am confused as to which datatype to use for this purpose; which is faster for insert and select operations?

A:

Two integers; Numerator and denominator. Insertion/storing will be pretty much the same speed for any data type which provides a reasonable representation of a fraction.


Q:

TwitterにAVCaptureSessionで撮影した動画をアップロードできない

iPhoneのカメラで15秒間動画を撮影し、その動画をTwitterにアップロードしようとすると「Request status was 413」とエラーが返ってきて動画をアップロードできません。
アップロードしている最中にログに「SLRequestBodyInputStream  read:maxLength: Total 6692864 bytes streamed, total length is 15382475」というようなものが表示され続けています。（表示されるたびにTotal 6692864の数字が増えていっています）
Twitterにアップロードしている部分のコードは以下になります。
class TwitterSharer: NSObject {

var videoPathURL: URL
var account: ACAccount!
let twitterUploadURL = URL(string: "https://upload.twitter.com/1.1/media/upload.json")
let twitterStatusURL = URL(string: "https://api.twitter.com/1.1/statuses/update.json")

init(url: URL) {
    videoPathURL = url
}

func authAccount(completion: @escaping (_ error: Bool)->Void) {
    let accountStore = ACAccountStore()
    let accountType:ACAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
    accountStore.requestAccessToAccounts(with: accountType, options: nil) { (granted, error) -> Void in
        if error != nil {
            print("error! \(error)")
            completion(false)
            return
        }

        if !granted {
            print("error! Twitterアカウントの利用が許可されていません")
            completion(false)
            return
        }

        let accounts = accountStore.accounts(with: accountType) as! [ACAccount]
        if accounts.count == 0 {
            print("error! 設定画面からアカウントを設定してください")
            completion(false)
            return
        }

        print("アカウント取得完了")

        self.account = accounts.first!

        guard let mediaData = NSData(contentsOf: self.videoPathURL) else {
            completion(false)
            return
        }

        self.postMedia(tweet: "test", mediaData: mediaData as Data, fileSize: String(mediaData.length), completion: completion)
    }
}

func post(completion: @escaping (_ error: Bool)->Void) {
    authAccount(completion: completion)
}

private func postMedia(tweet: String, mediaData: Data, fileSize: String, completion: @escaping (_ error: Bool)->Void) {
    var json: [String: Any]!

    // INIT リクエスト
    uploadVideoInitRequest(fileSize: fileSize, success: { (_ responseData: Data)->Void in
        do {
            json = try JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as! [String: Any]
        } catch {
            completion(false)
            return
        }

        let mediaIdString = json["media_id_string"] as! String

        // APPEND リクエスト
        self.uploadVideoAppendRequest(mediaData: mediaData, mediaIdString: mediaIdString, success: { () -> Void in

            // FINALIZE リクエスト
            self.uploadVideoFinalizeRequest(mediaIdString: mediaIdString, success: { (_ responseData: Data) -> Void in

                let statusRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: self.twitterStatusURL, parameters: ["status" : tweet, "media_ids" : mediaIdString])

                statusRequest?.account = self.account

                // 動画をつけてツイート
                statusRequest?.perform { (responseData, urlResponse, error) -> Void in
                    if error == nil {
                        completion(true)
                    } else {
                        completion(false)
                    }
                }
            }, completion: { (_ success: Bool) -> Void in
                if !success {
                    completion(false)
                }
            })
        }, completion: { (_ success: Bool) -> Void in
            if !success {
                completion(false)
            }
        })
    }, completion: { (_ success: Bool) -> Void in
        if !success {
            completion(false)
        }
    })
}

// INIT リクエスト
private func uploadVideoInitRequest(fileSize: String, success: @escaping (_ responseData: Data)->Void, completion: @escaping (_ error: Bool)->Void) {
    let initParams: [String: Any] = ["command": "INIT", "media_type": "video/mp4", "total_bytes": fileSize]
    let initRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: self.twitterUploadURL, parameters: initParams)
    initRequest!.account = account
    initRequest!.perform { (responseData, urlResponse, error) -> Void in

        if error == nil {
            success(responseData!)
        } else {
            completion(false)
            return
        }
    }
}

// APPEND リクエスト
private func uploadVideoAppendRequest(mediaData: Data, mediaIdString: String, success: @escaping () -> Void, completion: @escaping (_ error: Bool)->Void) {
    let appendParam: [NSString: Any] = ["command": "APPEND", "media_id": mediaIdString, "segment_index": "0"]
    let appendRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: self.twitterUploadURL, parameters: appendParam)
    appendRequest?.addMultipartData(mediaData, withName: "media", type: "video/mov", filename: nil)
    appendRequest?.account = account
    appendRequest?.perform { (responseData, urlResponse, error) -> Void in

        if urlResponse!.statusCode < 300 && urlResponse!.statusCode >= 200 {
            success()
        } else {
            completion(false)
            return
        }
    }
}

// FINALIZE リクエスト
private func uploadVideoFinalizeRequest(mediaIdString: String, success: @escaping (_ responseData: Data) -> Void, completion: @escaping (_ error: Bool)->Void) {
    let finalizeParam: [NSString: Any] = ["command": "FINALIZE", "media_id": mediaIdString]
    let finalizeRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: self.twitterUploadURL, parameters: finalizeParam)
    finalizeRequest?.account = account
    finalizeRequest?.perform { (responseData, urlResponse, error) -> Void in

        if error == nil {
            success(responseData!)
        } else {
            completion(false)
            return
        }
    }
}

}

試しに撮影する動画を軽くしようと思い、以下のようにAVCaptureSessionにAVCaptureSessionPresetLowを設定すると動画をTwitterにアップロードできるようになります。
func setUpCamera() {
    let devices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .front).devices

    do {
        let videoInput = try AVCaptureDeviceInput(device: devices?.first!) as AVCaptureDeviceInput
        captureSession.addInput(videoInput)
        let audioInput = try AVCaptureDeviceInput(device: audioDevice) as AVCaptureDeviceInput
        captureSession.addInput(audioInput);
    } catch {

    }
    captureSession.commitConfiguration()
    captureSession.addOutput(fileOutput)
    captureSession.sessionPreset = AVCaptureSessionPresetLow    //この行を追加するとアップロードできる
    captureSession.startRunning()
}

しかし動画がかなり荒いです。
普通に撮影した状態で動画をTwitterにアップロードしたいのですが、どうすればいいでしょうか？
Twitterに動画をアップロードする際に画質が少し荒くなるのは仕方ないことなのでしょうか？
いろいろ調べて見たもののこれ以上どうすればいいかわからないので、どなたかわかる方がいれば教えていただきたいです。よろしくお願いします。

A:

Swiftで動画アップロードを書いたことは無いですが…………
Twitterの動画アップロードAPI(chunked media)は、リクエスト1つあたりのPOSTを5MB以下に抑える必要があります。(おそらくこれを越えているため413が返されているのでしょう。)
ではファイル自体5MB以下に抑える必要があるのかというとそうではなく、5MB以下ごとに分割してPOSTすれば500MB辺りまではまず行けるようです。
なお、Twitterは現在確か2種類以上のサイズにアップロードされた動画をエンコードしてたはずですが、どちらにせよある程度の画質低下は不可避です…………
※なお、30秒を越える動画のアップロードにはasync uploadが必要です: CoreTweetで30秒を超える動画をTwitterにアップロードしてみる | ぴんくいろにっき


Q:

UBUNTU-xinput DONT save settings after restart, unplug, etc

Well, thing is that I have an Abyssus Razer that works perfectly on MATE, but on Debian, Elementary, OpenSUSE, and others the DEFAULT setting is super slow.
I solved the thing with XINPUT. It's even better than the original software, you can take control of it all.
But, when I restart, re-log, or something like that, the settings I did are reseted too.
Once, after tons of time doing it, it saved by itself. But I had to reinstall my OS and now every time I turn on my computer I have to do:
xinput set-prop 8 "libinput Accel Profile Enabled" 0, 1
xinput set-prop 8 "libinput Accel Speed" 0.500

That is a default speed.
+: "su" or "sudo" doesn't solve the problem
Hope you can help me, cause I have been looking around but couldn't find information about "saving xinput settings".
Thanks!

A:

Solved the problem with "alias"
alias mouse="xinput set-prop 8 279 0.500 && xinput set-prop 8 282 0, 1"

Never knew you can do this tricks...
Well, for now I'm happy with this solution so I close it, and hope can help someone my way of making it work.
be safe


Q:

Match a code string in some text

I have some code strings that I need to extract some data from, but specific data at that.
The strings are always in the same format.

I need to extract the text at the beginning between the ( and ), so it would extract List Options here.
I need to extract the text near the end @groups here.

The string I need at the end will always start with @
(List Options((join ", ", @groups))

I have tried:
^\((\w+).*, (@\w+)\)\)$

But it only gives me the word List

A:

This should work well for you.
^\(([^(]+)[^@]+([^)]+)\)+$

See working demo
Regular expression:
^          the beginning of the string
\(         look and match '('
 (         group and capture to \1:
  [^(]+    any character except: '(' (1 or more times)
 )         end of \1
  [^@]+    any character except: '@' (1 or more times)
 (         group and capture to \2:
  [^)]+    any character except: ')' (1 or more times)
 )         end of \2
 \)+       ')' (1 or more times)
$          before an optional \n, and the end of the string


Q:

Ruby Koans Proxy Project

I've just finished the Ruby Koans and one of the last projects was creating a Proxy class that sends methods to another class. I was wondering whether you would change anything about my solution (if there's something wrong or a better way to do it). I'm still a beginner and I want to get better.
require File.expand_path(File.dirname(__FILE__) + '/edgecase')

# Project: Create a Proxy Class
#
# In this assignment, create a proxy class (one is started for you
# below).  You should be able to initialize the proxy object with any
# object.  Any messages sent to the proxy object should be forwarded
# to the target object.  As each message is sent, the proxy should
# record the name of the method send.
#
# The proxy class is started for you.  You will need to add a method
# missing handler and any other supporting methods.  The specification
# of the Proxy class is given in the AboutProxyObjectProject koan.

class Proxy
  attr_reader(:messages)

  def method_missing(method_name, *args, &block)
    if @methods_to_pass.include?(method_name.to_s)
      @messages << method_name
      @object.__send__(method_name, *args, &block)
    else
      super(method_name, *args, &block)
    end
  end

  def called?(method_name)
    @messages.include?(method_name)
  end

  def number_of_times_called(method_name)
    @messages.count(method_name)
  end

  def initialize(target_object)
    @methods_to_pass, @messages = [], []
    @object = target_object
    @object.class.instance_methods(true).each { |method_name| @methods_to_pass << method_name; method_name }
  end

end

# The proxy object should pass the following Koan:
#
class AboutProxyObjectProject < EdgeCase::Koan
  def test_proxy_method_returns_wrapped_object
    # NOTE: The Television class is defined below
    tv = Proxy.new(Television.new)

    assert tv.instance_of?(Proxy)
  end

  def test_tv_methods_still_perform_their_function
    tv = Proxy.new(Television.new)

    tv.channel = 10
    tv.power

    assert_equal 10, tv.channel
    assert tv.on?
  end

  def test_proxy_records_messages_sent_to_tv
    tv = Proxy.new(Television.new)

    tv.power
    tv.channel = 10

    assert_equal [:power, :channel=], tv.messages
  end

  def test_proxy_handles_invalid_messages
    tv = Proxy.new(Television.new)

    assert_raise(NoMethodError) do
      tv.no_such_method
    end
  end

  def test_proxy_reports_methods_have_been_called
    tv = Proxy.new(Television.new)

    tv.power
    tv.power

    assert tv.called?(:power)
    assert ! tv.called?(:channel)
  end

  def test_proxy_counts_method_calls
    tv = Proxy.new(Television.new)

    tv.power
    tv.channel = 48
    tv.power

    assert_equal 2, tv.number_of_times_called(:power)
    assert_equal 1, tv.number_of_times_called(:channel=)
    assert_equal 0, tv.number_of_times_called(:on?)
  end

  def test_proxy_can_record_more_than_just_tv_objects
    proxy = Proxy.new("Code Mash 2009")

    proxy.upcase!
    result = proxy.split

    assert_equal ["CODE", "MASH", "2009"], result
    assert_equal [:upcase!, :split], proxy.messages
  end
end

# ====================================================================
# The following code is to support the testing of the Proxy class.  No
# changes should be necessary to anything below this comment.

# Example class using in the proxy testing above.
class Television
  attr_accessor :channel

  def power
    if @power == :on
      @power = :off
    else
      @power = :on
    end
  end

  def on?
    @power == :on
  end
end

# Tests for the Television class.  All of theses tests should pass.
class TelevisionTest < EdgeCase::Koan
  def test_it_turns_on
    tv = Television.new

    tv.power
    assert tv.on?
  end

  def test_it_also_turns_off
    tv = Television.new

    tv.power
    tv.power

    assert ! tv.on?
  end

  def test_edge_case_on_off
    tv = Television.new

    tv.power
    tv.power
    tv.power

    assert tv.on?

    tv.power

    assert ! tv.on?
  end

  def test_can_set_the_channel
    tv = Television.new

    tv.channel = 11
    assert_equal 11, tv.channel
  end
end

A:

@methods_to_pass, @messages = [], []
@object = target_object
@object.class.instance_methods(true).each { |method_name| @methods_to_pass << method_name; method_name }

Couple of things to note here:
First of all the ; method_name bit is completely unnecessary. I don't know why you put that there, but it serves no purpose and just confuses the reader.
Secondly foo = []; bar.each {|x| foo << x} is an overly verbose way to copy an array. You can just say foo = bar.dup. However in this case there is no reason to perform a copy, so you can just say foo = bar, i.e. @methods_to_pass = @object.class.instance_methods(true) (but don't - see below).
That being said storing the methods in an array like that is a bad idea for two reasons:

Since checking whether an item is in an array is O(n), your method_missing method and thus every proxied call becomes O(n). This is needlessly inefficient.
If @object has singleton methods or dynamically defined methods, those won't be forwarded as they won't show up in @object.class.instance_methods.

To fix these issues you should get rid of @methods_to_pass and instead use one of the following approaches:
Option a:
In method_missing replace if @methods_to_pass.include?(method_name.to_s) with if @object.respond_to?(method_name). This will be faster than searching through an array and it will also work for dynamically defined or singleton methods. However it will not work if @object has a custom method_missing method and does not override respond_to? to be in sync with method_missing. If you want to handle that case as well, you'll need to use one of the other two options.
Option b:
Just remove the whole if and always forward (and record) the method call. This way the behavior will be different from your code as invalid calls will be recorded in @messages. However since they will still cause a NoMethodError and the assignment doesn't actually state whether invalid calls should be recorded or not, it still meets the requirements.

Now let's talk about the @messages array:
Using an array to store the messages and then using count to find out how often a given message appears is again needless inefficient. What I'd do instead is use a Hash which maps each message to the number of times it's been called. This way you'd write @message = Hash.new(0) instead of @messages = [], @messages[method_name] += 1 instead of @messages << method_name and @messages[method_name] instead of @messages.count(method_name).

A:

sepp2k's responses are all good, I would add one more suggestion.  Your Proxy class should derive from BasicObject (if you use ruby 1.9.x).  At the moment any method defined on Proxy is by definition not missing.  For example given:
foo = Foo.new
pfoo = Proxy.new(foo)

if I asked for pfoo.class I would get Proxy because class is a method in the inheritance of Proxy.  With BasicObject this would instead return Foo and add an entry for "class" in the proxy object.
One other nit to pick, I would add an underscore in front of called and number_of_times_called.  Putting an underscore in a method is a clue to other programmers that the method is outside the normal operation of a class.  In this case it will help prevent name collision with the object you are going to proxy to.  The truly paranoid would actually call a method on a separate object to count calls leaving the entire namespace unused.  Think what would happen if you tried to proxy a Proxy instance. :)


Q:

Exporting ArcGIS Metadata as PDF using ArcPy?

I've been asked to automate the exporting of metadata from ESRI feature classes into .pdf files. We don't want the .xml files, rather a .pdf version of what you see in the Description panel in Catalog. Manually we can achieve this by using the print button in the description panel tools and then using the cutepdf print drive. But I don't see a print option for metadata in ArcPy, all I see are options for exporting to .xml files.
In ArcObjects the IGxView object which looks like it could do what I need.
Is there a way to do what I want in ArcPy or should I use ArcObjects and its IGxView instead?

A:

@dvdhns suggestions, are what you should do.
However you don't need to write a xslt for html conversion because Esri has done this for you. see this code snippet:
import arcpy
from arcpy import env
env.workspace = "C:/data"
#set local variables
dir = arcpy.GetInstallInfo("desktop")["InstallDir"]
xslt = dir + "Metadata/Stylesheets/ArcGIS.xsl"
arcpy.XSLTransform_conversion("vegetation", xslt, "vegetation.html", "#")

This code converts your table/Layer metadata directly to html. (You don't need to convert it to a standalone xml file)
Afterward, use this python library to convert formatted HTMLs to pdf.

A:

No. You cannot directly export ESRI Feature Class metadata into PDF files.
This is how I would attempt to do it using python, rather than ArcObjects:

Use arcpy to export the metadata to xml files.
Use python and xslt (xml style sheets) to format the xml files into something human readable, my recommendation is a simply formated txt or html file.
Use a python PDF library to convert the txt or html file you just created into a PDF.


Q:

Planet with a huge tree , people are going inside tree as food

I read this book a long time ago (+30 years)
The story is about a scientist that arrive on a planet where people (humans) worship a huge tree. There is a priestly class and a worker class on the planet. The scientist finds out that the workers are going inside the tree as food.
When the priests get a seed of the tree to an other planet, the scientist and others find a way to destroy the 'son of tree'.
In the end they will try to destroy the huge tree on the other planet.

A:

Possibly Son of the Tree by Jack Vance.

Similarities: Huge tree, visiting spaceman, ruling clique (Druids) over the Laity.  The Son of the Tree is destroyed in the end.
Dis-similarity: I don't remember them feeding people to the tree, and thumbing through the story, I don't see that either.  But I may have missed it (it's a long story).


Q:

Who writes option contracts and when do they get written?

When a person A decides to sell to open an options contract through his / her brokerage, I always thought that this results in an options contract being written on behalf of person A by the brokerage, which person A is obligated to fulfill in the event that another party buys and exercises the option.  In this case, the other party would be opening to buy, I guess.  But who buys the newly created option?  Is it a market maker, holding on to it until another investor buys it retail?  Similarly, if person A were to buy to open an option position, who would write the position?  Does the option get written as a result of this action?  Is a market maker or brokerage writing the option on the spot, or is it another person, call him / her person B, acting as an independent investor who has the option contract written when executing a sell to open action.  If it is, in fact, another person, how does the brokerage firm find this other person when person A buys to open?  Does the other person just put their written option up on the market for auction indefinitely?
I have the unnerving feeling that half of these ideas are probably wrong, but I do not know which ones...

A:

The buyer can be another investor who wishes to buy what the seller is selling, or the market maker who is obliged to take the other side.
The market matches buyer and sellers just like it does for stocks.
When I look to buy an option, it can be the same, either a seller owning the position or the market maker creating it.
When you buy an option contract, how often is the market maker providing the contract (vs. another investor)? is very similar, may even be 'duplicate'.


Q:

How to print/code multi-line html5/javascript within a php functions?

I'm fairly new to the world of webdev and have come across a small issue. I'm trying to implement a "zoom" functionality to a canvas diagram and need to add java functions but I'm not sure this is the way to go:
print "document.getElementById(\"plus\").addEventListener("click", function(){";
print " scale /= scaleMultiplier;";
print " draw(scale, translatePos);";
print "}, false);";

Is this the right way to add multiple lines of Javascript/html5 code within php functions?
Just in case its needed, my function:
function draw($num_of_exons, $start_positions, $end_positions, $start_first_exon, $end_last_exon, $target_pos, $coding_region_start, $coding_region_end, $canvas_x){

//Variable initilisations
//variable initialization removed

//Sort out target positions
//variable initialization removed

//Main Diagram

print "<canvas id=\"$canvas_x\" width=$CANVAS_WIDTH height=$CANVAS_HEIGHT     style=\"border:1px solid #c3c3c3;\">";
print "Your browser does not support the HTML5 canvas tag.";
print "</canvas>";

print "<script>";
print "var c = document.getElementById(\"$canvas_x\");";
print "var ctx = c.getContext(\"2d\");";
print "ctx.fillStyle = \"#273c61\";"; // colour

//CODING REGION

print "ctx.fillStyle = \"#80d04b\";"; //rect colour
print "ctx.fillRect($coding_start,$CODING_REGION_POSITION_CANVAS,($coding_end - $coding_start), $CODING_REGION_HEIGHT);"; //draw rectangle

for($x = 0; $x < $num_of_exons; $x++) {

    $start_pos = $start_positions[$x];
    $start_pos = scale($start_pos, $start_first_exon, $end_last_exon, $new_range_min, $new_range_max);

    $end_pos = $end_positions[$x];
    $end_pos = scale($end_pos, $start_first_exon, $end_last_exon, $new_range_min, $new_range_max);

    print "ctx.fillStyle = \"#41BFFF\";"; //rect colour
    print "ctx.shadowOffsetX = 4;";
    print "ctx.shadowOffsetY = 4;";
    print "ctx.shadowBlur = 1;";
    print "ctx.shadowColor = \"rgba( 0, 0, 0, 0.5 )\";";
    print "ctx.fillRect($start_pos,$ITEM_POSITION_CANVAS,($end_pos - $start_pos),$RECT_HEIGHT);"; //draw rectangle

    drawexonlines($x, $end_positions, $start_first_exon, $end_last_exon, $new_range_min, $new_range_max, $start_pos, $line_offset);
}

printtargets($target_pos_split_start, $start_first_exon, $target_pos_split_end, $end_last_exon, $new_range_min, $new_range_max, $ITEM_POSITION_CANVAS, $RECT_HEIGHT);

print "</script>";
}

Thanks

A:

Unlikely you will get a solid answer on this, as it is an opinion based question (coding style) and is quite broad.
With that said, I'd advise heavily against this coding style. There's no real reason to write your code like this - it's tedious, and even your example has errors. Without seeing more code, it's very hard to understand why you would need to write this type of logic with PHP, and why this can't just be written purely in JavaScript.

If you need to pass data from PHP to JavaScript you can echo values into JS variables. Using JSON as a bridge is a clean way to transfer PHP data over to JS, and create basic objects to work with. Here's a simple example.
<?php
  $phpVal = array(
    'numbers' => 7,
    'strings' => 'hello',
    'arrays' => array('one', 'two'),
    'objects' => array('property' => 'value')
  );
?>

..

<script>
  var jsVal = JSON.parse(<?php echo json_encode($phpVal); ?>);
  console.log(jsVal.numbers); // >> 7
  console.log(jsVal.strings); // >> "hello"
  console.log(jsVal.arrays);  // >> ["one", "two"]
  console.log(jsVal.objects); // >> Object {property: "value"}
</script>

Consider using this pattern to create objects with all the data you need, that you can then use with regularly written JavaScript.

Some reading material.
PHP

echo
json_encode

JS

Objects
JSON Object

Side note:

need to add java functions

JavaScript !== Java. Don't get these two languages confused, they are not directly related. If you need a shorthand for JavaScript, call it JS. Referring to JS functions as java functions is simply incorrect.


Q:

finding the probability of A happens before B in die rolling

I'm thinking about the following old exam question:
A die is rolled infinitely many times, what is the probability that (6,6) (i.e. two consecutive sixes) happens before (1,2)?
Since the expectations of waiting time for (6,6) and (1,2) could be calculated, I was trying to get it from there but I haven't seen the connection between them. Is it possible to get $P(\xi_1<\xi_2)$ with only $E(\xi_1)$ and $E(\xi_2)$, where $\xi_1$ and $\xi_2$ are the waiting times for $(6,6)$ and $(1,2)$ respectively? I also tried writing down all the possible events and sum them up, but the summation seems to be hard to calculate. Thanks for any help.

A:

Let $X$ be the random variable that represents the time of the first instance of $12$ and $Y$ be the random variable that represents the first time of the instance of $66$. Then $P(X=1)\neq P(Y=1)=0$ and $P(X=2)=P(Y=2)=1/36$ but $P(X=3)\neq P(Y=3)$.
Namely $P(X=3)=\frac{6}{216}$ and $P(Y=3)=\frac{5}{216}$. That's because any sequence $*12$ satisfies $X=3$, but $*66$ only satisfies $Y=3$ if the first roll is not $6$.
So it isn't as simple as the two being equal.
One tricky way to do this is to use a Markov process. Let $s_0$ be the start state. Let $s_1$ be the state of having a string ending in $1$ and not having a prior $66$ or $12$. Let $s_6$ be the state of ending in a $6$ with no prior $12$ or $66$. And let $s_{12}$ and $s_{66}$ be the state of having reached $12$ or $66$ first.
Then you are looking for:
$$(0,0,0,P(X<Y),P(Y>X))=\lim_{n\to\infty} (1,0,0,0,0) \begin{pmatrix}
\frac 46&\frac16&\frac 16&0&0\\
\frac36&\frac16&\frac16 &\frac16&0\\
\frac46&\frac16&0&0&\frac16\\
0&0&0&1&0\\
0&0&0&0&1
\end{pmatrix}^n$$
This can be done by expressing $(1,0,0,0,0)$ in terms of the left eigenvectors of the above matrix.
Wolfram Alpha gives me $P(X<Y)\approx 0.5538$ and $P(Y<X)\approx 0.4462$.That is $12$ has a better than 55% chance of coming before $66$.


Q:

Get Font Vectors

I'm trying to play around with the silhouette of fonts in Javascript, but I can't go forward without being able to get the vectors from the characters.  Is there any way to retrieve this information and use it?  Any examples of this being done?
Paper.JS seems like it could be pretty handy but I haven't found any font examples.

A:

There is no direct way to retrieve shapes from characters in JavaScript. I suspect that is because font rendering is not done directly by the browser. This task is usually delegated to a third party library like cario.
You could create the text in an SVG editor such as Inkscape, convert the text to paths (Path → Object to Path) and manipulate them via JavaScript.
Using SVG Fonts also seems like a way to go. This is basically an SVG file that saves the shapes of all characters. You could load this as XML into a HTML/JavaScript setup and process the character shapes from there. Font Squirrel has a generator for making @font-face kits. It also includes an SVG version of the font in the archive.


Q:

spliturl function appending twice

here's the code:
function chatWin(url,name){
    var nw;
    var splitUrlResults = url.split("#");

    url = appendDataWakeNVPs(splitUrlResults[0]) + '#' + splitUrlResults[1] ;

    nw=window.open(url,name,"height=600,width=433,left=100,top=100,resizable=yes,scrollbars=no,toolbar=no,status=no");

    if (nw.focus) {nw.focus();}
}

and then the link in the code:
PROD_TAB_EXPRT_LNK_EMAIL=javascript:chatWin('/customerService/contactUs/help.html#1','Help')

but the rendered code is:
<a href="javascript:chatWin('/customerService/contactUs/help.html#0#1','Help');">

Every link is getting #0 appended before the tab identifier- (#1 in this case).
thoughts?

A:

It looks to me like the only way url ends up with #0#1 on the end of it is if appendDataWakeNVP() is appending #0 onto it's return value and your code is then adding the #1 onto the end of that.
So, I think your problem is in appendDataWakeNVP().  I'd suggest stepping into that function in your favorite debugger and you can discover what it does.  Or grep for it in your source tree and examine it in your editor.  If it's suppose to add #0 onto the end and you can't change that, but you don't want that there, then you will have to remove that before appending your own hash onto the end of it.
Any hash value you don't want can be removed with this:
url = url.replace(/#.*$/, "");

So, you could change this line of code:
url = appendDataWakeNVPs(splitUrlResults[0]) + '#' + splitUrlResults[1] ;

to this:
url = appendDataWakeNVPs(splitUrlResults[0]).replace(/#.*$/, "") + '#' + splitUrlResults[1] ;


Q:

Hammer JS doesn't seem to work

I have some issues with Hammer JS,
in the chrome developer tool I have some errors :

Uncaught ReferenceError: TOUCH_ACTION_COMPUTE is not defined hammer.js:37(anonymous function)

The file seems to be corrupted ? but I downloaded it from hammer js and never opened it...

Uncaught ReferenceError: ifUndefined is not defined hammer.js:9Hammer hammer.js:9(anonymous function) main.js:663j jQuery.js:2k.fireWith jQuery.js:2n.extend.ready jQuery.js:2I

Don't know what this refers to...
jQuery is loaded in first in my HTML page
My script wich calls hammer actions :
var hammer = new Hammer($('img'));

    hammer.on("tap", function(ev){
        alert(ev);
    });

Hope you'll be able to help me, thanks in advance.

A:

You have probably reference the wrong js file in your webpage. If using the npm package make sure to reference <script src="/node_modules/hammerjs/hammer.js"></script> and NOT <script src="/node_modules/hammerjs/src/hammer.js"></script>


Q:

Description of a topological space using neighborhoods

Definition: Let $(X, \mathcal{T})$ be a topological space. For $x \in X$, we call $V \subseteq X$ neighborhood of $x$ if there exists $G
 \in \mathcal{T}$ such that $x \in G \subseteq V$. We write
  $\mathcal{V}(x)$ for the sets of all neighborhoods of $x$.
Theorem: Suppose $X$ is a topological space and $x \in X$, then $\mathcal{V}(x)$ satisfies:
$$(V_1): X \in \mathcal{V}(x)$$ $$(V_2):  \forall V \in
 \mathcal{V}(x): x \in V$$ $$(V_3): \forall V,W \in \mathcal{V}(x): V
 \cap W \in \mathcal{V}(x)$$ $$(V_4): V \in \mathcal{V}(x), V \subseteq
 W \implies W \in \mathcal{V}(x)$$ $$(V_5): \forall V \in
 \mathcal{V}(x): \exists W \in \mathcal{V}(x): \forall y \in W: V \in
 \mathcal{V}(y)$$
Conversely, if a family $(\mathcal{V}(x))_{x \in X}$ satisfies these
  $5$ conditions, then there exists a unique topology on $X$ such that
  for all $x \in X$, $\mathcal{V}(x)$ is the set of all neighborhoods of
  $x$.

Proof (my attempt): I'm stuck at the converse. I'll show what I tried.
Define $$\psi: \{\mathcal{T}\mid \mathcal{T} \mathrm{ \ topology \ on \ X}\} \to \{\mathcal{V}:=(\mathcal{V}(x))_{x \in X} \mid \mathcal{V} \mathrm{\ satisfies \ (V_1)-(V_5) }\}$$
$$\mathcal{T} \mapsto(\{A \mid \exists G \in \mathcal{T}: x \in G \subseteq A\})_{x \in X}$$
I want to show that this is a bijection, because then for every $\mathcal{V}$ satisfying the 5 given conditions, there is a unique topology we look for.
To do this, I defined what I believe is the inverse function:
$$\phi: (\mathcal{V}(x))_{x \in X} \mathrm{\ satisfying \ the \ conditions}\mapsto \{A \mid \forall a \in A: A \in \mathcal{V}(a)\}$$
Using the properties $(V_1)-(V_3)-(V_4)$, I managed to show that this is well defined: the image is a topology.
Now, one has to check that $\phi \circ \psi = 1$ and $\psi \circ \phi = 1$.
The first one of these equalities worked out.
For the second one, I ran into troubles:
I have to prove, that if $(\mathcal{V}(x))_x$ is a family satisfying those $5$ conditions, then $\psi \circ \phi((\mathcal{V}(x))_x) = (\{B \subseteq X \mid \exists G \in \{A \subseteq X \mid \forall a \in A: A \in \mathcal{V}(a)\}: x \in G \subseteq B\})_x= (\mathcal{V}(x))_x$
where I'm not sure about the last equality.
In particular, I want to prove that for a fixed $x \in X$:
$$\{B \subseteq X \mid \exists G \in \{A \subseteq X \mid \forall a \in A: A \in \mathcal{V}(a)\}: x \in G \subseteq B\}= \mathcal{V}(x)$$
and the $\supseteq$ part is giving me a lot of troubles.
This is what I did:
Let $B \in \mathcal{V}(x)$. Then, by $(V_5)$, there exists $W \in \mathcal{V}(x)$ such that $a \in W$ implies that $B \in \mathcal{V}(a)$. From this, it follows by $(V_2)$ that $W \subseteq B$. Because $W \in \mathcal{V(x)}$, it also follows that $x \in W \subseteq B$ so we are done when we can prove that
$$\forall a \in W: W \in \mathcal{V}(a)$$
but I did not manage to prove this. Can anyone help me to prove this?

A:

Your claim $\forall a\in W : W\in\mathcal{V}(a)$ is not true.
For example, let $X=\mathbb{R}$ and for each $x\in X$ set
$$
\mathcal{V}(x) = \{ A\subset\mathbb{R} \mid \exists\,\epsilon>0 \text{ such that } (x-\epsilon,x+\epsilon)\subset A \}
$$
Then it is easy to check the five conditions ($V_1$)-($V_5$) hold.
Now let us follow your proof. Let $x=0$ and choose $B=(-2,2)\in\mathcal{V}(0)$. Then $W=[-1,1]\in\mathcal{V}(0)$ satisfies $\forall\,a\in W \Rightarrow B\in\mathcal{V}(a)$. Notice that when $a=1\in W$, $B=(-2,2)\in\mathcal{V}(1)$ but $W\notin\mathcal{V}(1)$. It means that your claim is not true.
A comment for proof
In my opinion, the fifth condition ($V_5$) should be as follows:

($V_5$) : $\forall\,V\in\mathcal{V}(x) : \exists\,W\in\mathcal{V}(x) : \forall y\in W : W,V\in\mathcal{V}(y)$

Then the proof will be much easier.


Q:

How to change position of Regular price and Special price in product detail page?

I overriden product/price/amount/default.phtml file
<span class="price-container <?php /* @escapeNotVerified */ echo $block->getAdjustmentCssClasses() ?>"
    <?php echo $block->getSchema() ? ' itemprop="offers" itemscope itemtype="http://schema.org/Offer"' : '' ?>>
    <?php if ($block->getDisplayLabel()): ?>

            <?php /* @escapeNotVerified */ echo $block->getDisplayLabel(); ?>

    <?php endif; ?>
        <span <?php if ($block->getPriceId()): ?> id="<?php /* @escapeNotVerified */ echo $block->getPriceId() ?>"<?php endif;?>
            <?php echo($block->getPriceDisplayLabel()) ? 'data-label="' . $block->getPriceDisplayLabel() . $block->getPriceDisplayInclExclTaxes() . '"' : '' ?>
            data-price-amount="<?php /* @escapeNotVerified */ echo $block->getDisplayValue(); ?>"
            data-price-type="<?php /* @escapeNotVerified */ echo $block->getPriceType(); ?>"
            class="price-wrapper <?php /* @escapeNotVerified */ echo $block->getPriceWrapperCss(); ?>"
            <?php echo $block->getSchema() ? ' itemprop="price"' : '' ?>>
            <?php /* @escapeNotVerified */ echo $block->formatCurrency($block->getDisplayValue(), (bool)$block->getIncludeContainer()) ?>

    <?php if ($block->hasAdjustmentsHtml()): ?>
    <?php echo $block->getAdjustmentsHtml() ?>
    <?php endif; ?>
    <?php if ($block->getSchema()): ?>
    <meta itemprop="priceCurrency" content="<?php /* @escapeNotVerified */ echo $block->getDisplayCurrencyCode()?>" />
    <?php endif; ?>

A:

You can change position by overriding the file /var/www/html/magento2/vendor/magento/module-catalog/view/base/templates/product/price/final_price.phtml
    <?php if ($block->hasSpecialPrice()): ?>

            <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
                'display_label'     => __('Special Price'),
                'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
                'price_type'        => 'finalPrice',
                'include_container' => true,
                'schema' => $schema
            ]); ?>

            <?php /* @escapeNotVerified */ echo $block->renderAmount($priceModel->getAmount(), [
                'display_label'     => __('Regular Price'),
                'price_id'          => $block->getPriceId('old-price-' . $idSuffix),
                'price_type'        => 'oldPrice',
                'include_container' => true,
                'skip_adjustments'  => true
            ]); ?>

    <?php else: ?>
        <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
            'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
            'price_type'        => 'finalPrice',
            'include_container' => true,
            'schema' => $schema
        ]); ?>
    <?php endif; ?>

Changed it to the following
<?php if ($block->hasSpecialPrice()): ?>

        <?php /* @escapeNotVerified */ echo $block->renderAmount($priceModel->getAmount(), [
            'display_label'     => __('Regular Price'),
            'price_id'          => $block->getPriceId('old-price-' . $idSuffix),
            'price_type'        => 'oldPrice',
            'include_container' => true,
            'skip_adjustments'  => true
        ]); ?>

        <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
            'display_label'     => __('Special Price'),
            'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
            'price_type'        => 'finalPrice',
            'include_container' => true,
            'schema' => $schema
        ]); ?>

<?php else: ?>
    <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
        'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
        'price_type'        => 'finalPrice',
        'include_container' => true,
        'schema' => $schema
    ]); ?>
<?php endif; ?>

Hopefully it will help you.