Q:

Count rows based on first column in a tab delaminated file using Python (without using Pandas, Numpy, etc)

I have a tab delaminated file looks like this:
33 1 8
34 1 1
21 1 1
31 1 1
6 1 2
35 1 23
9 1 2
25 1 2
13 2 1
21 2 2
8 2 1
2 2 1
25 2 2
14 2 1
16 2 1
23 2 1
10 2 1
6 2 1
7 2 1
35 2 51
36 2 7
33 2 11
30 2 2
3 2 4
29 2 4
22 3 1
23 3 1
10 3 1
33 3 47
32 3 3
35 3 218
36 3 30
25 3 28
26 3 3
13 3 4
19 3 2
3 3 5
30 3 10
9 3 16
7 3 2
6 3 4
29 3 3
14 3 2
34 3 2
21 3 11
27 3 2
20 3 2
2 3 3
26 4 1
10 4 1
2 4 1

There are over 10000 rows in this file, I want to use the first column as key, for example, the first row, 33 is the key,  and then print out the count of rows that first column is 33 in the output file.
key,count
33,490
34,670
21,300
31,675
6,700
8,90
.
.
.

There should be 36 keys in the output file.
Below is my code so far
import csv

# Create dictionary to hold the data
valDic = {}
Count = 0

# Read data into dictionary
with open('matrix.mtx', 'r',) as inputfile:

    reader = csv.reader(inputfile, delimiter = '\t')
    next(reader)

    for row in reader:
        key = row[0]
        if key in valDic:
            valDic[key] +=1
            Count += 1

#Prepare new CSV
newcsvfile = [["ADT", "Count"]]

for key, Count in sorted(valDic.items()):
    newcsvfile.append([valDic[key], Count])

with open('results5.csv', "w", newline='') as outputfile:
    writer = csv.writer(outputfile)
    writer.writerows(newcsvfile)

A:

You could use collections.Counter:
import csv
from collections import Counter

with open('data.txt') as i, open('output.csv', 'w') as o:

    counts = Counter(key for key, *_ in map(str.split, i))  # split by space and get first element

    w = csv.writer(o)
    w.writerow(['key', 'count'])  # write header
    for item in counts.items():
        w.writerow(item)

Output (partial)
key,count
33,3
34,2
21,3
31,1
6,3
35,3
9,2
25,3
13,2
8,1
2,3
14,2

Notice that the partial output is for input sample. The notation in the counting and splitting line is known as extended iterable unpacking, an alternative way of writing is:
counts = Counter(splits[0] for splits in map(str.split, i))

Update
If you want the output sorted in ascending order, change the writing logic to:
w = csv.writer(o)
w.writerow(['key', 'count'])  # write header
for item in sorted(counts.items(), key=lambda x: int(x[0])):
    w.writerow(item)


Q:

How to access a singleton Android Activity in a backstack multiple times

A1 is the main activity. It is a single instance activity meaning it should not be instantiated more than once since it is expensive to re-create it.
The scenario is:

A1 calls A2
A2 calls A3
A3 calls A1

Expected backstack is:
Top -> [A1|A3|A2|A1] <- bottom
I would like A1 stay on the top of this stack. Therefore, when I hit the back button, I expect to return to A3, then A2, and finally back to A1.
Currently A1 is defined as launchMode=singleinstance. Naturally, second call to A1 clears all other activities (A2 and A3) from the backstack.
Question is, how can I let a singleton activity exist in a backstack more than once for navigation purposes?
Note: Assuming that the backstack structure is internally composed of references to the activities, then somehow I should be able to create two different references to a singleton Activity.

A:

how can I let a singleton activity exist in a backstack more than once for navigation purposes?

You can't. You would have to override default BACK button behavior, probably on all your activities, so that you force the flow to be what you want and do not finish() A1 until you are sure that you are done with it.
Or, rework your navigation to avoid A3 launching A1. For example, use a nav drawer to allow the user to get back to A1 whenever the user wants, but where you can wipe out the back stack as part of that navigation.
Or, make A1 cheaper, so creating two instances are not so expensive. Rarely are activities themselves expensive; usually, it is something that the activity loads that is expensive, and that could be shared (carefully) via singleton caches.
Or, consolidate this all into one activity, with fragments F1 through F3, where you will have a somewhat easier time hand-rolling the navigation.

Assuming that the backstack structure is internally composed of references to the activities, then somehow I should be able to create two different references to a singleton Activity.

No. That is akin to saying "assuming that the Web browser's back stack structure is internally composed of references to Web pages, then somehow I should be able to create two different references to a singleton Web page". Last I checked, that is not possible in Web development, because there is no such thing as a "singleton Web page". Android does not really have the concept of a "singleton activity", either -- singleInstance is really there more for navigation from outside the app into the app.


Q:

Mocking System.Web.Caching.Cache - Mock or check for null?

I'm writing some unit test and am wondering whether it's advantageous to mock the Cache and if so, how?
Currently in my tests I'm mocking out the HttpContextBase and wrapping it in a custom HttpContextFactory:
var mockedHttpContextBase = new Mock<HttpContextBase>();

IHttpContextFactory httpContextFactory = new HttpContextFactory
{
     Current = mockedHttpContextBase.Object
};

and when my code consumes an IHttpContextFactory I check if the cache is null before doing anything with it.
var cache = _httpContextFactory.Current.Cache;

Func<SomeReturnType> doSomeWork = () => _foo.someMethodIExecute(param1,param2);

return cache != null ? cache.GetOrStore("doSomeWorkCacheKey",doSomeWork, 900)
                     : doSomeWork.Invoke();

Is it right to check for the cache being null like this each time I use it or would you mock the cache also in the test so that it's not null when running your unit tests?

A:

After a bit of searching it seems that I can use HttpRuntime.Cache instead of System.Web.Caching.Cache when writing my unit tests.
Such that:
var mockedHttpContextBase = new Mock<HttpContextBase>();
mockedHttpContextBase.Setup(m => m.Cache).Returns(HttpRuntime.Cache);

The cache should never be null (it would be an appropriate exception if it was) so I can remove the null reference checking from my code.

A:

If your code assumes cache can be null and performs checks before accessing it (as it does now), you need to have two unit tests for each cache access:

cache exists and item is stored and retrieved (checking GetOrStore call)
cache is null and you simply assert delegate invocation

If this is common pattern (null checking), instead of having two tests each time cache dependency is required, I suggest wrapping it into Null Object Pattern and have it tested once and later simply use NOP as a dependency that can be mocked.
Edit: cache "mocking" example
var cache = new Cache();
// Add takes more parameters; fill whatever is necessary to make it work
cache.Add("doSomeWorkCacheKey", doSomeWork, ...);
var mockedHttpContextBase = new Mock<HttpContextBase>();
// tell your mock to return pre-configured cache
mockedHttpContextBase.Setup(m => m.Cache).Returns(cache);

IHttpContextFactory httpContextFactory = new HttpContextFactory
{
    Current = mockedHttpContextBase.Object
};


Q:

How to fix iTunes library? I copied the iTunes folder but the music does not appear in iTunes

I copied my iTunes folder and changed it in preferences. Then I did Library -> Organize Library. Why doesn't iTunes see the music? (I think I used this process before).
How to fix?
Using iTunes 10.

A:

What you should have done is hold the ⌥-key while starting iTunes and it will prompt you to choose a new library which is the iTunes Library.itl inside the iTunes folder you wanted to copy. If you still have a copy of the old folder, do the above. Otherwise, I think you just created a new library with 0 songs.


Q:

implementation of directed graph with two edges per node - recursive search function

I've started playing with structures, I've created one which I've called LR:
struct LR{
    int v;
    LR* L;
    LR* R;
};

I understand how to manipulate it in generic way - code in main below, before I've started building class, I've started to write recursive function which takes "address" of node in LR in form of string ("LRLRR") and returns needed LR, but I still get errors from compiler :
LR.cpp In function 'LR chooseNode(LR*, std::string)':
LR.cpp [Error] request for member 'L' in 'tree', which is of pointer type 'LR*'

(maybe you meant to use '->' ?) - error for line in part with recursion chooseNode(*tree.L,str2);
What am I doing wrong or rather how to debug it ? ( except the whole concept of my implementation which is rather excercise).
#include<iostream>
#include<string>
#define SHOW(a) std::cout << #a << ": " << (a) << std::endl
using namespace std;
struct LR{
    int v;
    LR* L;
    LR* R;
};

LR chooseNode(LR* tree, string str){// for example str="LRL"

            // for clarity I've cutted the most of the code

            if(str[0]=='L')
            chooseNode(*tree.L,str2);
        else if(str[0]=='R')
            chooseNode(*tree.R,str2);

};

int main(){

    LR d1,d2,d3;
    d1.v=4;
    d1.L=&d2;
    (*(d1.L)).L=&d3;
    d3.v=12345;
    SHOW((*(*d1.L).L).v);

    cout<<"Opis: "<<"\n";
    SHOW(int(&d1));
    SHOW(int(&d2));
    SHOW(sizeof(d2.v));

    return (0);
}

A:

What am I doing wrong?

tree is a pointer of type LR*
Accessing struct members from a pointer can be done with this syntax:
tree->L

Or (far less commonly, but it looks like what you were attempting)
(*tree).L

Or rather how to debug it ?

"Debugging" is a process done to a successfully built executable.  You have a compiler error, so debugging does not apply.


Q:

Verify using Moq that only these two method calls where called, and nothing else

I am using Moq for verifications and unit-testing.  I would like to verify that say a method 'Add' was called with parameter 1, and parameter 5, and not called for any other value except for those.
Is it possible to create verifications, something similar to the code below? (note this is not actual code!)
mock.Verify(x=>x.Add(1), Times.Once());
mock.Verify(x=>x.Add(5), Times.Once());
mock.Verify(x=>x.Add(It.IsAny<int>()), Times.Never());

A:

You can try this, passing a lambda expression to the third verification to exclude any value different from 1 and 5.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Tests.x21
{
    public interface IMyInterface
    {
        void Add(int num);
    }

    public class Executor
    {
        private IMyInterface _dep;

        public Executor(IMyInterface dep)
        {
            _dep = dep;
        }

        public void Execute()
        {
            _dep.Add(1);
            _dep.Add(5);
            _dep.Add(4);    // comment to make the test work
        }
    }

    [TestClass]
    public class UnitTest21
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mock = new Mock<IMyInterface>();
            var executor = new Executor(mock.Object);
            executor.Execute();
            mock.Verify(x => x.Add(1), Times.Once());
            mock.Verify(x => x.Add(5), Times.Once());
            mock.Verify(m => m.Add(It.Is<int>(num => num != 1 && num != 5)), Times.Never());
        }
    }
}


Q:

Page_load in asp.net

In asp.net, when working on web app, there is a function called 'Page_Load', which is empty. Is this called everytime the page is loaded? What if I remove this function? Essentially what is the main purpose of Page_Load?
Many Thanks.

A:

its main purpose it to do / verify / check things when the page is loading ( one of its start events).
this function is being called by reflection when AutoEventWireup is on.


Q:

select not initializing on filtered list

The following piece of code works, except for one issue, the UI's drop-down doesn't initialize to the contents of the model.  The model is correctly initialized, the cookies are correctly saved/loaded.  And the rest of the code has been working just fine for a while.  I'm at a loss as to why the select won't initialize.

app.controller("thisController",
    function ($scope, $http, $log, $rootScope, $location, $uibModal, $cookies) {

    $scope.saveCookie = function (key, value) {
        $cookies.putObject(key, value);
    }
    $scope.getCookie = function (key) {
        return $cookies.getObject(key);
    }
}
    <select class="form-control"
            id="yearDropdown"
            ng-model="selectedYear"
            ng-init="selectedYear=getCookie('selectedYear')"
            ng-change="saveCookie('selectedYear', selectedYear)"
            ng-options="contract.ContractYear for contract in contractList
                      | orderBy:'ContractYear'
                      | unique:'ContractYear'">
        <option value="">All years</option>
    </select>

https://imgur.com/a/fsir4

A:

The reason the <select>-element isn't initialized with the value loaded from the cookie, is because it attempts to match the object reference of the initialized object, with the references to the contract objects in your contractList-variable. Since the initialized object comes from a cookie, it object reference doesn't match any of the objects in the contractList.
To solve this, you can specify to the ngOptions-directive, which attribute it should use to match objects to each other. You do this by appending track by [expr] to the expression.
So to fix your issue, your template should look somewhat like this:
<select class="form-control"
        id="yearDropdown"
        ng-model="selectedYear"
        ng-init="selectedYear=getCookie('selectedYear')"
        ng-change="saveCookie('selectedYear', selectedYear)"
        ng-options="contract.ContractYear for contract in contractList
                  | orderBy:'ContractYear'
                  | unique:'ContractYear'
                  track by contract.ContractYear">
    <option value="">All years</option>
</select>

If you have some other unique identifier on the contract-object (an id for instance), you should naturally opt to track by that instead.
Note: I strongly recommend moving the ngInit logic to your controller.


Q:

Using external js file in angular 6 component

I am trying to use a js file into my angular 6 application. Steps I followed are as follows:
1. Created testfile.js file:

var testa = function () {
   function testMethod() {
        console.log('hello');
    }
}
var testmodule = new testa();
module.exports = testmodule;

2. In angular.cli.json. For testing purpose tesfile.js is at the same location as angular.cli.json is:

 "scripts": [
              "testfile.js"
            ],

3. In typings.d.ts file, declared it:

declare var testmodule: any;

4. In ts file, tried to use it as:

 public ngOnInit() {
        testmodule.testMethod()
    }

But when angular component is used, warning in console is:
Uncaught ReferenceError: testmodule is not defined

I tried another alternative, like importing js file inside .ts file as:

import * as mymodule '../../testfile.js'
"allowJs":  true
but this is also not identifying testmodule or testfile.

What wrong am I doing here?

A:

I made a demo: https://codesandbox.io/s/4jw6rk1j1x , like so:
testfile.js
function testa() {}
testa.prototype.testMethod = function testMethod() {
  console.log("hello");
};
var testmodule = new testa();

export { testmodule };

And in the main.ts
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

import { testmodule } from "./testfile";

testmodule.testMethod();

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.log(err));

You can see on the console tab the 'hello' text
Note that I made some changes in the testfile.js


Q:

new line into SELECT query sql server 2005

I want to do a new line in my sql select
I try this but it won't work
SELECT '1' + char(13) + '2'

AND
SELECT '1' + char(13) + char(10) + '2'

it always return 12
thanks for your answers
in fact I try to export data from sql to TXT file
but when I execute the bcp file it return concatenate rows

A:

The new line is in your result.  If you copy and paste the result from your query into notepad, for example, you'll see 1, new line, 2. The reason you see 1  2 in your result in the results window is because you are returning 1 row. Notice that len('1' + char(13) + char(10) + '2') = 4, that is because your chars are present, it's just represented as a single row (with multiple lines in the row).


Q:

Https problem with channel form

I have a problem with a channel form working over https.My form allows users edit their profiles for a staff directory and has a lot of fields including some assets , wygwam and matrix fields.When i go to the page over https all of those fields aren't working and i get errors like

Blocked loading mixed active content "http://mysite/themes/third_party/wygwam/lib/ckeditor/ckeditor.js"
Blocked loading mixed active content "http://mysite/themes/third_party/assets/scripts/matrix.min.js?2.5"

So the obvious problem is that these fields are requesting files over http rather than https but im not sure why this is happening.
I have setup my site to convert relative paths in my config

  $protocol                          = (isset($_SERVER['HTTPS']) &&     $_SERVER['HTTP'] == 'on') ? 'https://' : 'http://';
  $base_url                          = $protocol . $_SERVER['HTTP_HOST'];
  $base_path                         = $_SERVER['DOCUMENT_ROOT'];
  $system_folder                     = APPPATH . '../';
  $images_folder                     = 'images';
  $images_path                       = $base_path . '/' . $images_folder;
  $images_url                        = $base_url . '/' . $images_folder;

  $env_config['index_page']          = '';
  $env_config['site_index']          = '';
  $env_config['base_url']            = $base_url . '/';
  $env_config['site_url']            = $env_config['base_url'];
  $env_config['cp_url']              = $env_config['base_url'] .
'admin/index.php';
 $env_config['theme_folder_path']   = $base_path   . '/themes/';
 $env_config['theme_folder_url']    = $base_url    . '/themes/';
 $env_config['third_party_path']    = $base_path   '/admin/expressionengine/third_party/';

I have also set secure_return="yes"  and secure_action="yes" in my form header so im not sure where I am going wrong
Thanks for any help

A:

Ok I have decided to set https as my default  protocol
So i changed this
 $protocol= (isset($_SERVER['HTTPS']) &&     $_SERVER['HTTP'] == 'on') ? 'https://' : 'http://';

to this
 $protocol=  'https://';

This has sorted my issues and I hope to move the whole site to https soon


Q:

"Cars of Grab" or "Grab cars"

What is the difference between two phrases "Cars of Grab" and "Grab cars"? I used "Cars of Grab" phrase for the subject of the sentence but a native speaker suggested using "Grab cars" instead.
Note: Grab in the phrase is a company which does business in the transportation service.

A:

'Grab', being a company (or essentially, a 'brand'), becomes an attributive noun when used to modify 'cars'. So, 'Grab cars' refers to the cars that provide the transportation services of the company, 'Grab' (context-based, we know that the company 'Grab' provides transportation services).
'Cars of Grab', on the other hand, shows ownership.


Q:

send html mail via yahoo mail api with JSON

I am using to send yahoo mail api using JSON format to send mail. But even I use \r\n to make new line for the block of message that I want to send out, there is no effect when the recipient received it as a mail.
As there are some problem in making JSON if there are special characters, I am using StringEscapeUtils.escapeJavaScript method to make my message string valid eg. hello friend.\r\n testing with special characters ~`!@#$%^&*() \n{}[]|?/.>,< .
Sample JSON
{
  "method": "SendMessage",
  "params": [
    {
      "savecopy": true,
      "message": {
        "to": {
          "email": "test@yahoo.com",
          "name": "SendMessage Test User"
        },
        "from": {
          "email": "ctest@yahoo.com",
          "name": "SendMessage Test User"
        },
        "replyto": {
          "email": "test@yahoo.com",
          "name": "SendMessage Test User"
        },
        "inreplyto": "SendMessage InReplyTo Value",
        "mailer": "YahooMailRC",
        "subject": "Message with Stationery",
        "simplebody": {
          "text": "hello friend.\r\n testing with special characters ~`!@#$%^&*() \n{}[]|?/.>,<",
          "html": "hello friend.\r\n testing with special characters ~`!@#$%^&*() \n{}[]|?/.>,<"
        }
      }
    }
  ]
}

I use to escape \ when I create a valid string to make JSON object.
Note: If I only set data in text , not in html. Nothing appeared in received mail.
How can I format the text that I want to send out via Yahoo mail api to retain all the new line (HTML format style) ?

A:

I solved the issue by adding <PRE> tag to use the html format of my string.


Q:

Is it possible to uncheck “Reopen windows when logging back in” by default?

It is possible to disable the “Reopen windows when logging back in” option, but is it possible to just make it unchecked by default? I have OS X Lion.

A:

Besides completely removing it, as you linked, there is currently no way of unchecking the box by default.
An option to get around this is to use a keyboard shortcut, which completely skips the dialog box, and will shutdown normally. It acts as though you unchecked the box.
Control + Option + Command + Eject
Press all those together.


Q:

SQL Server 2008 BULK INSERT causes more reads than writes. Why?

I've huge a table (a few billion rows) with a clustered index and two non-clustered indices.
A BULK INSERT operation produces 112000 reads and only 383 writes (duration 19948ms).
It's very confusing to me. Why do reads exceed writes? How can I reduce it?
update
query

insert bulk DenormalizedPrice4 ([DP_ID] BigInt, [DP_CountryID] Int, [DP_OperatorID] SmallInt, [DP_OperatorPriceID] BigInt, [DP_SpoID] Int, [DP_TourTypeID] Int, [DP_CheckinDate] Date, [DP_CurrencyID] SmallInt, [DP_Cost] Decimal(9,2), [DP_FirstCityID] Int, [DP_FirstHotelID] Int, [DP_FirstBuildingID] Int, [DP_FirstHotelGlobalStarID] Int, [DP_FirstHotelGlobalMealID] Int, [DP_FirstHotelAccommodationTypeID] Int, [DP_FirstHotelRoomCategoryID] Int, [DP_FirstHotelRoomTypeID] Int, [DP_Days] TinyInt, [DP_Nights] TinyInt, [DP_ChildrenCount] TinyInt, [DP_AdultsCount] TinyInt, [DP_TariffID] Int, [DP_DepartureCityID] Int, [DP_DateCreated] SmallDateTime, [DP_DateDenormalized] SmallDateTime, [DP_IsHide] Bit, [DP_FirstHotelAccommodationID] Int) with (CHECK_CONSTRAINTS)

No triggers & foreign keys
Cluster Index by DP_ID
and two non-unique indexes(with fillfactor=90%)
And one more thing DB stored on RAID50 with stripe size 256K

A:

For each row you insert, the database has to:

Check contraints.  A unique constraint might require an index to be read into memory.  A foreign key constraint requires reading from another table.
Find the pages which have to be updated (the clustered index, and any other indexes)
Run any triggers that are defined on the table.

These activities might cause a lot of reads, and they have to be done for each row.  So it's perfectly normal to see hundreds of reads for a single row insert.  In fact, I'd take it as a healthy sign that the database is doing its work.


Q:

Failed to invoke future method

I am getting this error

Failed to invoke future method 'public static void
  GeoCodeAddressFutureForLeads(Set, String)' on class
  'Helper_GeoCode' for job id 'XXXXXXXXXXX'
caused by: System.DmlException: Insert failed. First exception on row
  0; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference
  converted lead: []

Please point out if anyone having solution.
Thanks in advance!

A:

@Ashwani is right.
You can put a where isConverted = false clause in the query for lead.


Q:

Virtual Keyboard (Linux/libevdev) - sending event

Trying to implement a virtual keyboard. The program sends a keystroke event in the 5 second cycle. Its working on PC (Ubuntu Linux). The problem is that nothing is displayed on Beaglebone Black/Raspberry Pi3.
Plaftorm Beaglebone Black, Debian Jessie:
debian@beaglebone:~$ uname -a
Linux beaglebone 4.9.9-ti-r22 #1 SMP PREEMPT Mon Feb 13 18:39:00 UTC 2017 armv7l GNU/Linux

Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <linux/uinput.h>

/* emit function is identical to of the first example */

void emit(int fd, int type, int code, int val)
{
   struct input_event ie;

   ie.type = type;
   ie.code = code;
   ie.value = val;
   /* timestamp values below are ignored */
   ie.time.tv_sec = 0;
   ie.time.tv_usec = 0;

   int res = write(fd, &ie, sizeof(ie));
   printf("emit write bytes=%d fd=%d code=%d val=%d\n",res, fd, code, val);
}

int main(void)
{
   struct uinput_user_dev uud;
   int version, rc, fd;

   fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
   printf("fd=%d\n",fd);

   rc = ioctl(fd, UI_GET_VERSION, &version);
   printf("rd=%d\n",rc);

   if (rc == 0 && version >= 5)
   {
    printf("Error! version=%d\n",version);
      //return 0;
   }

   /*
    * The ioctls below will enable the device that is about to be
    * created, to pass key events, in this case the space key.
    */
   int i1 = ioctl(fd, UI_SET_EVBIT, EV_KEY);
   int i2 = ioctl(fd, UI_SET_EVBIT, EV_SYN);
   int i3 = ioctl(fd, UI_SET_KEYBIT, KEY_D);
   int i4 = ioctl(fd, UI_SET_KEYBIT, KEY_U);
   int i5 = ioctl(fd, UI_SET_KEYBIT, KEY_P);
   int i6 = ioctl(fd, UI_SET_KEYBIT, KEY_A);

//  printf("ioctl = %d, %d, %d ,%d , %d, %d\n", i1,i2,i3,i4,i5,i6);

   memset(&uud, 0, sizeof(uud));
   snprintf(uud.name, UINPUT_MAX_NAME_SIZE, "uinput-keyboard");
   uud.id.bustype = BUS_HOST;
   uud.id.vendor  = 0x1;
   uud.id.product = 0x2;
   uud.id.version = 1;

   write(fd, &uud, sizeof(uud));
   sleep(2);

   int i = ioctl(fd, UI_DEV_CREATE);
   printf("dev create =%d\n", i);

   sleep(2);

   /* Key press, report the event, send key release, and report again */
for(;;)
{
   emit(fd, EV_KEY, KEY_D, 1);
   emit(fd, EV_SYN, SYN_REPORT, 1);
   sleep(1);
   emit(fd, EV_KEY, KEY_D, 0);
   emit(fd, EV_SYN, SYN_REPORT, 0);

   emit(fd, EV_KEY, KEY_U, 1);
   emit(fd, EV_SYN, SYN_REPORT, 0);
   emit(fd, EV_KEY, KEY_U, 0);
   emit(fd, EV_SYN, SYN_REPORT, 0);

   emit(fd, EV_KEY, KEY_P, 1);
   emit(fd, EV_SYN, SYN_REPORT, 0);
   emit(fd, EV_KEY, KEY_P, 0);
   emit(fd, EV_SYN, SYN_REPORT, 0);

   emit(fd, EV_KEY, KEY_A, 1);
   emit(fd, EV_SYN, SYN_REPORT, 0);
   emit(fd, EV_KEY, KEY_A, 0);
   emit(fd, EV_SYN, SYN_REPORT, 0);

   sleep(5);
}
   ioctl(fd, UI_DEV_DESTROY);

   close(fd);
   return 0;
}

lsinput - ev bit are correct? :
/dev/input/event1
   bustype : BUS_HOST
   vendor  : 0x1
   product : 0x2
   version : 1
   name    : "uinput-keyboard"
   bits ev : (null) (null)

Evtest - sending event to kernel (its OK):
root@beaglebone:/home/debian/KeyEvent# evtest
No device specified, trying to scan all of /dev/input/event*
Available devices:
/dev/input/event0:  tps65217_pwr_but
/dev/input/event1:  uinput-keyboard
Select the device event number [0-1]: 1
Input driver version is 1.0.1
Input device ID: bus 0x19 vendor 0x1 product 0x2 version 0x1
Input device name: "uinput-keyboard"
Supported events:
  Event type 0 (EV_SYN)
  Event type 1 (EV_KEY)
    Event code 22 (KEY_U)
    Event code 25 (KEY_P)
    Event code 30 (KEY_A)
    Event code 32 (KEY_D)
Properties:
Testing ... (interrupt to exit)
Event: time 1499869756.493690, type 1 (EV_KEY), code 32 (KEY_D), value 1
Event: time 1499869756.493690, -------------- SYN_REPORT ------------
Event: time 1499869757.494181, type 1 (EV_KEY), code 32 (KEY_D), value 0
Event: time 1499869757.494181, -------------- SYN_REPORT ------------
Event: time 1499869757.494304, type 1 (EV_KEY), code 22 (KEY_U), value 1
Event: time 1499869757.494304, -------------- SYN_REPORT ------------
Event: time 1499869757.494370, type 1 (EV_KEY), code 22 (KEY_U), value 0
Event: time 1499869757.494370, -------------- SYN_REPORT ------------
Event: time 1499869757.494434, type 1 (EV_KEY), code 25 (KEY_P), value 1
Event: time 1499869757.494434, -------------- SYN_REPORT ------------
Event: time 1499869757.494495, type 1 (EV_KEY), code 25 (KEY_P), value 0
Event: time 1499869757.494495, -------------- SYN_REPORT ------------
Event: time 1499869757.494558, type 1 (EV_KEY), code 30 (KEY_A), value 1
Event: time 1499869757.494558, -------------- SYN_REPORT ------------
Event: time 1499869757.499785, type 1 (EV_KEY), code 30 (KEY_A), value 0
Event: time 1499869757.499785, -------------- SYN_REPORT ------------
Event: time 1499869762.502378, type 1 (EV_KEY), code 32 (KEY_D), value 1
Event: time 1499869762.502378, -------------- SYN_REPORT ------------
Event: time 1499869763.225387, type 1 (EV_KEY), code 32 (KEY_D), value 0
Event: time 1499869763.225402, -------------- SYN_REPORT ------------
expected 16 bytes, got -1

A:

I solved this problem. Screen wasn't connect to BeagleBone/Raspberry and system was can't send character to screen.


Q:

Android background based on screen size

I'm creating an Android application, and want different background images for phone sized screens and tablet sized ones. I already have different resolution images for different resolutions (mdpi, hdpi etc.). The challenge is that most tablets use mdpi, but some phones might use it too.
I've tried to do some research, but only it seems to be possible to define screen sizes in the layouts, e.g. res/layout/layout-large. Does that mean I have to create a separate xml for tablets, linking to a @drawable/tablet-background? Or is there any other solutions, either xml or programmatic?

A:

mdpi, hpdi etc. refers to screen density and that's independent from the device being a tablet or a phone. If I understood correctly, what you're trying to do is to use different background images for tablet and for phones.
There are three ways:

Create an xml layout for tablet and an xml layout for phone using layout-large, layout-xlarge folders
Using the same xml layout (except for an element id) in layout and in layout-large folders and change the background programmatically using something like this:
public boolean isTablet(){
    return (findViewById(R.id.tablet_view) != null);
}

where tablet_view is an element id present only in the layout-large xml layout.
Another trick: Determine if the device is a smartphone or tablet?

A:

and want different background images for phone sized screens and
  tablet sized ones

Try the qualify the drawable folder with the desired screen size and also the density value for the target device, for example drawable-large-mdpi. The screen size must come first based on the configuration qualifiers table.


Q:

Are there money changing facilities at the Turkey/Georgia border, and how good are they?

Soon I hope to cross the border from Turkey to the Republic of Georgia and need to work out my money.
To minimize horrendous and unavoidable bank fees I prefer to withdraw larger amounts less frequently. But if a border crossing is imminent I need to know I can change my money in time and not at a rip-off rate. If I can't change money OK at the border I would withdraw a smallish amount in Turkey and then withdraw a larger amount when I get to Georgia and just have to suffer the extra fees.
So is there a money changer at the Turkey/Georgia border? Are the rates for changing Turkish Lira to Georgian Lari decent?

A:

I crossed the border from Turkey to Georgia about midnight last night.
There were no obvious exchange booths like at many borders but I didn't go into the duty free store.
I'm now in Tbilisi and most exchange places I've seen (of which there are many) only display rates for USD, EUR, and RUB.

UPDATE
I've now been in Georgia almost seven months and can say that at least in Tbilisi and Batumi it is not hard to find money changers that deal in TRY as well as AMD and AZN. But along with RUB the rates are very bad. The rates for USD and EUR are fair though.

A:

Lari to Lira exchange is not recommended, you should use USD as the middle currency. that way you would lose only acceptable exchange fees instead of very big margins.


Q:

Why is dd creating an enormous file when I try to create a backup disk image?

I've been trying to get CUDA to work on my system and in the process of messing with nvidia drivers I have broken ubuntu badly enough that I've had to reformat my drive partition multiple times. I've now been hit with that stick enough times that I'm trying to back up my partition once I've installed all my tools and programs and stuff, using dd (as recommended by a friend).
However, when I ran
sudo dd if=/dev/sda4 of=~/backup.img
I eventually got an error that my drive ran out of space. This was strange to me, since the partition is quite large and I have just a fresh ubuntu install along with a few (small) programs on it.
I figured what might be happening is that it was recursively trying to write a copy of what it had already written, so I tried writing the file directly to another partition instead:
sudo dd if=/dev/sda4 of=/media/Ye\ Olde\ Data/ubuntu\ reinstall\ backup/backup.img
But this took forever and I aborted the process once the file got to a size I was pretty sure was too big to contain only the data I wanted.
What is happening? Is it that /media has the other partitions mounted and thus it's treating the other partitions as part of /dev/sda4? Is it that dd copies the entire partition byte-for-byte, ignoring what bytes actually have files on them?
And whatever the case, how can I do what I am trying to do, correctly?
Oh, and here's my disk information, in case it matters:
sudo sfdisk -l /dev/sda

Disk /dev/sda: 62260 cylinders, 255 heads, 63 sectors/track
Warning: extended partition does not start at a cylinder boundary.
DOS and Linux will interpret the contents differently.
Units = cylinders of 8225280 bytes, blocks of 1024 bytes, counting from 0

   Device Boot Start     End   #cyls    #blocks   Id  System
/dev/sda1   *      0+     12-     13-    102400    7  HPFS/NTFS/exFAT
/dev/sda2         12+  14602-  14590- 117187500    7  HPFS/NTFS/exFAT
/dev/sda3      29192+  62260-  33069- 265622493+   5  Extended
/dev/sda4      14602+  29191-  14590- 117193728   83  Linux
/dev/sda5      61228+  62260-   1032-   8287232   82  Linux swap / Solaris
/dev/sda6      29192+  61227   32036- 257329138+   7  HPFS/NTFS/exFAT

A:

If you copy  a  partition with  dd, the output file will be as big as the partition.  dd does a physical copy of the disc, it has no knowledge of blank or used space.
If you compress the result file you will save a lot of space, though, given that blank space will compress away very well (beware, this is going to be computationally very heavy). You can even compress the output of dd on the fly, with something on the line of dd if=/dev/sdaX | gzip -c > compressed_file.gz.
really important:

Moreover, you cannot (never) do a dd on a live  (mounted)
  partition, the data recorded will be totally inconsistent and
  absolutely not useful for a backup. Think about it: blocks of data are
  continually allocated, moved and deleted; is like shooting a photo
  with long exposure time to a moving target.
To copy the partition with dd you must boot from a different one -
  live USB or whatever.

What would I do to solve the problem at hand (notice, only generic instruction because you need to know what you are doing)
First option buy Norton Ghost, or explore the opensource options: partimage and clonezilla (never tested myself).
Second option do it manually:

create an extra partition for backups, call it /dev/sdX (or use a common data partition, whatever).
to backup:

boot with live usb
mount the real root partition in /real
mount the extra partition in /extra
do a big tar, on the line of (cd /real && tar cvf /extra/mybck.tar.gz)

to restore

boot with live usb
mount the real root partition in /real
mount the extra partition in /extra
restore, on the line of (cd /real && tar xvpf /extra/mybck.tar.gz), beware of the p option to preserve metadata
chroot in /real
update grub or the bootloader you are using

You can substitute tar with your preferred archiver, just be sure it will respect ownership/mode of files. rsync is worth exploring.


Q:

Redirecting in 10,..9,... script

Hy,
I have a 10 sec. delay page.
var t = window.setTimeout('redirect(strUrl)', 11000);

And function redirect(strUrl) just does document.location
What would be nice if i have a little message displaying at the bottom of my page, for example:  Redirecting in 10 seconds...
"one second later that setTimeout fired"
...Redirecting to destiny in 9 seconds..
etc
ps. and the dots at the end going from left to right you know it. .. ...
I myselft would probably find out how to get that every second of timeout and just with jquery altered the number ...if that would be possible at all.

A:

var timeout = 11; // in seconds

var msgContainer = $('<div />').appendTo('body'),
    msg = $('<span />').appendTo(msgContainer),
    dots = $('<span />').appendTo(msgContainer);

var timeoutInterval = setInterval(function() {

   timeout--;

   msg.html('Redirecting in ' + timeout + ' seconds');

   if (timeout == 0) {
      clearInterval(timeoutInterval);
      redirect(strUrl);
   }

}, 1000);

setInterval(function() {

  if (dots.html().length == 3) {
      dots.html('');
  }

  dots.html(function(i, oldHtml) { return oldHtml += '.' });
}, 500);

See it on jsFiddle.
If you wanted to have the second(s) thing, replace the appropriate line above with...
msg.html('Redirecting in ' + timeout + ' second' + ((timeout != 1) ? 's' : ''));

Of course, this works well with English, but probably isn't as easy with other languages.


Q:

Category Nav tag with control over the depth that {% children %} goes

Looking at the docs, i can see that the category {% nav %} loop uses the categoryGroup as the starting point. But, i want the first top level category within the category group as the starting point.
So, i want to do something like:
{% set categories = craft.categories.slug('my-first-top-level-cat).first().getChildren() %}

{% nav category in categories %}

        {{ category.title }}

 {% ifchildren %}

   {% children %}

 {% endifchildren %}
{% endnav %}

But, doing this only returns the top level, no sub levels.
Also, i want to be able to limit the amount of children output as the there are a few sub trees.

A:

i did {% set categories = craft.categories.descendantOf(1066) %}
And then i did
{% nav category in categories.level(2) %}
{% endnav %}
Always get the answer myself just after i post these damn things.


Q:

Was the Sorcerer's Stone already in the Mirror of Erised when the Mirror was moved in the third-floor corridor?

In Harry Potter and the Sorcerer's Stone, the Mirror of Erised is said to be the ultimate protection against the impure of heart who desire to obtain the Stone only for their own desires.
However, the Mirror itself is not stored in Dumbledore's forbidden third-floor corridor until practically the end of the book.  Instead, it appears to be collecting dust in an unused classroom at least five floors above the kitchens, until Harry finds it and Dumbledore moves it, following their discussion.
It's assumed by the characters that the Stone is hidden underneath Fluffy in the third-floor corridor since it was moved to Hogwarts from the Gringotts vault, but given that the Mirror seems to be the only true protection against a powerful Dark Wizard, wouldn't it make more sense to hide the Stone in the Mirror from the very beginning?
Do we know anything else about whether the Sorcerer's Stone was stored in the Mirror of Erised before it was moved into the forbidden third-floor corridor?

A:

In Chapter Eleven of Philosopher's Stone we have the following passage:

"I'm tellin' yeh, yer wrong!" said Hagrid hotly. "I don' know why Harry's broom acted like that, but Snape wouldn' try an' kill a student! Now, listen to me, all three of yeh – yer meddlin' in things that don' concern yeh. It's dangerous. You forget that dog, an' you forget what it's guardin', that's between Professor Dumbledore an' Nicolas Flamel –"

Thus – at least as far as Hagrid knew – the Stone was at that point already guarded by Fluffy. Harry didn't discover the Mirror of Erised until the next chapter, which would mean that the Stone was not protected by the Mirror at that point.
However, there is also an implication that the Stone might have already been in the Mirror at that point. In Chapter Twelve, Dumbledore explained to Harry how the Mirror works, and then explicitly mentioned that this would prepare Harry if he ever came across it again:

"The Mirror will be moved to a new home tomorrow, Harry, and I ask you not to go looking for it again. If you ever do run across it, you will now be prepared.

In Chapter Seventeen Harry thinks that Dumbledore did this purposely in order to give Harry a chance:

"No, it isn't," said Harry thoughtfully. "He's a funny man, Dumbledore. I think he sort of wanted to give me a chance. I think he knows more or less everything that goes on here, you know. I reckon he had a pretty good idea we were going to try, and instead of stopping us, he just taught us enough to help. I don't think it was an accident he let me find out how the mirror worked. It's almost like he thought I had the right to face Voldemort if I could...."

In order for this to make sense the Stone would have had to already been in the Mirror back when Harry discovered the Mirror, or at the very least Dumbledore would have had to already have thought to store the Stone there. And if he had already thought of the idea, there doesn't seem to be much reason why he wouldn't have executed it immediately. Of course, though, there wouldn't be much point in having Fluffy and all the subsequent traps if the Stone wasn't even hidden there, unless the whole third-floor-corridor thing was just a decoy.


Q:

Time diffence between rows in a big table

I have a huge sql table (more than 1 billion) of user transactions.
I'd like to add a binary column which represents where or not the current user_id row is 40 minutes or less than the previous one.
For instance:
user_id | date
--------+--------------------
1       | 2011-01-01 12:15:00
1       | 2011-01-01 12:00:00
8       | 2011-01-01 15:00:00
8       | 2011-01-01 14:00:00

the result of the query would be:
user_id | date                | new
--------+---------------------+----
1       | 2011-01-01 12:15:00 | 0
1       | 2011-01-01 12:00:00 | 1
8       | 2011-01-01 15:00:00 | 1
8       | 2011-01-01 14:00:00 | 1

I'd like to avoid joining the entire table to itself
and maybe use a side table or an analytic function (over-partition).

A:

select user_id,
       date,
       case
          when date - lag(date) over (partition by user_id order by date) > interval '40' minute then 1
          else 0
       end as diff_flag
from the_table
order by user_id, date

It assumes that date is a timestamp column despite its name.
It's the only way I can see. An index on (user_id, date) might speed things up - especially on 9.2 where this could qualify for an index only scan. But this is going to scan the whole table (or the maybe only the index on 9.2)
Btw: it's not a good idea to name a column with a reserved word (date). Additionally date is a very poor name from a documentation point of view.


Q:

Does STM provide fine-grained locking for existing data structures?

Reading Bartosz Milewski's fantastic blog post on STM, I was excited to read the following:

But take into account an important fact: STM is very fine grained. For
  instance, when you’re inserting an item into a tree, the STM
  transaction will only lock the nodes that you are actually modifying.
  STM will easily beat a solution that uses one global lock per whole
  tree.

However, as I understand it, this behavior is not automatic, is it? If I use a TVar (Map k a), will it not act as a single global lock on the whole map? And to gain the benefit of this fine-grained behavior, I (or someone) would have to implement a map replacement (TMap, for example) that contains TVars internally, correct?
This might seem like an obvious question, but reading up on STM implementation I was confused between reads of TVars and reads of memory locations. I just want to make sure I have it right!
Bartosz goes further to say:

Per-node manual locking is hard to implement correctly because
  of the risk of deadlocks.

The difference with STM, as I understand it, is that while the STM implementation in effect uses locks the way a manually-locked solution might, the actual acquiry and release of locks is handled by the runtime, not the programmer - correct?

A:

A TVar is a mutable cell. With immutable structures no two threads can transmit modifications back and forth, so we need some notion of mutable cell to cause the effect. In particular, we have
writeTVar :: TVar a -> a -> STM ()

which creates an SMT action replacing the value inside the mutable cell. We can sequence a few of these operations together, building a bigger and more complex STM action, and then call
atomically :: STM a -> IO a

to atomically commit the whole STM action at once. This is the "transactional" part of software transactional memory: other threads with their own references to these mutable cells will only ever witness the entirety of the atomically-performed STM action, no subparts. To achieve this Haskell might use locking, or something more clever—it's a mere implementation detail. The only thing STM asks you be cognizant of is that the actions within your STM block may be run repeatedly as necessary—and so side effects outside of modification of some shared memory cells are prohibited.
So how do we achieve fine-grained concurrency? Easily: we just provide more mutable cells for various threads to synchronize upon. For instance, we can read at least 3 different Map types.
TVar (Map k v)
Map k (TVar v)
TVar (Map k (TVar v))

The first will allow concurrent threads to make modifications to the entire Map all at once such that no partial changes are visible. The second, allows changes at any stored value, but maintains that the structure of the map itself—the choice of keys and the selection of stored values—is immutable and changes cannot be easily propagated to other threads.
The final choice, TVar (Map k (TVar v)) is the most flexible. We can make wholesale modifications to the Map by synchronizing on the outer TVar and we can make changes to the values stored in the map by reading down to the value-TVars and synchronizing on actions within them. The full set of possible semantics available for such a tree is myriad allowing both "whole Map locking" and "individual value locking" to happen together.


Q:

How to declare complex numbers without their fields getting mixed up?

I try to create complex numbers but for whatever reason they always come up real part having imaginary value and imaginary part getting zeroed.
For example I expected this little test app to print several instances of (1,2) but all I'm getting is (2,0) no matter how I try to aproach it.
#include "stdafx.h"
#include <complex>
#include <iostream>
using namespace std;
int main()
{
    std::complex<double>** complexdouble_c;
    complexdouble_c = new std::complex<double>*[5];
    for (int i = 0; i < 5; ++i)
        complexdouble_c[i] = new std::complex<double>[2];

    for (int i = 0; i < 5 && i < 15; i++) {
        for (int j = 0; j < 2 && j < 15; j++) {
                double real = 1;
                double imag = 2;
                complexdouble_c[i][j] = (real, imag);
            }
        }
    for (int i = 0; i < 5 && i < 15; i++) {
        for (int j = 0; j < 2 && j < 15; j++) {
            std::cout << complexdouble_c[i][j];
        }
        std::cout << "\n";
    }
    std::complex<double> complexdouble;
    double real = 1.0;
    double imag = 2.0;
    complexdouble = (real, imag);
    std::cout << complexdouble;
    std::cout << complexdouble.real();
    std::cout << complexdouble.imag();
    getchar();
}

A:

Declare in this format. This will give the following output
std::complex<double> c(1, 2);
// 1 + 2i


Q:

Datafx Link Action (Not working)

Trying to understand why my datafx flow is not working.  I have 2 class WIPController.class(Master) and DeliverableEditFXMLController.class(Detail)
Below is how I create the flow
        StackPane pane = new StackPane();
        DefaultFlowContainer flowContainer = new DefaultFlowContainer(pane);
        Flow flow = new Flow(WIPController.class)
                .withLink(WIPController.class, "bEditAction", DeliverableEditFXMLController.class)
                .withLink(DeliverableEditFXMLController.class, "bSaveAction", WIPController.class)
                ;
        flow.createHandler().start(flowContainer);
        Scene scene = new Scene(pane);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

Below is bare WIPController.class
@FXMLController(value="fxml/WIP.fxml")
public class WIPController  {

    @FXMLViewFlowContext
    private ViewFlowContext context;

    @FXML
    private TreeTableView<CaseDeliverable> ttblWIP;

    @FXML
    @LinkAction(DeliverableEditFXMLController.class)
    private Button bTestAction;

    @FXML
    @ActionTrigger("bEditAction")
    private Button bEdit; }

bEdit button is meant to take you to (Details) controller.  View shows but will I click button nothing happens
I added bTestAction see if I could get it to happen via linkaction annotation but nothing happens.
@FXMLController("fxml/DeliverableEditFXML.fxml")
public class DeliverableEditFXMLController  {

    @FXMLViewFlowContext
    private ViewFlowContext context;

    @FXML
    @ActionTrigger("bSaveAction")
    private Button bSave;
}

Above is details controller as you can see trying to get bSave button take back to Master View.
At the moment bEdit button does not event take me to Detail view.  If anyone can help me understand what wrong with would greatly appreciate it.

A:

Nothing wrong with code but seems like jar was using for datafx was broken.
Download all jar for datafx from Mavern repository


Q:

How does ANDROID_ID on ARC (Chrome) differ from Android?

On Android, the ANDROID_ID is constant for a user profile on a device (see discussion here).  This does not appear to be the case on ARC, but ARC is very new and hopefully this will change.
It is also worth noting - in regards to device identification with ARC - that the Android serial # is not available on ARC, that WiFi MAC address is not currently available (yes, I've seen people talk about using this for device id), and product model information is not available.
Motivation: I know it is not now recommended, but I think a lot of apps use the ANDROID_ID to identify devices in their server database.
The behavior of ANDROID_ID on Android means that, if a user uninstalls your app and then re-installs it, you would know and could eg. re-sync their data to the device.  And if a user installs two apps of your apps, you know they are on the same device (and user profile).

A:

In my experience - using ARC runtime 42.4410.288.23 on Chrome 41.0.2272.118 m (stable) on Windows - a new ANDROID_ID is generated for every app install.
So, for example, if you uninstall your app and then re-install it, it will see a new ANDROID_ID.
I should test this on a Chromebook, since that is the only platform supported for deployment at this time, but I don't have a Chromebook available.


Q:

Distributed Lock Service with Windows Server AppFabric Caching

I have an extension method for the Microsoft.ApplicationServer.Caching.DataCache object found in the Windows Server AppFabric SDK that looks like this:
using System;
using System.Collections.Generic;
using Microsoft.ApplicationServer.Caching;

namespace Caching
{
    public static class CacheExtensions
    {
        private static Dictionary<string, object> locks = new Dictionary<string, object>();

        public static T Fetch<T>(this DataCache @this, string key, Func<T> func)
        {
            return @this.Fetch(key, func, TimeSpan.FromSeconds(30));
        }

        public static T Fetch<T>(this DataCache @this, string key, Func<T> func, TimeSpan timeout)
        {
            var result = @this.Get(key);

            if (result == null)
            {
                lock (GetLock(key))
                {
                    result = @this.Get(key);

                    if (result == null)
                    {
                        result = func();

                        if (result != null)
                        {
                            @this.Put(key, result, timeout);
                        }
                    }
                }
            }

            return (T)result;
        }

        private static object GetLock(string key)
        {
            object @lock = null;

            if (!locks.TryGetValue(key, out @lock))
            {
                lock (locks)
                {
                    if (!locks.TryGetValue(key, out @lock))
                    {
                        @lock = new object();
                        locks.Add(key, @lock);
                    }
                }
            }

            return @lock;
        }
    }
}

The intent is to let the developer write code that says, "fetch me some data by trying the cache first. if it's not available in cache execute the specified function, put the results in cache for the next caller, then return the results". Like this:
var data = dataCache.Fetch("key", () => SomeLongRunningOperation());

The locking limits executing the potentially long running function call to a single thread but only within a single process on the same machine. How would you expand on this pattern to make the locking distributed to prevent multiple processes/machines from executing the function at once?

A:

AppFabric has it's own distributed locking mechanism which you can access through the GetAndLock/PutAndUnlock family of methods. If your item is locked, a normal Get call will still succeed and return the last value, but further GetAndLock calls will throw an Exception. In the case where your client is requesting a cached object for the first time, you can still lock the key even though it doesn't really exist yet (it's kind of more like a reservation than a solid lock).
public static T Fetch<T>(this DataCache @this, string key, Func<T> func, TimeSpan timeout)
{
    var result = @this.Get(key);

    if (result == null)
    (
        DataCacheLockHandle handle;
        // We need a timespan to allow func time to run
        TimeSpan funcTimespan = New TimeSpan(0,1,0);

        try
        {
            // Lock the key
            // If something goes wrong here it will unlock at the end of funcTimespan
            var result = @this.GetAndLock(key, funcTimespan, handle);

            if (result == null)
            {
                // Still no value so go and run func
                result = func();

                @this.PutAndUnlock(key, result, handle, timeout);
            }
            else
            {
                // There's a value now so we'll unlock the key and reset it's timeout
                @this.Unlock(key, handle, timeout);
            }
        }
        catch (DataCacheException ex)
        {
            if (ex.ErrorCode == DataCacheErrorCode.ObjectLocked)
            {
                // Another process has locked the key so func must be running right now
                // We'll return null to the client
                result = null;
            }
        }

        if (result == null)
        {
            return null;
        }
        else
        {
            return (T)result;
        }
    )
}

A:

I was looking for a good implementation of this and came up with my own:
Distributed Lock with AppFabric Caching
Essentially it's an AcquireLock() extension method to the DataCache class which you can use like this:
DataCache cache = factory.GetCache("MyCache");
using (cache.AcquireLock("MyLock"))
{
    // Lock acquired, perform synchronized work here
}


Q:

Java string producing error when converting to an int

I am trying to use Integer.parseInt() to convert a string representing a phonenumber into an int I can use.
This is the error I'm getting:
Enter a 10-digit telephone number with optional space or dash after the first and the second block of three digits >
5558759142
Processing encrypted number "5558759142"
Exception in thread "main" java.lang.NumberFormatException: For input string: "5558759142"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)
    at TelephoneNumberValidator.main(TelephoneNumberValidator.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1

This is my code:
import java.util.*;
import java.lang.Integer;

public class TelephoneNumberValidator {
    public static void main(String[] args) {
        final String VALID_PHONE_PATTERN = "[0-9]{3}[-| ]?[0-9]{3}[-| ]?[0-9]{4}";
        final int NUMBERS_FOLLOWING_AREA_CODE = 7;
        final int DECRYPTED_AREA_CODE = 212;
        Scanner scanKeyboard = new Scanner(System.in);
        String userInput;

        do {
            System.out.println( "Enter a 10-digit telephone number with optional space or dash after the first and the second block of three digits >" );
            userInput = scanKeyboard.nextLine();
            //check to see if the phone number is correct
            if ( !userInput.matches(VALID_PHONE_PATTERN) )
            {
                System.out.println("The given input \" " + userInput + " \" is not valid");
            }
        }while ( !userInput.matches(VALID_PHONE_PATTERN) );

        //extract int from string
        String phoneJustNumbers = userInput;
        phoneJustNumbers = phoneJustNumbers.replaceAll("-",""); // replaces hyphens
        phoneJustNumbers = phoneJustNumbers.replaceAll(" ", "");

        System.out.println( "Processing encrypted number \"" + phoneJustNumbers + "\"" );
        //check the first 3 digits (aka area code) to see if it matches 212
        int areaCode =  Integer.parseInt(phoneJustNumbers);//gets area code
        int placeholderForAreaCode = 111; //set 111 so that each number in area code can be accounted for
        int placeholderForEntirePhoneNum = 1111111111; //set each digit to 1 so we can shift later
        for (int j = 0; j <= 9; j++)
        {
            if ( (areaCode + ( placeholderForAreaCode * j ) == DECRYPTED_AREA_CODE ) ) // we are shifting each digit by one
                                                                                // to see if it matches the decrypted area code
            {
                System.out.println("The telephone number is \"" + ( Integer.parseInt(phoneJustNumbers) * placeholderForEntirePhoneNum * j )
                        + "\" with a shift value of " + j);
            }
            else
            {
                System.out.println("The telephone number \"" + userInput + "\" cannot be decrypted area code." );
            }
        }

    }
}

So when I try to just substitute a hardcoded string it works using Integer.parseInt(). This leads me to believe the way I am generating cleaning up my string somehow stops this from working.
I am new to java so I don't know why that would be or what I have done wrong.

A:

The largest value int can be is 2,147,483,647. (See Integer.MAX_VALUE.) Your example phone number is much larger than that. Try using Long.parseLong() instead, as the largest value for a long is 9,223,372,036,854,775,807.


Q:

When i inputed values for elements in array, in for loop, after for loop them transformed

When i print baza[nlines] in for loop, result("outprint") is correct, it print what i inputed. But when i checked "outprint" after for loop, it somehow transform and both elements of baza[] is same. Example: i inputed for number_loops 2, for baza[0] "grass", and for baza[1] "beer", so when i printed it after for loop, baza[0] somehow become  same, like baza[1] , and it has been printing for both "beer".
int number_loops = 2;
char *baza[SIZE];
char baza_pojedinac[100];
char p[1000];
int nlines = 0;
for ( ;number_loops-- > 0 ; )
{
    getline(baza_pojedinac);
    baza_pojedinac[strlen(baza_pojedinac)-1] = '\0';
    strcpy(p, baza_pojedinac);

    baza[nlines] = p;
    printf("baza: %s\n",baza[nlines]);
    nlines++;

}

printf("first: %s\n",baza[0]); // result == "beer".
printf("second: %s\n",baza[1]); // result == "beer".

A:

After your for loop both baza[0] and baza[1] point to the same string p[], so they have to be the same thing. When you do baza[nlines] = p; you don't copy the string, you only say that baza[nlines] is now pointing to p.
There are a few ways to fix this, but the easiest is to just make baza a 2D array and copy the string into it:
char baza[10][SIZE];     //Increase if needing more than 10 lines
char baza_pojedinac[100];
int nlines = 0;

for ( ;number_loops-- > 0 ; )
{
    getline(baza_pojedinac);

    strcpy(baza[nlines], baza_pojedinac);
    printf("baza: %s\n",baza[nlines]);
    nlines++;

}

printf("first: %s\n",baza[0]);
printf("second: %s\n",baza[1]);

Edit
If you'd like to allocate strings instead you can do:
char* baza[SIZE];
char baza_pojedinac[100];
int nlines = 0;

for ( ;number_loops-- > 0 ; )
{
    getline(baza_pojedinac);

    baza[nlines] = malloc(100);
    strcpy(baza[nlines], baza_pojedinac);

    printf("baza: %s\n", baza[nlines]);
    nlines++;

}

printf("first: %s\n",baza[0]);
printf("second: %s\n",baza[1]);
...
free(baza[0]);   // Don't forget to free the memory eventually
free(baza[1]);


Q:

What's the reason why table layout in code is considered bad?

My colleagues tell me that table based formatting of code is bad and it is no readable and I should follow conventions. What's that bad about table based formatting? Why is it banned?
I'm asking because for me it's much more readable.
Examples (not real code):
if (res == ResultType.Failure)
  something = ProcessFailure(..);
if (res == ResultType.ScheduledAndMonitored)
  something = DoSomething(...) && DoSomething3(..);
if (res == ResultType.MoreInfoAvailable)
  info = GetInfo(..);
if (res == ResultType.OK && someCondition)
  something = DoSomething2(..);
.... continued

versus
if (res == ResultType.Failure)               something = ProcessFailure(..);
if (res == ResultType.ScheduledAndMonitored) something = DoSomething(...) && DoSomething3(..);
if (res == ResultType.MoreInfoAvailable)     info      = GetInfo(..);
if (res == ResultType.OK && someCondition)   something = DoSomething2(..);
.... continued

Why I think the second one is better:

I don't need to parse the text by eyes - I see the structure of the commands at one glance.
I see immediatelly

that there are some ifs and assignments
that the enum used in conditions is ResultType and nothing more
that only the last condition is composed from two expressions

Update: this is not a real code. I just wanted to show some example. Consider it like it's an old code that somebody wrote some time ago and you need to read it. Why the first formatting is preferred over the second?

A:

When your colleagues say you should follow conventions, does that mean your team has a formatting convention?  If that is the case, that is enough reason right there.  When everybody formats their code the same way, it is easier to read your teammate's code.

A:

The "table-based" layout you describe can be very useful in certain cases:
public string GetMessageFromErrorCode(int code)
{
    switch (code)
    {
        case 1: return "OK";
        case 2: return "Syntax Error";
        case 3: return "Other error";
    }
}

Note that this example is a valid exception to the c# rule that "All case statements must also include a break."
I am not fond of being rigid about code layout.  Following a coding standard is a good thing.  But as soon as you start doing things like using several parameters with long names in function calls, writing linq queries, or using anonymous methods or intricate lambda statements, it can make your code more readable to break the rules from time to time.
See Also:
Anonymous Methods / Lambda's (Coding Standards)

A:

The reason is simple.
If you are using spaces to indent everything, and make it lineup, it's a pain to keep it inline when a variable or condition changes.  You have to manually go in and add/remove spaces.
If you are using tabs to indent everything, and make it lineup, it won't look the same on everyone's computer since not everyone has their tabs set to the same width.  Some people have them set to 3 characters, others 5, others something different.  And what looks nice and neat and "table like" on your machine, looks like a mess on theirs.
Throw braces around the statements that are executed by the if, and format it normally.
if (res == ResultType.Failure)
{
  something = ProcessFailure(..);
}

if (res == ResultType.ScheduledAndMonitored)
{
  something = DoSomething(...) && DoSomething3(..);
}

if (res == ResultType.MoreInfoAvailable)
{
  info = GetInfo(..);
}

if (res == ResultType.OK && someCondition)
{
  something = DoSomething2(..);
}

Oh, and the other reason is, not everyone uses a fixed with font for programming.  Believe it or not, some developers use proportional fonts.


Q:

Merge multiple onChanged events to one in QML

I have created Canvas in QML, which have multiple properties. Canvas will draw something depending on those properties, and I want to use function requestPaint once (if some property/properties change), so I don't have to redraw Canvas multiple times.
Is there any way to merge multiple onPropertyChanged events into one?
Something, that will work like if(onAChanged || onBChanged)?
Thank you for your help!

A:

No, you can't merge multiple property change signals in one. This would be problematic for other things that depend on the signals.
However you might connect one function to multiple signals.
function doSomething() { ... }
onAChanged: doSomething()
onBChanged: doSomething()

You might also emit one signal:
signal someThingsChanged()
onAChanged: someThingsChanged()
onBChanged: someThingsChanged()
onSomeThingsChanged: { ... }

There is also the possibility to use [scripts] to automatically connect on function to multiple/all signals:
Connect dynamically to signals of dynamically created objects

To avoid multiple calls of the slot, you might set a bool property like:
property bool dirty

and check it e.g. once per render cycle.
I think a Timer with interval: 1 or the beforeRendering-signal should do that job.

Most likely however, what you try to do, is unnecessary, since a requestPaint does not directly trigger a paint and the collection of those requests is already handled by the Canvas. As a proof, see this small example:
Timer {
    interval: 100
    running: true
    repeat: true
    onTriggered: {
        console.log('RequestPaint')
        cvs.requestPaint()
    }
}
Timer {
    interval: 100
    running: true
    repeat: true
    onTriggered: {
        console.log('RequestPaint')
        cvs.requestPaint()
    }
}
Timer {
    interval: 100
    running: true
    repeat: true
    onTriggered: {
        console.log('RequestPaint')
        cvs.requestPaint()
    }
}

Canvas {
    id: cvs
    width: 100
    height: 100
    onPainted: console.log('Painted')
    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
        ctx.fillRect(0, 0, width, height);
    }
}

The three Timers all call requestPaint but onPainted is only called once.

qml: RequestPaint
qml: RequestPaint
qml: RequestPaint
qml: Painted
qml: RequestPaint
qml: RequestPaint
qml: RequestPaint
qml: Painted


Q:

Open Outlook application/ desktop to send mail via Windows 8 App

I am creating a windows 8 app to send mail from the entered fields. There are two approaches that i have tested and tried. But each one has its own limitation. My requirement is simple to send mail via outlook desktop app for the user. The content body of the mail is well formatted hence I used HTML to create it(Other ways if any let me know), there is an image attachment also of the InkManager used to take user sign.
Approach 1: Use share charm. All things work well but some times the app stops sharing then I need to restart or logoff from that account and then again login. And the clients wants to open his/ her outlook
Approach 2: Use mailto and open using  Launcher.LaunchUriAsync it gives me an option to choose outlook but I can't set the HTML content formatted and unable to put the InkManager used to take user sign as an image
How can I solve this issue?

A:

If you need to send the mail from the user's account these are the only two ways. Alternatives are using an external web service as Filip suggested or sending it directly from the app using a mail API such as Mail for Windows Store.
I have another remark regarding the first approach, though. In my experience the sharing typically stops working until the next logon when an app does something wrong handling the DataRequested event - this breaks the share charm for all the apps. If it happens to you during development or testing your own app, make sure you handle any exceptions that might happen in the event handler and also check that you are adding and removing the event handler properly. Also avoid stopping the app within this event handler when debugging. This should prevent the issue from occuring.


Q:

direct11 write data to buffer in pixel shader? (like ssbo in open)

I'm trying to write data to a buffer in hlsl shader. I know in opengl you need ssbo, but is there a corresponding buffer type in direct11?(I'm new to it).
p.s. I'm using monogame so the newest shader model available is 3.0.
thanks!

A:

Shader Model 3 corresponds to the DirectX 9 architecture. This architecture looks as follows:

(Source: https://msdn.microsoft.com/en-us/library/windows/desktop/bb219679(v=vs.85).aspx)
As you see, there is only one output from the pixel shader. This output can be a color or depth value and will be rendered to the render target. So, there is no way in DX9.
In DX10 (SM 4), the pipeline looks as follows:

Source: https://msdn.microsoft.com/en-us/library/windows/desktop/bb205123(v=vs.85).aspx
Again, the output of the pixel shader is color and depth. No way in DX10 either.
Finally, DirectX 11 (SM 5):

Source: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476882(v=vs.85).aspx
Now there is a way from the Pixel Shader to Memory Resources. The buffer type that you would need is the RWBuffer.


Q:

Simplest way to create a webview app for my own use?

I'm trying to do a simple application that will load a local html file for my Android 3.1 tablet to give presentations on. I'm not a programmer, but I read some tutorials about creating a simple webview app with Eclipse + Android SDK. But before I get dirty I wanted to know if there was a simpler way of just getting a simple app on my tablet that will in reality just be a full screen web browser. Thanks a lot everyone :)

A:

What's wrong with using a browser that that has a full screen mode? Dolphin has a full screen mode. Why bother creating an app, especially if you are not a programmer?


Q:

css how to prevent content from drifting underneath fixed position areas?

I've created an HTML template where I have a sidebar set to position: fixed; but when I minimize the browser to less width than the page is set to, the main content drifts underneath the sidebar when the user viewing sidescrolls.
Is there any fix to set the entire container with sidebar and the main content to be like a single fixed block?
http://jsfiddle.net/vuj6t/2/

body {
  height: 100%;
  overflow: auto;
  margin: 0;
  padding: 0;
  position: relative;
}

#container {
  margin: 0 auto;
  padding: 0;
  position: relative;
  width: 700px;
}

#sidebar {
  display: block;
  float: left;
  overflow: hidden;
  position: fixed;
  width: 200px;
}

#stream {
  float: right;
  margin: 0 0 0 210px;
  padding: 0;
  width: 490px;
}

A:

You could just absolutely position the sidebar on narrow screens using a simple media query like
@media (max-width: 690px) {
  #sidebar { position:absolute; }
}

http://jsfiddle.net/vuj6t/3/


Q:

Using touchscreen cellphone lcd module for custom projects

I intend to use the capacitive touch based lcd modules of cellphones in custom embedded projects,
I will be using this display with low cost stm32 boards.
Has anybody experimented with this approach ? Any ideas, links to datasheets ?
PS : I am specifically looking for touch integrated lcd modules, there is a hack available for nokia non touch modules already.

A:

It turns out to be easier, and much more cost-effective, to use LCD display + touchscreen integrated modules as sold on eBay or other sites, compared to using an LCD touchscreen from a cellphone.
For instance, this is a 2.2" TFT LCD with integrated touch panel, for $6.79 (approximately Rs.370) including free delivery to India:

If integrating the fine-pitch FPC connectors of such LCD panels is a problem, you can also buy compatible PCB adapters for such panels from eBay and other sites for as little as $3.99 (~ Rs.216) including shipping, which incorporate required support components, providing a standard 0.1" pin-out that can be used with your embedded development board / breadboard.

I have been using such touchscreen display modules on projects, and can report that they work well, and that the existing library support for most such modules, on the common microcontroller development platforms, saves a lot of time, effort and implementation risk, far outweighing any perceived value of jerry-rigging any display panel off an existing cellphone.


Q:

Result code 0 in POST in Swagger UI

When I use POST from the Swagger UI, the response code is 0. But when I run the generated CURL command in the command line, it works.
In my Swagger UI, GET method works. The problem happens only for POST.
@ApiParam(value = "test", required = true, allowMultiple = false) final myclass objectA)

A:

My question was as same as question. Need to add Access-Control-Allow-Headers


Q:

Looking for a coordinator for Book of the Month

I'd like to propose that we nominate someone to head up the book of the month club; we have several proposed books to look at already and probably about as much interest as we're going to get at this point.
Out of the suggestions, I'd like to recommend we start with Good Questions, Good Answers, even though it didn't get the most votes; it is freely available online, it is not directly related to any one Buddhist tradition, and because of the format, it fits well with the Q&A framework. Some of the other suggested books, while interesting, are either directed to a specific school of Buddhism or are not free online.
So, this question is two-fold; please comment on the suggestion to use Good Questions, Good Answers, and please post responses nominating yourself or others to take over the responsibility of coordinating the group.
Coordination probably doesn't involve much; just posting about the latest book on meta and working out a selection for the next month.

A:

I like this selection too. I'm a little shy about coming forward for coordinating, but if no one step up, I guess I could try...


Q:

In "R" iterate over specific columns

Update: Thanks jason and Buckminster - I used a variation of your suggestions
I used the below then adjusted for my function/data Again thanks
myFun<-function(x) {

        myDF$multiple[grep(" Mbps",myDF[,x])] <- 1000000
        myDF[,x] <- gsub(" Mbps","",myDF[,x])

        myDF$multiple[grep(" Kbps",myDF[,x])] <- 1000
        myDF[,x] <- gsub(" Kbps","",myDF[,x])

        myDF$multiple[grep(" bps",myDF[,x])] <- 1
        myDF[,x] <- gsub(" bps","",myDF[,x])

        myDF[,x] <- as.numeric(myDF[,x]) * myDF$multiple

}

cols<-c('MaximumIn','MaximumOut','AverageIn','AverageOut')
myDF[ ,2:5]<-lapply(cols,myFun)

UPDATED with dput(). I want to thank you for replying and realize that I could have made it easier to get help. I had to go back and sanitize and make the data small so that I could dput().

I'd like to create an optimized way to iterate over the 4 columns I care about, possibly using lappy.
Below are a few lines of my data with 6 columns, I only want to manipulate columns 2-5. This snippet has been processed with other code that i don't think is germane to my question.
Host      MaximumIn     MaximumOut  AverageIn   AverageOut  Site Name   Date
device1   30.63 Kbps    0 bps       24.60 Kbps  0 bps       SiteA       3/7/15
device12  1.13 Mbps     24.89 Kbps  21.76 Kbps  461 bps     SiteA       3/8/15
device1   698.44 Kbps   37.71 Kbps  17.49 Kbps  3.37 Kbps   SiteB       3/7/15

Here is a deput() of the dataframe see snippet above. I have a .csv file dput() but don't yet see how to upload that to this question.
structure(list(Host = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
7L, 8L, 9L, 10L), .Label = c("DeviceS1", "DeviceS2", "DeviceS3",
"DeviceS4", "DeviceS5", "deviceS2a", "deviceS2b", "devices5a",
"devices5b", "devices5c"), class = "factor"), MaximumIn = structure(c(5L,
2L, 3L, 1L, 4L, 6L, 7L, 8L, 11L, 10L, 9L), .Label = c("121.02 Kbps",
"27.11 Kbps", "39.08 Kbps", "62.22 Kbps", "698.44 Kbps", "1.21 Mbps",
"3.52 Mbps", "606.44 Kbps", "16.19 Mbps", "34.04 Mbps", "34.21 Mbps"
), class = "factor"), MaximumOut = structure(c(5L, 1L, 2L, 4L,
3L, 6L, 7L, 8L, 9L, 11L, 10L), .Label = c("0 bps", "10.58 Kbps",
"18.94 Kbps", "33.26 Kbps", "37.71 Kbps", "4.08 Mbps", "405.38 Kbps",
"930.44 Kbps", "15.35 Mbps", "192.88 Kbps", "2.98 Mbps"), class = "factor"),
    AverageIn = structure(c(4L, 2L, 1L, 5L, 3L, 8L, 7L, 6L, 10L,
    9L, 11L), .Label = c("10.83 Kbps", "24.57 Kbps", "3.87 Kbps",
    "30.36 Kbps", "9.76 Kbps", "170.21 Kbps", "210.04 Kbps",
    "312.39 Kbps", "20.08 Mbps", "21.60 Mbps", "5.95 Mbps"), class =     "factor"),
    AverageOut = structure(c(5L, 1L, 4L, 3L, 2L, 8L, 7L, 6L,
    11L, 10L, 9L), .Label = c("0 bps", "1.54 Kbps", "2.28 Kbps",
    "5.01 Kbps", "5.08 Kbps", "124.78 Kbps", "26.42 Kbps", "599.09 Kbps",
    "21.38 Kbps", "576.77 Kbps", "6.16 Mbps"), class = "factor"),
    `Site Name` = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
    3L, 3L, 3L), .Label = c("site1", "site2", "site5"), class = "factor"),
    Date = structure(c(16475, 16475, 16475, 16475, 16475, 16476,
    16476, 16476, 16476, 16476, 16476), class = "Date")), .Names = c("Host",
"MaximumIn", "MaximumOut", "AverageIn", "AverageOut", "Site Name",
"Date"), row.names = c(NA, 11L), class = "data.frame")

In the code below I manually edit then run for each column (MaximumIn, MaximumOut, AverageIn, AverageOut). What I do works but isn't up to the R (any language) standards for brevity. So the below is a candidate for  function based on columns?
myDF$multiple <- 1

myDF$multiple[grep(" Mbps",myDF$MaximumOut)] <- 1000000
myDF$MaximumOut <- gsub(" Mbps","",myDF$MaximumOut)

myDF$multiple[grep(" Kbps",myDF$MaximumOut)] <- 1000
myDF$MaximumOut <- gsub(" Kbps","",myDF$MaximumOut)

myDF$multiple[grep(" bps",myDF$MaximumOut)] <- 1
myDF$MaximumOut <- gsub(" bps","",myDF$MaximumOut)

myDF$MaximumOut <- as.numeric(myDF$MaximumOut) * myDF$multiple

A:

This seems simple enough. I didn't test as we weren't given data but you should get the gist.
myFun<-function(col) {

    myDF$multiple[grep(" Mbps",myDF[,col])] <- 1000000
    myDF[,col] <- gsub(" Mbps","",myDF[,col])

    myDF$multiple[grep(" Kbps",myDF[,col])] <- 1000
    myDF[,col] <- gsub(" Kbps","",myDF[,col])

    myDF$multiple[grep(" bps",myDF[,col])] <- 1
    myDF[,col] <- gsub(" bps","",myDF[,col])

    myDF[,col] <- as.numeric(myDF[,col]) * myDF$multiple

}

cols<-c('MaximumOut','AverageIn','AverageOut','MaximumIn')
lapply(cols,myFun)


Q:

How to schedule to run all unit tests?

I need to manage executing all unit tests on build server. Is there any idea about when is proper to run all of the unit tests on the build server.
There are too many of them, and it will take hours to run completely.
I have a few ideas about it, but I am not sure of them:

Nightly
When release for QA team
When release for Customer

A:

Unit tests which are run for hours are bad unit-tests. Since they have to test the pieces of code and mock all the real interfaces. So, basically they should be restricted only with your CPU, RAM capacity.
You probably mean that you use unit-test framework to run your integration tests or so.
If this is really the case I would recommend to break the whole set into the bunches aggregating the tests with the identical priority and run

the top priority on each build
others - overnight

Above options seem to be enough since your builds might be handed over to QA intraday so spending hours to test them with the whole set is not effective. Customer release is also not that unexpected thing so you can run your set several nights before the relase.


Q:

Jquery library symfony collection doesn't work with  element

When I add a element in my custom form theme, the incrementation of my collection doesn't works !
I use this library : https://github.com/ninsuo/symfony-collection
{% block PriceType_row %}
    {{ form_widget(form) }}
{% endblock %}

{% block PriceType_widget %}

            {{ form_widget(form.quantityFrom, {'attr': {'class': 'form-control'}}) }}

            {{ form_widget(form.quantityTo, {'attr': {'class': 'form-control'}}) }}

            {{ form_widget(form.bestUnitPrice, {'attr': {'class': 'form-control'}}) }}

        {{ form_widget(form.getPaid, {'attr': {'class': 'form-control'}}) }}

        {{ form_widget(form.vatRate, {'attr': {'class': 'form-control'}}) }}

{% endblock %}

{% block ProductType_widget %}
    {{ form_widget(form.prices) }}l
{% endblock %}

Thanks for your help ! :)

A:

[Auto response]
I musted add an elements_selector to my collection javascript
$('.collection-prices').collection({
   elements_selector: '> tr',
});


Q:

How can I install daemon on a CentOS box?

I'm basically looking for the equivalent of :

sudo apt-get install daemon

From Debian
I'm trying to configure a Solr daemon as outlined here https://stackoverflow.com/a/2150888/443779

A:

I don't believe you can get the Debian style daemon to work in CentOS, in CentOS it is more common to source /etc/init.d/functions in your init script.
This will make the daemon function available to you - with totally different options than the example you posted!
For a simple example check out the crond init script at /etc/init.d/crond.


Q:

Does $f(x) \in \mathbb{Z}[x]$ irreducible, imply $f(2x)$ also irreducible?

It is well known that $f(x+a) \in \mathbb{Z}[x]$ is irreducible when $f(x)$ is irreducible. I was wondering whether $f(2x)$ and in general whether $f(nx)$ is irreducible as well.
Though it is relatively easy to find counterexamples for $f(x^2)$ reducible with $f(x)$ irreducible (consider $f(x) = x^2+4$), I haven't been able to find counterexamples for $f(2x)$.
I tried to write $f(2x) = g(x)h(x)$ so that $f(x) = g(\frac{x}{2})h(\frac{x}{2})$ which are polynomials in $\mathbb{Q}[x]$. Then if $f(x) \in \mathbb{Z}[x]$ then maybe somehow $g(\frac{x}{2})$ and $h(\frac{x}{2})$ are both in $\mathbb{Z}[x]$ too?
Edit: by "irreducible" I meant that $f$ cannot be written as a product of two nonconstant polynomials.
Thanks in advance!

A:

It makes a difference if you are considering irreducibility in $\mathbb{Z}[x]$ or in $\mathbb{Q}[x]$.
A counterexample for the first case: $f(x) = x$ is irreducible in $\mathbb{Z}[x]$, but $f(2x) = 2\cdot x$ is not.
In the second case your statement is true for all $n\neq 0$, since then $n$ is a unit in $\mathbb{Q}[X]$, so $f(x)\mapsto f(nx)$ is an automorphism of $\mathbb{Q}[x]$.
UPDATE
After giving this answer,the following was added to the question

Edit: by "irreducible" I meant that f cannot be written as a product of two nonconstant polynomials.

First of all, this is a bit unfortunate, since it differs from the established definition of irreducibility in ring theory.
However by Gauss' Lemma, it turns out that your notion of "irreducibility" of a polynomial $f\in \mathbb Z[x]$ is exactly the same as the irreducibility of $f$ in $\mathbb Q[x]$, which is covered by the above discussion.


Q:

How to import constant from frontend side of Node app and use it at backend side, in POST route

Let's say I have some frontend code saved in "public/js/frontend.js":
// some jquery...
$(function() {
    // ...
});

//...

const names = ['abc123', 'qwe456', 'zxc789']
const rand = names[Math.floor(Math.random() * names.length)];
document.getElementById("captcha").src=`/img/captcha_${rand}.jpg`;

and I have some backend code saved here: "controllers/registration.js"
post: async (req, res, next) => {

    // ...

    if (valid.value.captcha_input !== 'rand') {

        // do something, i.e.
        req.flash('captcha_wrong', 'Please enter the characters you see to continue.');
        res.redirect('/registration');
        return;

    }
}

As you can see I need to export "rand" constant from "frondend.js" file and import it to "registration.js" file. The reason is I want to compare randomly picked value (from "names" array) with value entered by user, something like that:

The comparison will take place when user will click "submitt" button.
What I've tried so far:
1.
import { rand } from '../public/js/frontend';

in "registration.js", right after "npm start" command, gives me this in Terminal:
import { rand } from '../public/js/frontend';
^^^^^^

SyntaxError: Unexpected token import

2.
const { rand } = require('../public/js/frontend');

also in "registration.js", right after I click "submitt" button, gives me this in Browser:
ReferenceError: $ is not defined

3.
module.exports = rand;

in "frontend.js" gives me the same as 2.
4.
localStorage.setItem('rand', rand);

in "frontend.js" seems to work properly (with every reload of "http://localhost:5000/registration") Local Storage in Browser is updated), but
rand = localStorage.getItem('rand');

in "registration.js", right after I click "submitt" button, gives me this in Browser:
ReferenceError: localStorage is not defined

In summary, I do not know how to import "rand" constant from "frontend.js" without importing "$" - jQuery code I need for something else. And, I can not use Local Storage in backend side ("registration.js").
I will appreciate any useful hint. Thanks!

A:

In short, value from your variable is dynamically defined on the browser, server can't know its value without your browser sending it.
There are two ways to share value between browser and server.

Sharing file

In this case value must not be dynamically generated. You can create file inside your public folder that you import into your browser JS code using either <script> tag or using bundler solution such as Webpack. Then you will be also able to require that file inside Node.js server code as well by using global.require function. Note: This case works only if value is static. (predefined)

AJAX

This is the case which fits your needs. In this case you can generate value on the client and use it on the server. Basically generate value and send HTTP request to your server which should handle request and use/store value accordingly. This allows you to use dynamic values generated in  browser accessed by server.
As for your errors:
Your first error related to import keyword is because you do not use bundler (such as webpack) or type="module" property on your script tag (see here about that: https://jaketrent.com/post/import-js-module-without-dot-dot-slash/) but I would recommend using webpack due to browser compatibility.
Your browser probably knows $ is jQuery due to global import via script tag inside your html file. But on the server it doesn't exist or browser JS file that lives inside other html file where $ is not globally accessible throws this error.
global.localStorage is browser only object which doesn't exist inside Node.js, you can't use it on your server, use AJAX instead.
Basically these two JavaScript files you shared above live on different environments, one lives inside user's browser and other lives on your hosting server. To make them communicate use AJAX.


Q:

Showing 'old' value in table until actual commit

I have a table with an attribute that needs to be changed with a checkbox in a table (it's the  status of a row that gets upgraded). Apart from the column with the checkboxes, the attribute is also represented textually (readonly) in another column.
Ticking the checkbox and committing gives the proper behavior. However, if I sort the table at any column, after ticking the box but before committing, the textfield changes it's value accordingly, while it keeps showing the 'old' value if I choose not to sort the table. My client wants consistency by having the textual column to show the 'old' (uncommitted) data after sorting (while not loosing the ticks in the checkboxes), and only update this after the actual commit.
For now, I've tried to make a transient attribute which copies the value. I told this dummy attribute to never recalculate. However, sorting seems to do some kind of a requery, making this transient attribute to change along: ommitting my very purpose for it.
Any solution to keep showing the 'old' data until commit would be greatly appreciated!
I'm working on it with JDeveloper 11.1.1.4

A:

To make transient values not refresh on sorting table columns, create the transient attribute in EO first and then use it in VO.


Q:

Find and copy a row in Google Sheet

Sheet 1
There are items in columns A - F. How do I use VLOOKUP to find a row and copy it to Sheet 2 when it matches criteria in column F?
This is the formula in a cell on Sheet 2: =VLOOKUP(apple,Sheet1!A:F, 2, FALSE)

A:

When using VLOOKUP() the lookupvalue must be found in the first column of the lookuprange. If that is not the case, you can either use a combination of INDEX() and MATCH()
=INDEX(Sheet1!A:F, match("apple", Sheet1!F:F, 0))

or 'virtually' rearrange the layout of the table (on Sheet 1) so that the column where the match is to be expected (e.g. column F), is the first column.
=ArrayFormula(VLOOKUP("apple", {Sheet1!F:F, Sheet1!A:F}, {2,3,4,5,6,7}, 0))


Q:

Brownian Motion Conditional Expectation Question

I have a real number $x$, and $W$ is a standard Brownian motion. Let $0 < s < t$. How to find
$$
  \mathsf E[W_s | W_t = x]
$$
Please provide me with a step by step answer as I want to understand your steps and
the concept.
Many thanks in advance.

A:

Let $U_{s,t}=W_s-(s/t)W_t$ and $V_{s,t}=(s/t)W_t$. The process $W$ is centered gaussian, $\mathbb E(W_t^2)=t$ and $\mathbb E(W_sW_t)=s$, hence $U_{s,t}$ and $W_t$ are independent. Thus, $W_s=U_{s,t}+V_{s,t}$ where $U_{s,t}$ is centered and independent of $W_t$ and $V_{s,t}$ is measurable with respect to $W_t$.
Thus, $\mathbb E(W_s\mid W_t)=\mathbb E(U_{s,t}\mid W_t)+\mathbb E(V_{s,t}\mid W_t)=$ $____$ $+$ $____$ $=$ $____$.


Q:

Why would a salty damp road be slipperier than the same road just damp?

I came off this morning* on a road I ride every day, in all weather conditions.  Last night was frosty so the road was salted/gritted, but there was no visible frost nearby, it had warmed up from the overnight minimum, and the road is quite heavily used, both warming it and grinding the salt into the surface.  But the road was damp.
So why would a salty, damp road be worse than the same road just damp?
More info, just in case it's of interest:
I was only doing about 20km/h and I've taken that bend faster in the wet before, on the same tyres when running late for my train. I was following a racing line (outside-inside-outside) so although it's a fairly tight bend my line wasn't tight.
I don't believe I just hit an oily patch. It felt slippery underfoot (walkable SPDs) when I picked myself up having slid a little way.  Also I take pretty much the same line every day.
It was about 8.9 km into this ride.

* I'm OK, and so's the bike.

A:

It turns out there's actually some rather interesting science behind friction in the presence of water and salt.  Various model systems demonstrate that salt solutions really are better lubricants than plain (distilled) water between rubber and other materials, and by enough to matter.
Unfortunately little if any work has been done on the friction between real rubber and real wet roads in the presence of salt.  But there has been some work on more idealised systems.  One of the clearest results is from Experiments on the Lubrication of Raw Natural Rubber E.L. Ong and A.D. Roberts J. nat. Rubb. Res,, 1(1), 41-50 (1986).  Table 5 (below) is particularly interesting. Betwen raw natural rubber and Perspex the coefficient of friction reduced from 4.1 when dry, to 2.6 when wet and 1.5 when wet with salt solution.  A similar trend was observed for rubber-on-rubber friction. In other words in this system, in salt water there's about 60% of the grip compared to clean water. Fom the caption, "Stickslip motion tended to occur and maximum friction coefficients are quoted" (my emphasis). It's not clear whether this is true for all cases or just the salt solutions referred to in the preceeding sentence.

My journal access doesn't extend to reference 3 from this paper, Rubber friction in aqueous solutions containing ions, T.P.Mortimer & K.C.Ludema, Wear Volume 28, Issue 2, May 1974, Pages 197-206.  But the abstract of this latter paper states:

In the case of water lubrication of black rubber at slow speeds and
low pressures the lubricating ability of water is shown to be enhanced
by addition of electrolytes to the water. It is thought that negative
ions from the electrolytic solution collect on each sliding surface,
repel each other and prevent the close approach of two sliding
surfaces. Thus a thicker water film exists between the sliding
surfaces than if the ion layers did not exist. The thicker film
results in a reduced viscous drag force, lower than can be accounted
for by conventional hydrodynamics.

The ~40% reduction in friction from the table quoted above is enough to negate a reasonable safety margin when it comes to grip.  Applying this to my case I suspect an element of bad luck came into play too: That some tiny slip became unrecoverable because the overall friction was too lowThis would be especially the case as dynamic (sliding) friction is expected to be lower than rolling friction, thus extra grip is needed to recover a skid compared to avoiding it in the first place.
Further Reading:

Rubber Friction in Aqueous Solutions Containing Ions
Friction of rubber on ice in the presence of salt
DLVO and hydration forces between mica surfaces in Li+, Na+, K+, and Cs+ electrolyte solutions: A correlation of double-layer and hydration forces with surface cation exchange properties
Effect of aqueous cations on friction between rubber and glass


Q:

For $G$ a group, if $|G| = n$, $n$ composite, will $G$ have a proper subgroup?

I can see how it is indeed possible that $G$ has a proper subgroup i.e. possibly $n = km$ and there is an element of order $k$ that generates a cyclic proper subgroup, but I am trying to see why this must necessarily be the case. My argument goes as follows:
Let $G$ be a group of order $n$. Since $n$ is composite, we may write $n = km$ for $k,m \in\Bbb Z$.  If $G$ is cyclic, let the element that generates $G$ be $a$. Now consider $\langle a^k \rangle$ for $k$ the above divisor of $n$. This subgroup is nontrivial, and contains $m < n$ elements by Lagrange's Theorem, so we are done.
Else, if $G$ is not cyclic, then $n$ composite implies $n \ge 4$, thus there are at least $4$ elements in $G$, none of which has order $n$. Consider an element $b \in G$, $b \ne e$. Let the order of $b$ be $\ell < n$. Then $b$ generates a cyclic subgroup of order $\ell$ which must divide $n$, and since $\ell < n$, we know that $\langle b \rangle \subsetneq G$. Thus $G$ has a proper subgroup. $\Box$

Any feedback about the above proof is appreciated!

A:

If $G$ has order $n$ which is composite, then $n$ is divisible by some prime $p < n$. By Cauchy's theorem, $G$ has an element of order $p$. This element generates a proper subgroup of order $p$.

A:

Yes This is because user26857's comment deserves to be an answer -- it doesn't even use Cauchy:
Let $G$ be a finte group of order $n$ and assume that $n$ is composite, say $n=ab$ with integers $a,b>1$. In particular $n>1$ and so we can pick an element $x\in G$ with $x\ne 1$. Then $\langle x\rangle$ is a subgroup of some order $m$. As it contains $x$ and $1$, clearly $m\ge 2$. As it is in $G$, clearly $m\le n$. If $m<n$, it is a non-trivial proper subgroup, as desired. Remains the case that $m=n$. From what we know about cyclic groups, $\langle x^a\rangle$ is of order $b$, and $1<b<n$.