text:
Q: When should I create factory or VM in angular This is how my angular app looks like.
(function () {
"use strict";

angular
    .module("app")
    .controller("custCtrl", custCtrl);

custCtrl.$inject = ['dataService','custFactory'];

/* @ngInject */
function custCtrl(dataService, custFactory) {
    var vm = this;
    //line##
    vm.customer= custFactory.Create('customer');

    GetCustomers();
    function GetCustomers() {

        dataService.read().then(function (data) {
                vm.customer = data.fields;
            }
        });

    }

    return vm;
}
})();

Factory Method
(function () {
'use strict';

angular
    .module('app.factory')
    .factory('custFactory', custFactory);

custFactory.$inject = ['$q'];

/* @ngInject */
function custFactory($q) {
    var _create = function (type) {

        var obj = {};

        switch (type.toString().toLowerCase()) {
            case "customer":
                obj = new Customer();
                break;
            default:
                obj = null;
        }

        return obj;
    }

    return {
        Create: _create
    };
}
})();

View Model
 function Customer()
 {

var dto = this;

dto.Customer = {
  "Name" : "",
  "Gender" : "", // & so on
}

 return dto;
}

If you check my above custCtrl on //line##, I am calling factory method to instantiate customer object as below.
vm.customer= custFactory.Create('customer');

But if I don't create a customer VM & factory and simple assign an empty string as below.
        vm.customer= {};

Still its working with no issue.

So my question why should I create a VM & factory?? What is its
  benefit??

A: the controller alias is suitable when you have nested controllers,
while the factory or services are suitable to share data between different controllers.
For example it's useful to have your mehtod CreateCustomer if you use it from different controllers. Since you don't store data in it, it would be better to use a service instead. Anyway it allows you to save code.
EXAMPLE
var app = angular.module("myApp", []);

app.factory("myFactory", function(){
    var private = {
        users: {}
    };
    var data = {
        getUser: function(id){
             return private.users[id];
        },
        createUser: function(id){
            private.users[id] = someData;
            return private.currentUser;
        }
    };

    return data;
});

app.controller("myC1", ["myFactory", function(myFactory){

     $scope.user = myFactory.createUser(1);

}]);

app.controller("myC2", ["myFactory", function(myFactory){

     $scope.user = myFactory.getUser(1);

}]);

As you see the two controllers can access the same data

A: AngularJS patterns and best practices involve following the MV(whatever) pattern and designing/implementing modular components with high cohesion and low coupling. That way you can easily modify one piece of code without having to make changes in another piece of code.
Typically a factory or service is used as the layer of client-side code that interacts with a RESTful API or some sort of server-side code. Typically that is the only function of the factory. That way you can inject the factory into any controller that needs to use the factory's functions. When you need to modify how you call your API, you only need to make a change in the factory instead of every single controller that would use that function.
Similarly with the view model object you have created, you only need to make changes in one place. Imagine having five different controllers that all need to use a Customer object. Now you decide you want to remove the Name field and replace it with FirstName and LastName. Would you want to go through all your controllers and make that change, or would you want to just change the view model?
To give you the short answer. There's nothing functionally wrong with not creating a view model or a factory/service. From an architectural or design perspective, it makes tons of sense to have a strong separation of concerns in your application. Therefore, it makes sense to use a factory for data access and a view model for your data objects.
Try imagining your application growing to have hundreds of controllers/views and dozens of factories or services. It would be a huge pain to maintain that application if you didn't have these patterns and best practices implemented from the beginning of development.


text:
Q: Наследование дескрипторов в Windows Нужно передать готовое соединение другом процессу. Прочитал про наследование дескрипторов на msdn, но примеров не нашел. Как именно мне получит доступ к наследуемуму дескриптору сокета? Где он лежит?

A: Для дублирования дескрипторов сокетов следует использовать специальную функцию WSADuplicateSocket. Ее работа отличается от обычной DuplicateHandle, вместо нового дескриптора она заполняет структуру WSAPROTOCOL_INFO, которую необходимо самостоятельно передать в другой процесс и использовать для вызова WSASocket в нем.

A: Чтобы «другой» (дочерний) процесс мог получить доступ к дескриптору, открытому в вашем процессе, необходимо выполнить две вещи:

*

*Сделать дескриптор наследуемым (изначально создав его таким, либо склонировав через DuplicateHandle() с параметром bInheritHandle == true). Это сделает дескриптор видимым из дочернего процесса.

*Передать собственно дескриптор (четырёхбайтное целое число). Как это сделать — решайте сами. Можете воспользоваться стандартным потоком ввода/вывода, или открыть именованный канал, или послать оконное сообщение главному окну дочерней программы, или даже указать его в качестве параметра командной строки дочернего процесса, если дескриптор был открыт до вызова CreateProcess().
Если же вы попытаетесь передать дескриптор, для которого наследование разрешено не было, дочерний процесс не сможет получить к нему доступ, будто его не существует.

Где он лежит?

В ядре операционной системы, как обычно. Изменяется лишь проверка прав доступа при обращении к объекту за дескриптором. По умолчанию требуется точное соответствие обращающегося процесса и процесса-создателя. При включении же наследования критерий соответствия превращается из «только создатель» в «создатель и его потомки».
К слову, с помощью такой штуки, как DACL (передаваемой через параметры типа LPSECURITY_ATTRIBUTES) можно задавать ещё более гибкие разрешения.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel VBA how to copy cell content from one book to another I'm trying to create a macro which will copy a cell content from one workbook to another.
The problem is that in the original workbook there are links to another worksheet inside this workbook and after my macro does the job, the links are referring to the sheet of the source file.
For example in the source file I have =CONCATENATE(A1,Sheet2!A1) and after copying the cell content becomes =CONCATENATE(A1,[Source.xlsm]Sheet2!A1)
Ho to avoid appearing this [Source.xlsm] ?
Sub Copy()

    Dim wbk As Workbook

    Range("A1:B1").Copy

    Set wbk = Application.Workbooks.Open(ThisWorkbook.Path & "/subdir/destination.xlsx")
    With wbk.Sheets("Sheet1")
    Range("A1").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    End With
End Sub

Thanks in advance

A: Use the Range.Replace method to strip [Source.xlsm] from the formulas.
With wbk.Sheets("Sheet1")
    .Range("A1").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    .Cells.Replace What:="[Source.xlsm]", Replacement:="", LookAt:=xlPart, _
                   MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End With

btw, You were missing the . in .Range("A1").PasteSpecial...


text:
Q: Compile gpio-mockup in 5.4 I've checked out kernel 5.4 source and tried to compile gpio-mockup.c by running make -C /lib/modules/$(uname -r)/build M=$(pwd) modules the build succeeds but there is no gpio-mockup.ko. I think this means that I need to provide some configuration value but I don't know how and I don't know where. Regardless, can anyone help me to build the gpio-mockup kernel module?

A: Because the gpio-mockup module depends on some GPL symbols in the kernel it needs to be built with the kernel. This means you must build a whole new kernel.
git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git linux
cd linux
git checkout v5.4
cp /usr/lib/modules/$(uname -r)/build/.config ./
yes '' | make oldconfig
echo "CONFIG_GPIO_MOCKUP=m" >> .config
make -j $(nproc) deb-pkg LOCALVERSION=-gpio-mockup

This will produce Debian packages that can then be used to install a new kernel that will include the gpio-mockup kernel module.
NOTE: This is a vanilla kernel which may or may not have kernel modules your distribution usually provides (like ZFS on Ubuntu). Other steps may be necessary to get a custom kernel like your distribution provides.

A: You should enable CONFIG_IRQ_SIM=y, since gpio-mockup.ko is depended irq_sim.
please look at this picture


text:
Q: Modification to the 'excessive self-promotion' moderator private message The boilerplate text for the 'excessive self-promotion' moderator contact form includes a direct quote from the help center:

Be careful, because the community frowns on overt self-promotion and
  tends to vote it down and flag it as spam. Post good, relevant
  answers, and if some (but not all) happen to be about your product or
  website, so be it. However, you must disclose your affiliation in your
  answers. Also, if a huge percentage of your posts include a mention of
  your product or website, you're probably here for the wrong reasons.
  Our advertising rates are quite reasonable; contact our ad sales team
  for details. We also offer free community promotion ads for open source projects and non-profit organizations.

The sentence written in bold is not included in the actual message sent to users but is written in the help center.
I think this sentence should be included, it is important because the majority of SE sites do not have advertising and many have free community ads.
The following has no relevance to the majority of sites and should be reworded or removed on sites where it has no relevance.

Our advertising rates are quite reasonable; contact our ad sales team

A: It looks like the "excessive self-promotion" mod message template was changed at some point. It now points to the /help/promotion page, and the quoted text in the template only includes this portion:

The community here tends to vote down overt self-promotion and flag it as spam. Post good, relevant answers, and if some (but not all) happen to be about your product or website, that's okay. However, you must disclose your affiliation in your answers.

As such, I'm marking this as status-completed.


text:
Q: How to Get html table td value while clicking the Linkbutton and get the value in cs code through the button click Please Click Here for Code sample

A: Can you post your .cs code? (Just to get idea how you are handling the click event.)
From the code what I can think of the possible solution is (in code behind file):
    void lnkBtn_Command(Object sender, CommandEventArgs e) {
             string s = "You clicked: " + e.CommandArgument;
    }


text:
Q: EF6 - selection does not match with child table data Here is my classes:
1
public partial class SmsScheduleType
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

2
public partial class SmsSchedule
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    [ForeignKey("SiteId")]
    public virtual Site Site { get; set; }

    public int ScheduleTypeId { get; set; }
    [ForeignKey("Id")]
    public virtual SmsScheduleType SmsScheduleType { get; set; }

    public int DateToSend { get; set; }
    public int DayOfWeekToSend { get; set; }
    public string TimeToSend { get; set; }
    public string TextToSend { get; set; }
    public int Interval { get; set; }
}

Here is a SmsScheduleType data

**Id  Name**
1; "Running"
3; "Weekly"
4; "Monthly"
5; "Daily"
2; "Idle"

And this is

**Id SiteId DayOfWeekToSend TextToSend ScheduleTypeId DateToSend TimeToSend Interval Active**
2;     1;              0;  "Daily test";         5;          0;    "1500";    0;     t
4;     3;              0;  "Daily test";         1;          0;        "";   60;     f
5;     4;              0;     "Monthly";         4;          8;   "11:00";    0;     t

Query
var ready2send = context.SmsSchedules.ToList();
    foreach (var sch in ready2send)
    {
        Console.WriteLine("{0} is scheduled as {1}-{2}, {3}.", sch.Site.SiteID, sch.ScheduleTypeId ,sch.SmsScheduleType.Name, sch.SmsScheduleType.Id);
    }

Query result
BHE152 is scheduled as 5-Idle, 2.
BHE155 is scheduled as 1-Monthly, 4.
BHE156 is scheduled as 4-Daily, 5.

I cannot understand what is wrong. Why Ids are not matching?
please help
DB is postgres if it makes sense.

A: It should be:
public partial class SmsSchedule
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    [ForeignKey("SiteId")]
    public virtual Site Site { get; set; }

    public int ScheduleTypeId { get; set; }
    [ForeignKey("ScheduleTypeId ")]
    public virtual SmsScheduleType SmsScheduleType { get; set; }

    public int DateToSend { get; set; }
    public int DayOfWeekToSend { get; set; }
    public string TimeToSend { get; set; }
    public string TextToSend { get; set; }
    public int Interval { get; set; }
}

Note that I changed
[ForeignKey("Id")]

to
[ForeignKey("ScheduleTypeId ")]

When you use [ForeignKey("Id")] you tell EF that you store foreign key of SmsScheduleType table in Id filed of SmsSchedule table


text:
Q: Get value in function odoo I need get value from current form field:
Ex:
time = fields.Many2one('time.project', domain=lambda self: self._get_time())
vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True)
def _get_time(self):
   vehicle_val = Get selected vehicle id from field vehicle_id on current form.

   times = self.env['project.vehicle'].search([('vehicle_id', '=', vehicle_val)

A: In this case you should use onchange to change the domain every
time the value of the vehicle is changed.
@api.onchange('vehicle_id')
def dynamic_domain(self):
    vehicle_val =??
    times = self.env['project.vehicle'].search([('vehicle_id', '=', vehicle_val)])
    return {'domain': {'times': [('id', 'in', times.ids)]}}

Hope this helps you.


text:
Q: returning varchar(MAX) from a function returns truncated string I am having a strange problem. I have a function which returns a large string by concatenating several other strings.
In some cases the string is too long and is getting truncated.
For example, there is an instance when a string of length 379999 is supposed to be returned, but what I see is that the string is truncated and the length is only 65536.
I am sure that varchar(MAX) can hold a string greater that 65536, but where am I going wrong here? The function has been shown below.
[UPDATE]
this function is being used in several stored procedures, and the stored procedures are used by the crystal reports to display data.
[UPDATE END]
ALTER FUNCTION [dbo].[GetShipContSernText](
@shipContNum numeric(9)) returns Varchar(MAX) begin

declare serns cursor for

select
    serial_number
from
    serial_number_view
where
    ship_cont_num = @shipContNum
    and
    template_id is null

open serns;

declare @text varchar(MAX);
declare @serialNumber nvarchar(50);

fetch next from serns into @serialNumber;

while (@@FETCH_STATUS = 0)
begin
    -- cannot concat a null string.

    if (@text is null)
             set @text = @serialNumber;
    else
          set @text = @text + N', ' + @serialNumber;
    end
    fetch next from serns into @serialNumber;
end;

close serns;
deallocate serns;

return @text;
end

A: Is there a reason you can't return the rows and concatenate in the code?
You are mixing varchar and nvarchar.
Also you need to use SQL Native Client to be able to use varchar(max) as a return value.

A: the function is indeed returning a sting more than 65536 characters, i used the LEN function and found the length to be much greater. It was the grid which was restricting the length. Now i need to find why is the crystal report truncating the string.
Bunch of thanks to Jonas :)

A: There is a bug in Crystal Reports which makes it interpret varchar(max) fields as varchar(255)
see here: http://www.crystalreportsbook.com/Forum/forum_posts.asp?TID=5843&PID=17503


text:
Q: HTML Data Scraping (I think) I am currently doing some work for a client which happens to be a video game group for the game World of Warcraft.
They want to show their current rating on their website.
The ratings are shown here.
They would like to have the number for 'Oceanic', and the number for 'US' displayed on their website.
Is anyone able to show me a way that I can have those numbers automatically update on the website should they change?
Thanks!

A: You can use this snippet to scrap the data - assuming PHP is okay since you're running wordpress. I'd save these values in a database/flatline/cache.
<?php

$data = file_get_contents('http://www.wowprogress.com/guild/us/caelestrasz/Crimson/rating.tier13_25');

$oceanic = explode('
Oceanic:
', $data);
$oceanic = substr($oceanic[1], 4, strpos($oceanic[1], '
') - 4);

$us = explode('
US:
', $data);
$us = substr($us[1], 4, strpos($us[1], '
') - 4);

echo 'Oceanic: ' . $oceanic . "
\n";
echo 'US: ' . $us . "
\n";

A: It's quite easy. I prefer using simplehtmldom, but you can also use the builtin php dom parsing methods.
require 'simple_html_dom.php';
$html = file_get_html('http://www.wowprogress.com/guild/us/caelestrasz/Crimson/rating.tier13_25');
$xxx = $html->find('div.guildStats dl dd');

foreach($xxx as $k)
echo $k->plaintext."\n";

A: Due to cross domain security you cannot do this with javascript, you will have to get your information server side if you have access to it.

A: Here's a solution with RegEx.
<?php

$data = implode('', file('http://www.wowprogress.com/guild/us/caelestrasz/Crimson/rating.tier13_25'));
$pat_world = '/(\d+)<\/span>/';
$pat_us = '/
US:\D+(\d+)/';

preg_match($pat_world, $data, $world);
preg_match($pat_us, $data, $us);

echo $world[1];
echo "\n\n";
echo $us[1];

I know everyone is anti-regex for web scraping, but I think it works just great in simple situations like this.


text:
Q: c# how to create a typed dataset from a dataset or a XML file? I have XML file that I can easily load into a dataset.
    DataSet ds = new DataSet();
    ds.ReadXml(e.FullPath);

However, I did like to have a typed dataset instead.
Is there a way to build the typed dataset from the XML or the untyped dataset?
The goal here is to avoid design it because there is a lot of column and it remove the change of making mistake while typing.

A: It is really easy to do. Here is a step by step guide.
(You must have visual studio installed of course)
1. From the XML File, create a XSD File.
This can be acheived by loading the XML file into a dataset and then writing the schema. The following code take care of this step.
        DataSet ds = new DataSet();
        ds.ReadXml(e.FullPath);
        ds.WriteXml(@"C:\test.xsd", XmlWriteMode.WriteSchema);

Verify the XSD file is good and doesn't contains junk.
2. Locate where "xsd.exe" is on your computer.
In my case, it was here :
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools
3. Copy/paste the xsd file into the folder found at step2.
4. Run command prompt and change directory to folder found at step2.
Open a command prompt (Windows+R, type "cmd" and hit enter). Then navigate to the folder found at step2. ("cd enter-your-directory-here")
    cd C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

Quick tips, you can copy/paste the directory into the prompt using the mouse's right click.
5. From the command prompt, launch xsd.exe with desired argument.
Type or paste the following command in the command prompt and press enter.
    xsd.exe /d /l:cs test.xsd /eld /n:MyDesiredNameSpace

If needed, you can find details about arguments in msdn documentation.
Given your xsd file was valid, it will output a cs file into the folder. Here is what console output.

6. Include the generated file into your project.
Copy and paste the generated .cs file into your solution folder and include it to your project.
Using (right-click include existing item)

7. Rename the typed dataset with an appropriate name.
The generated typed dataset is "NewDataset".
Rename it for a more decent name. (use refactor feature)


text:
Q: div float right does not work in IE I have to place two divs in a single line , one div to the left and other to the right.
Below is the code i used.
var sendDate = document.createElement('div');
sendDate.style.width = "40%";
sendDate.style.cssFloat = "left";

var dueDate = document.createElement('div');
dueDate.style.width = "40%";
dueDate.style.cssFloat = "right";

But this works fine in FF and Chrome , but not in IE.
In IE , the duedate comes below the senddate instead of aligning to the right of senddate.
I have spent enough time trying to find a solution but no luck. I tried to clear the float of senddate as well but it dint work.
Please let me know how to achieve this in IE.
TIA...

A: try something like this
CSS
.left { float:left; }
.right { float:right; }

JAVASCRIPT CODE
var sendDate = document.createElement('div');
sendDate.style.width = "40%";
sendDate.className = "left";

Or use jquery which will manage your browser compatibility


text:
Q: Given $f:\left(x,y\right) \mapsto \left(u,v\right)$, to find regions in $xy$-plane that map onto a given region in $uv$-plane Let $f:\mathbb{R}^2 \to \mathbb{R}^2$ be given by
$$\left(u,v\right)=f\left(x,y\right)=\left(x-y,xy\right)$$
Problem : Which regions in $xy$-plane map onto the rectangle $\left[0,1\right] \times \left[1,4\right]$ in the $uv$-plane.
My progress : $u=x-y,\,v=xy \Rightarrow y=\frac{-u\pm\sqrt{u^2+4v}}{2},\,x=\frac{2v}{-u\pm\sqrt{u^2+4v}}$. Thus, it is clear that there will be two regions in the $xy$-plane (one corresponding to $+\sqrt{u^2+4v}$ and the other corresponding to $-\sqrt{u^2+4v}$) that map to $\left[0,1\right] \times \left[1,4\right]$ in the $uv$-plane. The regions will be given by
\begin{align*}
&R_1=\left\{\left(\frac{2v}{-u+\sqrt{u^2+4v}},\frac{-u+\sqrt{u^2+4v}}{2}\right):\left(u,v\right) \in \left[0,1\right] \times \left[1,4\right]\right\}\\
&R_2=\left\{\left(\frac{2v}{-u-\sqrt{u^2+4v}},\frac{-u-\sqrt{u^2+4v}}{2}\right):\left(u,v\right) \in \left[0,1\right] \times \left[1,4\right]\right\}
\end{align*}
Where I am stuck : I cannot find $R_1$ and $R_2$ explicitly. Any help regarding this would be much appreciated.

A: Hint: Here is a plot:
\begin{align}\color{blue}{0\leq x-y\leq1}\\
\color{green}{1\leq xy\leq4}\\
\end{align}

A solution could thus be: $$(x,y)\in[1,2]\times \{1\}\cup\{2\}\times [1,2]$$
In general, any region that contains a curve which goes from one boundary of the blue region to the other, and the same for the green curve will do.

A: HINT
The segment from $(0,1)$ to $(1,1)$ that is $(x,y)=(t,1)$ with $t\in[0,1]$ is mapped to
$$(u,v)=(x-y,xy)=(t-1,t) \quad v=u+1$$
from $(-1,0)$ to $(0,1)$  and so on.


text:
Q: Select multiple min values from subset of values I am creating an access system. The access system is based on that a user can be a member of more than one group, the domain is where the user ask for access. For example an user can be a member of two groups, both these groups can have access to the domain and the user can be a member of the domain. I want the lowest access right to be the valid one, say you get added to a group that have lower right in that domain that right should precede the other right.
The problem is that i want to select each domain and get all the access rights for each domain.
So the problem is to select a min value from multiple subset. Got an idea to how to do this ?
So i have tried :
SELECT r.* FROM `domain` as d
INNER JOIN (
    SELECT domain, min(`update`) FROM `right`
    ) r ON d.name = r.domain;

This gives me the result :
domain          min(update)
Another test    true
What i want is :
domain          min(update)
Another test    true
Some Name       true
Sql fiddle link : http://sqlfiddle.com/#!9/841183
Export of the sql table with test values:
CREATE TABLE `domain` (
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `displayName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `domain`
  ADD PRIMARY KEY (`name`);

CREATE TABLE `groups` (
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created_by` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `groups`
  ADD PRIMARY KEY (`name`),
  ADD KEY `groups_created_by_foreign` (`created_by`);

CREATE TABLE `right` (
  `domain` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `group` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `read` tinyint(1) NOT NULL,
  `update` tinyint(1) NOT NULL,
  `create` tinyint(1) NOT NULL,
  `delete` tinyint(1) NOT NULL,
  `modify` tinyint(1) NOT NULL,
  `execute` tinyint(1) NOT NULL,
  `created_by` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `right`
  ADD PRIMARY KEY (`domain`,`group`),
  ADD KEY `right_group_foreign` (`group`),
  ADD KEY `right_created_by_foreign` (`created_by`);

INSERT INTO `domain` (`name`, `displayName`, `description`, `created_at`, `updated_at`) VALUES
('Another test', 'Another test', NULL, '2016-08-22 12:05:06', '2016-08-22 12:05:06'),
('Some Name', 'Some Name', NULL, '2016-08-19 03:57:00', '2016-08-19 03:57:00');

INSERT INTO `groups` (`name`, `created_by`, `created_at`, `updated_at`) VALUES
('groupTest', NULL, '2016-08-22 12:06:48', '2016-08-22 12:06:48'),
('testGroup', NULL, '2016-08-19 03:56:35', '2016-08-19 03:56:35');

INSERT INTO `right` (`domain`, `group`, `read`, `update`, `create`, `delete`, `modify`, `execute`, `created_by`, `created_at`, `updated_at`) VALUES
('Another test', 'groupTest', 0, 1, 0, 0, 0, 0, NULL, '2016-08-22 12:07:02', '2016-08-22 12:07:02'),
('Another test', 'TestGroup', 1, 1, 0, 0, 0, 0, NULL, '2016-08-22 12:06:04', '2016-08-22 12:06:04'),
('Some Name', 'TestGroup', 0, 1, 0, 0, 0, 0, NULL, '2016-08-19 03:57:05', '2016-08-19 03:57:05');

A: You need to use the group by clause to get the minimum values by groups. By groups here I mean the domains:
select d.name, min(`update`) as min_update_right
from domain d
inner join `right` r on d.name = r.domain
group by d.name

If you want additional fields from the domain table to be present in the select list, then you need to add those fields to the group by list as well.
However, I would consider using a bitmap (or in MySQL the set data type) instead of multiple fields to store access rights. Simple bitwise operations could give you the overall access right to a domain.


text:
Q: Unable to run react server and node backend at the same time using concurrently This is my node backend package json file
"scripts": {
"start": "node server",
"server":"nodemon server",
"client":"npm start --perfix client",
"dev":"concurrently "npm run server" "npm run client""
},
This is my react package.json file
  },
  "proxy": "http://localhost:8080/"
}

I have set my PORT variable to 8080 . And when i run npm run dev, i get this error in terminal
[1] node:events:504
[1]       throw er; // Unhandled 'error' event
[1]       ^
[1]
[1] Error: listen EADDRINUSE: address already in use :::8080
[1]     at Server.setupListenHandle [as _listen2] (node:net:1330:16)
[1]     at listenInCluster (node:net:1378:12)
[1]     at Server.listen (node:net:1465:7)
[1]     at Function.listen (C:\xampp\htdocs\node\own\expense\node_modules\express\lib\application.js:635:24)
[1]     at Object.<anonymous> (C:\xampp\htdocs\node\own\expense\server.js:18:5)
[1]     at Module._compile (node:internal/modules/cjs/loader:1103:14)
[1]     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
[1]     at Module.load (node:internal/modules/cjs/loader:981:32)
[1]     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
[1]     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
[1] Emitted 'error' event on Server instance at:
[1]     at emitErrorNT (node:net:1357:8)
[1]     at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[1]   code: 'EADDRINUSE',
[1]   errno: -4091,
[1]   syscall: 'listen',
[1]   address: '::',
[1]   port: 8080
[1] }
[1] npm run client exited with code 1

I am trying to run react server and node server at the same time using concurrently. But I am getting the same error even though I tried changing ports many and times and also killed all the processes running on that port.
Am i doing anything wrong ?
I have removed all the other code form package.json file from both client and server and only kept related code.
Please let me any way from which i can run both react and node servers from npm run dev command ?


text:
Q: Tensorflow cost not updating I am working through Andrew Ng's ML course on Coursera, and have recently had the opportunity to apply tensorflow to a real world environment, at which point things promptly fell over :D.
My code below works insofar as it doesn't produce any bugs... but neither does the cost change. From what I have read, and from what I understand, this is because the gradients are all zero. The thing is, I don't understand why this is and how to fix it...
The problem I am working on is a regression model implemented as a shallow neural net with 1 hidden layer of 10 units, to estimate daily sales across a large portfolio of properties.
So, code:
def create_placeholders():

X = tf.placeholder(tf.float32, [13, None], name="X")
Y = tf.placeholder(tf.float32, [1, None], name="Y")

return X, Y

# Initialise weights and biases. Hidden layer of 10, output layer of 1
def initialise_parameters():
    W1 = tf.get_variable("W1", [10, 13], initializer=tf.contrib.layers.xavier_initializer(seed=1))
    b1 = tf.get_variable("b1", [10, 1], initializer=tf.zeros_initializer())
    W2 = tf.get_variable("W2", [1, 10], initializer=tf.contrib.layers.xavier_initializer(seed=1))
    b2 = tf.get_variable("b2", [1, 1], initializer=tf.zeros_initializer())

    parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2}

    return parameters

def forward_propagation(X, parameters):

    # Retrieve the parameters from the dictionary "parameters"
    W1 = parameters['W1']
    b1 = parameters['b1']
    W2 = parameters['W2']
    b2 = parameters['b2']

    Z1 = tf.add(tf.matmul(W1, X), b1)
    A1 = tf.nn.relu(Z1)
    Z2 = tf.add(tf.matmul(W2, A1), b2)
    A2 = tf.nn.relu(Z2)
    # Have a relu output because a) why not, and b) its sales data so negatives are nonsense.
    return A2

# COST FUNCTION
def compute_cost(y_hat, y):
    # Originally tried reduce_mean but gave same outcome of constant cost
    cost = tf.reduce_sum(tf.square(y_hat - y))

    return cost

# CHECK DIMENSIONS ARE ALL GOOD
[x.shape for x in [X_train, Y_train, X_test, Y_test]]
Out[48]: [(13, 331768), (1, 331768), (13, 41471), (1, 41471)]

# W1 shape = (10, 13), W1*X = (10,13) * (13, m) = (10, m)
# W2 shape = (1, 10),  W2 * (W1*X) = (1,10) * (10, m) = (1,m)
# good

# X's have all been normalised using sklean.preprocessing.StandardScaler()

learning_rate = 0.0001
tf.reset_default_graph()

costs = []  # To keep track of the cost
X, Y = create_placeholders()

# Initialize parameters
parameters = initialise_parameters()

y_hat = forward_propagation(X, parameters)

cost = compute_cost(y_hat, Y)

optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)
# Alternative
# optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    # Run the initialization
    sess.run(init)

    # Do the training loop
    # Range is small here but have done up to 2000 and get same result.
    for epoch in range(10):
        _, epoch_cost = sess.run([optimizer, cost], feed_dict={X: X_train, Y: Y_train})
        print(epoch_cost)

Output:
8.932417e+17
9.986363e+32
8.9324173e+17
8.9324173e+17
8.9324173e+17
8.9324173e+17
8.9324173e+17
8.9324173e+17
8.9324173e+17
8.9324173e+17

Where am I going wrong with this? What is causing the gradient to be zero?
Thanks
Sample data:
pd.DataFrame(X_train).iloc[:, :3]
Out[38]:
           0         1         2
0  -2.639472  1.567537  0.000027
1   0.611774  0.377617 -0.317175
2   0.228070  0.095461  0.129151
3   0.098627  0.924450 -1.553019
4   0.428524  1.053880 -0.661481
5  -0.068319  1.084136  2.015653
6   0.788444  0.882707 -0.555907
7   0.450732  1.168514 -0.576461
8   0.438508 -0.281488 -0.338060
9   0.241477 -0.014153 -0.582811
10  0.248324  0.020088 -0.174162
11  0.007352 -1.261135  1.666470
12  0.134369  0.191141  0.235396

pd.DataFrame(y_train).iloc[:, :3]
Out[43]:
               0             1             2
0  279637.377287  2.796952e+06  57194.231303

Row means (rows = features, columns = observations) are zero
pd.DataFrame(X_train).mean(axis=1)
Out[41]:
0     5.572480e-12
1     2.818636e-14
2    -3.316111e-17
3    -2.587781e-12
4     3.080923e-13
5     1.078905e-13
6    -4.661424e-15
7     1.534782e-13
8    -9.438911e-13
9     2.328588e-14
10   -2.219427e-14
11   -9.047083e-15


text:
Q: Hadoop view created with CTE misbehaves Here is the view definition(Runs fine. View gets created)
CREATE OR REPLACE VIEW my_view
AS WITH Q1
AS (SELECT MAX(LOAD_DT) AS LOAD_DT FROM load_table WHERE UCASE(TBL_NM) = 'FACT_TABLE')
SELECT F.COLUMN1
, F.COLUMN2
FROM   Q1, FACT_TABLE F
WHERE  Q1.LOAD_DT = F.TRAN_DT
;

However, when run
SELECT * from my_view;

getting following error message:
FAILED: SemanticException Line N:M Table not found 'Q1' in definition of view my_view....etc..
Looks like hive is trying to treat the Q1 (wich is CTE) as a physical table. Any ideas how to work around this?
Thank You,
Natalia

A: We have faced the similar issue in our environment. To answer your question, it's a bug in Hive. Fortunately, we have a workaround to make it work. If you were using impala and hive and both are using same metastore. Create the view in Impala and it will work on both hive and impala.
Reason:
Hive is appending your database name to the CTE reference created which is causing the issue.
Thanks,
Neo


text:
Q: Extract coordinates from a polygon I need to extract the coordinates from a 2D polygon then calculate the maximum and minimum of the x and y coordinates. I know it sounds simple, but I've found it impossible to do so far. Below is my code:
a = Cases[poly, {_ , _}, Infinity];

coord = Table[{a[[x,1]]*1, a[[x,2]]*1}, {x, 1, Length[a], 1}];

Min[coord]

Where poly is a predefined polygon. The outcome of the Min function is this:

A very large output was generated. Here is a sample of it.
Min[ -43.7405, <<143>>,
     Polygon[{{151.137, -34.062}, {151.137, -34.062}, {151.137, -34.0619}, <<14319>>,
              {151.137, -34.0622}, {151.137, -34.0621}, {151.137, -34.062}}]]

The same thing happens if I leave out the line of code that uses Table to create coord, and instead just try to calculate the minimum of  a. This one has got me completely stumped. Any help would be greatly appreciated.
Edit
Ok here's the output of FullForm[poly]

A very large output was generates. Here is a sample of it:

List[ List[Polygon[  List[List[151.228, -33.956], List[151.228, -33.9561],
      List[151.226, -33.9563], <<976>>, List[151.229, -33.9559],
      List[151.228, -33.956], List[151.228, -33.956]]], <<1388>>, List[<<1>>]]

A: It appears your data poly is not in the form you think it is.  So without a specific example at hand, I will give a fairly general solution, which is not hard to do.

*

*First extract each Polygon directive from the graphics data.

*Each Polygon may contain more than one polygon: separate them.

*Find the x and y bounds of each polygon.

For the graphics, I'll use the shape of Italy from CountryData.  It consists of three polygons.
bounds[coords_?(MatrixQ[#, NumericQ] &)] := Module[{x, y},
   {x, y} = Transpose[coords];
   {{Min[x], Max[x]}, {Min[y], Max[y]}}
   ];

italy = CountryData["Italy", "Shape"];

directives = Cases[italy, Polygon[pts_, ___] :> pts, Infinity]; (* strip any options *)
polygons = Cases[directives, _?(Depth[#] == 3 &), Infinity];
ranges = bounds /@ polygons
(*
   {{{-0.0763244, 0.0757934}, {-0.0848148, 0.0742848}},
    {{-0.0621578, -0.0398592}, {-0.067826, -0.0264755}},
    {{-0.00564986, 0.0386553}, {-0.107569, -0.0784857}}}
*)

Illustration:
Show[
 italy,
 Graphics[{Opacity[0.3],
   MapThread[{#1, EdgeForm[#1], Rectangle @@ Transpose@#2} &,
     {{Red, Yellow, Blue}, ranges}]
   }]
 ]

A: The output of Fullform shows that your poly variable is not just a Polygon but is actually a list containing, among other things, the Polygon.
Even though Graphics is showing your Polygon, if you hover over the actual graphic I expect you'll see it complain:

"... is not a Graphics primitive or directive".

To extract the Polygon and then the points, do this:
poly = poly[[1,1]];
points = poly[[1]];

To understand what I did above, you should read up on Expressions, especially the tutorials.
As rasher hinted in his comment, you can get the minimum and maximum x- and y-coordinates as below:
{xmin, xmax, ymin, ymax} = {Min[points[[All, 1]]],
  Max[points[[All, 1]]], Min[points[[All, 2]]], Max[points[[All, 2]]]}

There are more concise ways to do this, but I think this will be more understandable.


text:
Q: Probability of each of the three Christmas puddings having exactly 2 coins
A cook makes plum puddings for Christmas. He stirs 6 coins into the pudding mixture thoroughly before dividing it into three equal portions. What is the probability there are 2 coins in each pudding?

The answer is 10/81, but I cannot work out how to arrive at this answer.

What I worked out so far:
A = pudding A has exactly 2 coins
$P(A) = P(B) = P(C) = {6\choose 2}(1/3)^2(2/3)^4$
$P(A~\text{or}~B~\text{or}~C) = 3P(A) - 2P(A~\text{and}~B~\text{and}~C)$ [because $P(A~\text{and}~B) = P(A~\text{and}~B~\text{and}~C)$]
so
$P(A~\text{and}~B~\text{and}~C) = 3P(A)/2P(A~\text{or}~B~\text{or}~C)$
so I guess I just need to figure out what $P(A~\text{or}~B~\text{or}~C)$ is.

A: You shouldn't use the binomial distribution here as it is a multinominal distribution problem (a generalization of the binomial).
So let's gather what we have:
n = 6 (total number of events)
n1 = 2 in part 1 (pudding #1)
n2 = 2 in part 2 (pudding #2)
n3 = 2 in part 3 (pudding #3)
p1 = 2/6 (probability to get 2 from n1)
p2 = 2/6 (probability to get 2 from n2)
p3 = 2/6 (probability to get 2 from n3)

the formula goes like this:

so let's put the numbers in motion:
$p = \frac{6!}{(2!*2!*2!)} *(\frac{2}{6})^2 * (\frac{2}{6})^2 * (\frac{2}{6})^2 = 0.12345
$
and we get

10/81

A: Call the number of pieces in each section $A$, $B$, and $C$. Because $A+B+C=6$, you are interested in $Pr(A=2, B=2) = Pr(B=2|A=2)Pr(A=2)$.
$Pr(A=2)$ is a simple binomial calculation: $A\sim Binom(6, 1/3)$, so $Pr(A=2) = {6\choose 2}(1/3)^2(2/3)^4 = 80/243$.
Conditioned on $A$ having two pieces, $B\sim Binom(4, 1/2)$, so $Pr(B=2|A=2) = {4\choose 2}(1/2)^4 = 3/8$.
Multiplying these together, we conclude that $Pr(A=2, B=2) = 10/81$.


text:
Q: Was Palpatine involved in setting up Ahsoka? In season 5 of Star Wars: The Clone Wars, when the Jedi Temple was bombed (which put the Jedi Order in suspect only to damage their reputation) I thought Palpatine was behind this.
All militaristic setup to lure Ahsoka in the trap made my belief more powerful.
But, in the season finale, it was shown that another Jedi was behind this and the trap against Ahsoka didn't look official after that. It looked possible for a Jedi to setup such things (putting key card in front of Ahsoka, killing clones with Ahsoka's lightsaber etc).
But, I still suspect about Palpatine's involvement. Is there a solid clue to say Palpatine was involved in this from any level?

A: The short answer is no, Palpatine has not been established to have had any direct influence in the bombing of the Jedi Temple. However, as Pasteur said, "Chance favors the prepared mind," and Palpatine has certainly set up circumstances so that such an event could occur.
He has kept the Clone Wars dragging on for several years, turning the opinion of the public against the heavily-involved Jedi. By having the Jedi fight in the war, he created a moral dilemma for those in the Order, who thought of themselves as peacekeepers. He placed people like Tarkin in the military, who advocated against the Jedi.
It's worth noting, however, that Barriss Offee's motivations are covered only briefly, but she says that the Jedi are serving the Dark Side by fighting in the war. This leads me to question what she knows, or at least what she thinks she knows. Did she find out that Palpatine was a Sith? Does she only suspect that Jedi are being manipulated by some unidentified Sith? Could Palpatine have tricked her in some way? Or is it just that she feels that any fighting at all is serving the Dark Side?
While this is entirely speculation, it seems possible that Palpatine could have had some direct influence on her, especially given his ability to manipulate people.


text:
Q: middleware.js in nextjs doesn't work at all import { NextResponse } from 'next/server'

const middleware = (request) => {
  if (request.nextUrl.pathname === request.nextUrl.pathname.toLocaleLowerCase())
    return NextResponse.next()
  return NextResponse.redirect(
    `${request.nextUrl.origin}${request.nextUrl.pathname.toLocaleLowerCase()}`
  )
}

export { middleware }

(Next v.12.2.3)
No matter what I code, pages/middleware.js seems not running at all!
I wanna redirect uppercase urls to lowercase urls.
what should I do?

A: The documentation says:

Create a middleware.ts (or .js) file at the same level as your pages directory

So it shouldn't be inside pages/, but in the same directory as pages/.


text:
Q: Hive XML Serdie xpath retreiving null values I have the sample XML file, Sorry for editing the sample xml missed some tags

<?xml version="1.0"?>
 <wd:File xmlns:wd="urn:com.workday/bsvc">
 <wd:Report_Entry>
 <wd:All_Candidate_Job_Profiles wd:Descriptor="Manager I">
 <wd:ID wd:type="WID">e83ebdbd2a0a013fcbb5009a49e9d9d4</wd:ID>
 <wd:ID wd:type="Job_Profile_ID">US-100017363</wd:ID>
 </wd:All_Candidate_Job_Profiles>
 <wd:All_Companies_as_Text>Xyz, Inc.</wd:All_Companies_as_Text>
 <wd:All_Watched_Companies>0</wd:All_Watched_Companies>
 </wd:Report_Entry>
 <wd:Report_Entry>
 <wd:All_Candidate_Job_Profiles wd:Descriptor="Manager II">
 <wd:ID wd:type="WID">e83ebdbd2a0a013fcbb5009a49e9d9d4</wd:ID>
 <wd:ID wd:type="Job_Profile_ID">US-100017363</wd:ID>
 </wd:All_Candidate_Job_Profiles>
 <wd:All_Companies_as_Text>abc, Inc.</wd:All_Companies_as_Text>
 <wd:All_Watched_Companies>0</wd:All_Watched_Companies>
 </wd:Report_Entry>
 </wd:File>

I am trying to load the data using the following query:
CREATE external TABLE ww_hr_dl_staging_hiring.recruiting_candidates_serdie(
        All_Candidate_Job_Profiles array<string>,
        All_Companies_as_Text string,
        All_Watched_Companies string
        )
        ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
        WITH SERDEPROPERTIES (
        'column.xpath.All_Companies_as_Text'='wd:File/wd:Report_Entry/*
        [local-name()=\"wd:All_Companies_as_Text\"]/text()',
        'column.xpath.All_Watched_Companies'='wd:File/wd:Report_Entry/*
        [local-name()=\"wd:All_Watched_Companies\"]/text()'
        )
        STORED AS
        INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
        OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
        TBLPROPERTIES (
        'xmlinput.start'='<wd:File xmlns',
        'xmlinput.end'='</wd:File>'
        );

Loading data from hdfs using load data inpath 'path' into 'tablename'
Up on selecting the data from the query i am getting null values
select * from ww_hr_dl_staging_hiring.recruiting_candidates_serdie;
OK
NULL    NULL
My output should retreive

Manager I Xyz, Inc 0
Manager II abc inc 0

A: This is because the XPATH you are using is not matching with any element. The correct xpath should be.

//*[local-name(.)="All_Companies_as_Text"]/text()
//*[local-name(.)="All_Watched_Companies"]/text()

This is the working code
CREATE external TABLE temp.recruiting_candidates_serdie(
        All_Companies_as_Text string,
        All_Watched_Companies string
        )
        ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
        WITH SERDEPROPERTIES (
        'column.xpath.All_Companies_as_Text'='//*[local-name(.)="All_Companies_as_Text"]/text()',
        'column.xpath.All_Watched_Companies'='//*[local-name(.)="All_Watched_Companies"]/text()'
        )
        STORED AS
        INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
        OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
        location '/tmp/test_xml/table'
        TBLPROPERTIES (
        'xmlinput.start'='<wd:File xmlns',
        'xmlinput.end'='</wd:File>'
        )


text:
Q: group by clause on data how to write a query to select the student_id and Sum the amount paid for course attendance, grouped by student
the table:
SQL> desc attendances
 Name                                      Null?    Type
 ----------------------------------------- -------- -------------
 RUNNING_ID                                         NUMBER(5)
 STUDENT_ID                                         NUMBER(4)
 EVALUATION                                         VARCHAR2(1)
 AMOUNT_PAID                                        NUMBER(6,2)

I have managed to get to this point, then I'm running into errors:
SELECT SUM(AMOUNT_PAID)
FROM ATTENDANCES;

A: if I got you right this is something what you want
SELECT student_id,SUM(AMOUNT_PAID)
FROM ATTENDANCES group by student_id;


text:
Q: How to check for one word per line in a file using fgets I am pulling words from a file but I need to check if the file follows a specific format.
"The source file format is one word per line. If a line does not follow that format, then it should be skipped" My code is not checking for this and I have no idea how I would even begin its just pulling one line no matter what and strtok it word by word. please help me. Im a beginner.
I tried using an if statement to check for new lines and I couldn't seem to get it to work maybe I just had it in the wrong place.
const char *get_word_from_file(FILE *file)
{

        char words[MAX_WORDS][MAX_WORD_LEN]; // inner one is the outer most view
        char buf[MAX_LINE_LEN];
        size_t idx = 0;

        while (fgets(buf, sizeof(buf), file))
        {
                char *word = strtok(buf, " ?.,\n-\"");
                while (word)
                {

                        strncpy(words[idx], word, sizeof(words[idx])); // Destination, src, size of destination to prevent overflow
                        word = strtok(NULL, " ?.,\n-\"");
                        ++idx;
                }
        }
        fclose(file);
        srandom(time(NULL)); // seeding with current time
        // generating a random number and picking a word from words array
        int random_number = random() % idx;
        char *random_word = words[random_number];
        // Allocating memory for the word
        char *verified_random_word = allocate_word_memory(random_word);
        return verified_random_word;
}


text:
Q: Баг с blur(), помогите пожалуйста! Доброго времени суток!
С последним обновлением Google Chrome до 66 версии, появился очевидный баг с анимацией при наличии там filter:blur(). При наведении картинка мигает.
В Opere тоже наблюдается такой эффект, но намного слабее, некое дергание. Такой же эффект был и в предыдущей версии Google Chrome, а с последней версией все стало еще хуже. В Firefox же все гладко как и задумывалось. Это как-нибудь возможно исправить?
Наглядный пример на Codepen: https://codepen.io/anon/pen/GdpvdW
HTML:

This element has a background-image, which should be blured

    <input id="searchMain" class="animated fadeIn delay">

CSS
target{
  height: 100px;
  width: 500px;
  background: url(http://lorempixel.com/500/100);
}
.blur {
  -webkit-animation: blur 0.5s linear forwards;
  -moz-animation: blur 0.5s linear forwards;
  -ms-animation: blur 0.5s linear forwards;
  -o-animation: blur 0.5s linear forwards;
  animation: blur 0.5s linear forwards;
  -webkit-animation-delay: 1s;
  -moz-animation-delay: 1s;
  animation-delay: 1s;
}
.delay {
  -webkit-animation-delay: 1s;
  -moz-animation-delay: 1s;
  animation-delay: 1s;
}
@-webkit-keyframes blur {
  to {
    -webkit-filter: blur(5px);
    filter: blur(5px);
  }
}
@-moz-keyframes blur {
  to {
    -moz-filter: blur(5px);
    filter: blur(5px);
  }
}
@keyframes blur {
  to {
    -webkit-filter: blur(5px);
    -moz-filter: blur(5px);
    filter: blur(5px);
  }
}

A: В моем хроме помогло не нулевое значение для blur, например:
filter: blur(0.01px);

#target{
  height: 100px;
  width: 500px;
  background: url(http://lorempixel.com/500/100);
}
.blur {
    -webkit-filter: blur(3px);
    -moz-filter: blur(3px);
    -o-filter: blur(3px);
    -ms-filter: blur(3px);
    filter: blur(3px);
    opacity: 1;
    transition: opacity .2s linear,-webkit-filter .4s linear;
}

.blur:hover {
  -webkit-filter: blur(0.01px);
    -moz-filter: blur(0.01px);
    -o-filter: blur(0.01px);
    -ms-filter: blur(0.01px);
    filter: blur(0.01px);
    opacity: 1;
}

This element has a background-image, which should be blured


text:
Q: VBA - Import Macro - How do i add to the current data when importing? I have created a macro to import data from another workbook, but i have to set which row to start. I was wondering how i would alter the code to paste the import data to the last empty row (so its adding to the table).
Currently the macro, prompts to click the file you would like to import, then imports the data from certain col from source WB to target WB. But as you can see it as been assigned the row to paste. My question is how do i get it to paste at the last empty row, so it is collecting the data rather then over writing the data.
Would i need to change the "targetSheet.Range("R2", "R4000").Value = sourceSheet.Range("Q2", "Q4000").Value"
Public Sub Extract_Excel_file()

''//--------------------------------------------
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Sheets("Raw Data")
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
sourceSheet.Range("A2", "V400").NumberFormat = "@" ''//Set all cells to
text format.

' sourceSheet.Range("A2", "A4000").NumberFormat = "@" ''//Set all cells
to text format.
targetSheet.Range("B2", "B4000").Value = sourceSheet.Range("A2",
"A4000").Value
targetSheet.Range("C2", "C4000").Value = sourceSheet.Range("B2",
"B4000").Value
targetSheet.Range("D2", "D4000").Value = sourceSheet.Range("C2",
"C4000").Value
targetSheet.Range("E2", "E4000").Value = sourceSheet.Range("D2",
"D4000").Value
targetSheet.Range("F2", "F4000").Value = sourceSheet.Range("E2",
"E4000").Value
targetSheet.Range("G2", "G4000").Value = sourceSheet.Range("F2",
"F4000").Value
targetSheet.Range("H2", "H4000").Value = sourceSheet.Range("G2",
"G4000").Value
targetSheet.Range("I2", "I4000").Value = sourceSheet.Range("H2",
"H4000").Value
targetSheet.Range("J2", "J4000").Value = sourceSheet.Range("I2",
"I4000").Value
targetSheet.Range("K2", "K4000").Value = sourceSheet.Range("J2",
"J4000").Value
targetSheet.Range("L2", "L4000").Value = sourceSheet.Range("K2",
"K4000").Value
targetSheet.Range("M2", "M4000").Value = sourceSheet.Range("L2",
"L4000").Value
targetSheet.Range("N2", "N4000").Value = sourceSheet.Range("M2",
"M4000").Value
targetSheet.Range("O2", "O4000").Value = sourceSheet.Range("N2",
"N4000").Value
targetSheet.Range("P2", "P4000").Value = sourceSheet.Range("O2",
"O4000").Value
targetSheet.Range("L2", "L4000").Value = sourceSheet.Range("P2",
"P4000").Value
targetSheet.Range("Q2", "Q4000").Value = sourceSheet.Range("L2",
"L4000").Value
targetSheet.Range("R2", "R4000").Value = sourceSheet.Range("Q2",
"Q4000").Value

' Close customer workbook
Application.DisplayAlerts = False ''//Don't promt to Save
customerWorkbook.Close
Application.DisplayAlerts = True   '' undo Don't promt to Save

End Sub

I just want it to collect the data rather then overriding it each month.


text:
Q: How to print a big dimension of confusion matrix I'm trying to print a confusion matrix but getting a partial print of it (with ...), how can I enforce it to print all values of my dimension = 100?
to print the accuracy during training process and to print a confusion matrix at the end.
tried both ways of printing confusion matrix: sklearn & tensorflow, but both isn't printing a full matrix output
Confusion Matrix :

0 0 0 ... 0 0 0
1 0 0 ... 0 0 0
0 1 0 ... 0 0 0

...

0 1 0 ... 0 0 0
0 0 1 ... 0 0 0
0 0 0 ... 0 0 0

I'm new to deep learning and trying to implement the tensorflow example of fizzbuzz game.
given an array of numbers from 1 to 100, need to print:
- fizz for all i mod 3==0
- buzz for all i mod 5==0
- fizzbuzz for all i mod 15==0
import numpy as np
import tensorflow as tf
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report

NUM_DIGITS = 10
VICTOR_SIZE = 4
# Represent each input by an array of its binary digits.
def binary_encode(i, num_digits):
    # print (np.array([i >> d & 1 for d in range(num_digits)]))
    return np.array([i >> d & 1 for d in range(num_digits)])

# One-hot encode the desired outputs: [number, "fizz", "buzz", "fizzbuzz"]
def fizz_buzz_encode(i):
    if   i % 15 == 0: return np.array([0, 0, 0, 1])
    elif i % 5  == 0: return np.array([0, 0, 1, 0])
    elif i % 3  == 0: return np.array([0, 1, 0, 0])
    else:             return np.array([1, 0, 0, 0])

# Our goal is to produce fizzbuzz for the numbers 1 to 100. So it would be
# unfair to include these in our training data. Accordingly, the training data
# corresponds to the numbers 101 to (2 ** NUM_DIGITS - 1).
trX = np.array([binary_encode(i, NUM_DIGITS) for i in range(101, 2 ** NUM_DIGITS)])
trY = np.array([fizz_buzz_encode(i)          for i in range(101, 2 ** NUM_DIGITS)])

# We'll want to randomly initialize weights.
def init_weights(shape):
    return tf.Variable(tf.random_normal(shape, stddev=0.01))

# Our model is a standard 1-hidden-layer multi-layer-perceptron with ReLU
# activation. The softmax (which turns arbitrary real-valued outputs into
# probabilities) gets applied in the cost function.
def model(X, w_h, w_o):
    h = tf.nn.relu(tf.matmul(X, w_h))
    return tf.matmul(h, w_o)

# Our variables. The input has width NUM_DIGITS, and the output has width 4.
X = tf.placeholder("float", [None, NUM_DIGITS])
Y = tf.placeholder("float", [None, VICTOR_SIZE])

# How many units in the hidden layer.
NUM_HIDDEN = 100

# Initialize the weights.
w_h = init_weights([NUM_DIGITS, NUM_HIDDEN])
w_o = init_weights([NUM_HIDDEN, VICTOR_SIZE])

# Predict y given x using the model.
py_x = model(X, w_h, w_o)

# We'll train our model by minimizing a cost function.
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y)) ##TODO
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = py_x, labels=Y))
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) #consider adam optimizer

# And we'll make predictions by choosing the largest output.
predict_op = tf.argmax(py_x, 1)

# Finally, we need a way to turn a prediction (and an original number)
# into a fizz buzz output
def fizz_buzz(i, prediction):
    return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]

def analyze_results(actual, predicted):
    #print("\nAnalyze results.....................................................")

    #print("Accuracy Score :", accuracy_score(actual, predicted, normalize=False))
    print("Confusion Matrix :\n", confusion_matrix(actual, predicted))
    # to evaluate the accuracy of a classification (performance of classifier)
    # print("Report :", classification_report(actual, predicted))

BATCH_SIZE = 128 #consider smaller batches

# Launch the graph in a session
with tf.Session() as sess:
    ##TODO
    #tf.initialize_all_variables().run()
    sess.run(tf.global_variables_initializer())

    for epoch in range(10000):
        # Shuffle the data before each training iteration.
        p = np.random.permutation(range(len(trX))) #random order of input
        trX, trY = trX[p], trY[p]

        # Train in batches of 128 inputs.
        for start in range(0, len(trX), BATCH_SIZE):
            end = start + BATCH_SIZE
            sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})

        # And print the current accuracy on the training data.
        print("current accuracy on the training data: ", epoch, np.mean(np.argmax(trY, axis=1) ==
                             sess.run(predict_op, feed_dict={X: trX, Y: trY})))

    # And now for some fizz buzz
    numbers = np.arange(1, 101)

    teX = np.transpose(binary_encode(numbers, NUM_DIGITS))
    teY = sess.run(predict_op, feed_dict={X: teX})
    output = np.vectorize(fizz_buzz)(numbers, teY)

    print("\nOutput = ", output)

    # print("\naccuracy = ", np.mean(np.argmax(trY, axis=1) == sess.run(predict_op, feed_dict={X: trX, Y: trY})))

    # conf_matrix = tf.confusion_matrix(labels=numbers, predictions=teY) #, num_classes=None, dtype=None, name=None)
    # print("\nConfusion Matrix :\n", sess.run(conf_matrix, feed_dict={X: trX, Y: trY}))
    # print("\nConfusion Matrix :\n", confusion_matrix(numbers, teY)) # Using Sklearn

    analyze_results(numbers, teY)

A: Did you try using numpy.set_printoptions ?
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)


text:
Q: Dynamically generated jbuttons I'm trying to make a GUI for that simulates elevators in a building (really to test threading/c-scan), but when generating the buttons for the elevator control panel and the buttons for each individual floor, I'm kind of stuck. I thinking about trying to generate a new pair of buttons for each floor, and generating a new control panel per elevator. Also there's the difficulty of having a variable amount of floors. Anyway my question what is this best way to go about doing this? Perhaps it's not necessary to generate new buttons for everything and just use one set and change what the actions do per floor/elevator? I'm asking because I'm not very familiar with GUIs. Thanks for the help

A: In this case that the number of floors is variable you can create an array of buttons:
JButton[] buttons = new JButton[MAX_NUMBER_OF_FLOORS];

Then when you determine the exact of number of floors at runtime, you can go to instantiate and add the buttons:
for(int i=0; i<numberOfFloors; i++) {
    buttons[i] = new JButton();
    controlPanel.add(buttons[i]);
}

Something like this should work.
Assign MAX_NUMBER_OF_FLOORS a big number like 100, there should be a possible limit given by the problem.

A: If all the elevators, and the control panel are the same, you can use a singular method and pass in the elevator or the control panel. CustomPanel extends JPanel and has a method foo.
public void createElevatorButtons(final CustomPanel panel) {
    ArrayList<JButton> buttons = new ArrayList<>(); //arraylist of buttons we can keep track of
    JPanel buttonPanel = new JPanel(); //the visible component
    for(int i = 1; i <= numberOfFloors;i++) {
        JButton button = new JButton(String.valueOf(i)); //creates buttons for floors 1 to max
        buttons.add(button);
        buttonPanel.add(button);
    }
    panel.add(buttonPanel);

    //add the action listeners
    for(JButton button : buttons) {
        button.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JButton floor = (JButton) e.getSource();
                int floorNumber = Integer.parseInt(floor.getText());
                panel.foo(floorNumber); //we tell the elevator/panel/whatever to do something, you will have to extend JPanel to do foo
            }
        });
    }
}


text:
Q: Instability of Lagrange interpolation at too high n Let's say we have multiple integer sequences, some coming from polynomials (of unknown degrees), some coming from non-polynomials. For example: $a = 1,4,9,16,32,...$
We want to figure out whether $a$ is coming from a polynomial or not. My idea was to fit a Lagrange polynomial on the first $n$ elements ($a_{1}$ to $a_{n}$) in the sequence. Then use the Lagrange Polynomial to calculate the error between the correct next $n$ values (from $a_{n+1}$ to $a_{2n}$) and the 'predicted' values from the Lagrange Polynomial. An error of $0$ would then indicate that the sequence is likely from a polynomial, an error $>0$ would indicate that either $n$ is chosen too small (i.e. the degree is higher than $n$) or the sequence does not come from a polynomial.
Regarding the above example, this works all right when I use small $n$, for example, $n = 10$. However, when setting $n$ to 100, the fitted Lagrange Polynomial has degree a lot higher than 2. And the error gets rather large. But I need a high $n$ to be able to detect polynomials of high degree.
Is there a method of interpolation that does not suffer from this problem? Or can the Lagrange Method be used differently on this task? It seems as this is similar to regularization in machine learning where small or $0$ values are prefered.


text:
Q: D3 Labels text amount slightly off I'm having a problem with my D3 bar chart not displaying the correct amount for the label text. It seems like it's slightly off, and I'm not sure why.
I'm trying to get the text labels to display whatever the newNumber is within the dataset.
Here's the code I'm using:

     var w = 800;
  var h = 600;
  var padding = 5;
  var maxNumber = 100;

  //Generate random numbers
  var dataset = [];
            for (var i = 0; i < 21; i++) {
             var newNumber = Math.random() * maxNumber;
             dataset.push(newNumber);
            }

        var xScale = d3.scale.ordinal()
   .domain(d3.range(dataset.length))
   .rangeRoundBands([padding, w - padding], 0.05);

  var yScale = d3.scale.linear()
   .domain([d3.max(dataset), 0])
   .range([padding, h - padding]);

  var xAxis = d3.svg.axis()
   .scale(xScale)
   .orient("bottom");

  var yAxis = d3.svg.axis()
   .scale(yScale)
   .orient("left");

  var svg = d3.select("body")
     .append("svg")
     .attr("width", w)
     .attr("height", h);

  svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("x", function(d, i) {
     return xScale(i) + padding;
    })
    .attr("y", function(d) {
     return h - yScale(d) - padding - 15;
    })
    .attr("width", xScale.rangeBand())
    .attr("fill", "rgba(95, 159, 229, 0.3");

  svg.selectAll("rect")
    .data(dataset)
    .transition().delay(function(d, i) {
        return i / dataset.length * 800;
    })
    .duration(1500)
    .ease("linear")
    .attr("y", function(d) {
     return h - yScale(d) - padding - 15;
    })
    .attr("height", function(d) {
     return yScale(d);
    });

   svg.selectAll("text")
      .data(dataset)
      .enter()
      .append("text")
      .text(function(d) {
        return Math.floor(d3.max(dataset) - d);
      })
      .attr("text-anchor", "middle")
      .attr("x", function(d, i) {
        return xScale(i) + padding + 15;
      })
      .attr("y", function(d) {
        return h - yScale(d) - padding - 20;
      })
      .attr("font-family", "sans-serif")
      .attr("font-size", "11px")

  svg.append("g")
   .attr("class", "xAxis")
   .attr("transform", "translate(0," + (h - padding - 15) + ")")
   .call(xAxis);

  svg.append("g")
   .attr("class", "yAxis")
   .attr("transform", "translate(" + (padding + 15) + ",0)")
   .call(yAxis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>D3: BDAS Bar Chart Test</title>

  <style>
   svg {
    padding-left: 15px;
    padding-top: 30px;
   }

   rect {
    transition: 0.1s;
   }
   rect:hover {
    fill: rgba(95, 159, 229, 1);
   }

   .xAxis path, .yAxis path {
    fill: #aaa;
    height: 0.5px;
   }

   .xAxis .tick text, .yAxis .tick text {
    font-family: sans-serif;
    fill: #aaa;
    font-size: 15px;
   }
  </style>
 </head>
 <body>

 </body>
</html>

A: I looked at your coded and changed it a bit and it should work now.
   var w = 800 ;
    var h = 600 ;
    var padding = 20;

    //Generate random numbers
    var dataset = [];
        for (var i = 0; i < 21; i++) {
            var newNumber = Math.random() *100;
            dataset.push(newNumber);
        }

    var xScale = d3.scale.ordinal()
        .domain(d3.range(dataset.length))
        .rangeRoundBands([padding, w - padding], 0.05);

    var yScale = d3.scale.linear()
        .domain([0,d3.max(dataset)])
        .range([h - padding,padding]);

    var xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yScale)
        .orient("left");

    var svg = d3.select("body")
                .append("svg")
                .attr("width", w)
                .attr("height", h);

    svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x", function(d, i) { return xScale(i);})
            .attr("y", function(d) {return yScale(d);})
            .attr("width", xScale.rangeBand())
            .attr("fill", "rgba(95, 159, 229, 0.3")
            .attr("height", function(d) { return h - yScale(d) - padding; });

    svg.selectAll("rect")
            .data(dataset)
            .transition().delay(function(d, i) { return i / dataset.length * 800;})
            .duration(1500)
            .ease("linear")
            .attr("y", function(d) { return yScale(d);})
            .attr("height", function(d) { return h - yScale(d) - padding; });

        svg.selectAll("text")
           .data(dataset)
           .enter()
           .append("text")
           .text(function(d) {
                return Math.floor(d);
           })
           .attr("text-anchor", "middle")
           .attr("x", function(d, i) {
                return (xScale(i)+15);
           })
           .attr("y", function(d) {
                console.log(h-yScale(d))
                return (yScale(d)-padding) ;
           })
           .attr("font-family", "sans-serif")
           .attr("font-size", "11px")

    svg.append("g")
        .attr("class", "xAxis")
        .attr("transform", "translate(0," + (h-padding) + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "yAxis")
        .attr("transform", "translate(" + (padding + 10) + ",0)")
        .call(yAxis);


text:
Q: cv::drawMatches(...) not drawing I've been trying to make a SURF implementation work and I have been having some trouble, now I finally think i got it 'right' but I have one small problem.
The problem is pretty straight forward and I am sure its something simple but I can't solve it. The image displays right and everything but the matches are not drawn. Here is my code.
#include <stdio.h>
#include "opencv2/xfeatures2d.hpp"
#include <opencv2/opencv.hpp>
#include "opencv2/features2d/features2d.hpp"

using namespace cv;
using namespace std;

int main(int argc, char** argv ){

if ( argc != 3 ) {
    printf("usage: DisplayImage.out <Image1_Path> <Image2_Path>\n");
    return -1;
}

Mat image, image2;
image = imread( argv[1], 0 );
image2 = imread(argv[2], 0);

if ( !image.data ){
    printf("No image data \n");
    return -1;
}

if ( !image2.data ){
    printf("No image data \n");
    return -1;
}

/*
Ptr<FeatureDetector> detector = FastFeatureDetector::create(15);
vector<KeyPoint> keypoints1, keypoints2;
detector->detect(image, keypoints1);
detector->detect(image2, keypoints2);

Ptr<xfeatures2d::SURF> extractor = xfeatures2d::SURF::create();
Mat descriptors1, descriptors2;

extractor->compute(image, keypoints1, descriptors1);
extractor->compute(image2, keypoints2, descriptors2);

BFMatcher::BFMatcher matcher(L2<float>);
//BruteForceMatcher<L2<float> > matcher;
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
*/

Ptr<xfeatures2d::SURF> surf = cv::xfeatures2d::SURF::create();
vector<KeyPoint> keypoints1, keypoints2;
Mat descriptors1, descriptors2;
surf->detectAndCompute(image,noArray(), keypoints1, descriptors1, true);
//BFMatcher::BFMatcher matcher(L2<float>);
BFMatcher::BFMatcher matcher(NORM_HAMMING);
vector<DMatch> matches;
Mat res;

matcher.match(descriptors1,descriptors2, matches);
drawMatches(image, keypoints1, image2, keypoints2, matches, res);

namedWindow("Display Image", WINDOW_AUTOSIZE );
imshow("Display Image", res);

waitKey(0);

return 0;
}


text:
Q: Textbooks on Matrix Calculus? See this question on Math SE.
Short story: I read The Elements of Statistical Learning and got frustrated when I was trying to verify some of the results, e.g., given
$$\text{RSS}(\beta) = \left(\mathbf{y}-\mathbf{X}\beta\right)^{T}\left(\mathbf{y}-\mathbf{X}\beta\right)\text{,}$$
then
$$\begin{align}&\dfrac{\partial\text{RSS}}{\partial \beta} = -2\mathbf{X}^{T}\left(\mathbf{y}-\mathbf{X}\beta\right) \\
&\dfrac{\partial^2\text{RSS}}{\partial \beta\text{ }\partial \beta^{T}} = 2\mathbf{X}^{T}\mathbf{X}\text{.}
\end{align}$$
I am looking for a matrix calculus book which is written like your traditional calculus book (i.e., proofs of theorems, examples, exercises on computation, etc.). I have already seen this question and feel that the text by Magnus and Neudecker focuses too much on the theory, and the text I have by Gentle focuses too little on the theory and too much on the computation side.
Is there a happy medium out there which is accessible to someone with a background in undergraduate analysis?

A: If you found too much theory in the book of Magnus and Neudecker, I recommend this one, also authored by Magnus:
Abadir, K.M. and Magnus, J.R.
Matrix Algebra
Cambridge University Press, 2005
that has more emphasis on the applications of matrix calculus.

A: I would highly recommend this 26 pages paper from Stanford University:
"Linear Algebra Review and Reference" by Zico Kolter
It really focus on typical Sum calculations with a lot of i and j everywhere and tells you the corresponding matrix calculation (i.e. using their "vectorized" implementation).
It helps you recognize right away what type of matrix formula you should write to do your calculations.

A: A user self-deleted the following helpful answer, which I here reproduce in full so that its information is not lost:

You don't really need a lot of results on vector and matrix derivatives for ML, and Tom Minka's paper covers most of it, but the definitive treatment is Magnus & Neudecker's Matrix Differential Calculus with Applications in Statistics and Econometrics.

Indeed, Magnus & Neudecker has excellent reviews on Amazon and Tom Minka's paper (Old and New Matrix Algebra Useful for Statistics, 2000) contains many useful formulas, although he warns "this is advanced material."

A: For most matrix questions I always first refer to "The Matrix Cookbook" (see here).
It is regularly updated due to feedback from various sources. There are proofs contained within, however it is mostly intended as a handbook.


text:
Q: Javascript Form Dropdown That changes second Dropdown option First and foremost, I know this must be simple but I am just not seeing how to do what I need to do.
What I need is a JS form dropdown that lists an array of locations. In which a second dropdown will then show a selected group of 'course dates'. Because all of the locations have varying dates of service, this second dropdown will need to change upon the first initial selection.
<select class="form-control" id="campus" name="campus" required="" title="Campus">
            <option value="AIMNAT" style="alignment-adjust:middle;" selected="selected">Select Your Nearest Location</option>
            <option value="AMA">Atlanta, GA</option>
            <option value="AMD">Dallas, TX</option>
            <option value="AMH">Houston, TX</option>
            <option value="AMI">Indianapolis, IN</option>
            <option value="AMK">Kansas City, MO</option>
            <option value="AIML">Las Vegas, NV</option>
            <option value="AMO">Orlando, FL</option>
            <option value="AMP">Philadelphia, PA</option>
            <option value="AMS">San Francisco, CA</option>
            <option value="AMN">Virginia Beach, VA</option>
            <option value="AMM">Washington, DC</option>

            </select>

I have my location form selection above, I am just not sure how to go about adding the right course schedules to each location as above. The second dropdown will need to state, "Choose your schedule" and then have a populated list of dates that are pertainable to the campus the user selected. As an example for Atlanta, I would need August 19-20th, September 16-17th, and October 14-15th. And for Dallas I would need August 5-6th & 12-13th, September 9-10 & 16-17, October 14-15 & 21-22, and November 11-12 & 18-19.
Thank you so much for your knowledge, insight, and assistance.

A: Simply put, here's what I would have done:
var locations = {
    "AMA" : {
        "August 19-20",
        "September 19-20",
        "January 19-20"
    },
    "AMH" : {
        "August 19-20",
        "September 19-20",
        "January 19-20"
    },
    "AIML" : {
        "August 19-20",
        "September 19-20",
        "January 19-20"
    }
};

// when user selects a location
$('.locations-select').on('change', function() {
    // get selected option
    var location = $('.locations-select option:selected');

    // clear the pervious options for dates
    $('.dates-select').empty();

    // popluate dates
    $.each(locations[locaiton], function(idx, el) {
        $('.dates-select').append('<option value="' + idx + '">' + el + "</option>");
    })
})

And a bit of explanation:

*

*You need to know which timings map to which locations. If this map
is not static (I just did it for simplicity), you might need to do
an AJAX call to the server to fetch the list by location

*When location is selected, you clear the dates select and populate
it with valid dates options.

A: var data=[
{"ID":"AMA", "ParentID":null, "value":"Atlanta, GA"},{"ID":"date", "ParentID":"AMA", "value":"August 19-20th"},
{"ID":"date", "ParentID":"AMA", "value":"September 16-17th"},{"ID":"date", "ParentID":"AMA", "value":"October 14-15th"},
{"ID":"AMD", "ParentID":null, "value":"Dallas, TX"},{"ID":"date", "ParentID":"AMD", "value":"August 5-6th"},
{"ID":"date", "ParentID":"AMD", "value":"August 12-13th"},{"ID":"date", "ParentID":"AMD", "value":"September 9-10 "},
];

keep all your data in json format like above.
Now when in the first dropdown Atlanta will be selected, search it in the json and get its ID value. Now again search whose parentID is same as Atlanta's ID. Get their value and append in second dropdown. You just need a couple of search operations in the json. Hope it helps you.


text:
Q: How to get the indicies from sort or member commands in MAXIMA The sort or member functions in MAXIMA do not return the indicies of elements sorted or the index of element being searched for. Is there a sort function that returns indices? Thanks.
Sven

A: There aren't built-in functions for those tasks, but I think you can write something fairly easily:
member_index (x, l) :=
 (sublist_indices (l, lambda ([y], x = y)),
  if %% = [] then false else first (%%));

This member_index function returns the index of the first instance of x. If you want indices for all instances, just remove the if expression and return %% instead.
ranks (l) :=
  block ([l1, l2],
         makelist ([l[i], i], i, length (l)),
         l1 : sort (%%, lambda ([x, y], orderlessp (x, y))),
         l2 : makelist (0, length (l)),
         for i thru length (l) do l2[l1[i][2]] : i,
         l2);

This ranks function returns integer values when there are ties (i.e. same values). Sometimes it is preferable to return the average rank for ties; that take a little more code. There is a ranks function in share/amatrix/wilcoxon.mac which does average ties. You can load that function via load(wilcoxon);.


text:
Q: Kodak still camera udev problem My still camera is not includev in udev list.
lsusb stands:
Bus 007 Device 016: ID 040a:058b Kodak Co. Digital Camera

So I add to /usr/lib/udev/rules.d/40-libgphoto2.rules
ATTRS{idVendor}=="040a", ATTRS{idProduct}=="058b", ENV{ID_GPHOTO2}="1", ENV{GPHOTO2_DRIVER}="proprietary"

according to the entry for similar unit from the same vendor but different idProduct "058a"
But my camera is not available from any photo app including gwenview or even from any filemanager. Simply can not be mounted as a storage.
Any idea how to correct my entry in udev?

A: I had the same issue. Kodak cameras by default present themselves as PTP cameras, not as USB mass storage devices to the USB host. This gives you two possibilities:

*

*use the camera's menu to switch it to something like "USB mass storage device" instead of something like "PTP camera"

*use the software gphoto2 to obtain pictures from your PTP camera.

If you insist your camera is a USB mass storage device please call
hwinfo --block --short

This will list all block devices (incl. USB storage devices) visible to your kernel.
I documented my experiences at http://www.linuxintro.org/wiki/Digital_camera

A: I worked at Kodak for 15+ years and have used the products extensively. I would recommend getting a card reader and just taking the cards out of the camera and plugging them into the reader instead. You will save yourself a lot of annoyance and aggravations.
USB card readers can usually be picked up for 10-20 US dollars. Ironically I use several that I picked up at the Kodak employee store, they're worth their weight in gold. The readers I purchased could read a variety of card formats and were designed to be portable so they can easily be thrown in the bag with the cameras as well.
I do this for all my cameras, all brands and it's just a lot easier than monkeying around with attaching the cameras to the computer.
USB readers
This is the reader that I picked up, it's for sale on Amazon for $7 US dollars.

There are tons of others that are similar to this one. These readers are often called 40-in-1's or 50-in-1's because they can read a variety of card form-factors.


text:
Q: Android - get X and Y coordinates of dynamically drawn bitmaps I am making an Android app with OpenStreetMaps (using osmdroid).
On this map, markers are shown (the long/lat and other data for these markers are retrieved from a json file). These markers are OverlayItems and are all shown correctly on the MapView. The X and Y coordinates for these bitmaps are calculated by getting a projection of the mapview and then from the geopoint's X and Y in combination with the bitmaps width/2 and height/2 the bitmap is drawn on his correct location on the worldmap.
Long story short: the X and Y values for the bitmaps are calculated dynamically.
My question is, I'm writing code that should occur when the user has clicked (=made a touch event) on a marker-bitmap. For this, I need to check if the event's X and Y is within the bounds of the bitmap.
How can I do this?
Unfortunately, there doesn't seem to be an easy bitmap.getX or .getY, which is basically what I need.
This is the code for drawing the bitmaps (happens in the @Override draw()) if it could be of any use:
for(OverlayItem p: waypointMarkers){
                IGeoPoint in = p.getPoint();
                Point out = new Point();
                mapview.getProjection().toPixels(in, out);

                Bitmap bm = BitmapFactory.decodeResource(getResources(),
                        R.drawable.marker);

                bitmaps.put(bm, p);

                canvas.drawBitmap(bm,
                        out.x - bm.getWidth()/2,    //shift the bitmap center
                        out.y - bm.getHeight()/2,   //shift the bitmap center
                        null);

            }

The bitmaps.put(bm, p); is a HashMap with Bitmap, OverlayItem pair. Later in my code, I'm looping through the keys of this HashMap and there is where I want to check for the bitmap's X and Y.
for(Bitmap b: bitmaps.keySet()){
            if (x >= xOfBitmap && x < (xOfBitmap + yourBitmap.getWidth())
                    && y >= yOfBitmap && y < (yOfBitmap + yourBitmap.getHeight())) {
                //found this on StackOverflow, if this is true than user has clicked somewhere on the bitmap
            }

Thanks in advance.

A: You could have a look at OSMBonusPack Marker.
As it implements the touch event detection, looking at its source code (hitTest method) will give you a working example.
And maybe you can just use it, if it matches your need.


text:
Q: Slurm multifactor priority - how to configure Slurm to consider past usage? I'm trying to configure our Slurm to allocate users' jobs according to past usage.
The goal is to have the job priority consider past time usage of mainly GPUs.
I understand I must use the FairShare tree to configure its weight, but I'm not sure how to configure for Fairshare what variables to consider. I just don't seems to get the gist of how this is supposed to work.
Current configuration is:
###Job Priority##
#Fair tree, multifactor with its parameters (http://slurm.schedmd.com/fair_tree.html)
#PriorityFlags=FAIR_TREE
#PriorityType=priority/multifactor
#PriorityDecayHalfLife=14-0
#PriorityMaxAge=7-0
#PriorityUsageResetPeriod=NONE
#PriorityWeightAge=100
#PriorityWeightFairshare=10000
#Unused weights
#PriorityWeightJobSize=0
#PriorityWeightPartition=0
#PriorityWeightQOS=0

Possible configuration (correct me if I'm wrong):
###Job Priority##
#Fair tree, multifactor with its parameters (http://slurm.schedmd.com/fair_tree.html)
PriorityType=priority/multifactor
#PriorityDecayHalfLife=14-0 PriorityMaxAge=7-0  PriorityWeightAge=1000 PriorityWeightFairshare=10000
#Unused weights PriorityWeightJobSize=100 PriorityWeightPartition=0 PriorityWeightQOS=0

PriorityUsageResetPeriod=MONTHLY

AccountingStorageTRES=gres/gpu,gres/gpu:geforce_rtx_1080,gres/gpu:titan,gres/gpu:quadro,gres/gpu:geforce_rtx_3090,gres/gpu:v100
TRESBillingWeights="CPU=1.0,Mem=0.25G,gres/gpu=1.0"

Would this do the trick? Change the weights for TRESBilling?
Thanks to those who would answer!


text:
Q: ng-change sends different values on chosen select Dears, I am using a chosen select drop down list in select tag, and I added an ng-change tag to bind it to a function. Also I made a console.log to monitor the sent key. I found that when page load and select one item from the list it works good and sends the correct key. BUT when I select the same item it sends the key of the next item in the list. any help how to fix it
HTML

    <select ng-change="GetUsersList(j)" data-placeholder="Choose a Job"
            ng-model="j" id="chosenValueID" class="chosen-select"
            tabindex="1"
            ng-options="j.JobKey as j.JobDesc for j in jobs">
    </select>

Angularjs
 $scope.GetUsersList = function (job) {
        //var jobkey1 = $("#chosenValueID").chosen().val();
        //$scope.jobkey2 = jobkey1.substring(7);
        console.log(job);
        $scope.ShowLoading('slow');
        FieldsSecuritySrv.GetUsersList("FieldsSecurity/GetUsersList?hospid=" + $scope.hospitalid + '&jobkey=' + job).then(function (response) {
            $scope.UsersList = (response.data);

            GetFieldsList();
            GetCategriesList();
            GetPatientSheets();

            $scope.HideLoading('slow');
        })
    }

Thanks in Advance

A: your j variable in HTML is somehow messy, it is indexed for ng-repeat and used as ng-modal as well, so $scope.j is also created :(
<select ng-change="GetUsersList()" data-placeholder="Choose a Job" ng-model="selectedJob" id="chosenValueID" class="chosen-select"
        tabindex="1" ng-options="j.JobDesc for j in jobs"></select>

In angular:
//initialize the way u like
$scope.selectedJob = $scope.Jobs[0];

$scope.GetUsersList = function () {
        //var jobkey1 = $("#chosenValueID").chosen().val();
        //$scope.jobkey2 = jobkey1.substring(7);
        console.log($scope.selectedJob.jobKey);
        $scope.ShowLoading('slow');
        FieldsSecuritySrv.GetUsersList("FieldsSecurity/GetUsersList?hospid=" + $scope.hospitalid + '&jobkey=' + $scope.selectedJob.jobKey).then(function (response) {
            $scope.UsersList = (response.data);

            GetFieldsList();
            GetCategriesList();
            GetPatientSheets();

            $scope.HideLoading('slow');
        })
    }

A: No idea how you can bind jobs but can try ...

 angular.module('myApp', [])
    .controller('myCtrl', ['$scope', function($scope) {

      $scope.count = 0;
      $scope.jobs=[
                    {JobKey : "1", JobDesc : "IT"},
                    {JobKey : "2", JobDesc : "Sales"},
                    {JobKey : "3", JobDesc : "Marketing"}
                  ];

      $scope.GetUsersList = function(job){
        alert(job);
      }
    }]);
<!DOCTYPE html>

      <select ng-change="GetUsersList(j)" data-placeholder="Choose a Job" ng-model="j"  id="chosenValueID" class="chosen-select" tabindex="1" ng-options="j.JobKey as j.JobDesc for j in jobs"> </select>


text:
Q: Can you use a Column obtained using a formula in the formula used to obtain another column? I'm using a query like:
SELECT C1, C1+C2,C (C1+C2)*C3 FROM T1 WHERE C2='XX'

Now, the second column's formula is C1+C2 and the third column is the second multiplied by C3.
So, what I want to know is, if something like this is possible:
SELECT C1,C1+C2 AS NEWC, NEWC*C3 FROM T1 WHERE C2='XX'

This query seems trivial, but actually I have a huge 4-line query over which I'd like to use a way out if there is one, since the query is getting lengthened pointlessly due to repeating the formula already stated in previous columns.

A: You can use subqueries to remove duplicate code:
SELECT C1, NEWC, NEWC*C3
  FROM (SELECT C1, C1+C2 NEWC, C3
          FROM T1
         WHERE C2='XX')

Sometimes, the readability can be improved by moving the subquery to the WITH clause:
WITH intermediate_result AS (
   SELECT C1, C1+C2 NEWC, C3
     FROM T1
    WHERE C2='XX'
)
SELECT C1, NEWC, NEWC*C3
  FROM intermediate_result


text:
Q: Unable to Connect to a Remote JVM using JStat From the Jstat Documentation , jstat can be connected to a local as well as remote JVM. The URI can be formed as
 [protocol:][//]lvmid[@hostname[:port]/servername]

I have a JVM running on one of the servers (CentOS) with JMX enabled -
xyz   23878     1  0 Jun01 ?        04:37:00 java -Xms1g -Xmx1g -XX:NewSize=512m -Xloggc:../9301/logs/gc.log -verbose:gc -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=../9301/logs/oom.log **-Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.port=19301 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false** -jar ../0.1.14/xyz-0.1.14.jar -serviceName <name> -dataCenter <name> servicePort 9301

I am able to connect to the JVM, from my local machine, using JVisualVM which uses a 2 step process -

*

*Prompts to add the remote machine via jstatd connection on default port 1099 -> I am able to do so and server gets added proving RMI Registry is available

*After Adding the server, you can add a JMX connection to the JVM on the exposed port -> Success as JMX is exposed by my program on port 19301 and I am able to view the details
I am, however, not able to use jstat for the same purpose though.
Running jstat -gc process_id@servername gives me the below exception -
RMI Registry not available at <servername>:1099
Connection refused to host: <servername>; nested exception is:
    java.net.ConnectException: Connection refused

Checked various sources over the net and they talk about having the jstatd
running which I believe is running as VisualVM was able to add the machine.
Ques: How should I frame the [vmid] part in the jstat command to connect

A: You need to run jstatd on a remote host in order to use jstat.
Having RMI Registry running is not enough. The Registry is just for registering various RMI services. -Dcom.sun.management.jmxremote option starts jmxrmi service (which works for VisualVM), but jstat looks for JStatRemoteHost service.
Once you've started jstatd, use jstat -options process_id@servername command to monitor the remote VM.


text:
Q: Controlling VS code with a launchpad I really enjoy using vs code but there are some many shortcuts to remember and every new plugins come with a new set.
Of course, I can use the command palette in order to quickly execute a command, but I would like something even more faster such as assigning a shortcut to any of the keys for a device like a Novation Launchpad midi controller.
Stackoverflow is maybe not the best plase to ask this question but I didn't knew where to post it, so is there anyone who tried something like this? I have seen this video (https://www.youtube.com/watch?v=LOyNUGS4RC8) linking such a device with visual studio so perhaps someone created a software dedicated for vs code already.
Regards,
Johnny -

A: I've setup this with MIDI Loupe and midiStroke.
MIDI Loupe listens your device and logs channel/key/value you just hit on your midi controller - with this tool you inspect your device's output.
Then in midiStroke you map controls to shortcuts.
Note: I've found my midiStroke setup for M-Audio Axiom 49 keys don't require values (only key number) but controls (e.g. record start) do require it. Also for me letter keys didn't not work if uppercased (e.g. for garageband recording start I need simply R button hit and R should be r in this case)
Detailed tutorial here


text:
Q: How can I use jQuery to assign every element in a class its current height to its data-height attribute? So if I were dealing with just one element, I could use the following:
$("#id").attr( "data-height" , $("#id").css("height") );

But is there any way to do this with every element in a class?

A: $('.myElem').each(function() {

    $this = $(this);
    $this.attr('data-height', $this.height());

});

You could also just use the .data() method
$('.myElem').each(function() {

    $this = $(this);
    $this.data('height', $this.height());

});

A: $('.className').children().each(function(i, obj) {
  $(obj).attr('data-height', $(obj).css('height'));
});


text:
Q: node.js - attaching event handlers on time I'm studying node.js and came across this example in the node.js manual:
...
var req = http.request(options);
req.end();

req.on('upgrade', function(res, socket, upgradeHead) {
  console.log('got upgraded!');
  socket.end();
  process.exit(0);
});
...

What I see in this example is that handler attached to an event of HTTP request, after the request is created and even after it is (scheduled to be) sent. To make things even worse, manuals says:

If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.

Isn't it possible for the event to occur before req.on(... had a chance to attach a handler ? I suspect I don't understand something in node's asynchronous model. Or this code from node manual designed in hope that network request will take longer than executing next line of code ?!
Another example:
http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Here, HTTP request will be initiated immediately after the object created, and we attach an error handler only afterwards. Again, (1) is it a code that works only because of
network latencies, (2) I don't get something about node.js concepts, or (2b) event will "wait" until I attach a handler to it ?
EDIT:
Even better example, also from manual. Good and Bad examples below are different only because in the good one we attach the event quick enough and thus have low chances to miss data, or it is never possible to miss data this way (and why ?!)
// Good
request.on('response', function (response) {
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

// Bad - misses all or part of the body
request.on('response', function (response) {
  setTimeout(function () {
    response.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  }, 10);
});

A: What you miss is that JavaScript isn't asynchronous at all! What I mean is that JavaScript is single-threaded and asynchronous operations are actually not asynochronous. There is a very fancy queue model which gives as the illusion of JavaScript being asynchronous (don't get me wrong: it still is the most efficient model).
So what does it mean? It means that once the synchronous code is running it is impossible for other code to be running parallely. So for example in this code
var req = http.request(options);
req.end();
req.on(...);

the request is scheduled, but the main thread (i.e. the operation) hasn't ended at req.end(). As long as the main operation has not finished no asynchronous code can fire in-between. In particular the handler is always set before the actual event has any chance to occure.
One more example to make it a bit clearer. Consider this code:
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
    while(true) { } // <------ infinite loop doing nothing
}).listen(1337, '127.0.0.1');

Note that the first request will finish with success. But any other request will never get a response. This is because the loop will never finish the operation and JavaScript cannot jump to another event because of it. This code permamently crashes the app beyond any hope. So be careful with synchronous code with Node.js. :)

A: The key thing to understand is that there is only a single event loop and control ONLY leaves the current "tick" of the event loop when you call an asynchronous function. Usually this happens naturally when you do I/O (every few lines of code is common) or call setTimeout/setInterval (fairly rare). So as long as all of your event handlers are registered within the same tick of the event loop, you will never loose any data. Moreover, within that tick of the event loop, it doesn't matter what order you attach your handlers, because during that tick your code is literally the only thing node is executing, so no other code can receive I/O or invoke any event handlers until the current event loop tick completes. It's not about waiting "long enough" or network latency or anything like that. It's the simplicity of a single event loop that guarantees predictable operation with regard to the event handler functions.


text:
Q: How to combine data from different Excel tabs into master sheet using VBA I am using the below script to copy data from "Sheet1" of a multi-sheet Excel file into a master sheet of another Excel file. It's working perfectly for one sheet. Now I need to get it to run through all the sheets pasting the data into the next available row in the Master file.
Please note: all the sheets use the same password.
Please help!
Thanks,
Yohanan
Sub CopyRanges()
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim LastRow As Long

Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\Datafile.xls")

Sheets("Sheet1").Unprotect ("Password1")

With WB2.Sheets("Sheet1")
  LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
End With
WB2.Sheets("71235").Range("B6:M" & LastRow).Copy
WB1.Sheets("Output").Range("A2").PasteSpecial xlPasteValues

Sheets("Sheet1").Protect ("FTCCTOR")
WB2.Close
End Sub

A: Try this:
Sub CopyRanges()
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim LastRow As Long
Dim sht As Worksheet

Set WB1 = ActiveWorkbook
Set WB2 = Workbooks.Open(WB1.Path & "\Datafile.xls")

For Each sht In WB2.Sheets
    With sht
        .Unprotect ("Password1")
        LastRow = .Range("B" & .Rows.count).End(xlUp).Row
        WB1.Sheets("Output").Range("A" & WB1.Sheets("Output").Rows.count).End(xlUp).Resize(LastRow - 5, 12).value = .Range("B6:M" & LastRow).value
        .Protect ("Password1")
    End With
Next sht
WB2.Close
End Sub

When only wanting the values it is faster to assign the values than to copy them.


text:
Q: How to Read Request Input from Route? Okay so i am having some trouble. I am trying to read the Input Values from the Post Form in Laravel. However i am getting a Method Not Allowed.
My Routes:

Route::get('/', function () {
    return View::make('pages/home');
});

Route::post('/summoner/data', function (Request $request) {
    return redirect()->url($request->region .'/'. $request->summonername);
});

Error:
[![Error I am getting][1]][1]

As you can see from above code i am trying to send my details to an Api. I am not sure if this is the best way of doing it though so i am open to suggestions. But at the moment i cannot read any Input Data from the Form.

A: You can easily do this assuming you already injected the Request
// Request is injected to the closure
Route::post('/summoner/data', function (Request $request) {

  // To see the whole POST body
  $bodyContent = $request->getContent();
  dd($bodyContent);

  // Get fullname input
  echo $request->get('fullname')

});