Q:

Should Repositories's services depend on each other?

Assume I have 2 entities Foo and Bar as follows:
public class Foo
{
    public int FooID {get;set;}
    public string FooName {get;set;}
}

public class Bar
{
    public int BarID {get;set;}
    public string BarName {get;set;}
    public int FooID {get;set;}
}

For each entity will have its repository:
public class FooRepository
{
    public IEnumerable<Foo> getFoo()
    {
        //do something
    }
}

public class BarRepository
{
    public IEnumerable<Bar> getBar()
    {
        //do something
    }

    public IEnumerable<Bar> getBar(int FooID)
    {
        //get bar base on foo id
    }
}

Each of those repositories will have an associated service:
public class FooService
{
    //depend on Foo repository
}

public class BarService
{
    //depend on Bar repository
}

Now I want to make a function to see if a Foo is in used in Bar. I thought of 2 methods to implement this function:
Method 1:
public class BarService
{
    private BarRepository repository = new BarRepository();

    public bool isFooExisted(int FooID)
    {
        var bars = this.repository.getBar(FooID);
        return bars.Count > 0;
    }
}

Somehow, this is look like it is violating Single Responsible Principle since BarService is used to check for a Foo. So I came up with method 2:
Method 2:
public class BarService
{
    private BarRepository repository = new BarRepository();

    public IEnumerable<Bar> getBar(int FooID)
    {
        return this.repository.getBar(FooID);
    }
}

public class FooService
{
    private BarService service = new BarService();

    public bool isFooExisted(int FooID)
    {
        var bars = service.getBar(FooID);
        return bars.Count > 0;
    }
}

I wonder is it a good idea for services depend on each other like this. Please suggest me which one of those method above is good to follow or any other method will help

A:

I personally would avoid services using other services because sooner or later you'll get a circular reference. Having the services not depend on each other also makes for looser coupling and ease of testability. So i would go for method 1.
The problem with this approach comes when you want to reuse functionality between services. In your case you can just defer calls to the respective repository, but in more complex cases you may need to add a domain object that contain common business logic that can be re-used in the different services. For example, if you had to have a complex isFooExisted method in both services, you might do something like this (note that I have changed your code to use dependency injection to make your code more testable):
public class BarService
{
    private FooEntity fooEntity;

    public BarService(IFooRepository repository)
    {
        this.fooEntity = new FooEntity(repository);
    }

    public IEnumerable<Foo> getFoo(int FooID)
    {
        return fooEntity.getFoo(FooID);
    }
}

public class FooService
{
    private FooEntity fooEntity;

    public FooService(IFooRepository repository)
    {
        this.fooEntity = new FooEntity(repository);
    }

    public IEnumerable<Foo> getFoo(int FooID)
    {
        return fooEntity.getFoo(FooID);
    }
}

public class FooEntity
{
    private IFooRepository repository;

    public FooEntity(IFooRepository repository)
    {
        this.repository = repository;
    }

    public bool isFooExisted(int FooID)
    {
        /** Complex business logix **/
    }
}

And for the simple case I'd just use the same repository directly and not have the domain object:
public class BarService
{
    private IFooRepository repository;

    public BarService(IFooRepository repository)
    {
        this.repository = repository;
    }
    ...
}

public class FooService
{
    private IFooRepository repository;

    public FooService(IFooRepository repository)
    {
        this.repository = repository;
    }
    ...
}

Hope this helps.


Q:

Need help with MAAS

I'm new to MAAS and I'm trying to setup my first cluster.
My cluster will consist of 3 servers:
1x Master [M001] (Web UI, DHCP, PXE boot etc.)
2x Node [Fancy-Cord & Polished-Ghost] (MySQL, Apache webserver etc.)
Yet, I cannot seem to figure out how it works.
I have 2 NICs on M001, 1 which is connected to my home network (eth0), and 1 connected to a switch (SW015) for the nodes (eth1).
when I type ifconfig in the console, it only showsup eth0...

When I bootup one of my (should become) nodes (Fancy-cord of Polished-Ghost, doesn't matter), and have them go for the PXE, it shows:
pxe-e18 server response timeout
also, when I attach a laptop (with windows 8.1) to SW015, it seems DHCP doesn't do anything, how do I fix this? (since I think solving the DHCP issue might help me solve the issue of PXE)
If you need additional information, feel free to ask, but don't expect me to be a wizard knowing where everything is found (I'm VERY new to MAAS)
UPDATE1:
This is how my networks tab looks like (http://M001/MAAS/networks/Cluster/edit/)

UPDATE2:
Managed to get a littlebit of progress (I guess)
Instead of pxe-e18 server response timeout I now get pxe-e51: No DHCP or proxyDHCP offers were received

A:

Managed to have it to work!
I had to go in the /etc/network/interfaces file and add:
auto eth1
iface eth1 inet static
    address 10.0.0.1
    netmask 255.255.255.0


Q:

Вывод AlertDialog'a в IntentService'e

Ребята, есть задача, не знаю как подойти.
В методе override onHandleIntent есть try catch, в который мне нужно засунуть вывод AlertDialog, как правильно это сделать, я не знаю, так как тут интерфейса нет(+ получается придётся стучатсья в активити)?
Код класса
class GcmRegistrationIntentService : IntentService("GcmRegistrationIntentService") {

override fun onHandleIntent(intent: Intent?) {
    try {
        val gcmSenderId = FlavorSettings.gcmSenderId
        val systemToken = if (gcmSenderId.isEmpty()) gcmSenderId
            else InstanceID.getInstance(this).getToken(gcmSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null)
        if (PreferenceRepository.gcmToken != systemToken) {
            PreferenceRepository.gcmToken = systemToken
            if (UserSession.isUserSignedIn() && ProfilesRepository.lastProfile() != null) {
                JobManager.scheduleAutoSync()
            }
        }
    } catch (e: Exception) {
        e.log()
    }
}

}

A:

Вывод диалога из Service является антипаттерном. Сервис - это по определению то что должно работать в фоне и естественно пытаться из него что-то вывести на уровень UI выглядит мягко говоря сомнительно.
Рекомендуемые варианты:

Отправить бродкаст, который будет выловлен где-то и обработан
Вывести нотификацию или тоаст
Воспользоваться стандартным паттерном взаимодействия сервиса с Activity и уже в Activity обработать диалог.

Но если уж совсем неймется, то посмотрите лайфхак предлагаемый в Хабре
Update
По поводу хаков с EventBus/otto/rxJava отвечу лишь одной цитатой:

A common misunderstanding about Android multitasking is the difference between a process and an application. In Android these are not tightly coupled entities: applications may seem present to the user without an actual process currently running the app; multiple applications may share processes, or one application may make use of multiple processes depending on its needs; the process(es) of an application may be kept around by Android even when that application is not actively doing something.

В вольном переводе это означает, что невозможно гарантировать, что приложение и сервис будут всегда находиться в пределах одного процесса.
Коли уж так, то наверное иногда связка Activity-Service через EventBus будет работать, но это же наверное не совсем то чего мы хотим, не правда ли?

A:

А задумка из комментария на самом деле неплохая.
В своём сервисе стучитесь с помощью EventBus'a в класс:
EventBus.getDefault().post(ErrorEvent())

В самом классе ErrorEvent в зависимости от Ваших потребностей добавляйте нужные поля.
Ну а далее, то место(фрагмент/активити) в которое вы хотите поместить реализуйте Ваш AllertDialog в методе onEvent, передавая в него аргументы этого пустого класса(также дополнительно в аннотацию стоит прописать ThreadMode.MAIN):
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEvent(event: ErrorEvent) {
    //some functions ...
}

Ну и не забывайте в этом классе в методе onStart реализовать:
EventBus.getDefault().register(this)

И в методе onStop:
EventBus.getDefault().unregister(this)

Upd:
Так как Android по умолчанию строит работу приложения в один процесс, то волноваться не стоит по поводу их работы в разных процессах. Если же Вы не уверены, то загляните в AndroidManifest.xml и просмотрите атрибут process в Вашем приложении и убедитесь что нет различий.


Q:

splitting up of xml file using java

< ?xml version="1.0" encoding="utf-8"? >
   < rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:ynews="http://news.yahoo.com/rss/" version="2.0" >  < channel >
< title>Cricket News Headlines | Cricket News - Yahoo! News India< /title>
< link>http://in.news.yahoo.com/cricket/< /link>
< description>Check out the latest Cricket news headlines from Yahoo! News India. Find top Cricket stories and in-depth coverage of
  Cricket news from India and around the world.< /description>
< language>en-IN< /language>
< copyright>Copyright (c) 2011 Yahoo! Inc. All rights reserved< /copyright>
< pubDate>2011-04-06T15:30:02+05:30< /pubDate>
< ttl>5< /ttl>
< image>
< title>Cricket News Headlines | Cricket News - Yahoo! News India< /title>
< link>http://in.news.yahoo.com/cricket/< /link>
< url>http://l.yimg.com/os/mit/media/m/index/img/Yahoo_logo_en-
  IN.gif< /url>
< /image>
  < item>< title>Hectic schedule will drain players, says Dhoni< /title>
< description>Chennai, Apr 6 (PTI) ...< /description>
< link>http://in.news.yahoo.com/hectic-schedule-drain-players-says-dhoni-20110406-023100-889.html< /link>
< pubDate>2011-04-06T09:31:00Z< /pubDate>
< source>PTI< /source>
< guid isPermaLink="false">/hectic-schedule-drain-players-says-dhoni-20110406-023100-889.html< /guid>
< /item>
< item>
< title>India, Pakistan trade secretaries to meet on April 27-28< /title>
< description>New Delhi, Apr 6 (PTI)  ...< /description>
< link>http://in.news.yahoo.com/india-pakistan-trade-secretaries-meet-april-27-28-20110406-023100-140.html< /link>

I want only the HEADLINES  from this XML, that is only between < item>< title>MESSAGES< /title> tags.  Also have to print the message one after other continuously. how can i do this.

A:

I would use the javax.xml.xpath APIs that are included in Java SE 5 for this.
import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        XPath xPath = XPathFactory.newInstance().newXPath();

        FileReader reader = new FileReader("input.xml");
        InputSource xml = new InputSource(reader);
        NodeList titleNodes = (NodeList) xPath.evaluate("//item/title", xml, XPathConstants.NODESET);

        for(int x=0; x<titleNodes.getLength(); x++) {
            System.out.println(titleNodes.item(x).getTextContent());
        }
    }

}


Q:

CSS element selector is more specific than HTML attributes?

Ok so here's a simple test case
What I was trying is that, if we use attributes to style elements(I know which is a very very bad idea, but I did it for experimentation)
So the question is that is CSS basic element selector styles more specific than HTML attributes?
Kinda CSS - 1 / HTML - 0
If CSS not used, HTML - 1
Test Case HTML

        Hello 1
        Hello 2
        Hello 3

CSS
table, table td {
    border: 0;
}

So overall CSS is specific than HTML for styling? Or is there anything we can override CSS with attributes except the style attribute.

A:

From the CSS 2.1 specification:

The UA may choose to honor presentational attributes in an HTML source document. If so, these attributes are translated to the corresponding CSS rules with specificity equal to 0, and are treated as if they were inserted at the start of the author style sheet. They may therefore be overridden by subsequent style sheet rules. In a transition phase, this policy will make it easier for stylistic attributes to coexist with style sheets.

Similar language exists in CSS Cascading and Inheritance Level 3

So overall CSS is specific than HTML for styling?

Yes. Don't use HTML for styling. We have CSS now.

Or is there anything we can override CSS with attributes except the style attribute

Nothing. The style attribute is just a way to apply CSS to an element anyway. (As is using JavaScript to modify the DOM properties generated by the style attribute.)


Q:

calendar scheduler algorithm

I'm looking for an algorithm that, given a set of items containing a start time, end time, type, and id, it will return a set of all sets of items that fit together (no overlapping times and all types are represented in the set).
S = [("8:00AM", "9:00AM", "Breakfast With Mindy", 234),
     ("11:40AM", "12:40PM", "Go to Gym", 219),
     ("12:00PM", "1:00PM", "Lunch With Steve", 079),
     ("12:40PM", "1:20PM", "Lunch With Steve", 189)]

Algorithm(S) => [[("8:00AM", "9:00AM", "Breakfast With Mindy", 234),
                  ("11:40AM", "12:40PM", "Go to Gym", 219),
                  ("12:40PM", "1:20PM", "Lunch With Steve", 189)]]

Thanks!

A:

This can be solved using graph theory. I would create an array, which contains the items sorted by start time and end time for equal start times: (added some more items to the example):
no.:  id: [ start  -   end  ] type
---------------------------------------------------------
 0:  234: [08:00AM - 09:00AM] Breakfast With Mindy
 1:  400: [09:00AM - 07:00PM] Check out stackoverflow.com
 2:  219: [11:40AM - 12:40PM] Go to Gym
 3:   79: [12:00PM - 01:00PM] Lunch With Steve
 4:  189: [12:40PM - 01:20PM] Lunch With Steve
 5:  270: [01:00PM - 05:00PM] Go to Tennis
 6:  300: [06:40PM - 07:20PM] Dinner With Family
 7:  250: [07:20PM - 08:00PM] Check out stackoverflow.com

After that i would create a list with the array no. of the least item that could be the possible next item. If there isn't a next item, -1 is added:
 0 |  1 |  2 |  3 |  4 |  5 |  6 |  7
 1 |  7 |  4 |  5 |  6 |  6 |  7 | -1

With that list it is possible to generate a directed acyclic graph. Every vertice has a connection to the vertices starting from the next item. But for vertices where already is a vertices bewteen them no edge is made. I'll try to explain with the example. For the vertice 0 the next item is 1. So a edge is made 0 -> 1. The next item from 1 is 7, that means the range for the vertices which are connected from vertice 0 is now from 1 to (7-1). Because vertice 2 is in the range of 1 to 6, another edge 0 -> 2 is made and the range updates to 1 to (4-1) (because 4 is the next item of 2). Because vertice 3 is in the range of 1 to 3 one more edge 0 -> 3 is made. That was the last edge for vertice 0. That has to be continued with all vertices leading to such a graph:

Until now we are in O(n2). After that all paths can be found using a depth first search-like algorithm and then eliminating the duplicated types from each path.
For that example there are 4 solutions, but none of them has all types because it is not possible for the example to do Go to Gym, Lunch With Steve and Go to Tennis.
Also this search for all paths has a worst case complexity of O(2n). For example the following graph has 2n/2 possible paths from a start vertice to an end vertice.

(source: archive.org)
There could be made some more optimisation, like merging some vertices before searching for all paths. But that is not ever possible. In the first example vertice 3 and 4 can't be merged even though they are of the same type. But in the last example vertice 4 and 5 can be merged if they are of the same type. Which means it doesn't matter which activity you choose, both are valid. This can speed up calculation of all paths dramatically.
Maybe there is also a clever way to consider duplicate types earlier to eliminate them, but worst case is still O(2n) if you want all possible paths.
EDIT1:
It is possible to determine if there are sets that contain all types and get a t least one such solution in polynomial time. I found a algorithm with a worst case time of O(n4) and O(n2) space. I'll take an new example which has a solution with all types, but is more complex.
no.:  id: [ start  -   end  ] type
---------------------------------------------------------
 0:  234: [08:00AM - 09:00AM] A
 1:  400: [10:00AM - 11:00AM] B
 2:  219: [10:20AM - 11:20AM] C
 3:   79: [10:40AM - 11:40AM] D
 4:  189: [11:30AM - 12:30PM] D
 5:  270: [12:00PM - 06:00PM] B
 6:  300: [02:00PM - 03:00PM] E
 7:  250: [02:20PM - 03:20PM] B
 8:  325: [02:40PM - 03:40PM] F
 9:  150: [03:30PM - 04:30PM] F
10:  175: [05:40PM - 06:40PM] E
11:  275: [07:00PM - 08:00PM] G

1.) Count the different types in the item set. This is possible in O(nlogn). It is 7 for that example.
2.) Create a n*n-matrix, that represents which nodes can reach the actual node and which can be reached from the actual node. For example if position (2,4) is set to 1, means that there is a path from node 2 to node 4 in the graph and (4,2) is set to 1 too, because node 4 can be reached from node 2. This is possible in O(n2). For the example the matrix would look like that:
111111111111
110011111111
101011111111
100101111111
111010111111
111101000001
111110100111
111110010111
111110001011
111110110111
111110111111
111111111111

3.) Now we have in every row, which nodes can be reached. We can also mark each node in a row which is not yet marked, if it is of the same type as a node that can be reached. We set that matrix positions from 0 to 2. This is possible in O(n3). In the example there is no way from node 1 to node 3, but node 4 has the same type D as node 3 and there is a path from node 1 to node 4. So we get this matrix:
111111111111
110211111111
121211111111
120121111111
111212111111
111121020001
111112122111
111112212111
111112221211
111112112111
111112111111
111111111111

4.) The nodes that still contains 0's (in the corresponding rows) can't be part of the solution and we can remove them from the graph. If there were at least one node to remove we start again in step 2.) with the smaller graph. Because we removed at least one node, we have to go back to step 2.) at most n times, but most often this will only happend few times. If there are no 0's left in the matrix we can continue with step 5.). This is possible in O(n2). For the example it is not possible to build a path with node 1 that also contains a node with type C. Therefore it contains a 0 and is removed like node 3 and node 5. In the next loop with the smaller graph node 6 and node 8 will be removed.
5.) Count the different types in the remainig set of items/nodes. If it is smaller than the first count there is no solution that can represent all types. So we have to find another way to get a good solution. If it is the same as the first count we now have a smaller graph which still holds all the possible solutions. O(nlogn)
6.) To get one solution we pick a start node (it doesn't matter which, because all nodes that are left in the graph are part of a solution). O(1)
7.) We remove every node that can't be reached from the choosen node. O(n)
8.) We create a matrix like in step 2.) and 3.) for that graph and remove the nodes that can not reach nodes of any type like in step 4.). O(n3)
9.) We choose one of the next nodes from the node we choosen before and continue with 7.) until there we are at a end node and the graph only has one path left.
That way it is also possible to get all paths, but that can still be exponential many. After all it should be faster than finding solutions in the original graph.


Q:

Pyspark String and list of objects

I have a string with a
https://hdchjhjedjekdn.com/{}_public.xml with a place holder and I have list of objects
201611339349202661,
 201611309349201761,
 201543179349200944,
 201631099349200733,
 201610909349200511,
 201630749349201058,
 201601319349200235,
 201641069349200909,
 201542999349200004,
 201611319349201771,
 201641329349200119,
 201513219349200536,
 201543159349201769,
 201612029349200631,
 201621339349202247,
 201611259349200506,
 201611829349200301,
 201543169349201114,
 201543209349204979,
 201641039349200509,
 201621309349200642,
 201512789349200031,
 201601939349200520
I would like to fill the placeholder with the list of objects.
Like:
s = (https://hdchjhjedjekdn.com/201611339349202661_public.xml, https://hdchjhjedjekdn.com/201611309349201761_public.xml, https://hdchjhjedjekdn.com/201543179349200944_public.xml,........)
Any help would be appreciated using pyspark

A:

Parallelize your list of ids and broadcast the url string across workers. Then apply map to create the formatted string,
>>>l = [201611339349202661, 201611309349201761, 201543179349200944, 201631099349200733, 201610909349200511, 201630749349201058, 201601319349200235, 201641069349200909, 201542999349200004, 201611319349201771, 201641329349200119, 201513219349200536, 201543159349201769, 201612029349200631, 201621339349202247, 201611259349200506, 201611829349200301, 201543169349201114, 201543209349204979, 201641039349200509, 201621309349200642, 201512789349200031, 201601939349200520]
>>>rdd = sc.parallelize(l)
>>>rdd.getNumPartitions()
12 ## I have used 12 workers
>>>brd_url = sc.broadcast('https://hdchjhjedjekdn.com/{}_public.xml')
>>>rdd1 = rdd.map(lambda x:brd_url.value.format(x))
>>>rdd1.take(2)
['https://hdchjhjedjekdn.com/201611339349202661_public.xml', 'https://hdchjhjedjekdn.com/201611309349201761_public.xml']

Hope this helps.


Q:

Converting array of objects into array for Google Charts

I have an array of objects:
    [
      {
      SalePrice:"18000",
      TotalValue:"22500"
      ratio:1.25
      }
      {
      SalePrice:"128000",
      TotalValue:"212500"
      ratio:1.05
      }
    ]

and I want to form it into an array. like:
[
        [18000,  22500, 1.25],
        [128000,  212500, 1.05]
]

Using JS (ES6 is ok). I have tried using somelike like:
let array = data.map(({SalePrice, TotalValue, ratio}) => SalePrice, TotalValue, ratio).filter(s => s, t = >t, r => r);

but that doesn't work could anyone enlighten me please?

A:

Maybe something like the following:
const data = [{SalePrice:"18000",TotalValue:"22500",ratio:1.25},{SalePrice: "128000",TotalValue:"212500",ratio:1.05}]
const mappedToArray = data.map(d => Array.from(Object.values(d)))
//[["18000", "22500", 1.25],["128000", "212500", 1.05]]

The advantage of this approach is not having to rely on hardcoded keys to access to properties in your object which the other answer does need. Which could also be a disadvantage in it's own if that includes properties Google Charts does not need.


Q:

FB.getLoginStatus() called before calling FB.init()

I want to check if a user is logged-in in facebook using the Facebook JavaScript JDK and jQuery.
But even with a timeout of 10 seconds I get this error message:
FB.getLoginStatus() called before calling FB.init().
Here is my code:

Any ideas on how to get this work?
thanks christian

A:

Hi I think you are calling fb.init without passing your application ID. It should be like this
FB.init({
        appId: "Your API ID",
        status: true,
        cookie: true,
        xfbml: true
});

I hope this will work.

A:

Not a pro at this but have you tried:
FB.Event.subscribe('auth.login', yourFunc);

And yourFunc should have one arg (response) where you check:
response.status == 'connected'


Q:

How to get the current item in view for Semantic Zoom control

I am using Semantic Zoom control to show the list of Contacts in my WinRT application. When I manually scroll the list, I want to get the current item which is in view (there will be more than one items in view, but I would like to get the closest one which is in view). So that I can save the scrolling position to set it as it is when user navigates back to this list of contact.
Any suggestion?
I tried getting the current Selected Index but it never got updated while scrolling through the list:
int lastViewedItem = ((ListViewBase)this.semanticZoom.ZoomedInView).SelectedIndex;

On navigating back
(ListViewBase)this.semanticZoom.ZoomedInView).SelectedIndex = lastViewedItem;

 ((ListViewBase)this.semanticZoom.ZoomedInView).ScrollIntoView(((ListViewBase)this.semanticZoom.ZoomedInView).SelectedItem);

A:

I've created an extension to do just for any known ItemsControl that I knew here.
using System;
using System.Collections;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

/// <summary>
/// Gets the first visible element.
/// </summary>
/// <param name="itemsControl">The ItemsControl.</param>
/// <returns>The first visible item or null if not found.</returns>
public static object GetFirstVisibleItem(this ItemsControl itemsControl)
{
    var index = GetFirstVisibleIndex(itemsControl);

    if (index == -1)
    {
        return null;
    }

    var list = itemsControl.ItemsSource as IList;

    if (itemsControl.ItemsSource != null &&
        list != null &&
        list.Count > index)
    {
        return list[index];
    }

    if (itemsControl.Items != null &&
        itemsControl.Items.Count > index)
    {
        return itemsControl.Items[index];
    }

    throw new InvalidOperationException();
}

/// <summary>
/// Gets the index of the first visible element.
/// </summary>
/// <param name="itemsControl">The ItemsControl.</param>
/// <returns>The index of the first visible item or -1 if not found.</returns>
public static int GetFirstVisibleIndex(this ItemsControl itemsControl)
{
    // First checking if no items source or an empty one is used
    if (itemsControl.ItemsSource == null)
    {
        return -1;
    }

    var enumItemsSource = itemsControl.ItemsSource as IEnumerable;

    if (enumItemsSource != null && !enumItemsSource.GetEnumerator().MoveNext())
    {
        return -1;
    }

    // Check if a modern panel is used as an items panel
    var sourcePanel = itemsControl.ItemsPanelRoot;

    if (sourcePanel == null)
    {
        throw new InvalidOperationException("Can't get first visible index from an ItemsControl with no ItemsPanel.");
    }

    var isp = sourcePanel as ItemsStackPanel;

    if (isp != null)
    {
        return isp.FirstVisibleIndex;
    }

    var iwg = sourcePanel as ItemsWrapGrid;

    if (iwg != null)
    {
        return iwg.FirstVisibleIndex;
    }

    // Check containers for first one in view
    if (sourcePanel.Children.Count == 0)
    {
        return -1;
    }

    if (itemsControl.ActualWidth == 0)
    {
        throw new InvalidOperationException("Can't get first visible index from an ItemsControl that is not loaded or has zero size.");
    }

    for (int i = 0; i < sourcePanel.Children.Count; i++)
    {
        var container = (FrameworkElement)sourcePanel.Children[i];
        var bounds = container.TransformToVisual(itemsControl).TransformBounds(new Rect(0, 0, container.ActualWidth, container.ActualHeight));

        if (bounds.Left < itemsControl.ActualWidth &&
            bounds.Top < itemsControl.ActualHeight &&
            bounds.Right > 0 &&
            bounds.Bottom > 0)
        {
            return itemsControl.IndexFromContainer(container);
        }
    }

    throw new InvalidOperationException();
}


Q:

android expanded notification view

I have an app that puts the date in the status bar, but in order to make it look decent, I have to use two notifications.  This causes it to use two expanded notifications when you pull down the status bar.  Is there any way to get rid of one of the expanded views(or both of them)?

A:

Is there any way to get rid of one of
  the expanded views(or both of them)?

No, sorry.


Q:

Get count of value for 15 min periods

I have a DataFrame with a DateTimeIndex. I would like to get the count of all different (integer) values for column col1 for each 15 min period.
I have looked at groupby and count but this doesn't seem to work.
Any suggestion appreciated!

A:

result = df.groupby(pd.TimeGrouper('15Min')['col1'].apply(lambda x: x.value_counts()))

should do the trick.


Q:

$g(\alpha )=f(\alpha )$

Can anyone help me prove the following?
Let $V$ be a finite dimensional vector space over field $F$ and let $W$ be a subspace of $V$. If $f$ is a linear functional on $W$ , prove there is a linear functional $g$ on $V$ such that $g(\alpha ) = f(\alpha )$ for each $\alpha$ in the subspace $W$.
Thanks in advance..

A:

Hint: Choose a basis $(v_1, \ldots, v_k)$ for $W$ and extend it to a basis $(v_1, \ldots, v_k, \ldots, v_n)$ of $V$. Let $g \colon V \rightarrow \mathbb{F}$ be the unique linear map satisfying
$$ g(v_i) = \begin{cases} f(v_i) & 1 \leq i \leq k, \\ 0 & k + 1 \leq i \leq n. \end{cases} $$


Q:

How to prevent sleeping in Android

I 'm working with GPS in my application. When phone go to sleep, the GPS's data don't update. I want to stay phone screen wake up until my app will be close. How can I prevent sleeping in Android?

A:

Use a WakeLock. Bear in mind that using a WakeLock for a long period of time will drain the battery, which your users may not appreciate.


Q:

How to avoid open-redirect vulnerability and safely redirect on successful login (HINT: ASP.NET MVC 2 default code is vulnerable)

Normally, when a site requires that you are logged in before you can access a certain page, you are taken to the login screen and after successfully authenticating yourself, you are redirected back to the originally requested page. This is great for usability - but without careful scrutiny, this feature can easily become an open redirect vulnerability.
Sadly, for an example of this vulnerability, look no further than the default LogOn action provided by ASP.NET MVC 2:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid) {
        if (MembershipService.ValidateUser(model.UserName, model.Password)) {
            FormsService.SignIn(model.UserName, model.RememberMe);

            if (!String.IsNullOrEmpty(returnUrl)) {
                return Redirect(returnUrl); // open redirect vulnerability HERE
            } else {
                return RedirectToAction("Index", "Home");
            }

        } else {
            ModelState.AddModelError("", "User name or password incorrect...");
        }
    }

    return View(model);
}

If a user is successfully authenticated, they are redirected to "returnUrl" (if it was provided via the login form submission).
Here is a simple example attack (one of many, actually) that exploits this vulnerability:

Attacker, pretending to be victim's bank, sends an email to victim containing a link, like this: http://www.mybank.com/logon?returnUrl=http://www.badsite.com
Having been taught to verify the ENTIRE domain name (e.g., google.com = GOOD, google.com.as31x.example.com = BAD), the victim knows the link is OK - there isn't any tricky sub-domain phishing going on.
The victim clicks the link, sees their actual familiar banking website and is asked to logon
Victim logs on and is subsequently redirected to http://www.badsite.com which is made to look exactly like victim's bank's website, so victim doesn't know he is now on a different site.
http://www.badsite.com says something like "We need to update our records - please type in some extremely personal information below: [ssn], [address], [phone number], etc."
Victim, still thinking he is on his banking website, falls for the ploy and provides attacker with the information

Any ideas on how to maintain this redirect-on-successful-login functionality yet avoid the open-redirect vulnerability?
I'm leaning toward the option of splitting the "returnUrl" parameter into controller/action parts and use "RedirectToRouteResult" instead of simply "Redirect". Does this approach open any new vulnerabilities?
Update
By limiting myself to controller/action routes, I can't redirect to custom routes (e.g. /backend/calendar/2010/05/21). I know that by passing more parameters to the LogOn action, I could get it to work, but I feel like I'll always be revisiting this method -- keeping it up to date with our routing scheme. So, instead of splitting the returnUrl into its controller/action parts, I am keeping returnUrl as-is and parsing it to make sure it contains only a relative path (e.g., /users/1) and not an absolute path (e.g., http://www.badsite.com/users/1). Here is the code I'm using:
private static bool CheckRedirect(string url) {
    try {
        new Uri(url, UriKind.Relative);
    }
    catch (UriFormatException e) {
        return false;
    }

    return true;
}

Side note: I know this open-redirect may not seem to be a big deal compared to the likes of XSS and CSRF, but us developers are the only thing protecting our customers from the bad guys - anything we can do to make the bad guys' job harder is a win in my book.
Thanks, Brad

A:

Jon Galloway wrote up an article with a solution for MVC 2 (and 1).
Here's the snippet that should help with your issue:
SECURED (original article updated 2014)
private bool IsLocalUrl(string url)
{
  return System.Web.WebPages.RequestExtensions.IsUrlLocalToHost(
      RequestContext.HttpContext.Request, url);
}

A:

Yes this is a vulnerability. Before redirecting you need to inspect the returnUrl string parameter by passing it to a Uri object and make sure that the target domain is the same as the requesting domain. You should also take into account the case when returnUrl is a relative address like /admin. No problem in this case as the redirect will be to the same application.


Q:

Get rows of a Telerik RadGrid

I'm working on a RadGrid, and I want to access its rows but it seems it does not have a .Rows property.
Here's what I have tried until now:

How can I access rgCustomers's Rows collection? I want to add a button to each row.

A:

According to Telerik's documentation,
"Each dynamic row in the grid represents a record from the specified data source. Dynamic rows are represented by the GridDataItem class (a descendent of GridItem).
Each GridTableView has a set of rows (the Items collection) of type GridDataItem."
So you want to use the Items collection of the grid, which is a collection of GridDataItems.
protected void btnLoad_Click(object sender, EventArgs e)
{
  rgCustomers.DataSource = odsCustomers;
  rgCustomers.DataBind();
  foreach (GridDataItem row in rgCustomers.Items)
  {
  }
}

A:

I'm assuming it's WPF/Silverlight RadGrid?
If You want to access row control in databound grid  (not row data) - You'll have to use ItemContainerGenerator property of RadGrid. For example:
rgCustomers.ItemContainerGenerator.ContainerFromIndex(0);

or
rgCustomers.ItemContainerGenerator.ContainerFromItem(odsCustomers[0]);

will return first row control (of type RadGridViewRow if I remember correctly)


Q:

How to import date column from csv in python in format d/m/y

I have a data sheet in which issue_d is a date column having values stored in a format - 11-Dec. On clicking any cell of the column, date is coming as 12/11/2018.
But  while reading the csv file, issue_d is getting imported as 11-Dec. Year is not getting imported.
How do I get the issue_d column in format- d/m/y?
Code i tried -
import pandas
data=pandas.read_csv('Project_data.csv')
print(data)

checking issue_d column: data['issue_d']
result :
0         11-Dec
1         11-Dec
2         11-Dec

expected:
0         11-Dec-2018
1         11-Dec-2018
2         11-Dec-201

A:

You can use to_datetime with add year to column:
df['issue_d'] = pd.to_datetime(df['issue_d'] + '-2018')
print (df)
     issue_d
0 2018-12-11
1 2018-12-11
2 2018-12-11


Q:

How to authenticate without prompt to CRM Dynamics Online webservices with ADAL, NetStandard, and Azure AD

I'm currently trying to create a Xamarin App in order to get some info from a Dynamics 365 online instance. The code that authenticate with AD and access the CRM api is deported in a NetStandard (v1.6) Library.
I use the following NuGets :

Microsoft.IdentityModel.Clients.ActiveDirectory (3.13.9)
NETStandard.Library (1.6.1)

I followed the following tutorial in order to link AD with my Dynamics instance : https://nishantrana.me/2016/11/13/register-a-dynamics-365-app-with-azure-active-directory/
Here is my ActiveDirectory helper :
public static class ADHelper
    {

        public async static Task<AuthenticationResult> GetAuthAsync(Uri uri, ClientCredential creditential)
        {
            AuthenticationParameters ap = await AuthenticationParameters.CreateFromResourceUrlAsync(uri);

            String authorityUrl = ap.Authority;
            String resourceUrl = ap.Resource;

            AuthenticationResult result = null;

            AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
            result = await authContext.AcquireTokenAsync(resourceUrl, creditential);
            return result;
        }
    }

And my CRM API Client :
public class CRMClient
{
    private AuthenticationResult Auth { get; set; }
    private Uri baseUri { get; set; }

    public CRMClient(Uri uri, ClientCredential creditential)
    {
        baseUri = uri;
        Auth = ADHelper.GetAuthAsync(uri, creditential).Result;
    }

    public void getObject()
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Auth.AccessToken);
            client.Timeout = new TimeSpan(0, 2, 0);
            client.BaseAddress = baseUri;
            HttpResponseMessage message = client.GetAsync("/accounts").Result;
            String content = message.Content.ReadAsStringAsync().Result;
        }
    }

Parameters used for CRMClient Constructor :

https://[my_crm_instance_Url]/api/data/v8.2/ => the data OData endpoint
ClientCredential(AppId, AppKey) => as credential

Azure AD gives me a token back, but UserInfo, TenantId and idToken are all null (This could be a part of the cause of my problem).
Currently, the returned content is the HTML office 365 login page instead of the data I wanted to get.
Could someone help me?

A:

I create a full blog post here
http://phuocle.net/crm/dynamics-365-online-s2s-authentication-full-explain.aspx


Q:

How can I make bullets be vertically aligned on a unordered list?

How can I align all my bullets perfectly?
Expected result: Bullets line up to one another
Actual result: They move depending on how big the text is for the
JSFiddle for clarification:
https://jsfiddle.net/hk12hhp1/
Result I want (look at red line):
http://prntscr.com/grt24m (make bullets aligned just like red line is straight)
Fiddle code:

test1wef

test2ferwfwergwerg

test3grew

#center-everything{
  text-align: center;
  background-color: gray;
  height:  100px;
  width:  200px;
  list-style-position: inside;
}

Note: I still want text-align to be center

A:

An alternative solution, using pseudo-element to create the bullet, with position: absolute positioning it on the left.

#center-everything {
  text-align: center;
  background-color: gray;
  height: 100px;
  width: 200px;
  list-style-position: inside;
}

ul {
  list-style: none;
}

li {
  padding-left: 20px;
  position: relative;
}

li:before {
  content: '☻';
  position: absolute;
  left: 0;
  top: 1px;
  font-size: 10px;
}

test1wef

test2ferwfwergwerg

test3grew


Q:

How to simplify an expression with absolute and log functions?

I'm confused with regard to simplifying this expression:
$$
|x| - |x-A| > \ln(\Gamma)
$$
I was thinking of taking square on both ends, and that's basically where I got confused. Should I square the whole left side of the expression, i.e. $(|x| - |x-A|)^2$ or can I get away with just squaring them individually?
If I decide to square them individually, I get the following:
$$
 2Ax - A^2 > (\ln(\Gamma))^2
$$
Finally:
$$
x > (\ln(\Gamma)^2 + A^2)/2A
$$
Am I doing this correctly?

A:

No, you can't square terms being added together individually. For instance, this is true:
$$1+1=2,$$
but this is not:
$$1^2+1^2=2^2.$$
Depending on what you want, you could make a number of simplifications. One would be to multiply by $|x|+|x-A|$, creating a difference of squares on the left to get:
$$x^2-(x-A)^2 > \ln(\Gamma)(|x|+|x-A|).$$
If you want to get rid of every absolute value, then you'll have to square multiple times. For instance, assuming both sides are positive, you can square the whole expression to get
$$x^2+(x-A)^2 -|x(x-A)|>\ln(\Gamma)^2$$
And then rearrange to get
$$x^2+(x-A)^2-\ln(\Gamma)^2>|x(x-A)|$$
and then square again (since both sides are positive now, assuming their were initially)
$$(x^2+(x-A)^2-\ln(\Gamma)^2)^2>x^2(x-A)^2$$
which has no absolute values.

However, algebraic manipulations are not a particularly good way to attack this sort of problem. If we split into cases, then we can get rid of the absolute values entirely; for instance, if we assume $A$ is positive (it's easy to work out the necessary modifications if it negative) we split into cases:

Case 1: $x\leq 0$. Then $x-A<0$ so $|x|=-x$ and $|x-A|=-x+A$. Thus the inequality is $-A > \ln(\Gamma)$ in this case.
Case 2: $0\leq x \leq A$. Then $|x|=x$ and $|x-A|=-x+A$. The inequality is $2x - A > \ln(\Gamma)$ in this case.
Case 3: $A \leq x$. Then $|x|=x$ and $|x-A|=x-A$. The inequality is $A>\ln(\Gamma)$ in this case.

We can quickly work out constraints on $x$ assuming $A$ is positive - in particular, if $-A>\ln(\Gamma)$, then all $x$ satisfy the inequality. If $A\leq \ln(\Gamma)$, then no $x$ satisfy the inequality. If $-A\leq \ln(\Gamma)<A$, then any $x$ greater than $\frac{\ln(\Gamma)+A}2$ satisfies the inequality.


Q:

How do you find the value of $\sum_{r=0}^{44} \tan^2(2r+1)$?

Problem:
Find the value of $$\sum_{r=0}^{44} \tan^2(2r+1)$$
Note: The angles here are in degrees.

I don't know how to solve this question because trigonometric simplifications didn't get me anywhere. I think there was a method to solve this question using complex numbers which I no longer remember. Any hint/help will be appreciated.

A:

Using an idea similar to this answer, note that the function
$$
\frac{90/z}{z^{90}-1}
$$
has residue $1$ for $z=e^{k\pi i/45}$ and residue $-90$ at $z=0$.
On $|z|=1$,
$$
\tan(\theta/2)=-i\frac{z-1}{z+1}
$$
Integrating
$$
f(z)=-\left(\frac{z-1}{z+1}\right)^2\frac{90/z}{z^{90}-1}
$$
around a large circle is $0$ since the integrand is approximately $|z|^{-91}$. Thus, the sum of residues is
$$
2\sum_{k=0}^{44}\tan^2\left(\frac{2k\pi}{180}\right)+\operatorname*{Res}_{z=0}f(z)+\operatorname*{Res}_{z=-1}f(z)=0
$$
Since $\operatorname*{Res}\limits_{z=0}f(z)=90$ and $\operatorname*{Res}
\limits_{z=-1}f(z)=-\frac{8102}{3}$, we get
$$
\begin{align}
\sum_{k=0}^{44}\tan^2\left(\frac{2k\pi}{180}\right)
&=\frac12\left(\frac{8102}{3}-90\right)\\
&=\frac{3916}{3}
\end{align}
$$
The sum in the question is the difference between the value in answer cited above and this value, that is
$$
\begin{align}
\sum_{k=0}^{44}\tan^2\left(\frac{(2k+1)\pi}{180}\right)
&=\frac{15931}{3}-\frac{3916}{3}\\
&=4005
\end{align}
$$

A:

Using Sum of tangent functions where arguments are in specific arithmetic series,
$$\tan90x=\dfrac{\binom{90}1t-\binom{90}3t^3+\cdots+\binom{90}{89}t^{89}}{\binom{90}0-\binom{90}2t^2+\cdots+\binom{90}{90}t^{90}}$$ where $t=\tan x$
If $\tan 90x=\tan90^\circ=\infty$
$90x=180^\circ n+90^\circ=90^\circ(2n+1)$ where $n$ is any integer
$\implies x=(2n+1)^\circ$ where $n\equiv0,1,2,\cdots,88,89\pmod{90}$
So, the roots of $$t^{90}-\binom{90}{88}t^{88}+\cdots=0$$
are  $\tan(2n+1)^\circ$ where $n\equiv0,1,2,\cdots,88,89\pmod{90}$
Now as $-\tan(2n+1)^\circ=\tan\{180^\circ-(2n+1)^\circ\}=\tan\{2(89-n)+1)^\circ\}$
$$\implies\sum_{r=0}^{89}\tan^2(2n+1)^\circ=2\sum_{r=0}^{44}\tan^2(2n+1)^\circ$$
and the roots of $$s^{45}-\binom{90}{88}s^{44}+\cdots=0$$ are $\tan^2(2n+1)^\circ$ where $n\equiv0,1,2,\cdots,88,89\pmod{90}$
Using Vieta's formula,
$$\sum_{r=0}^{89}\tan^2(2n+1)^\circ=\binom{90}{88}=\binom{90}{90-88}=?$$
Can you take it from here?


Q:

Unfortunately, Application has stopped

i am facing a serious problem. i want to get latitude and longitude but application stopped abnormally. i don't know why. i also took permission in menifest. kindly help me, any kind of help will be highly appreciated. Thanks
This is my Fragment

public class FragmentThree extends Fragment {
    FindLocation  Fl;
    GPSTracker  gps;
    public FragmentThree() {
        Fl = new FindLocation();
        gps = new GPSTracker(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.location, container, false);
        Location location = gps.getLocation();
        String latLongString = gps.updateWithNewLocation(location);
        Toast.makeText(getActivity(), latLongString, Toast.LENGTH_SHORT).show();
        return view;
   }
}

GpsTracker.java

public class GPSTracker {
    Context mContext;

     public GPSTracker(Context mContext){
           this.mContext = mContext;
     }

    public Location getLocation(){
        LocationManager locationManager;
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) mContext.getSystemService(context);

        String provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);

        return location;
    }

    public String updateWithNewLocation(Location location) {
        String latLongString;

        if (location != null){
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;
        }else{
            latLongString = "No Location";
        }

        return latLongString;
    }
}

A:

 gps = new GPSTracker(getActivity());

getActivity returns null at instantiation time. You have to wait until the fragment is attached to the Activity. You should wait until onAttach is called. Also getLastKnownLocation returns null if a location has not yet been acquired


Q:

PHP error when using simple file upload script: failed to open stream: No such file or directory

I'm a PHP n00b but followed the instructions as per this excellent tut:
PHP Tizag file upload tutorial
However, whilst this worked perfectly on my Mac (OSX 10.8) running the default built-in Apache, it fails and doesn't work on a CentOS 6 box. Looking through the Apache logs I get this:
failed to open stream: No such file or directory

The permissions have been set to 777 on the "uploads" folder which is in the root of /var/www/html  (on the mac it's /Library/Webserver/Documents)
[Tue Apr 30 13:05:11 2013] [error] [client (My IP Address)] PHP Warning:  move_uploaded_file(uploads/Today notes.txt): failed to open stream: No such file or directory in /var/www/html/test/uploads3.php on line 8, referer: ht*p://serverip.myserver.com/test/form4.html

[Tue Apr 30 13:05:11 2013] [error] [client (my IP address)] PHP Warning:  move_uploaded_file(): Unable to move '/tmp/phpc8AGo8' to 'uploads/Today notes.txt' in /var/www/html/test/uploads3.php on line 8, referer: ht*p://serverip.myserver.com/test/form4.html

Am I missing some setting in PHP or Apache to enable this to work properly?
Many thanks in advance.

A:

According to your question the uploads folder is in /var/www/html, however going by the error message it is trying to upload into /var/www/html/test/uploads which doesn't exist
Either you need to fix the code to upload to the correct path, or you need to create an uploads directory in the test directory


Q:

How to avoid multi threads working on a same task records without using lock?

I've a application, need to use windows service with multiple threads to read 100 task record from SQL server table or mongodb collection, once a thread finish to read the 100 task, it must to set the status from 0('not processing') to 50(means 'processing'), then the thread will do some business logic, once it's done, then update the status from 50 to 100(means 'DONE') OR -1(means 'error encountered'). My question is how to prevent several different threads to read the same 100 records from table if I choose not to use the lock?

A:

It's very simple. Just pick a reasonable number of records to process in a pass. Say you have 53,000 records and you choose 250 as the number to do per pass. That means you have 212 work units that need to be done and you can number them from 0 to 211 inclusive. Work unit N includes records 250*N to 250*N+249 inclusive.
Now the problem reduces to giving each thread an undone work unit to do. So long as all work units are done and no two threads attempt to do the same work unit, no database locks are needed.
How you assign the work units to threads is language specific. But the simplest way is to use some kind of a thread pool and dispatch each work unit to that thread pool.


Q:

Android: Keyboard hiding EditText in Fragment [Material]

Premise: I have a fragment located within a frame layout in the activity layout. The application is in full screen mode.

Problem: When the keyboard lifts up, it hides some edit text, even the one that currently has the focus.

Actions already taken: I have already tried setting the flags in the manifest:
android:windowSoftInputMode="adjustPan"
// OR
android:windowSoftInputMode="adjustResize"
// OR ...

but nothing worked. I also tried setting the flag in the fragment's onCreateView (I also tried in onCreate), but without success.
...
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
...

Question: What could be the problem? What am I doing wrong?

A:

I have found the solution to the problem: i was using com.google.android.material:material:1.2.0-alpha02 apparently it seems to have problems with the auto-adjustment of the screen.
Changing with com.google.android.material:material:1.2.0-alpha06 it worked properly.


Q:

Why we have two ears vs. one mouth?

A Rebbi told us in the name of the Vilna Gaon that we have two ears and one mouth because we should spend more time listening than talking. (Sounds like Epictetus', "We have two ears and one mouth so we can listen twice as much as we speak") Where is this Gra located?

A:

I saw the following quoted as the Vilna Gaon's commentary to Mishlei 11:2:

שעיקר החכמה הוא בהצנועים ששותקין מלומר תורתם ודעתם, רק שומעין מרבותם. כי
   כאשר הוא יאמר דבריו, לא יוסיף לו כלום, אבל כאשר ישמע מרבו, יוסיף לו דברים. ... ולכן העינים הם שתים, והאזנים הם שתים, לראות בתורה שבכתב ולשמוע בתורה שבעל פה, אבל הפה הוא אחד

Roughly translated: "Wisdom is chiefly found in those who are quiet and opt to learn from their teachers rather than state their own views. For the individual gains nothing from saying aloud his own opinions, but does benefit from listening to his teacher...and therefore there are two eyes to help one see Torah in written form, and two ears to help one hear Torah in verbal form, but only one mouth."


Q:

Cursor position in textarea with different font and height-line size

I try to set the font size (13px) and line-height size (23px) for textarea control.
For example the first code: ( http://jsfiddle.net/D6T4f/ )
<TEXTAREA style="font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 23px; height: 70px;"></TEXTAREA>

If I click inside the blank textarea the cursor will be located on correct position.
But in this code I include style background-color: ( http://jsfiddle.net/4e2dL/ )
<TEXTAREA style="background-color: white; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 23px; height: 70px;"></TEXTAREA>

I added only one style background-color: white;. So, if I try to click inside the textarea the cursor will be located not like in the first code (slightly higher). But If I start typing some text, the cursor will move to correct position.
How to avoid this if I need to use this style?
The problem appears in IE 9. Chrome (latest) is OK.
The same problem caused also if I use style background-image: none;
Thanks!

A:

with it only being an IE9 issue, it looks to be a that when you add the background style it is also overriding and removing some other standard IE9 styles.
The solution, you are going to need to be more explicit with your styles to help normalise the styles that are affecting the textareas, I have put an example together where the styles of the textarea have been completely overwritten by the css styles to bring the two inline: http://jsfiddle.net/PXgxU/2/


Q:

Why can we use matrices to represent elements of polynomial vector space?

I think I understand the concept of the polynomial vector space over a field F (set of polynomial functions whose coefficients are part of F), but when describing a transformation from one polynomial vector space to another —- why are we allowed to use matrices to describe that? Matrices aren’t elements of the polynomial vector space, but it is its own vector space right? For example, when describing the transformation matrix for the linear transformation that is the derivative of a polynomial, we have a matrix of coefficients and then multiply that by whatever input column coefficient vector we have that represents a polynomial, but that column vector itself is not part of the polynomial vector space so how do we know it describes a polynomial in the first place?

A:

Consider the vector space $P_{n - 1}(k)$ of polynomials of degree $\leq n - 1$ with coefficients in the field $k.$ Observe that the standard basis of $P_{n - 1}(k)$ is $\mathscr B = \{1, x, x^2, \dots, x^{n - 1}\}.$ (Use the derivative to prove that these are linearly independent.) Consider a linear operator $T : P_{n - 1}(k) \to P_{n - 1}(k).$ Given any polynomial $p(x)$ in $P_{n - 1}(k),$ we can write $T(p(x))$ in terms of the basis $\mathscr B.$ Particularly, $$\begin{align*} T(1) &= a_{11} + a_{21} x + \cdots + a_{n1} x^{n - 1}, \\ \\
T(x) &= a_{12} + a_{22} x + \cdots + a_{n2} x^{n-1}, \\ &\phantom{\,\,} \vdots \\ T(x^{n-1}) &= a_{1n} + a_{2n} x + \cdots + a_{nn} x^{n - 1}, \end{align*}$$ from which we obtain an $n \times n$ matrix $A = [a_{ij}]_{1 \leq i, j \leq n}$ with coefficients in $k.$ (Explicitly, $A$ is the matrix whose $j$th column is $T(x^{j - 1}).$) We refer to $A$ as the matrix of $T$ with respect to $\mathscr B.$
Example. Consider the vector space $P_2(\mathbb R)$ of polynomials of degree $\leq 2$ with coefficients in $\mathbb R$ (the real numbers). Recall that the derivative satisfies $\frac d {dx} [C \cdot p(x)] = C \cdot p'(x)$ for all real numbers $C$ and $\frac d {dx} [p(x) + q(x)] = p'(x) + q'(x)$ for all polynomials $p(x)$ and $q(x),$ hence differentiation is a linear transformation. By the Power Rule, we have that $\deg p'(x) = \deg p(x) - 1,$ hence the map $D : P_2(\mathbb R) \to P_2(\mathbb R)$ defined by $D(p(x)) = p'(x)$ is a linear operator. Considering that $$\begin{align*} D(1) &= 0, \\ \\ D(x) &= 1, \text{ and} \\ \\ D(x^2) &= 2x, \end{align*}$$ we find that the matrix of $D$ with respect to $\mathscr B = \{1, x, x^2\}$ is given by $A = \begin{pmatrix} 0 & 1 & 0 \\ 0 & 0 & 2 \\ 0 & 0 & 0 \end{pmatrix}.$


Q:

Move item in array to last position

I have an array of objects. I want to move a selected object to the last position in the array. How do I do this in javascript or jquery?
Here is some code I have:
var sortedProductRow = this.product_row;

for (var s in sortedProductRow) {
    if (sortedProductRow[s]["parent_product_type"] != "")
        // Move this object to last position in the array
}

I'm looping through this with a for loop, and I want the output to be ordered so that all objects that does not have a "parent_product_type" value comes first, then those with a value.

A:

to move an element (of which you know the index) to the end of an array, do this:
array.push(array.splice(index, 1)[0]);

If you don't have the index, and only the element, then do this:
array.push(array.splice(array.indexOf(element), 1)[0]);

Example:

    var arr = [1, 2, 6, 3, 4, 5];
    arr.push(arr.splice(arr.indexOf(6), 1)[0]);
    console.log(arr); // [1, 2, 3, 4, 5, 6]

NOTE:
this only works with Arrays (created with the [ ... ] syntax or
  Array()) not with Objects (created with the { ... } syntax or
  Object())

A:

Moving the first element of an array to the end of the same array

    var a = [5,1,2,3,4];
    a.push(a.shift());
    console.log(a); // [1,2,3,4,5]

or this way

    var a = [5,1,2,3,4];
    var b = a.shift();
    a[a.length] = b;
    console.log(a); // [1,2,3,4,5]

Moving any element of an array to any position in the same array

    // move element '5' (index = 2) to the end (index = 4)
    var a = [1, 2, 5, 4, 3];
    a.splice(4,0,a.splice(2,1)[0]);
    console.log(a); // [1, 2, 4, 3, 5]

or it could be converted to a prototype as well, like this where x represents the current position of element while y represents the new position in array

var a = [1, 2, 5, 4, 3];
Array.prototype.move = function(x, y){
      this.splice(y, 0, this.splice(x, 1)[0]);
      return this;
    };

    a.move(2,4);
    console.log(a); // ["1", "2", "4", "3", "5"]

Answer to the @jkalandarov comment
function moveToTheEnd(arr, word){
  arr.map((elem, index) => {
    if(elem.toLowerCase() === word.toLowerCase()){
      arr.splice(index, 1);
      arr.push(elem);
    }
  })
  return arr;
}
console.log(moveToTheEnd(["Banana", "Orange", "Apple", "Mango", "Lemon"],"Orange"));


Q:

Validation Rule for Picklist

Hi Req as follow : There is two Picklist Values Filed safety Check and Unit Safety Check and another picklist value as Status :
Hence Status must be in the "In Progress" state when there must be some value in Field Safety check and Unit Safety check" also i need to bypass the Profile "System Administrator"  and One Permission Set "FSL"
My Code:
AND(
    ($Profile.Name <> "System Administrator"),
    AND(
          ISPICKVAL( Status ,"In Progress" ),
          (ISPICKVAL( Field_Safety_Check__c , '' )),
          (ISPICKVAL( Unit_Safety_Check__c , ''))
     ))

A:

Below rule should meet your requirement
AND(
$Profile.Name <> "System Administrator",
ISPICKVAL(Status ,"In Progress"),
OR(
ISPICKVAL(Field_Safety_Check__c , ''),
ISPICKVAL(Unit_Safety_Check__c , '')
    )
)

This will throw you an error when any of the two picklist fields are left blank when in In Progress status. If you want to give error only  when both fields are empty, then you will have to remove the OR condition.
The above validation rule bypasses the System Administrator profile. And if you want to bypass this rule for a permission set, there is no direct way to do so. You cannot directly use permission set in validation rule instead you can create a custom permission and bypass the validation rule using that custom permission. You can check this link and check for "Solution #3 – Custom Permissions" approach.


Q:

Performance issue in encryption and decryption

I m using this process as given in this link
 to encrypt my entire database
here i have use 1 master key 2 certificate 2 symmetric key with algorithm aes_256
i build a raw table where i stored all the encrypted data from the main table which is been protected by 1 procedure and 2 trigger one for update and another for insertion then i created a view of the same name of the main table
plz for more reference check the link
But when i alter the code in my database having data more then 200 tables and few tables containing 1400000 rows each and every query slow down so i need to do performance turning. for what i m looking into some alternative for big database
i know that encrypting entire database will slow down but it is the requirement and delay can't be accepted above 10 sec but now i m having above 2 min
suggest me what to do

Please check the code . and suggested me about any performance tuning that i can work on it
 i thought of changing in sql query changed in where clause as we will convert the sql where condition statement into encrypted form n check into the row table but thing is dat in certain cases the application want entire tables in hand that will again cause error

A:

What to do?
Throw out your ridiculous approach.
Upgrade to SQL Server 2008 R2 ENTERPRISE
Then use this database database encryption.
Works. Higher CPU usage but a LOT more efccient than your approach.


Q:

Delete all rows in all tables which aren't used in any FK relation anymore

In order to trim a production database for loading in a test system, we've deleted rows in many tables. This now left us with cruft in a couple of tables, namely rows which aren't used in any FK relation anymore. What I want to achieve is like the garbage collection in Java.
Or to put it another way: If I have M tables in the database. N of them (i.e. most but not all) have foreign key relations. I've deleted a couple of high level rows (i.e. which only have outgoing FK relations) via SQL. This leaves the rows in the related tables alone.
Does someone have a SQL stored procedure or a Java program which finds the N tables and then follows all the FK relations to delete rows which are no longer needed.
If finding the N tables to too complex, I could probably provide the script a list of tables to scan or, preferably, a negative list of tables to ignore.
Also note:

We have some tables which are used in many (>50) FK relations, i.e. A, B, C, ... all use rows in Z.
All FK relations use the technical PK column which is always a single column.

A:

This issue is addressed in the MySQL Performance blog, http://www.percona.com/blog/2011/11/18/eventual-consistency-in-mysql/
He provides the following meta query, to generate queries that will identify orphaned nodes;
SELECT CONCAT(
 'SELECT ', GROUP_CONCAT(DISTINCT CONCAT(K.CONSTRAINT_NAME, '.', P.COLUMN_NAME,
  ' AS `', P.TABLE_SCHEMA, '.', P.TABLE_NAME, '.', P.COLUMN_NAME, '`') ORDER BY P.ORDINAL_POSITION), ' ',
 'FROM ', K.TABLE_SCHEMA, '.', K.TABLE_NAME, ' AS ', K.CONSTRAINT_NAME, ' ',
 'LEFT OUTER JOIN ', K.REFERENCED_TABLE_SCHEMA, '.', K.REFERENCED_TABLE_NAME, ' AS ', K.REFERENCED_TABLE_NAME, ' ',
 ' ON (', GROUP_CONCAT(CONCAT(K.CONSTRAINT_NAME, '.', K.COLUMN_NAME) ORDER BY K.ORDINAL_POSITION),
 ') = (', GROUP_CONCAT(CONCAT(K.REFERENCED_TABLE_NAME, '.', K.REFERENCED_COLUMN_NAME) ORDER BY K.ORDINAL_POSITION), ') ',
 'WHERE ', K.REFERENCED_TABLE_NAME, '.', K.REFERENCED_COLUMN_NAME, ' IS NULL;'
 ) AS _SQL
 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE P
 ON (K.TABLE_SCHEMA, K.TABLE_NAME) = (P.TABLE_SCHEMA, P.TABLE_NAME)
 AND P.CONSTRAINT_NAME = 'PRIMARY'
 WHERE K.REFERENCED_TABLE_NAME IS NOT NULL
 GROUP BY K.CONSTRAINT_NAME;

I converted this to find childless parents, producing;
SELECT CONCAT(
 'SELECT ', GROUP_CONCAT(CONCAT(K.REFERENCED_TABLE_NAME, '.', K.REFERENCED_COLUMN_NAME) ORDER BY K.ORDINAL_POSITION), ' ',

 'FROM ', K.REFERENCED_TABLE_SCHEMA, '.', K.REFERENCED_TABLE_NAME, ' AS ', K.REFERENCED_TABLE_NAME, ' ',
 'LEFT OUTER JOIN ', K.TABLE_SCHEMA, '.', K.TABLE_NAME, ' AS ', K.CONSTRAINT_NAME, ' ',
 ' ON (', GROUP_CONCAT(CONCAT(K.CONSTRAINT_NAME, '.', K.COLUMN_NAME) ORDER BY K.ORDINAL_POSITION),
 ') = (', GROUP_CONCAT(CONCAT(K.REFERENCED_TABLE_NAME, '.', K.REFERENCED_COLUMN_NAME) ORDER BY K.ORDINAL_POSITION), ') ',
 'WHERE ', K.CONSTRAINT_NAME, '.', K.COLUMN_NAME, ' IS NULL;'
 ) AS _SQL
 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE P
 ON (K.TABLE_SCHEMA, K.TABLE_NAME) = (P.TABLE_SCHEMA, P.TABLE_NAME)
 AND P.CONSTRAINT_NAME = 'PRIMARY'
 WHERE K.REFERENCED_TABLE_NAME IS NOT NULL
 GROUP BY K.CONSTRAINT_NAME;

A:

Even simple stored procedures are usually a little ugly, and this was an interesting exercise in pushing stored procedures well beyond the point where it's easy to take them.
To use the code below, launch your MySQL shell, use your target database, paste the big block of stored procedures from below, and then execute
CALL delete_orphans_from_all_tables();

to delete all orphaned rows from all tables in your database.
To provide a zoomed-out overview:

delete_orphans_from_all_tables is the entry point. All other sprocs are prefixed with dofat to make clear that they relate to delete_orphans_from_all_tables and make it less noisy to have them kicking around.
delete_orphans_from_all_tables works by calling dofat_delete_orphans_from_all_tables_iter repeatedly until there are no more rows to delete.
dofat_delete_orphans_from_all_tables_iter works by looping over all the tables that are targets of foreign key constraints, and for each table deleting all rows that currently aren't referenced from anywhere.

Here's the code:
delimiter //
CREATE PROCEDURE dofat_store_tables_targeted_by_foreign_keys ()
BEGIN
    -- This procedure creates a temporary table called TargetTableNames
    -- containing the names of all tables that are the target of any foreign
    -- key relation.

    SET @db_name = DATABASE();

    DROP TEMPORARY TABLE IF EXISTS TargetTableNames;
    CREATE TEMPORARY TABLE TargetTableNames (
        table_name VARCHAR(255) NOT NULL
    );

    PREPARE stmt FROM
   'INSERT INTO TargetTableNames(table_name)
    SELECT DISTINCT referenced_table_name
    FROM INFORMATION_SCHEMA.key_column_usage
    WHERE referenced_table_schema = ?';

    EXECUTE stmt USING @db_name;
END//

CREATE PROCEDURE dofat_deletion_clause_for_table(
    IN table_name VARCHAR(255), OUT result text
)
DETERMINISTIC
BEGIN
    -- Given a table Foo, where Foo.col1 is referenced by Bar.col1, and
    -- Foo.col2 is referenced by Qwe.col3, this will return a string like:
    --
    -- NOT (Foo.col1 IN (SELECT col1 FROM BAR) <=> 1) AND
    -- NOT (Foo.col2 IN (SELECT col3 FROM Qwe) <=> 1)
    --
    -- This is used by dofat_delete_orphans_from_table to target only orphaned
    -- rows.
    --
    -- The odd-looking `NOT (x IN y <=> 1)` construct is used in favour of the
    -- more obvious (x NOT IN y) construct to handle nulls properly; note that
    -- (x NOT IN y) will evaluate to NULL if either x is NULL or if x is not in
    -- y and *any* value in y is NULL.

    SET @db_name = DATABASE();
    SET @table_name = table_name;

    PREPARE stmt FROM
   'SELECT GROUP_CONCAT(
        CONCAT(
            \'NOT (\', @table_name, \'.\', referenced_column_name, \' IN (\',
            \'SELECT \', column_name, \' FROM \', table_name, \')\',
            \' <=> 1)\'
        )
        SEPARATOR \' AND \'
    ) INTO @result
    FROM INFORMATION_SCHEMA.key_column_usage
    WHERE
        referenced_table_schema = ?
        AND referenced_table_name = ?';
    EXECUTE stmt USING @db_name, @table_name;

    SET result = @result;
END//

CREATE PROCEDURE dofat_delete_orphans_from_table (table_name varchar(255))
BEGIN
    -- Takes as an argument the name of a table that is the target of at least
    -- one foreign key.
    -- Deletes from that table all rows that are not currently referenced by
    -- any foreign key.

    CALL dofat_deletion_clause_for_table(table_name, @deletion_clause);
    SET @stmt = CONCAT(
       'DELETE FROM ', @table_name,
       ' WHERE ', @deletion_clause
    );

    PREPARE stmt FROM @stmt;
    EXECUTE stmt;
END//

CREATE PROCEDURE dofat_delete_orphans_from_all_tables_iter(
    OUT rows_deleted INT
)
BEGIN
    -- dofat_store_tables_targeted_by_foreign_keys must be called before this
    -- will work.
    --
    -- Loops ONCE over all tables that are currently referenced by a foreign
    -- key. For each table, deletes all rows that are not currently referenced.
    -- Note that this is not guaranteed to leave all tables without orphans,
    -- since the deletion of rows from a table late in the sequence may leave
    -- rows from a table early in the sequence orphaned.
    DECLARE loop_done BOOL;

    -- Variable name needs to differ from the column name we use to populate it
    -- because of bug http://bugs.mysql.com/bug.php?id=28227
    DECLARE table_name_ VARCHAR(255);

    DECLARE curs CURSOR FOR SELECT table_name FROM TargetTableNames;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET loop_done = TRUE;

    SET rows_deleted = 0;
    SET loop_done = FALSE;

    OPEN curs;
    REPEAT
        FETCH curs INTO table_name_;
        CALL dofat_delete_orphans_from_table(table_name_);
        SET rows_deleted = rows_deleted + ROW_COUNT();
    UNTIL loop_done END REPEAT;
    CLOSE curs;
END//

CREATE PROCEDURE delete_orphans_from_all_tables ()
BEGIN
    CALL dofat_store_tables_targeted_by_foreign_keys();
    REPEAT
        CALL dofat_delete_orphans_from_all_tables_iter(@rows_deleted);
    UNTIL @rows_deleted = 0 END REPEAT;
END//
delimiter ;

As an aside, this exercise has taught me about a few things that make writing code of this level of complexity using MySQL sprocs a frustrating business. I mention all these only because they may help you, or a curious future reader, understand what look like crazy stylistic choices in the code above.

Grossly verbose syntax and boilerplate for simple things. e.g.

needing to declare and assign on different lines
needing to set delimiters around procedure definitions
needing to use a PREPARE/EXECUTE combo to use dynamic SQL).

Utter lack of referential transparency:

PREPARE stmt FROM CONCAT( ... ); is a syntax error, while @foo = CONCAT( ... ); PREPARE stmt FROM @foo; is not.
EXECUTE stmt USING @foo is fine, but EXECUTE stmt USING foo where foo is a procedure variable is a syntax error.
A SELECT statement and a procedure whose last statement is a select statement both return a result set, but pretty much everything you'd ever like to do with a result set (like looping over it or checking if something is IN it) can only be targeted at a SELECT statement, not a CALL statement.
You can pass a session variable as an OUT parameter to a sproc, but you can't pass a sproc variable as an OUT parameter to a sproc.

Totally arbitrary restrictions and bizarre behaviours that blindside you:

No dynamic SQL allowed in functions, only in procedures
Using a cursor to fetch from a column into a procedure variable of the same name always sets the variable to NULL but throws no warning or error

Lack of ability to cleanly pass result sets between procedures
Result sets are a basic type in SQL; they're what SELECTs return and you think about them as objects when using SQL from the application layer. But within a MySQL sproc, you can't assign them to variables or pass them from one sproc to another. If you truly need this functionality, you have to have one sproc write a result set into a temporary table so that another sproc can read it.
Eccentric and unfamiliar constructs and idioms:

Three equivalent ways of assigning to a variable - SET foo = bar, SELECT foo = bar and SELECT bar INTO foo.
You'd expect that you should use procedure variables for all your state and avoid session variables for the same reasons that you avoid globals in a normal programming language. But in fact you need to use session variables everywhere because so many language constructs (like OUT params and EXECUTE) won't accept any other kind of variable.
The syntax for using a cursor to loop over a result set just looks alien.

Despite these obstacles, you can still piece together small programs like this with sprocs if you are determined.


Q:

Want to creat a search for my wordpress theme

im new in wordpress , i've made my first theme
and i need your help guys , i want to creat a search for my theme
this is my search form :
searchform.php
<div class="search-home">
    <form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
        <input class="schome" type="text" id="search-box" value="<?php the_search_query(); ?>" placeholder="find your favorite game">
        <button> search </button>
    </form>
    </div>

what should i do pls ?

A:

WordPress uses the s key for search. If you add name="s" to the input field this would probably work out of the box.
Also make sure the button element has type="submit" so your browser knows this is the submit button.


Q:

Pairing Labels with Images when building a UI

In a prototype 4X space game that I am working on recently, I have two different scroll panes to show the ships and the stars of the player.  The ships are displayed in a vertical scroll pane on the right side of the screen, and the stars are displayed in a horizontal scroll pane running along the bottom. Here is a picture for the sake of clarity:

With the vertical scroll pane, displaying the labels along with the images is very straightforward. When iterating over the list of ships, a label is added for each ship, then a row, then the ship image.
The horizontal scroll pane presents a problem, however.  I want to have the label displayed above the corresponding image.  Accomplishing this is a bit more complicated than simply adding a row between each element in the table.
I thought about having two lists, iterating over the first list and getting the correct element from the second list based on the index.  Instead of doing this, I went with a Map<Label, Image>.  I'm not sure about this decision, and would love feedback on this approach.  It feels wrong to be using a Map here, because I will never be using it to look up the values based on the keys.
First, I have this method that creates the contents that will be used when building the scroll pane:
private void createContents() {
    this.contents = new HashMap<Label, Image>();

    for (Star star : this.game.getPlayerStars()) {

        Image starImage = new Image(this.libGDXGame.starTextures.get(star.type));
        starImage.addListener(new StarClickListener(star) {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                StarScrollPane.this.gameScreen.playerClickedStar(star);
            }
        });

        Label starLabel = new Label(star.type.name(), this.libGDXGame.skin);

        this.contents.put(starLabel, starImage);
    }
}

Then I have another method that actually creates the table and adds the contents to it like this:
    for (Label label : this.contents.keySet()) {
        this.starTable.add(label);
    }

    this.starTable.row();

    for (Image image : this.contents.values()) {
        this.starTable.add(image).width(width).height(height);
    }

By adding all of the labels to the table, then one row, then all of the images, they line up perfectly.

A:

A HashMap does not guarantee any order whatsoever, so that is a bad idea to use.
Your Image and Label belongs together, so make a class where they actually do belong together.
public class StarView {
    private final Label label;
    private final Image colorImage;
    // constructor and stuff...
}

private void createContents() {
    this.contents = new ArrayList<StarView>();

    for (Star star : this.game.getPlayerStars()) {

        Image starImage = new Image(this.libGDXGame.starTextures.get(star.type));
        starImage.addListener(new StarClickListener(star) {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                StarScrollPane.this.gameScreen.playerClickedStar(star);
            }
        });

        Label starLabel = new Label(star.type.name(), this.libGDXGame.skin);

        this.contents.add(new StarView(starLabel, starImage));
    }

    for (StarView starView : this.contents) {
        this.starTable.add(starView.label);
    }

    this.starTable.row();

    for (StarView starView : this.contents) {
        this.starTable.add(starView.image).width(width).height(height);
    }
}

This could be combined with @Vogel's suggestion about changing the layout manager. Or you could make the StarView extend Actor and put it in a horizontal group.

A:

I think you're using the wrong layout manager for this problem. What you seem to be looking for is a grid layout or even a small container Pane.
Consider:
for (Map.Entry<Label, Value> entry : contents) {
    this.starTable.add(createPane(entry.getKey(), entry.getValue());
}

This allows you to painlessly line these two things up. In addition to that you may want to look into finding a Tuple or Pair you can use so that you can actually go with a List<Pair<Label, Image>> instead of the hack-around with a Map


Q:

Using HMAC to secure a "widget"

Let's say I have a web "widget" that a customer could include on their website. They would include the widget by adding an iframe that points to a URL on my site. I want to ensure that my widget can only be used by paying customers so I was thinking of using an HMAC (HMAC-SHA256 specifically) to verify the customer like so:

The URL would contain a customer ID (randomly generated 6 character hexadecimal number), a timestamp (the current time in seconds since UNIX Epoch), and the HMAC "signature". Since the widget is displayed in an iframe, all of these parameters would be sent clear-text (as a GET request).
The "signature" would be computed based on the URL (since there are multiple widgets), the customer ID, and the timestamp, with a (randomly generated) secret key that would be given to the customer.
On the server, the timestamp is checked to ensure that it falls within a specific window (15 minutes, for example) to prevent replays, and then the signature is checked by recomputing the HMAC and comparing.

I patterned my design off Amazon's web services, but Amazon's scheme requires that some of this data is passed via HTTP headers which would be encrypted over SSL. I don't have that luxury, since everything needs to be passed via GET parameters.
Does this sound reasonably secure? A coworker mentioned that it may not be very secure because all of the inputs to the HMAC algorithm are available in clear-text. An attacker would still need to figure out the way in which the URL, customer ID, and timestamp are combined to create an input to the HMAC algorithm, but, if they did, then they'd have both the input and output. My coworker worried that this information could be used to obtain the secret key via brute force or rainbow tables. Everything I've found via searching seems to indicate that our sun would explode before brute force would finish, and rainbow tables don't work on HMAC's, but the wide world of cryptography is very foreign to me. Plus, most of the answers I've found are 2+ years old and much can change... maybe some new vulnerability was found in the last 2 years or something...
So, is this reasonably secure? And, if not, what can I do to improve security?

A:

Yes, this sounds secure to me.  HMAC, like any secure MAC algorithm, is designed to be existentially unforgeable under chosen-plaintext attacks: that is to say, even if the attacker was allowed to request from you the MACs for any set of messages they wanted, they would not be able to compute a valid MAC for any message they didn't request it for.
(Of course, this is only guaranteed to hold if the hash algorithm used to instantiate HMAC meets the security assumptions set out in the HMAC security proof.  In practice, though, secure cryptographic hash algorithms like the SHA-2 family are believed to meet these assumptions — and, in any case, HMAC is a very robust construction and seems to be very tolerant of even rather poor hashes like MD5.)
Of course, I'm assuming that all clients will be getting their own HMAC keys, so that you can revoke keys if they're compromised or simply if the client stops subscribing to your service.


Q:

Aprons for the home chef

What do I look for in a good high quality apron?
Where can I go to get one?

A:

What sort of tasks are you looking to protect yourself from?
If it's really messy stuff, or to wear while doing the dishes, you might want something that's non-absorbant, like PVC.  I've only really seen them at restaurant supply stores, but it's possible that you might be able to get them from chemistry supply places, also.  (and in this case, pockets are not a good idea, as they collect stuff that you've then got to clean out).
For long hours of grilling, I like something that's more insulating, which in my case would be a leather welder's apron, which you can get from welding supply stores.  I've looked around for something that might be more reflective of radiant heat, but haven't had any luck.
For just general practical use, something that cleans up easily is important.  Restaurant supply stores are a good bet for those sorts of things, but you can sometimes find them in stores that sell grills when it's that season.
For the decorative ones, you basically have two styles -- printed ones with witty/obnoxious sayings on them.  I typically find them online.
The other more frilly decorative ones ... you can find at most housewares stores, some department stores, and if you want something more one of a kind, try esty.
... as for features ... I'm not a fan of pockets, myself.  I guess they're useful for thermometers and timers, but mine clip on, or sit up on a counter or next to the grill, so I don't care.  What I do care about is that they cover the areas that you're trying to protect (an adjustable neck strap is so much better than tying a knot in the line around the neck so try to shorten it) and they don't have straps so long that they get snagged if I sit down for lean up against something.
And it should come on and off without too much difficulty ... which I've only really noticed is a problem with some designs of welder's aprons (it's hard to explain ... it doesn't just go over the neck, and attach in back) ... or if you have to tie off the top to shorten the neck opening.

A:

The primary purpose of an apron is to keep you clean, because cooking gets you dirty. This is why I don't like the common cotton aprons you can get everywhere, they absorb dirt and keep stains. If you insist on cotton, get a white or natural colored one (not dyed, and certainly not printed) so you can wash it at 90° and use bleach and other stain removing chemicals.
What I prefer are treated aprons. They are made from the same material as some hiking jackets, and repel dirt and water. You cannot wash them at too high a setting, but you don't need that. Just remember to not use fabric softener on them, and renew the coating every month or two using an impregnating spray for outdoor clothing. The one I like is by Le Creuset, with an adjustable neck strap and a clean design which covers a lot of body area, and you can easily get it from Amazon. It also has pockets, which I find essential for stuffing a pair of pot holders - when I suddenly smell something burning, I have no time for searching for them somewhere else. But I imagine there are other brands which will do as well. If you insist on having a witty saying on your apron, it is probably better to get a high-quality coated apron and have it screen printed or stitched than buying a poorly functioning complete with a saying.
This is the Le Creuset apron:

I didn't know that you can get pure PVC aprons until I read Joe's answer. I can imagine they will be sweat-inducing, because they are not breathable, but as I know PVC, they will also be even easier to clean than coated cloth. He says they are hard to get, but I can tell you that aprons are one of the easiest things to sew, so if you want one badly, why not just buy some PVC table cloth and make one? (I am assuming here that you can get your hands on a sewing machine; you don't need much experience in sewing for making an apron, and cheap/free patterns for aprons are easy to come by).
For special needs, there are all kinds of aprons, but I don't think you need them as a hobby cook. You can get protection from extreme heat, acids/bases, shards flying through the air (as in hacking wood to kindling, or in smallish explosions), or even radiation, but I hope you have none of those in your kitchen. If you just want a high show off factor, take a look here. That's a butcher's apron from aluminum plates by De Buyer. If you get it complete with the chain mail glove (seriously), you are ready for the next ren faire. .

A:

It depends on what you want, really. If you want something pretty and frilly, those are pretty easy to find anywhere. If you want something a bit stronger, easy to clean, and that will stand up to more than the average "for-looks" apron, I would suggest looking at a kitchen-supply store, the sort that sells various kitchen supplies and gadgets. You should be able to find a heavier apron with pockets - I have a heavier cotton one with adjustable straps and a couple of pockets that I found in the kitchen section at Zellers, for example.


Q:

Redefine (or reconfirm) Node and Vertex in 3D-GIS

Sorry if this sounds too broad and opinion-soliciting...
I think the difference between Node and Vertex had been discussed before (for instance) Difference between node and vertex in GIS?, good and detailed discussions between renowned GIS leaders are open for us (me) to learn.
And my take is (sorry again if this is too simplistic... and I can be totally wrong...) "Vertex" is for location (xy) and "Node" includes its topology.
Is it still valid, given we now have 3D-GIS more closer than before? I mean; Vertex is the XYZ locator?

A:

To me a vertex can be a 2d or 3d coordinate. It's a mathematical point in space (2d or 3d) where lines meet.
(Caveat: my background is Computer Science).
A "node" is an object in an object-oriented system (C++ in the case of QGIS and Qt). As such, it can have any information attached to it (as a control point in a bezier curve, x and y coordinates on the canvas, elevation etc.). It can also be part of a network (and have a degree etc.)
I'd say that a node is an abstraction of a vertex. A node might choose to ignore the z-value, in which case it is the same as a point in 2D. Or it might include it, in which case it's 3D.
I've written code to export gdal rasters to .obj files; Blender is very specific on what it means by a vertex - xyz :)


Q:

How to force a checkbox if user clicks it twice?

Is it possible to have to two checkboxes appear as blank on pageload.
But if the user clicks an option, then they can never click off it - so at the moment the user can toggle between the options and you can only tick once. However if they press the ticked box twice it removes the tick.
HTML
My Billing Address is the same <input type="checkbox" class="sameCheck" name="toggleOracleAddress" id="toggleOracleAddress" value="SAME" />

My Billing Address is the different <input type="checkbox" class="sameDifferent" name="toggleOracleAddress" id="toggleOracleAddress" value="DIFFERENT" />

jQUERY
$(document).ready(function(){
    //////////////////
    //####     SAME ADDRESS
    //////////////////
    $('.sameCheck').click(function() {
        $('.sameDifferent').removeAttr('checked');
        $('#proceedIsOn').slideUp();
    });
    //////////////////
    //####     DIFFERENT ADDRESS
    //////////////////
    $('.sameDifferent').click(function() {
        $('.sameCheck').removeAttr('checked');
        $('#proceedIsOn').slideDown();
    });
});

JSFIDDLE HERE http://jsfiddle.net/mRwMt/

A:

Just set it to checked on every click :
$(document).ready(function(){
    $('.sameCheck').click(function() {
        this.checked = true;
        $('#proceedIsOn').slideUp();
    });
    $('.sameDifferent').click(function() {
        this.checked = true;
        $('#proceedIsOn').slideDown();
    });
});

FIDDLE
or to avoid the sliding as well :
$(document).ready(function(){
    $('.sameCheck').click(function() {
        if (!this.checked) return false;
        $('#proceedIsOn').slideUp();
    });
    $('.sameDifferent').click(function() {
        if (!this.checked) return false;
        $('#proceedIsOn').slideDown();
    });
});

Or to just toggle between boxes :
$(document).ready(function(){
    $('.sameCheck').click(function() {
        if (this.checked) {
            $(this).siblings('input[type"text"]').prop('checked', false);
            $('#proceedIsOn').slideUp();
        }else{
            return false;
        }
    });
    $('.sameDifferent').click(function() {
        if (this.checked) {
            $(this).siblings('input[type"text"]').prop('checked', false);
            $('#proceedIsOn').slideDown();
        }else{
            return false;
        }
    });
});

FIDDLE


Q:

How to write Fibonacci with generator without stop number

I went through Beginning Python fibonacci generator
How to write with out stop number where we want to stop.
My Code of FIbnocci is below
def Fibonnaci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    else:
        return (Fibonnaci(n-1)+ Fibonnaci(n-2))

n = int(input())
print(Fibonnaci(n))

I wrote with yield statement but its infinite loop running
def fib(n):
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib(7)

Desired out >
    13

A:

You don't want to loop infinitely; you need to keep track of how many times you've performed an operation.
Hold the state of a counter in your loop while you generate elements.  Keep going until count >= n.
def fib(n):
     count = 0
     a, b = 0, 1
     while count < n:
             yield a
             a, b = b, a + b
             count += 1

You can then leverage this in a list comprehension to get all of the values up to that Fibonacci number if you so desire.
[i for i in fib(10)]


Q:

The largest eigenvalue of a "hyperbolic" matrix

Given an integer $n\ge 1$, what is the largest eigenvalue $\lambda_n$ of the matrix $M_n=(m_{ij})_{1\le i,j\le n}$ with the elements $m_{ij}$ equal to $0$ or $1$ according to whether $ij>n$ or $ij\le n$?
It is not difficult to show that
  $$ c\sqrt n \le \lambda_n \le C\sqrt{n\log n} $$
for appropriate positive absolute constants $c$ and $C$, and numerical
computations seem to suggest that the truth may lie somewhere in between.

To make the problem a little bit "more visual", the first four matrices in question are as follows:

$M_1=\begin{pmatrix} 1 \end{pmatrix}$ $\quad$
    $M_2=\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}$ $\quad$
    $M_3=\begin{pmatrix} 1 & 1 & 1 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \end{pmatrix}$ $\quad$
    $M_4=\begin{pmatrix} 1 & 1 & 1 & 1 \\ 1 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 1 & 0 & 0 & 0 \end{pmatrix}$

A:

I think, $C\sqrt{n}$ is an upper bound aswell. Take vector $x=(x_1,\dots,x_n)$ with $x_j=j^{-1/2}$. Then $(Ax)_i$ behaves like $C\sqrt{n/i}=C\sqrt{n}x_i$. But we know that if $(Ax)_i\leq C x_i$ for vector $x$ with positive coordinates, then the largest eigenvalue of $A$ does not exceed $C$ (kind of Perron-Frobenius).
(This answer is very ugly displayed, I do not know why).


Q:

How to get the current MTU of an interface in C#

I want to show the current network interface mtu value to the user. The user can change the mtu by the netsh command e.g. for the interface with id 11:
netsh interface ipv4 set subinterface 11 mtu=1700 store=persistent

How can I read the current MTU of an interface by the id or interface name?
If I use the NetworkInterface class example from the System.Net.NetworkInformation namespace all interfaces have an MTU of 1500. But with the netsh command (see above) I get the correct MTU values of e.g. 1700.

This is the example:
https://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface(v=vs.110).aspx
public static void ShowNetworkInterfaces()
{
    IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
    Console.WriteLine("Interface information for {0}.{1}     ",
            computerProperties.HostName, computerProperties.DomainName);
    if (nics == null || nics.Length < 1)
    {
        Console.WriteLine("  No network interfaces found.");
        return;
    }

    Console.WriteLine("  Number of interfaces .................... : {0}", nics.Length);
    foreach (NetworkInterface adapter in nics)
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
        Console.WriteLine();
        Console.WriteLine(adapter.Description);
        Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
        Console.WriteLine("  Interface type .......................... : {0}", adapter.NetworkInterfaceType);
        Console.WriteLine("  Physical Address ........................ : {0}",
                   adapter.GetPhysicalAddress().ToString());
        Console.WriteLine("  Operational status ...................... : {0}",
            adapter.OperationalStatus);
        string versions ="";

        // Create a display string for the supported IP versions.
        if (adapter.Supports(NetworkInterfaceComponent.IPv4))
        {
             versions = "IPv4";
         }
        if (adapter.Supports(NetworkInterfaceComponent.IPv6))
        {
            if (versions.Length > 0)
            {
                versions += " ";
             }
            versions += "IPv6";
        }
        Console.WriteLine("  IP version .............................. : {0}", versions);
        ShowIPAddresses(properties);

        // The following information is not useful for loopback adapters.
        if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
        {
            continue;
        }
        Console.WriteLine("  DNS suffix .............................. : {0}",
            properties.DnsSuffix);

        string label;
        if (adapter.Supports(NetworkInterfaceComponent.IPv4))
        {
            IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties();
            Console.WriteLine("  MTU...................................... : {0}", ipv4.Mtu);
            if (ipv4.UsesWins)
            {

                IPAddressCollection winsServers = properties.WinsServersAddresses;
                if (winsServers.Count > 0)
                {
                    label = "  WINS Servers ............................ :";
                    ShowIPAddresses(label, winsServers);
                }
            }
        }

        Console.WriteLine("  DNS enabled ............................. : {0}",
            properties.IsDnsEnabled);
        Console.WriteLine("  Dynamically configured DNS .............. : {0}",
            properties.IsDynamicDnsEnabled);
        Console.WriteLine("  Receive Only ............................ : {0}",
            adapter.IsReceiveOnly);
        Console.WriteLine("  Multicast ............................... : {0}",
            adapter.SupportsMulticast);
        ShowInterfaceStatistics(adapter);

        Console.WriteLine();
    }

A:

I've found the answer by myself. I have to change the MTU also for the ipv6 interface like:
netsh interface ipv4 set subinterface 11 mtu=1700 store=persistent

netsh interface ipv6 set subinterface 11 mtu=1700 store=persistent


Q:

Perl WSDL11 Can't Make it to Work on two WSDL files

This question is related to the issue I encountered on my Perl Program using XML::Compile::WSD11 Perl Module in which my company Webservice uses multiple WSDL with XML import.
The original post that describe this issue can be found here. From that post, I tried the suggestion of imatveev13 to use the addWSDL API from XML::Compile::WSDL11 and the code snippet is shown below.
The two WSDL files used in the test Perl program are: WSDL0 and WSDL1.
#!/usr/bin/perl

use 5.018;
use strict;
use warnings;

use Data::Dumper qw{Dumper};

use XML::Compile::SOAP11; # XML::Compile::SOAP 2.x
use XML::Compile::WSDL11;
use XML::Compile::Transport::SOAPHTTP;

my $WSDL0 = 'CamstarWebClient0.wsdl';
my $WSDL1 = 'CamstarWebClient1.wsdl';

# Create service proxy for web service
my $wsdlXml0 = XML::LibXML->new->parse_file($WSDL0);
my $wsdlXml1 = XML::LibXML->new->parse_file($WSDL1);

my $SoapSrv = XML::Compile::WSDL11->new();
$SoapSrv->addWSDL($wsdlXml0);
$SoapSrv->addWSDL($wsdlXml1);

print Dumper($SoapSrv);

# Compile all service methods
my (%SoapOps);
foreach my $SoapOp ($SoapSrv->operations)
{
    print Dumper($SoapOp);
    # XML::Compile::SOAP 2.x
    if ($XML::Compile::SOAP::VERSION > 1.99)
    {
        $SoapOps{$SoapOp->name}
            = $SoapSrv->compileClient(operation => $SoapOp->name,
                                      port => "ICamstar");
    }
}

print "\n";
exit;

Running the code gave me an error: cannot find port 'ICamstar', pick from BasicHttpBinding_ICamstar.
I also tried without specifying the port since the service do not implement multiple port but it gave me a different error.
Can't locate object method "_writer_body_rpcenc_hook" via package "XML::Compile::SOAP11::Client" at /usr/local/share/perl5/XML/Compile/SOAP.pm line 155.
Appreciate any help from the community. Thanks.

A:

Make sure to use the module XML::Compile::SOAP11::Encoding on top of your script:
use XML::Compile::SOAP11::Encoding;