text:
Q: Spring converts csv to array, but not to list I have a declaration in a POJO that looks something like this:
@Value("${prefix.someList}")
private List<String> list;

I have a line in a properties file that looks like this:
prefix.list   = some,stuff,with,comma,separators

I also added a @PostConstruct method to the POJO, only so I could add a line I could set a breakpoint on.
When I hit the breakpoint, I look at the "list" property, and it has a SINGLE entry with the value "some,stuff,with,comma,separators".
I also added the following declaration:
@Value("${prefix.someList}")
private String[] array;

At the breakpoint, the array had 5 entries, with the expected values.
If I convert the first expression to
"#{'${prefix.list}'.split(',')}"

Then it does produce a list with the expected entries, but I'd prefer not to do that. It's a little more complicated, and doesn't defend against empty list properties.
I then did some googling for this problem.  I saw suggestions that I should add a "ConversionService" bean, instantiated with "new DefaultConversionService()".  I did this. I also discovered the references in there for "StringToCollectionConverter" and "StringToArrayConverter".  I set breakpoints in expected places in these classes.
I found the DefaultConversionService being created, along with the two converter classes.  However, the "convert" methods in those classes was never called, even the "array" one, even though something was doing the conversion.
I then even commented out my Bean that creates the DefaultConversionService, and I found the result was identical (I noticed the constructor was being hit twice).
So, in short, conversion of string to list is not happening, even though string to array is, but I have no idea what mechanism is supposed to be doing this, because neither of the expected converters seem to even be used, even though the array conversion is being done somewhere.
I'm using Spring 5.0.9 with Java 8.
To be clear, the other post that is allegedly a duplicate of this does not help.  First, the "answer" is simply a suboptimal workaround that really shouldn't be necessary.  The other suggestion in that post didn't make any difference.
Update:
It was suggested that I should construct a minimal reproducible example.  Fortunately, start.spring.io makes it simple to produce a Spring boot skeleton (I didn't mention before that this is a Spring Boot app).
I took the sample maven and java8 project.  Note that I selected version 2.1.0, but my own project is using 2.0.5.
I added a dummy class, added a @Component annotation, added a list and array property, a @PostConstruct method that prints the list and length of the list, and defined a csv list property in application.properties.
I ran it.  It did what you said it would.  It worked fine, producing a list with as many elements as there were in the csv list.  It was curious, however, that it still doesn't appear to be calling the converters in the conversion service.  None of the breakpoints in the converter classes were hit.
Then, I changed the spring boot version in the pom from 2.1.0 to 2.0.5 and reran my test.  Boom.  I got exactly the behavior I've been seeing.  it produced a list with one element, where the string was the entire csv list.
So, it appears that something was changed or fixed between 2.0.5 and 2.1.0 that made this work properly.
I can't upgrade right now, so I can't use this solution.  I would search through the spring-boot change log, but as I never saw it hit the expected converter classes, I wonder what is actually doing this.
Update:
If it matters, here's my simple pojo that I added to the springboot skeleton:
package com.example.demo;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Stuff {
    @Value("${stuffList}")
    private List<String>    stuffList;
    @Value("${stuffList}")
    private String[]    stuffArray;

    public final List<String> getStuffList() { return stuffList; }

    public final void setStuffList(List<String> stuffList) { this.stuffList = stuffList; }

    public final String[] getStuffArray() { return stuffArray; }

    public final void setStuffArray(String[] stuffArray) { this.stuffArray = stuffArray; }

    @PostConstruct
    public void stuff() {
        System.out.println("stuffList[" + stuffList + "] len[" + stuffList.size() + "]");
    }
}

With Springboot 2.1.0, the len is 3.  With 2.0.5, the len is 1.  Neither of them call "`org.springframework.core.convert.support.StringToCollectionConverter.convert(Object, TypeDescriptor, TypeDescriptor)'"
And this is the main class, unmodified from the skeleton.
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Update:
Ok, the solution is described at Reading a List from properties file and load with spring annotation @Value , but it's not the accepted answer.  The correct answer is the one that describes defining the bean of type ConversionService with an object of type DefaultConversionService.
What can be confusing is that if you set some breakpoints in DefaultConversionService before adding that bean, you will hit them.  However, it appears that Spring uses that class by default for other things besides property value resolution.  Once I added the bean (and I did it in the correct class), that got the StringToCollection converter to work properly.


text:
Q: Pell's d prime (often) implies that x(d-1) is prime? I have found a few patterns in my study of Pell's equation x(d)^2-dy(d)^2=1.
One is this: If d is a prime then x(d-1) is also prime.
It doesn't hold for all primes, but it is a pattern which holds for 17 of the 21 first (relevant) primes from 2 to 100. (There are more primes below 100 but several values are irrelevant since x(d-1) does not exist d=2, 5, 17 and 37).
I know that in many cases you will find a pattern which is just from statistics with just a few numbers.  I believe the phenomenon even has its own law, "the law of small numbers"   (among which "anything can happen").
My inability to use mathematical software makes it impractical to improve my statistics. Does anybody know if this pattern prevails for a collection of the equations with higher numbers of d, or if there might be a reason for such a pattern?

A: As I understand it by $x(d)$ you mean the $x$ for the smallest solution in positive integers.
Since $x(d-1)$ satisfies $x^2-(d-1)y^2=1$ it cannot have any common factor with $d-1$ or with $y$. For odd primes $d$ this rules out 2 and at least one other prime $<d$ as possible factors for $x$, which should make the occurence of prime $x(d-1)$ very slightly less surprising.
Checking the occurence for the first $N$ primes I got this table, which illustrates that the cases where $x(d-1)$ are prime are a minority for $N$ larger than 150, and look to be a diminishing proportion as $N$ grows.
$$
\begin{array}{c|c|c|c}
N & \mathrm{Relevant} & x(d-1)~\mathrm{is~prime} & \mathrm{fraction} \\
\hline\\
25 & 21 & 17 & 81\% \\
100 & 92 & 54 & 59\% \\
150 & 69 & 150 & 49\% \\
1000 & 983 & 252 & 26\% \\
10000 & 9949 & 1220 & 12\% \\
20000 & 19932 & 1987 & 10\% \\
\end{array}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use ruby syntactic sugar to print different strings depending on the format of the string I have a method is_numeric? which checks if a string is numeric.
I would like to print out the string to the console as part of a sentence, if the string is numeric I would like to surround it in ' marks.
At present I have something like this...
def i_hate_james_blunt_this_much(how_much)
    if how_much.is_numeric?
        puts "a hate james blunt this much : '" + string + "'\n"
    else
        puts "a hate james blunt this much : " + string + "\n"
    end
end

but I am sure ruby has some syntactic sugar to make it look sweeter, anyone?

A: How about:
output_string = "a hate james blunt this much : "
output_string += how_much.is_numeris? ? "'#{string}'" : string

A: Another variant:
hate = how_much.is_numeric? ? "'#{how_much}'" : how_much
puts "i hate james blunt this much : #{hate}\n"

A: q = how_much.is_numeric?? "'" : ""

And then
puts "a hate james blunt this much : %s%s%s" % [q, how_much, q]

or
puts "a hate james blunt this much : " + q + how_much + q


text:
Q: Мало приложений в Ubuntu Software После установки убунты 16.04, в магазине приложений мало программ. Нет ни хромиума, ни скайпа. Показаны только те, которые уже установлены. С интернетом проблем нет, система только после установки. Как можно решить данную проблему?
В "Программы и обновления". Первые 4 галки стоят.
В папке /etc/apt/sources.list.d нет файлов
Содержимое файла /etc/apt/sources.list :
#deb cdrom:[Ubuntu 16.04 LTS _Xenial Xerus_ - Release amd64 (20160420.1)]/ xenial main restricted

# See htt p://help. ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb htt p://ru. archive.ubuntu.com/ubuntu/ xenial main restricted
# deb-src ht tp://ru. archive.ubuntu.com/ubuntu/ xenial main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb ht tp://ru. archive.ubuntu.com/ubuntu/ xenial-updates main restricted
# deb-src htt p://ru. archive.ubuntu.com/ubuntu/ xenial-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
deb ht tp://ru. archive.ubuntu.com/ubuntu/ xenial universe
# deb-src htt p://ru. archive.ubuntu.com/ubuntu/ xenial universe
deb htt p://ru. archive.ubuntu.com/ubuntu/ xenial-updates universe
# deb-src htt p://ru. archive.ubuntu.com/ubuntu/ xenial-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb htt p://ru. archive.ubuntu.com/ubuntu/ xenial multiverse
# deb-src htt p://ru. archive.ubuntu.com/ubuntu/ xenial multiverse
deb htt p://ru. archive.ubuntu.com/ubuntu/ xenial-updates multiverse
# deb-src htt p://ru. archive.ubuntu.com/ubuntu/ xenial-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb htt p://ru. archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse
# deb-src htt p://ru. archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb htt p://archive. canonical.com/ubuntu xenial partner
# deb-src htt p://archive .canonical.com/ubuntu xenial partner

deb htt p://security. ubuntu.com/ubuntu xenial-security main restricted
# deb-src htt p://security. ubuntu.com/ubuntu xenial-security main restricted
deb htt p://security. ubuntu.com/ubuntu xenial-security universe
# deb-src htt p://security. ubuntu.com/ubuntu xenial-security universe
deb htt p://security. ubuntu.com/ubuntu xenial-security multiverse
# deb-src htt p://security. ubuntu.com/ubuntu xenial-security multiverse

A: Для установки именно Google Chrome надо добавить официальный репозиторий:
sudo -i

echo -e '\n \e[1;36m' Добавляется репозиторий Google Chrome '\e[0m \n'
echo 'deb http://dl.google.com/linux/chrome/deb/ stable main' > /etc/apt/sources.list.d/google-chrome.list
wget -q https://dl-ssl.google.com/linux/linux_signing_key.pub -O - | apt-key add -
apt-get update
apt-get -y install google-chrome-stable

Skype есть в партнёрском репозитории. Он у тебя в листинге:
# deb http://archive. canonical.com/ubuntu xenial partner

Строку надо раскоментировать и тоже обновить индекс пакетов через sudo apt-get update
А ещё официальный flash player лежит в виде пакета adobe-flash-properties-gtk.
UPD про skype (теперь вообще официальная репа):
echo 'deb https://repo.skype.com/deb stable main' > /etc/apt/sources.list.d/skypeforlinux.list
wget -O - https://repo.skype.com/data/SKYPE-GPG-KEY | apt-key add -
apt-get update
apt-get install skypeforlinux -y

A: Как я помню хром отказался от поддержки 32 битной версии И удалил все chrome из репозитория, его тама нету как и репозитория. Используйте chromium это практически тоже самое что и chrome(даже так, chrome это надстройки над chromium), + он открытый.
Про скайп не знаю, не пользуюсь. Все зависит от репозиториев.


text:
Q: Unable to get value from JSON after mySQL var sender_username = req.session.user_id;
var recipient_username = req.body.recipient_username;
var content = req.body.content;

var sql = ' SELECT sender_username, recipient_username, COUNT(recipient_username) as count FROM message WHERE sender_username = "'+sender_username+'" AND recipient_username = "'+recipient_username+'" GROUP BY sender_username LIMIT 1 ';
var message_no = 0;
var data;

connection.query(sql, function(err, result) {
    if (err) {
        res.send(err);
    }
    else {
        data = result;
        // res.send(data); < - this works
        // res.send(result); <- this works
        // res.send(result.count); <- undefined
    }
});

res.send(data); // undefined (can't seem to save to variable after connection.query())

The res.send(result); seems to work. It gives:
[{"sender_username":"sender","recipient_username":"recipient","count":2}]

I am just trying to get the value for count and save that to a variable, but things like result.count are returning undefined for some reason.

A: It's because the JSON is an array, so you should access it like the following
res.send(result[0].count);


text:
Q: Function pointer conversion in C As I heard, It is not safe to convert pointer to function to void*.
Okay, is it safe to cast
void (*enumerate) (void (*)(const struct foo *event, void *), void *)
to
void (*enumerate) (void (*)(const void *event, void *), void *)
and then call it with
void (*)(const void *, void *) as first argument, which treats its first void* as struct foo*?

A: No, this is not safe. It's not guaranteed by the C standard that a struct foo * and a void * have the same size and format. In general, casting function pointers to other function pointer types is a recipe for disaster. The safe solution is to insert an extra function that converts the arguments to the right type, just as you'd do when writing a comparison function for qsort that handles non-void * arguments:
static int compare_foo_as_voidp(void const *a, void const *b)
{
    return compare_foo((struct foo const *)a, (struct foo const *)b);
}

(As Oli Charlesworth writes in the comment, the cast itself is not the problem, but calling through the pointer causes UB.)


text:
Q: Nuxt3 + Vite - devserver restarts when editing any file I have a Nuxt3 (nuxt@3.0.0-rc.8) app using Vite (@nuxt/vite-builder@3.0.0-rc.8). I am developing from within a docker .devcontainer.
When I run yarn dev the devserver spins up and listens on port 3000 and everything works great. However when I change any file (e.g. a .vue component) I see the change hot-module-reloaded into my browser instantly, which is the behaviour I want.
BUT the devserver also sees the change and restarts itself.
I have a server route setup:
./server
    routes/
        my-route.ts

which does an expensive operation when first run, and caches the result for subsequent requests. Since the devserver restarts on every change, this expensive operation happens on every change, making dev quite slow.
So every change to a clientside .vue file results in the following server log:
✔ Vite server built in 397ms
Starting expensive operation from my-route...
...done in 123 second

How can I make it so only changes inside the ./server/ folder, or to nuxt.config.ts, or to plugins/*.server.ts etc will cause the devserver to restart? And other changes to clientside components will leave the server running and use HMR?


text:
Q: Nested lists python Can anyone tell me how can I call for indexes in a nested list?
Generally I just write:
for i in range (list)

but what if I have a list with nested lists as below:
Nlist = [[2,2,2],[3,3,3],[4,4,4]...]

and I want to go through the indexes of each one separately?

A: Try this setup:
a = [["a","b","c",],["d","e"],["f","g","h"]]

To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]
The first brackets reference which nested list you're accessing, the second pair references the item in that list.

A: If you really need the indices you can just do what you said again for the inner list:
l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

But it is more pythonic to iterate through the list itself:
for inner_l in l:
    for item in inner_l:
        print item

If you really need the indices you can also use enumerate:
for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]

A: You can do this. Adapt it to your situation:
  for l in Nlist:
      for item in l:
        print item

A: The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:
Example:
input -> [1,2,[3,4]]
output -> [1,2,3,4]

The code below gives me the result, but I would like to know if anyone can create a simpler answer:
def get_elements_from_nested_list(l, new_l):
    if l is not None:
        e = l[0]
        if isinstance(e, list):
            get_elements_from_nested_list(e, new_l)
        else:
            new_l.append(e)
        if len(l) > 1:
            return get_elements_from_nested_list(l[1:], new_l)
        else:
            return new_l

Call of the method
l = [1,2,[3,4]]
new_l = []

get_elements_from_nested_list(l, new_l)

A: n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
  results = []
  for numbers in lists:
    for numbers2 in numbers:
        results.append(numbers2)
  return results
print flatten(n)

Output: n = [1,2,3,4,5,6,7,8,9]

A: I think you want to access list values and their indices simultaneously and separately:
l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
    for j in range(l_item_len):
        print(f'List[{i}][{j}] : {l[i][j]}'  )


text:
Q: First Object in Set> that satisfies a predicate Abstract idea
I want to get the first value coming out of a set of Futures, that satisfies a given predicate.
If a satisfying value is found, all other Futures should be cancelled. If no value is found after all Futures have returned the execution should be terminated (by returning a default value or throwing an exception).
Concrete example
public boolean isThereVacantHotelRooms(Set<URL> hotelApiUrls) {
    // returns true if any provided server responds with a number larger than 0
}

I'm looking for a pretty way of implementing the above in Java 8 (external libs are fine). I have tried implementing it with CompletableFuture as well as RxJava, but I both feel very non-idiomatic for this problem and I end up with lots of ugly code.

A: I think, your case can be accomplished with a combination of merge, filter and take:
List<Observable<HotelInfo>> hotels = new ArrayList<>();
for (URL u : urls) {
    Observable<HotelInfo> hotelInfo = networkAPI.askHotel(u);
    hotels.add(hotelInfo);
}
Observable.merge(hotels)
.filter(h -> h.vacancy > 0)
.take(1)
.subscribe(h -> System.out.println("Winner: " + h), Throwable::printStackTrace);

A: Since you have tried other solutions, here's the bayou solution for comparison
// throw exception for failure
public void checkVacantHotelRooms(Set<URL> hotelApiUrls) throws Exception
{
    checkVacantHotelRoomsAsync(hotelApiUrls)  // Async<Void>
        .timeout(Duration.ofSeconds(10))      // cancel on 10s
        .sync();    //  async -> sync
}

public Async<Void> checkVacantHotelRoomsAsync(Set<URL> hotelApiUrls)
{
    Stream<Async<Void>> resultStream = hotelApiUrls.stream()    // Stream<URL>
        .map(this::getResponseBodyAsync)                        // Stream<Async<String>>
        .map(asyncBody->asyncBody.map(this::checkResponse));    // Stream<Async<Void>

    return AsyncBundle.anyOf(resultStream);
    // succeeds if one result succeeds; others will be cancelled
}

Void checkResponse(String responseBody) throws Exception
{
    if(responseBody.contains("something"))
        return (Void)null;
    throw new Exception("none in this hotel");
}

-----

HttpClient httpClient = new HttpClient();
int maxBodyLength = 1000;

Async<String> getResponseBodyAsync(URL url)
{
    Async<HttpResponse> asyncResponse = httpClient.doGet(url.toExternalForm());
    return asyncResponse.then(resp->resp.bodyString(maxBodyLength));
}


text:
Q: Can we distribute Enterprise ios app through Apple Business manager? I have gone through this solution here. I am confused between B2B apps and enterprise apps. Does both are same? I am distributing my enterprise app using https(itms-services) link to other users.
So, how to do this with Apple Business manager? Does Apple Business manage has any store like AppStore where we have to upload the IPA file or anything else that I have to do?

A: Enterprise apps are signed using an enterprise program key and can be distributed directly to that enterprise's devices.  There is no Apple review of enterprise apps.
B2B apps are submitted to App Store Connect using a corporate or company developer program membership. They are reviewed by Apple. They are ether made available for specific Apple IDs to "purchase" (they can be free, with payment made directly to the developer) using the Volume Purchase Program.
Apple Business Manager provides a portal where organisations can:

*

*Perform Volume Purchase Program purchases (which may be regular App Store apps or B2B apps)

*Enrol devices in the Apple Device Enrolment program to force association with an MDM "out of box".

Apple Business Manager is not involved in actually distributing apps.
An MDM can be used to distribute both Enterprise and B2B apps.


text:
Q: how can i insert a form search like twitter I am wondering how should i proceed with a rails form search like twitter to search multiple models.
I have implemented a search model/controller which will search based on the textbox and will eventually have ajax. But i am just wondering how can i implement it in my header file. Rendering may do is job but not sure how to call the searches controller.
Thanks in advance. Followed this tutorial http://railscasts.com/episodes/111-advanced-search-form

A: One approach would be to create a Search class. Create a form partial that has a query input that when submitted, is send to the Search class. Search will then come up with a collection of search results, which you then output to a separate view. Having a Search class allows you to keep additional capabilities to your search--additional models and ways to rank results.
Here is an skeletal example...
class Search
  attr_accessor :query

  def initialize(*args)
    self.query = args[0] && args[0][:query] ? args[0][:query] : nil
  end

  def elements
    query.nil? ? [] : query.downcase.split(/ /)
  end

  def class_a
    class_a_objects = []
    ...some code that finds the objects you are searching for...
    return class_a_objects.uniq
  end

  def class_b
    class_a_objects = []
    ...some code that finds the objects you are searching for...
    return issuers.uniq
  end

  def class_c
    ..
  end

  ....

  def results
    class_a_objects + class_b_objects + class_c_objects
  end

end

In your searching code for each class, use the 'elements' method to search through the individual query objects.
For the form
= form_tag("/search", :method => :get) do
  = text_field 'search', :query
  = submit_tag 'search'

Routes.rb
match '/search' => "search#query", :as => 'search'

Then a Search controller with a 'query' action. In this controller, simply do
class SearchController
   def query
     @results = Search.new(:query => params[:search][:query] ).results
   end
end

Add a view 'search' for this controller action, where you render your @results. Your results will be a collection of individual objects from different classes, so your view can handle each item separately, which can be handled with additional partials, based on the object class.


text:
Q: My GcmTaskService provokes ANR I made a Service that aims at retrieving data on a server every 10 hours when internet is on.
I've very rarely used Service before and I don't understand what happen there,but when I start my app, I get an ANR before the first layout is displayed, after a moment the layout appears and I can continue (but I've noticed one other screen change that is now very slow) :
E/ActivityManager: ANR in com.m360.android.debug
                                                  PID: 17742
                                                  Reason: executing service com.m360.android.debug/com.m360.android.service.offline.SyncOfflineContentService
                                                  Load: 11.95 / 12.06 / 12.2
                                                  CPU usage from 0ms to 7113ms later:
                                                    95% 17742/com.m360.android.debug: 93% user + 1.9% kernel / faults: 4145 minor 1 major
                                                    46% 2133/system_server: 19% user + 26% kernel / faults: 5070 minor 4 major
                                                    0% 335/debuggerd: 0% user + 0% kernel / faults: 9088 minor 5 major
                                                    13% 4932/com.android.phone: 4.7% user + 8.2% kernel / faults: 3168 minor
                                                    8.1% 4109/com.android.systemui: 3.6% user + 4.4% kernel / faults: 2137 minor
                                                    6.3% 21043/com.google.android.apps.maps: 3% user + 3.2% kernel / faults: 709 minor
                                                    5% 25184/adbd: 0.5% user + 4.4% kernel / faults: 2042 minor
                                                    2.6% 264/surfaceflinger: 0.7% user + 1.9% kernel
                                                    2.6% 4922/com.quicinc.cne.CNEService: 1.2% user + 1.4% kernel / faults: 810 minor
                                                    0% 4927/com.qualcomm.qti.tetherservice: 0% user + 0% kernel / faults: 806 minor 2 major
                                                    1.1% 188/mmcqd/0: 0% user + 1.1% kernel
                                                    1.1% 193/ueventd: 0.4% user + 0.7% kernel
                                                    0.8% 6737/mpdecision: 0% user + 0.8% kernel
                                                    0.5% 16314/ksoftirqd/3: 0% user + 0.5% kernel
                                                    0.4% 3/ksoftirqd/0: 0% user + 0.4% kernel
                                                    0.4% 3487/com.android.chrome: 0.4% user + 0% kernel / faults: 350 minor 60 major
                                                    0.4% 16316/kworker/3:1: 0% user + 0.4% kernel
                                                    0.4% 30162/kworker/0:0: 0% user + 0.4% kernel
                                                    0.2% 7/kworker/u:0H: 0% user + 0.2% kernel
                                                    0.2% 159/cfinteractive: 0% user + 0.2% kernel
                                                    0.2% 1047/kworker/u:5: 0% user + 0.2% kernel
                                                    0.2% 1457/com.whatsapp: 0.2% user + 0% kernel
                                                    0.2% 6653/irq/33-cpubw_hw: 0% user + 0.2% kernel
                                                    0.2% 13154/kworker/0:0H: 0% user + 0.2% kernel
                                                    0.2% 16313/kworker/3:0H: 0% user + 0.2% kernel
                                                    0.2% 30595/kworker/0:1: 0% user + 0.2% kernel
                                                    0.1% 181/boost_sync/0: 0% user + 0.1% kernel
                                                    0.1% 184/boost_sync/3: 0% user + 0.1% kernel
                                                    0.1% 212/logd: 0.1% user + 0% kernel
                                                    0.1% 261/healthd: 0% user + 0.1% kernel
                                                    0.1% 334/netd: 0% user + 0.1% kernel / faults: 18 minor
                                                    0% 371/oemlogkit: 0% user + 0% kernel
                                                    0.1% 10135/com.google.android.talk: 0.1% user + 0% kernel
                                                    0.1% 16176/logcat: 0.1% user + 0% kernel
                                                    0.1% 22082/com.google.android.apps.messaging: 0.1% user + 0% kernel
                                                    0.1% 25409/kworker/u:3: 0% user + 0.1% kernel
                                                   +0% 18943/migration/2: 0% user + 0% kernel
                                                   +0% 18944/kworker/2:0: 0% user + 0% kernel
                                                   +0% 18945/kworker/2:0H: 0% user + 0% kernel
                                                   +0% 18946/ksoftirqd/2: 0% user + 0% kernel
                                                   +0% 18947/kworker/2:1: 0% user + 0% kernel
                                                   +0% 18955/migration/1: 0% user + 0% kernel
                                                   +0% 18956/kworker/1:0: 0% user + 0% kernel
                                                   +0% 18957/kworker/1:0H: 0% user + 0% kernel
                                                   +0% 18958/ksoftirqd/1: 0% user + 0% kernel
                                                  70% TOTAL: 44% user + 24% kernel + 0.7% iowait + 0.1% softirq
                                                  CPU usage from 6332ms to 6867ms later:
                                                    92% 17742/com.m360.android.debug: 92% user + 0% kernel
                                                      90% 17742/0.android.debug: 90% user + 0% kernel
                                                    5.6% 2133/system_server: 1.8% user + 3.7% kernel / faults: 9 minor
                                                      5.6% 2241/ActivityManager: 1.8% user + 3.7% kernel
                                                      1.8% 4039/Binder_3: 1.8% user + 0% kernel
                                                    4.6% 21043/com.google.android.apps.maps: 0% user + 4.6% kernel / faults: 19 minor
                                                      4.6% 21043/droid.apps.maps: 0% user + 4.6% kernel
                                                    5% 25184/adbd: 0% user + 5% kernel / faults: 166 minor
                                                      3.3% 25184/adbd: 0% user + 3.3% kernel
                                                     +0% 18939/adbd: 0% user + 0% kernel
                                                    2.4% 264/surfaceflinger: 0% user + 2.4% kernel
                                                      1.2% 298/DispSync: 0% user + 1.2% kernel
                                                      1.2% 324/EventThread: 1.2% user + 0% kernel
                                                    1.1% 3/ksoftirqd/0: 0% user + 1.1% kernel
                                                    1.1% 7/kworker/u:0H: 0% user + 1.1% kernel
                                                    1.3% 6737/mpdecision: 0% user + 1.3% kernel
                                                      1.3% 6756/mpdecision: 0% user + 1.3% kernel
                                                    1.4% 16314/ksoftirqd/3: 0% user + 1.4% kernel
                                                   +0% 18938/sh: 0% user + 0% kernel
                                                   +0% 18942/ps: 0% user + 0% kernel
                                                  54% TOTAL: 40% user + 14% kernel
03-20 18:20:02.174 2133-18959/? E/ActivityManager: Error reading /data/anr/traces.txt
                                                   java.io.FileNotFoundException: /data/anr/traces.txt: open failed: ENOENT (No such file or directory)
                                                       at libcore.io.IoBridge.open(IoBridge.java:452)
                                                       at java.io.FileInputStream.<init>(FileInputStream.java:76)
                                                       at android.os.FileUtils.readTextFile(FileUtils.java:236)
                                                       at com.android.server.am.ActivityManagerService$21.run(ActivityManagerService.java:13183)
                                                    Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
                                                       at libcore.io.Posix.open(Native Method)
                                                       at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
                                                       at libcore.io.IoBridge.open(IoBridge.java:438)
                                                       at java.io.FileInputStream.<init>(FileInputStream.java:76)
                                                       at android.os.FileUtils.readTextFile(FileUtils.java:236)
                                                       at com.android.server.am.ActivityManagerService$21.run(ActivityManagerService.java:13183)

Note also that onRunTask is never called (well the log at first line is never displayed)
Gcm version : compile 'com.google.android.gms:play-services-gcm:10.2.0'
maybe that's the issue I've updated it this morning, before I started to get the ANRs
the way I defined it in my manifest :
    <service
        android:name=".service.offline.SyncOfflineContentService"
        android:description="@string/connection"
        android:exported="true"

        android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
        <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
        </intent-filter>
    </service>

my service :
public class SyncOfflineContentService extends GcmTaskService {

 private final static String TAG = "SyncOfflineContentSer";

 //private final static long SYNC_PERIOD_SECONDS = 36000;
 private final static long SYNC_PERIOD_SECONDS = 30;
 private final static String PERIODIC_SYNC_TAG = "SyncOfflineContentService Done";

 private final Api api;
 private final ImageManagerFactory imageManagerFactory;
 private final FileManager fileManager;

 public SyncOfflineContentService() {
  api = Api.getInstance();
  imageManagerFactory = new ImageManagerFactory();
  fileManager = new FileManager(api.getOkHttpClient());
 }

 @Override
 public int onRunTask(TaskParams taskParams) {
   Log.i(TAG, "onRunTask called");

   try (Realm realm = Realm.getDefaultInstance()) {
    try {

     //some networking

     realm.executeTransaction(new Realm.Transaction() {
      @Override
      public void execute(Realm realm) {
       //storing data in Realm storage
      }
     });
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  } //auto close

 return GcmNetworkManager.RESULT_SUCCESS;
}

public static void scheduleSync(final Context ctx) {
 Log.i(TAG, "scheduleSync");

 GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(ctx);
 PeriodicTask periodicTask = new PeriodicTask.Builder()
  .setPeriod(SYNC_PERIOD_SECONDS) // occurs at *most* once this many seconds - note that you can't control when
  .setRequiredNetwork(PeriodicTask.NETWORK_STATE_CONNECTED) // various connectivity scenarios are available
  .setTag(PERIODIC_SYNC_TAG) // returned at execution time to your endpoint
  .setService(SyncOfflineContentService.class) // the GcmTaskServer you created earlier
  .setPersisted(true) // persists across reboots or not
  .setUpdateCurrent(true) // replace an existing task with a matching tag - defaults to false!
  .build();
 gcmNetworkManager.schedule(periodicTask);

}

public static void stopSync(Context ctx) {
 Log.i(TAG, "stopSync");
 GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(ctx);
 gcmNetworkManager.cancelAllTasks(SyncOfflineContentService.class);
}
}

I was inspired by this blog post :
http://speakman.net.nz/blog/2016/04/26/implementing-gcm-network-manager-for-periodic-network-requests-on-android/
thanks a lot !


text:
Q: Drilldown using HighStocks I am using HighStocks v5.0.7 for creating graphs. For a specific graph I would like to implement drilldown feature.
Do I need to add any additional modules for this?
Currently I tried without any additional modules which is not working.
Note: I am working on Ruby on Rails App.
Any ideas?

A: I enabled drill down by downloading the drilldown js file from http://code.highcharts.com/modules/drilldown.js and updated application.js by adding //= require highcharts/modules/drilldown.
This is the same for highstock as well.


text:
Q: Is "upstairs" correct here? On the 10th floor, the two men pulled out their guns and started shooting at each other.
On the third floor, the office workers could hear the gunfire upstairs.

*

*Can upstairs be used about a floor that is more than one floor above?

*Is upstairs the most natural word you could think of to use here?

A: Yes, "upstairs" is often used to describe a floor above the one you have previously mentioned, even in buildings with many floors.
I can't find fault with your example, yet it doesn't feel quite right because you state right at the beginning that the people are on the third floor. As you must have already stated that the gunfire is occurring on the 10th floor, to then add "upstairs" at the end of the sentence is something of a redundancy.
As an alternative, you could say:

The office workers on the third floor could hear the gunfire from upstairs.

or

Office workers said the gunfire could be heard from as far away as the third floor.


text: Q: Anything for C# Similar to Java JPA to build queries with Methods directly? got a quick question to see if there is anything for C# that is equivalent to the functionality that I use with Java's JPA an Hibernate for the findBy___ and findAllBy____ build queries / methods that you can do in Java - where you are able to create functions in Java to query the tables without having to write queries, you just need to write a method in your repository class with findAllBy<columnName>EqualsAnd<anotherColumnName>Equals?


text:
Q: Are there any options of bash with which it is invoked? I find that the default shell that I use when I start Terminal (with Ctrl+Alt+T) is /bin/bash.
And running the built-in command type on bash as:
type -p bash

returns the result as:
/bin/bash

Suggesting the same executable is run when I do Ctrl+Alt+T or say bash.
This shell is the same as an invocation of the command bash with some of its options passed to it right? If yes, what are these options?
As an example, perhaps the -i option gets passed so as to make the bash shell interactive?
PS: Maybe this is related too, but I cannot seem to piece together all the pieces here.

A: Usually, no, the terminal does not pass any options to bash. bash does, however, assume a set of default options depending on how it was invoked. From man bash, section INVOCATION:
An interactive shell is one started without  non-option  arguments  and
without the -c option whose standard input and error are both connected
to terminals (as determined by isatty(3)), or one started with  the  -i
option.   PS1 is set and $- includes i if bash is interactive, allowing
a shell script or a startup file to test this state.

An interactive shell further activates other options.
Further some defaults apply based on the invocation name (sh vs bash). Reading on (section on set):
-h      Remember  the location of commands as they are looked up
        for execution.  This is enabled by default.
-m      Monitor mode.  Job control is enabled.  This  option  is
        on  by  default  for  interactive shells on systems that
        support it (see JOB CONTROL above)
-B      The  shell performs brace expansion (see Brace Expansion
        above).  This is on by default.
-H      Enable !  style history substitution.  This option is on
        by default when the shell is interactive.

Combined, simply invoking bash on a terminal will enable these options.
You can confirm this by checking the value of the $- special variable:
$ echo $-
himBH

An additional option that maybe set is if your terminal is set to start login shells. In that case -l is explicitly passed by the terminal as an option.


text:
Q: Using System.IO.StreamWriter to write another line I need to update the students score with a new score but I cant get it to write to the line that the students current score it at. It just deletes the whole text.
Alex,letmein,0
David,qwerty1,0
John,password,0
Paul,lion,0
Luke,bennett,0
Ronald,Mcdonald,0
Erin,german,0
Laura,Scotland,0
Ross,extra,0
Alan,beverage,0
Try
 fileName = "C:\Documents and Settings\Student\Desktop\Task10\primary4.txt"
 Dim sWriter As New System.IO.StreamWriter(fileName)
           index = lblPosition.Text
            sWriter.Write(username(index))
            sWriter.Write(",")
            sWriter.Write(password(index))
            sWriter.Write(",")
            sWriter.WriteLine(updatescore(position)
            sWriter.Close()
            MessageBox.Show("Writing file to disk")
            Me.Close()
     Catch ex As Exception
     MessageBox.Show(ex.Message)
End Try

A: You cannot update a specific line in a text file.  You can only rewrite a text file from scratch or append to it.  Which is not what you want here.
You have to use File.ReadAllLines() to get a string[] with the lines in the text file.  Search the specific element in the array that you want to update.  Then write it all back with File.WriteAllLines().
This is expensive of course, but your text file is small.  This is the primary reason why database engines are popular.

A: I see at least one additional bug in here (an exception would result in leaving the file open).  You should do something like this instead:
fileName = "C:\Documents and Settings\Student\Desktop\Task10\primary4.txt"
Dim sWriter As IO.StreamWriter
Try
    sWriter = New IO.StreamWriter(fileName, True)
    index = lblPosition.Text
    sWriter.Write(username(index))
    sWriter.Write(",")
    sWriter.Write(password(index))
    sWriter.Write(",")
    sWriter.WriteLine(updatescore(position)
    MessageBox.Show("Writing file to disk")
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    sWriter.Close()
End Try
Me.Close()


text:
Q: Show different text from option I have a dropdown with all countries and their phone code. My drop down as a limited space, so the text must be short.
When the dropdown is open, I want to show the the country name and the phone code, but when a user select an option, I only want to show the phone code on the dropdown as the selected value.
<select ng-model="country" ng-options="c.phoneNumberCountryCode as (c.countryName + ' (+' + c.phoneNumberCountryCode + ')' ) for c in countriesList">
</select>

http://jsfiddle.net/0fadq61k/

A: I would combine ng-selected with ng-click in an attempt to achieve this. The problem with ng-click (inherent in Angular itself) is that while it does refresh your whole list, it does not refresh the already selected item. I would suggest that you change your design. One thing you could do is use for example the first 3 letters of the country name, or a similar combination. Place the following code in your fiddle to see an example:
HTML

     <select ng-model="country" ng-options="c.phoneNumberCountryCode as (c.countryName + ' (+' + c.phoneNumberCountryCode + ')' ) for c in countriesList" ng-selected="onCodeSelected(country)" ng-click="onClick()">
     </select>

JS
var app = angular.module('app', []);

function Ctrl($scope) {

  //this should be in a service
  $scope.countriesList = [{
    id: 0,
    countryName: 'Portugal',
    phoneNumberCountryCode: '351'
  }, {
    id: 1,
    countryName: 'Spain',
    phoneNumberCountryCode: '34'
  }, {
    id: 2,
    countryName: 'UK',
    phoneNumberCountryCode: '44'
      }, {
    id: 3,
    countryName: 'Australia',
    phoneNumberCountryCode: '61'
  }];

    $scope.onClick = function () {
    //refresh data from service instead of hardcoded like below
        $scope.countriesList[0].countryName = "Portugal";
      $scope.countriesList[1].countryName = "Spain";
      $scope.countriesList[2].countryName = "UK";
      $scope.countriesList[3].countryName = "Australia";
  }

    $scope.onCodeSelected = function(countryCode) {
    if (countryCode) {
     angular.forEach($scope.countriesList, function(value, key) {
        if (value.phoneNumberCountryCode === countryCode) {
            var countryShort = $scope.countriesList[value.id].countryName.substring(0, 3);
            $scope.countriesList[value.id].countryName = countryShort;
        }
      })
    }
  }
}

A: Can you try this,

    <select ng-options="item as item.id for item in items" ng-model="selected"
      ng-change="dispThis(selected)"
    ></select> {{output}}

and in script
  var app = angular.module('app', []);

function Ctrl($scope) {

  $scope.items = [{
    label: 'Portugal',
    id: '351'
  }, {
    label: 'Spain',
    id: '34'
  }];

  $scope.dispThis = function(c){

      console.log(c);
      $scope.output = "Country: "+c.label+" & Ph.code "+
            c.id

    };
}


text:
Q: How to search charged option in a v-select i have this v-select whose items charge dinamicaly, the user can choose several options from it, the problem is i have to many options and i want the user can search the option that he/she wants writing text:
       <v-col cols="7">
          <v-select
            v-model="fillModReparacion.listamanodeObraC"
            :items="fillModReparacion.listamanodeObra"
            item-value="itg_id"
            item-text="itg_descripcion"
            attach
            chips
            label="Mano de Obra"
            multiple
            outlined
            clearable
            return-object
          ></v-select>
        </v-col>

A: You can use v-slot:prepend-item to prepend the search before the options list inside v-select.
Live Demo :

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: () => ({
    searchTerm: "",
    fruits: [
      "Apples",
      "Apricots",
      "Avocado",
      "Bananas",
      "Blueberries",
      "Blackberries",
      "Dates",
      "Eggplant",
      "Figs",
      "Grapes",
      "Grapefruit",
      "Guava"
    ],
    fruitsCopy: [],
    selectedFruits: []
  }),
  mounted() {
    this.fruitsCopy = [...this.fruits];
  },

  computed: {},
  methods: {
    searchFruits(e) {
      if (!this.searchTerm) {
        this.fruits = this.fruitsCopy;
      }
      this.fruits = this.fruitsCopy.filter((fruit) => {
        return fruit.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
      });
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.2.21/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vuetify@2.2.21/dist/vuetify.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css"/>
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-select v-model="selectedFruits" :items="fruits" attach label="Favorite Fruits" multiple>
        <template v-slot:prepend-item>
          <v-list-item>
            <v-list-item-content>
              <v-text-field v-model="searchTerm" placeholder="Search" @input="searchFruits"></v-text-field>
            </v-list-item-content>
          </v-list-item>
          <v-divider class="mt-2"></v-divider>
        </template>
      </v-select>
    </v-container>
  </v-app>
</div>


text:
Q: Update Panel and Drop Down List databinding twice - lifecycle I think this is an asp.net page life cycle question, but none the less, i can't quite figure it out.
I have a drop down list in an update panel that lists users and then shows details below it (update or delete).  When the I click delete, the code behind goes and clears the ddl (to remove the deleted user), and then rebinds it.  All fine.  Somewhere between the end of the code behind and when the page updates, it then appends the list again.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DropDownList1.AppendDataBoundItems = true;
        DropDownList1.Items.Insert(0, new ListItem("Select a User", "select"));
        DropDownList1.SelectedValue = "select";
        DropDownList1.DataSourceID = "srcUsers";
        DropDownList1.DataBind();
    }
}
protected void btnDelete_Click(object sender, EventArgs e)
{
    DropDownList1.AppendDataBoundItems = false;
    DropDownList1.DataSourceID = "srcUsers";
    DropDownList1.DataBind();
    DropDownList1.AppendDataBoundItems = true;
    DropDownList1.Items.Insert(0, new ListItem("Select a User", "select"));
    DropDownList1.SelectedValue = "select";
}//at this point, the quick watch shows the correct count for the ddl

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
     <asp:DropDownList ID="DropDownList1"  Width="150"  runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
     </asp:DropDownList>
  </ContentTemplate>
  <Triggers>
     <asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
  </Triggers>
</asp:UpdatePanel>

Note: srcUsers is a object data source
If I remove the ddl binding code from the button, then it doesn't update the ddl at all (with it in, it does it twice!)
Where is it binding the second time?  Why isn't it binding if I remove the button code?  How come I can't step through this in VS?

A: Himadri's code got me thinking (thanks for the effort!!!!) that for delete operations, i really didn't need to rebind the dropdownlist, i have the SelectedValue.... so i can just delete it from the dropdownlist.
DropDownList1.Items.Remove(selectedValue);

Duh.
I have on the other half of the page code that does an insert type operation (hence the update panel) that was calling the same code (Himadri's BindCombo) and having the same issue, but i think i can find a similar solution.
I still would like to know how the VS debugger lets that happen.
Thanks again Himadri!

A: Check the code below if it can help you.
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindCombo();

        }
    }
    public void BindCombo()
    {
        DropDownList1.Items.Clear();
        DropDownList1.AppendDataBoundItems = true;
        DropDownList1.Items.Insert(0, new ListItem("Select a Category", "select"));
        DropDownList1.SelectedValue = "select";
        DropDownList1.DataSourceID = "ds1";
        DropDownList1.DataBind();

    }

   protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //---- It can be placed in delete button's click event also ------//
        ds1.DeleteCommand = "Delete from Categories where CategoryID="+DropDownList1.SelectedValue;
        ds1.Delete();
        BindCombo();
        //---- It can be placed in delete button's click event also ------//
    }


text:
Q: In subversion, how can I un-hijack a file? Currently, my team has a set of files that should not be under version control, but they are.  I would like to remove them from our subversion repository, and allow everyone to keep their local versions.  What is the best way to accomplish this?
Deleting the files removes them from the repository, as well as everyone's local file system.  Using the --keep-local flag almost works.  It allows me to keep the copy on my machine, deletes it from the repository, but still removes the files from everyone else's file system.
Thanks!

A: After you delete the file, your users will have to recover the file from the repository using svn export.
$ svn export -r x path ./

Where x is a revision where the file existed before it was deleted, path is the full path to the file, and ./ is where the file will be placed.
See svn help export for more information.

A: When you remove it from the repo, it's will end up removing it from the other working copies.
When you do come to putting a new system in place, one technique that usually works quite well is to have the code look for a local file (say config-local.php) which is specifically ignored (and so never gets put into the repository), and a common file that is read in if the more specific one is not found.  That would either have a generic configuration, or throw an error to have them create a local version.

A: You can only delete the file, and accept that it gets deleted everywhere. Users can always recover the file from subversion using a subversion export command.

A: Instead of deleting it, move it to some backup filename (in SVN of course). Then set the svn:ignore property on the old name.
The files will be deleted anyway, but nobody will lose their changes.


text:
Q: Can't bind selection to WPF Combobox I would like to have a ComboBox with two options "M" and "F" and set the selection from my code with a string of one of the values.  This seems so basic it's embarassing to even ask.  However, I haven't seen a single example that doesn't include 50 lines of code with custom classes, etc, etc.  To make things even easier, I want to prefill the two option in my XAML.  Why is this simple task making me feel like a mental midget?  This is what I have:
<ComboBox x:Name="cboGender"  >
    <ComboBoxItem Tag="M" Content="M"></ComboBoxItem>
    <ComboBoxItem Tag="F" Content="F"></ComboBoxItem>
</ComboBox>

Code Behind:
cboGender.SelectedValue = "M";

Please help before I smash my computer and go back to ASP.NET development forever.

A: Try the following:
cboGender.ItemsSource = new string [] { "M", "F" };
cboGender.SelectedItem = "M";

You need to set the ItemsSource to the collection of items. The ComboBox will then generate the ComboBoxItems for you.

A: Add the SelectedValuePath and it works:
<ComboBox x:Name="cboGender" SelectedValuePath="Content" >
    <ComboBoxItem Tag="M" Content="M"></ComboBoxItem>
    <ComboBoxItem Tag="F" Content="F"></ComboBoxItem>
</ComboBox>

(SelectedValuePath="Tag" would work, too, having the same data in two places seems quite redundant either way though)

As a side-note, similar to Colin's answer you can set the items like this:
xmlns:sys="clr-namespace:System;assembly=mscorlib"

<ComboBox x:Name="cboGender">
    <sys:String>M</sys:String>
    <sys:String>F</sys:String>
</ComboBox>

(Both SelectedItem and SelectedValue work in this case)

A: Try this - cboGender.SelectedIndex = 0; before smashing your system.. :)

A: To a first approximation, if you ever manipulate WPF UI elements in code you're doing it wrong.  Sure, you can create a combo box with an "M" and an "F" and preset its selection:
<ComboBox>
  <ComboBoxItem>M</ComboBoxItem>
  <ComboBoxItem>F</ComboBoxItem>
  <ComboBox.SelectedIndex>0</ComboBox.SelectedIndex>
</ComboBox>

But then what?  What do you do with that selection?  If your answer involves something like this:
if cboGender.SelectedValue == "M"

you're traveling down a road that will lead you to writing programs that are very hard to maintain.
If, on the other hand, you create a class to bind your UI to, like this:
public class MyViewModel
{
   public MyViewModelClass()
   {
      Gender = "M";
   }

   public IEnumerable<string> Genders { get { return new string[] { "M", "F" } };

   public string Gender { get; set; }
}

Then your XAML - assuming that somewhere along the line you've set the DataContext to an instance of MyViewModel - becomes:
<ComboBox ItemsSource="{Binding Genders}" SelectedValue="{Binding Gender}"/>

Any other logic that uses the Gender property now looks at this class, not the UI.  So you can change the UI without affecting your logic, and vice versa.
(Note that while view models typically implement INotifyPropertyChanged, you only need to do this if you're going to be changing the Gender in your code and want the new values to be reflected in the UI.)


text:
Q: LightDM: What's the difference between a seat and a session? My background desire is to configure LightDM to display a greeter on more than one virtual terminal after boot.
That aside, I'm reading LightDM docs, the best of which I've found are repeated in numerous wikis and exemplified here:
https://wiki.parabola.nu/LightDM
I can sort of follow the default configs just fine, but what loses me is what the distinction between a seat and session is.
If I switch users, and run "dm-tool list-seats" I see one seat with two sessions and I have a session on vt7 and a session on vt8.
And yet the only clues I find on-line from people having asked about same seem to duplicate seats:

*

*How to enable second x session on tty8 in 14.04

*https://unix.stackexchange.com/questions/87169/autostart-all-lightdm-seats-and-show-one-as-default
and it seems to me, to a basic element missing from the documentation underpinning this: what is a seat and what is a session and how do they differ?
The corollary is:
Can we configure lightdm to start

*

*one seat with two sessions (on vt7 and vt8 say), or

*two seats with one session each (on vt7 and vt8 say)

It would be nice if this were better documented and if the fancy takes me I'll file an issue asking for it here:
https://github.com/CanonicalLtd/lightdm

A: The concepts are a part of systemd.
There are definitions and explenations of the terms session and seats in this link:
https://www.freedesktop.org/wiki/Software/systemd/multiseat/
This page also include a link to a page describing implication for display managers as LightDM.


text:
Q: What is the matrix of inertia of a thin rectangular plate? I only want to get sure how the matrix looks like,
Is it : $\begin{bmatrix}
\frac{Mb^2}{3} &0  &0 \\
 0&\frac{Ma^2}{3}  & 0\\
 0& 0 & \frac{M(a^2+b^2)}{3}
\end{bmatrix}$
Or not ?(a=length,b=width,M=mass)


text:
Q: How can I get the spatial correlation between two datsets in r? I have two arrays:
data1=array(-10:30, c(2160,1080,12))
data2=array(-20:30, c(2160,1080,12))
#Add in some NAs
ind <- which(data1 %in% sample(data1, 1500))
data1[ind] <- NA

One is modelled global gridded data (lon,lat,month) and the other, global gridded observations (lon,lat,month).
I want to assess how 'skillful' the modelled data is at recreating the obs. I think the best way to do this is with a spatial correlation between the datasets. How can I do that?
I tried a straightforward x<-cor(data1,data2) but that just returned x<-NA_real_.
Then I was thinking that I probably have to break it up by month or season. So, just looking at one month x<-cor(data1[,,1],data2[,,1]) it returned a matrix of size 1080*1080 (most of which are NAs).
How can I get a spatial correlation between these two datasets? i.e. I want to see where the modelled data performs 'well' i.e. has high correlation with observations, or where it does badly (low correlation with observations).


text:
Q: Tomcat 7 not starting in Eclipse 4.2 (timeout). How to get more verbose output? I am really struggling with an Eclipse project where Tomcat is giving me timeout. I thought at first this might be a mistake I did in some project configuration, so I reverted to an earlier version of my code. However this is still giving the same error! When I try to start a new project (Spring MVC) along the existing one, the new one seems to work fine and (if I disable the non-working one) the server now starts.
My question really is: How can I get more verbose output or log from Tomcat? The server telling me "it was unable to start within the time limit" does not really help me. Most of the solutions I have found for this kind of problem arent really solutions either, but "remove the server and add it again" or "Delete your eclipse workspace and start over again", etc. Is it really not possible to get Tomcat 7 to do some proper debug-logging to tell me whats going on?
The following is all the output I get:
mai 03, 2013 1:17:45 PM org.apache.catalina.core.AprLifecycleListener init
mai 03, 2013 1:17:46 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:kneip' did not find a matching property.
mai 03, 2013 1:17:46 PM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
mai 03, 2013 1:17:46 PM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
mai 03, 2013 1:17:46 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 666 ms
mai 03, 2013 1:17:46 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
mai 03, 2013 1:17:46 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
mai 03, 2013 1:17:57 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri May 03 13:17:57 CEST 2013]; root of context hierarchy
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Successfully resolved class for [net.krg.kneip.AppConfig]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4cb8a2a9: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,appConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,camel,jmsConfig,activeMq,pooledConnectionFactory,jmsConnectionFactory,applicationContextProvider]; root of factory hierarchy

Thanks in advance!

A: In the end you need to increase the timeout limit for startup of tomcat from eclipse.

*

*Double click on the Server ("Apache Tomcat") within the "Servers" view.

*Open the "Timeouts" Section

*increase "Start (in seconds)" to 120

(this does not lead to more log information, but it should solve your problem.)


text:
Q: How to sync up your git dev branch after you've merged+squashed a PR to master, in GitHub? So GitHub has the ability to merge+squash commits for a PR.
We follow the process of PR'ing code from dev -> master.
Previously, I've been just 'merging' the PR's but that generates a new commit which says: "Merge Pull Request #1 from foo/bar". :( Boooo...
So I thought I might try the new Squash Commits thingy with GH. This created a new commit with all my previous commits squashed. Ok, so far so good.
I then went back to my dev branch (on my developer machine) .. pulled down upstream/master (which was where the PR and squash-merge happened)) and it now added another commit to my local history! It didn't go "Oh .. wow. you're waaay out of line .. lets sync up". It just did a merge.
So the Squash+Merge button squashed 4 commits and replaced it with 1 ...
the pull upstream/master on my localhost machine now has my 4 commits still there AND the Squashed-commit the PR did AND a new commit which is "Merge branch master .. blah ... noise ..spam" commit :( :( :(
Is there a special trick/workflow I should be doing after a merge-squash has occurred .. to make sure my dev branch is properly sync'd? Like .. does everyone just delete their localhost dev branch before they do a pull upstream/master back down to their localhost and into a (newly created) dev branch?
Remember: the goal here is to avoid those crappy "Merge Pull Request #2.." merge bubble messages.
Or are people just doing this via the CLI for the time being until GitHub learns how to do this :(

A: I think the problem is with your workflow: usually once you merge a pull request (no matter which method you use) you are then done with that branch. If you want to do further changes, you better create a new feature branch out of current upstream/master and later you could open another pull request to merge it back.
In case you really want to stick to a single long-lived branch for all development (the one you call dev), there are a few caveats you have to keep in mind:

*

*If you are not the only one working on that branch, you have to avoid any kind of history rewriting. No rebasing, no squashing, no resetting, not even amending commits. This basically rules out using squash merge.

*If you are sure you are the only one working on that branch, and you use GitHub's squash option to merge pull requests as you did, then you must reset you local dev branch to latest upstream/master before resuming your work there. That also means that later you will need to force-push to upstream to create a new pull request.

The last point is error-prone and will affect previous code reviews so personally I would choose to just use short-lived feature branches.

A: If your dev branch was merged and squashed then you don't need it anymore. Just reset it to upstream/master.
If there is some newer changes you can call git rebase -i upstream/master instead and remove all commits which was merged, rebasing the rest.

A: There is a better solution for merging and squashing your commits without an extra commit saying "Merge Foo branch in Bar" . You should always prefer rebasing instead of merging and then squashing. So rebase will help you in merging two branches without any extra commit. You should try rebasing the branch instead of merging. Here is the detailed explanation for the same here.


text:
Q: Vector space of infinite sequences in $\Bbb R$ How do you show that the set of infinite sequences with entries in $\Bbb R$ is uncountably infinite-dimensional as a vector space over $\Bbb R$.

A: Step 1: There is a family $\{A_r\mid r\in\Bbb R\}$ such that $A_r\subseteq\Bbb N$, and for $r\neq r'$ the intersection $A_r\cap A_{r'}$ is finite.
Step 2: Consider the characteristic functions of $A_r$ from the family of Step 1. Can they be linearly dependent?
(Another option is to use a diagonal argument to show that given any countable family of vectors, there is one not spanned by them. The above method has the benefit of showing that the dimension is as large as it can be, not just uncountable.)

A: Hint: For each $n \in \mathbb N$,can you see that $ \mathbb R ^n$ sits in your vector space?


text:
Q: Returning view to original position after pan gesture, swift I have a UIView (the red one in the image) I can pan in the x-axis. I can return the view back to the original position but I want to return to that position as though it's being pulled by a light spring, or sort of easing back to the original position with some sort of deceleration.
At the moment it weirdly jumps back to that position.
This is my relevant code and an image is attached to show the view in it's maximum position.

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {

        if recognizer.state == UIGestureRecognizerState.Ended {

            print(backgroundView.center.x) //120.0
            print(backgroundView.center.y) //64.0

            let xDivision = Double(backgroundView.center.x/120.0)
            print(xDivision)

            recognizer.view?.center = CGPointMake(120.0, 64.0)

            self.view.frame = CGRectMake(backgroundView.center.x, 0, self.view.frame.width , self.view.frame.height)

            UIView.animateWithDuration(xDivision, delay: 0.0, usingSpringWithDamping: 2.0, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {

                self.view.center.x = 120.0

                }, completion: { (true) in

                    print("Animation Complete")
                    print(self.backgroundView.center.x)
            })

        }

        let translation: CGPoint = recognizer.translationInView(self.view)
        //recognizer.view?.center = CGPointMake((recognizer.view?.center.x)!, (recognizer.view?.center.y)! + translation.y)
        recognizer.setTranslation(CGPointMake(0, 0), inView: self.view)

        var center: CGPoint = (recognizer.view?.center)!
        print(center.x)
        center.x += translation.x
        if center.x < 50.0 || center.x > 320.0 {
            return
        }
        recognizer.view?.center = center

    }

Any ideas on how I can achieve that. A good example of this animation is this app - http://rise.simplebots.co
Thanks.

A: If you are using Auto Layout, changing the frame or center properties can cause problems. Have you thought about just changing the constraint's constant? Like:
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {

    switch recognizer.state {
    case .Began:
        //do something

    case .Changed:
        let translation = recognizer.translationInView(self.view)
        self.leftContraint.constant = self.leftContraint.constant + translation.x
        recognizer.setTranslation(.zero, inView: self.view)

    case .Ended:
        UIView.animateWithDuration(1,
            delay: 0,
            options: .CurveEaseOut,
            animations: {
                self.leftContraint.constant = //your value
                self.view.layoutIfNeeded()
            },
            completion: nil)

    default: ()
    }
}

That helped me with a similar problem.


text:
Q: Why access denied for user within permitted group? First let me start off by saying that I'm not an IT expert, and I've just been experimenting a lot lately with sharing and permissions in Windows 8.1. I've reached a point of extreme confusion right now and I can't find anything online.
Since I'm not running a professional edition of Windows 8.1, I've had to use the net LOCALGROUP command in the command prompt to add users to groups etc.
I basically made a LOCALGROUP called HomeSecure, and added two users (AdminOne and AdminTwo) to it. Both of these users are also in the Administrators group and are indeed administrator accounts in Windows. It sounds pointless but it's because I'm attempting to manually simulate HomeGroup functionality, and plan to add non-administrator accounts from other workstations using the net GROUP command instead once I've got the basics.
I have checked, and the commands worked just fine. The administrator accounts are in that group. The confusion comes about when I remove absolutely all user and group permissions (including Everyone) from my C:\Users\AdminOne and C:\Users\AdminTwo folders except Administrators and SYSTEM, then proceed to add allow permissions for the HomeSecure group...
All of the groups I gave Full Control of the folders to. I went into the advanced settings and made sure everything was checked, and even made the HomeSecure group take ownership of the folders. It's also worth mentioning that I made all of the child objects inherit the owners and permissions of these folders.
But even after all of that, I still can't access the above folders from the network using HomeSecure members. I also can't access them straight from C:\ without it prompting me for administrative consent.
Accessing via the network, I get: You do not have permission to access ----- Contact your network administrator to request access.
Accessing via C:\, I get: You currently don't have permission to access this folder. Click continue to permanently get access to this folder.
If I press continue, all that Windows does is add allow permissions for the current user (AdminOne or AdminTwo) which seems redundant because they were already allowed? They were already allowed via the HomeSecure permissions?
Why? Shouldn't AdminOne and AdminTwo be allowed to access both folders normally since they are in the HomeSecure group?

A: There are a few you're probably running into here:
Token update
Group memberships are stored in the user's token, copies of which are attached to each process running as that user. Run whoami /all in a command prompt to see what groups appear in your token. The one attached to the whoami process will be the one inherited from cmd, which is inherited from explorer. If the group membership does not appear, you need to log off and back on. Then, Windows will recognize that you are indeed a member of an appropriate group, and will let you do things that the group is allowed to do.
Share permissions
When sharing files through Windows shares, there are two access control lists that the user has to pass. First is the ACL on the share itself (not the folder). You can access this ACL by clicking the Permissions button in the shared folder's advanced sharing settings. The normal file system ACL is then checked. If either ACL has a deny entry for the user or one of its groups, the operation is denied. If either ACL has no relevant entry for the user or its groups, the operation is denied.
UAC
Note that membership in powerful default groups like Administrators is ignored for network shares that are not part of domains unless you turn UAC off. Also, if Explorer is not running elevated, it will prompt you for admin credentials if you try to navigate to a folder that only Administrators can get into.


text:
Q: Retrieving multiple rows from seperate model in django relationships I've been struggling with this puzzled for a few hours. Here's a schema of what I'm trying to do.

I have a user model and a profile model, it's a one-to-one relationship, but I'd like to be able to query a user and retrieve all the email addresses (from the User model) for users that share the same company (from the Profile Model). To be fair, my understanding of django is limited, but I went through the serializer relations guide and tried my hands at most approach described there, to no avail. At this point, I'm not even sure I'm on the right path.
So, my understanding of it is

*

*From the user, I need to fetch the profile (a source='profile' approach may work)

*From that profile, I need to retrieve the company

*From that company, I need to retrieve all the user_id that belongs to that company

*From those user_ids, I need to lookup the email fields of all those users

*I need to also filter out the email address of the user making the request

Does this make any sense? At this point, I'm trying to accomplish all of that from the serializer, but was unsuccessful. Here are some snippets of code I tried, but I doubt any of them will point towards any form of solution, unfortunately.
class TeamEmailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email']

class UserSerializer(serializers.ModelSerializer):

    ...

    # only one of them was present at a time, but none gave any promising results

    test_one = Profile.objects.filter(source=profile.company.id).values_list('user_id', flat=True)

    test_one = serializers.RelatedField(source='profile.company.id', read_only=True)

    test_one = TeamEmailsSerializer(many=True, read_only=True)

    test_one = serializers.PrimaryKeyRelatedField(source='email', queryset=User.objects.filter())

    class Meta:
        model = User
        fields = (
            'test_one'
        )

I'm grateful for any clue that may lead towards a solution.

A: First, you should add company FK on your user as well, it will make things much easier for you.
Then you can define a new method on User model:
class User(AbstractBaseUser):
  ...

  def other_users_emails(self):
    return self.company.users.exclude(pk=self.id).values_list('email', flat=True)

Then in your serializer add 'other_users_emails' to the fields list.
Alternatively you could modify to_representation method on your serializer and add 'other_users_emails' attribute directly there


text:
Q: How to create a column based on two conditions from other data frame? I'm trying to create a column that identifies if the row meets two conditions. For example, I have a table similar to this:
> dat <- data.frame(Date = c(rep(c("2019-01-01", "2019-02-01","2019-03-01", "2019-04-01"), 4)),
+                   Rep = c(rep("Mike", 4), rep("Tasha", 4), rep("Dane", 4), rep("Trish", 4)),
+                   Manager = c(rep("Amber", 2), rep("Michelle", 2), rep("Debbie", 4), rep("Brian", 4), rep("Tim", 3), "Trevor"),
+                   Sales = floor(runif(16, min = 0, max = 10)))
> dat
         Date   Rep  Manager Sales
1  2019-01-01  Mike    Amber     6
2  2019-02-01  Mike    Amber     3
3  2019-03-01  Mike Michelle     9
4  2019-04-01  Mike Michelle     2
5  2019-01-01 Tasha   Debbie     9
6  2019-02-01 Tasha   Debbie     6
7  2019-03-01 Tasha   Debbie     0
8  2019-04-01 Tasha   Debbie     4
9  2019-01-01  Dane    Brian     3
10 2019-02-01  Dane    Brian     6
11 2019-03-01  Dane    Brian     6
12 2019-04-01  Dane    Brian     1
13 2019-01-01 Trish      Tim     6
14 2019-02-01 Trish      Tim     7
15 2019-03-01 Trish      Tim     6
16 2019-04-01 Trish   Trevor     1

Out of the Reps that have switched manager, I would like to identify weather this manager is the first or the second manager with respect to the date. The ideal output would look something like:
         Date   Rep  Manager Sales  New_Column
1  2019-01-01  Mike    Amber     6           1
2  2019-02-01  Mike    Amber     3           1
3  2019-03-01  Mike Michelle     9           2
4  2019-04-01  Mike Michelle     2           2
5  2019-01-01 Trish      Tim     6           1
6  2019-02-01 Trish      Tim     7           1
7  2019-03-01 Trish      Tim     6           1
8  2019-04-01 Trish   Trevor     1           2

I have tried a few things but they're not quite working out. I have created two separate data frames where one consists of the first instance of that Rep and associated manager (df1) and the other one consists of the last instance of that rep and associated manager (df2). The code that I have tried that has gotten the closest is:
dat$New_Column <- ifelse(dat$Rep %in% df1$Rep & dat$Manager %in% df1$Manager, 1,
                         ifelse(dat$Rep %in% df2$Rep & dat$Manager %in% df2$Manager, 2, NA))

However this reads as two separate conditions, rather than having a condition of a condition (i.e. If Mike exists in the first instance and Amber exists in the first instance assign 1 rather than If Mike exists with the manager Amber in the first instance assign 1). Any help would be really appreciated. Thank you!

A: An option is to first grouped by 'Rep' filter the rows where the number of unique 'Manager' is 2, and then add a column by matching the 'Manager' with the unique elements of 'Manager' to get the indices
library(dplyr)
dat %>%
  group_by(Rep) %>%
  filter(n_distinct(Manager) == 2) %>%
  mutate(New_Column = match(Manager, unique(Manager)))
# A tibble: 8 x 5
# Groups:   Rep [2]
#  Date       Rep   Manager  Sales New_Column
#  <chr>      <chr> <chr>    <int>      <int>
#1 2019-01-01 Mike  Amber        6          1
#2 2019-02-01 Mike  Amber        3          1
#3 2019-03-01 Mike  Michelle     9          2
#4 2019-04-01 Mike  Michelle     2          2
#5 2019-01-01 Trish Tim          6          1
#6 2019-02-01 Trish Tim          7          1
#7 2019-03-01 Trish Tim          6          1
#8 2019-04-01 Trish Trevor       1          2


text:
Q: windows forms app.config on common files folder I have an application that stores single username and password on the app.config file.
I currently have the app.config writable on runtime so that the user will be able to change it.
problem begins upon installation using a setup project , the app.config is installed on the program files which is not writable for any user.
So , i have changed the app.config location upon installation to the common files folder so it will be accessible for reading and writing for all users.
Now, upon installation it seems that the data stored there is inaccessible at all , using ConfigurationManager.AppSettings["networkPath"] for example returns empty strings.
what am i doing wrong ?

A: You can do it in two ways:

*

*Give special permission to app config file in program files by your installer. We do it using innosetup. If you are incapable of it, then do it from your program startup:
static void Main()
{
    GrantAccess()
}

private static bool GrantAccess()
{
    FileInfo fInfo = new FileInfo(Assembly.GetEntryAssembly().Location + ".config");
    FileSecurity dSecurity = fInfo .GetAccessControl();
    fSecurity.AddAccessRule(new FileSystemAccessRule("everyone",
                                                     FileSystemRights.FullControl,
                                                     AccessControlType.Allow));
    fInfo .SetAccessControl(fSecurity);
    return true;
}

*Else you can choose another location to place your appconfig file, and then read it like this:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), Assembly.GetEntryAssembly().GetName().Name) + ".exe.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,
                                                                       ConfigurationUserLevel.None);
return config.AppSettings.Settings["Key"].Value);

This is a poor choice in my opinion.


text:
Q: Return List from multiple search in C# I have TextBox where users can input many numbers (1 per line).
Then, I'm querying a Child Table which has those numbers.
Those numbers are ForeignKeys from Primary Table.
Primary Table - tblOrders
Child Table - tblOrderItems (ForeignKey is OrderID)
public class OrderItems
{
    public int ID { get; set; }
    public string Order { get; set; }
    public string Status { get; set; }
    public DateTime DataC { get; set; }
    public int Item { get; set; }
}

public IEnumerable<OrderItems> LoadItems()
{
    List<OrderItems> list = new List<OrderItems>();
    string[] textArray = TxtOrder.Text.Split(new string[] { ronment.NewLine }, StringSplitOptions.None);
    foreach (var text in textArray.Distinct())
    {
        var ctx = new DbContext();
        var query = (from p in ctx.tblOrderItems.AsQueryable()
                     join m in ctx.tblOrders on p.RegistID equals m.RegistID
                     where m.Order.Contains(text)
                     select new OrderItems
                     {
                         ID = p.RegistTID,
                         Order = m.Order,
                         Status = p.Status,
                         DataC = m.DataC,
                         Item = p.Item
                     }).FirstOrDefault();
        list.Add(query);
    }
    return list;
}

The problem: Querying like this in the Primary Key, I get correct values because I only get 1 record per item added in TxtOrder Textbox.
But I'm querying tblOrderItems and the tblOrderItems has many records related to 1 record in tblOrders and I can't get them all to my DataGridView.

A: To get the items instead of the item, you need to:
Use ToList instead of FirstOrDefault and AddRange instead of Add.


text:
Q: Sharing data between controllers and dealing with update/change notifications I'm trying to get my head around sharing data between multiple controllers, but couldn't find out yet how this is supposed to work (the angular way). I have create a Data service that look something like this:
angular.module('myapp.services')
  .service('DataSet', function($rootScope) {

  return {

    filter: function(filterMethod) {
      /// ... do async stuff
      $rootScope.$broadcast("Data::filtered");
    },

    brush: function(brushed) {
      /// ... do async stuff
      $rootScope.$broadcast("Data::brushed");
    },

    load: function() {
      /// ... do async stuff
      $rootScope.$broadcast("Data::loaded");
    }
  };
});

Next I want to reuse and update data from this service, so I use it in my controller as follows:
angular.module('myapp.controllers')
  .controller('FilterCtrl', function ($scope, $rootScope, DataSet) {

  $scope.safeApply = function(fn) {
    var phase = this.$root.$$phase;
    if(phase == '$apply' || phase == '$digest') {
      if(fn && (typeof(fn) === 'function')) {
        fn();
      }
    } else {
      this.$apply(fn);
    }
  };

  function updateBrushed() {
    $scope.safeApply(function() {
      $scope.brushed = DataSet.brushed;
    });
  };

  $scope.brushed = [];

  $scope.keepSelected = function() {
    DataSet.filter(DataSet.FilterMethod.KEEP);
  };

  $scope.removeSelected = function() {
    DataSet.filter(DataSet.FilterMethod.REMOVE);
  };

  $scope.$on('Data::brushed', updateBrushed);
  $scope.$on('Data::filtered', updateBrushed);
});

The problem I have is basically illustrated by the use of the saveApply call. Basically I got this code from here: https://coderwall.com/p/ngisma. What I don't understand though is why I need it. As far as I can see, I'm 'within' $angular when updating the DataSet service. Nevertheless, the view for the Filter controller doesn't get updated without a call to saveApply ($apply doesn't work at all because than I run into the apply already in progress issue).
So, basically my question boils down to: is the approach above a good way to share data, and if so how is notification of changes in the service supposed to work?
Update: Based on Julian Hollman his suggestion I came to the following solution: http://jsfiddle.net/Ljfadvru/7/. This more or less illustrates the full workflow I was working on, though some of it is automatically induced in the fiddle, as opposed to user-interaction based in my real application. What I like about this approach is that it only sends signals when all data is updated.
Working with references, as suggested by Ed Hinchliffe, is nice as well. However, I'm working on a web visualization framework and I'm expecting tens of thousands of items. Clearing arrays and pushing new elements (which seem to me the consequence of this proposal) is really not feasible (if I understand this paradigm well, it would also result in a re-rendering of my vis for every single change). I stand corrected though if there are suggestions for further improvement.

A: $broadcast doesn't trigger an $apply and I bet your "async stuff" is not $http from angular.
So something happens outside of angular and angular doesn't know that something has changed.
In my opinion the best thing in that case is to write a wrapper for your async code and trigger $apply after date came back from the backend. Don't do it in the controller.

A: To be honest, I'm not sure quite sure about exactly what is going on with the digest loops in your particular scenario, but I don't think you are approaching this the right way.
The 'angular' way, is to use promises.
Your service should be more like this:
angular.module('myapp.services')
  .service('DataSet', function($rootScope) {
  return {
    filter: function(filterMethod) {
      var returnData = []
      $http.get('/some/stuff').then(function(data){
        for(i in data){
          returnData.push(data[i]);
        }
      });
      return returnData;
    }
  };
});

This sets up an empty placeholder object (returnData) that can be immediately passed to the controller, but a reference is kept so that when the data returns you can retrospectively populate that object. Because the controller and the service reference the same object, it'll 'just work'.
This way you don't have to worry about dealing with $digest or $apply or $broadcast.
You controller can just call $scope.filtered = DataSet.filter();
EDIT
If you want to be able to access the exact same data from multiple controllers:
angular.module('myapp.services')
  .factory('DataSet', function($http) {

  var cache = {
    filtered: []
  }

  return {
    getFiltered: function(){
      if(cache.filtered.length) return cache.filtered;
      $http.get('/some/url/').then(function(data){
        for(i in data){
          cache.filtered.push(data[i]);
        }
      });
    }
  };
});


text:
Q: Use a switch case for a verification function (LWJGL keyboard input)? What the title says. Is it possible?
As far as I know, there is no getKeyPressed or anything of the sort. I want to use a switch case for organization (and practice) as well as speed (or so I was informed).
Basically, the switch case clause(?) is just a boolean return. But how can I check if a key is pressed based on a value passed into it without a pasta bowl of if / else statements?
Obviously this code doesn't work, but I'm looking for something like it.
public void moveCamera() {
    switch (Keyboard.isKeyDown(!!!CASE CHECKING HERE!!!)) {
        case Keyboard.KEY_W:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_A:
            position.x += MOVE_SPEED;
            break;

        case Keyboard.KEY_S:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_D:
            position.x += MOVE_SPEED;
            break;
    }
}

A: Here is a solution that I liked (but did not try) from @KysonTyner.

You can switch on getEventKey(). This will hit your current cases and then you can wrap the whole switch statement with if (getEventKeyState()) {switch/case}. There is no need to use an event listener. – Kylon Tyner

As for what I used, I abandoned the idea of a switch entirely, as I realized that the movement speed would multiply if there were more than one direction of input.
I wanted to support multiple directions of motion for diagonal movement, so it wouldn't be "ghosting" as keys were pressed.
What I did is separate the functions, one to test keyboard input, and one to move the camera. There doesn't have to be any special logic for the key input, as it simply passes an LWJGL Vector3f to the camera move function.
Then, in camera move, I normalized that vector and altered the positions accordingly.
This is a simplified version of my Camera class for demonstration. I removed everything except translation.
package spikespaz.engine.main;

import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector3f;

// Created by spike on 7/3/2017.
public final class Camera {
    private Camera() {}

    private float moveSpeed = 0.2f;
    private Vector3f position = new Vector3f(0, 0, 0);

    public Camera(Vector3f position, Vector3f rotation) {
        this.position = position;
    }

            public void updateKeyInput() {
        Vector3f direction = new Vector3f(0, 0, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
            direction.x = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
            direction.x = -1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
            direction.y = -1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
            direction.y = 1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
            direction.z = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
            direction.z = -1;
        }

        translate(direction);
    }

    private void translate(Vector3f direction) {
        Vector3f normalized = direction.normalise(null);
        Vector3f.add(position, (Vector3f) normalized.scale(moveSpeed), position);
    }

    public float getMoveSpeed() {
        return moveSpeed;
    }

    public void setMoveSpeed(float moveSpeed) {
        this.moveSpeed = moveSpeed;
    }
}

Translate is relative. In the full class I have another function to set absolute position, without the move speed.
In the above example, the input vector for translate is simply a direction. The function should coordinate that based on the movement speed for each frame.