text:
Q: Guardar en matriz ¿Cómo hago para que se guarde letra por letra de la nueva palabra en una matriz?
#include<stdio.h>
int main()
{
    int  i=0,j,arr[26]={},temp;
    char  s[10],arr1[10],*p;
    printf("Enter the string\n");
    scanf("%s",s);
    p=s;
    while(*p!='\0')
         {
            temp=((*p)>92)?(*p)-'a':(*p)-'A';
            if(arr[temp]==0)
              {
                 arr1[i]=temp+'a';
                 arr[temp]=1;
                 i++;
              }
            p++;
         }
    for(j=0;j<i;j++)
        {
           printf("%c",arr1[j]);
        }
    return 0;
}

A: Ya que no has especificado nada, se me ocurrió hacer el ejemplo más vago y simple en C. Tus variables tienen nombres tan raros que dudo que tú mismo puedas entender lo que hace tu programa, ten buena practica y haz tu código legible, y sigue practicando.
Te recomiendo leer el libro de la biblia del C, "el lenguaje C por kernighan y ritchie"
#include "stdio.h"

int main() {
    //insertas las filas y las columnas de la matriz
    int filas, columnas;
    scanf("%d %d", &filas, &columnas);

    //creas la matriz de caracteres
    char arreglo[filas][columnas], letra;

    //insertamos letras(caracteres) no palabras
    for (int i = 0; i < filas; i++) {
        for (int j = 0; j < columnas; j++) {
            printf("Ingresa una letra: \n");
            scanf("%c", &letra);
            arreglo[i][j] = letra
        }
    }

    //imprimimos la matriz
    for (int i = 0; i < filas; i++) {
        for (int j = 0; j < columnas; j++) {
            printf("%c", arreglo[i][j]);
        }
        printf("\n");
    }
}


text:
Q: No data available in table - datatables jquery issue I have a jquery-datatables that I am populating from a method in C#.
The C# method returns some json which I have validated.  However my columns never get populated and instead I get a message that says No data available in table.
I'm completely stuck so hoping someone can help!
var table = $('#example').DataTable({
        ajax: {
            url: pageUrl,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            dataSrc: function (data) {
                console.log(data.d);
                return $.parseJSON(data.d);
            }
        },
        "pageLength": 50,
        fixedHeader: true,
        responsive: true,
        "columns": [
            {
                "data": "key",
                "render": function (data, type, row, meta) {
                    if (type === 'display') {
                        data = '' + data + '';
                    }

                    return data;
                } },
            { "data": "summary" },
            { "data": "created" },
            { "data": "updated" },
            { "data": "Status" },
            { "data": "priority" },
            { "data": "reporter" },
            { "data": "assignee" }
        ],
        autoWidth: false,
        "columnDefs": [
            { "width": "50%", "targets": 0 },
            { "width": "5%", "targets": 1 },
            { "width": "5%", "targets": 2 },
            { "width": "5%", "targets": 3 },
            { "width": "5%", "targets": 4 },
            { "width": "5%", "targets": 5 }
        ],
        "order": [[1, 'asc']],
        "success": fnsuccesscallback,
        "error": fnerrorcallback
    });

    function fnsuccesscallback(data) {
        alert(data.d);

    }

    function fnerrorcallback(result) {
        alert(result.statusText);
    }

And this is the data in the console.log output:
{"summary":"External Change Request Form: tester - 19/1/2021","created":"2021-01-19T15:32:02+00:00","updated":"2021-06-03T08:59:17+01:00","status":"To Do","key":"ITS-4711","assignee":"Bob","priority":"Low","reporter":"Dave"}

A: The issue is this part:
        dataType: "json",
        dataSrc: function (data) {
            console.log(data.d);
            return $.parseJSON(data.d);
        }

in dataSrc callback, data will already be a javascript object, not a JSON string.  Calling $.parseJSON(object) will generate an error, which it looks like datatables is catching (and ignoring, which is bad practice).
Thus giving an unrelated error message that there's no data, rather than that the data processing failed.
Change return $.parseJSON(data.d); to just
return data.d;

redpajama_set_name: RedPajamaStackExchange


text:
Q: make new ajax request when previous one finished i have checkboxes on html page for which JQuery click event is triggered which makes the ajax call. Once request is finished html page is rendered with response data.
fetchActivites = ()->
  $.ajax
    beforeSend: ()->
      $('#checkbox_loader').show()

    url: "/project/users/"
    success: (data, textStatus, jqXHR) ->
      plotData(data, is_append)
    complete: ()->
      $('#checkbox_loader').hide()

Issue is, while one ajax request is going on. user can click another check box and another ajax request is made, before first one getting completed. which is messing up the data to be rendered.
$(document).on "change", ".selectpicker", (evt) ->
  fetchActivites()

using async: false, seems bad practice, have its own drawbacks.
Is there any other way to accomplish the task ?

A: Since noone has come around here is a javascript solution.
var pending; //current request
function enqueueFetchActivities(/*args*/) {
    var current,
        ctx = this,  //save current context
        args = [].slice.call(arguments), //and arguments
        doFetch = function() { //transparent invoker;
            return fetchActivities.apply(ctx, args);
        };
    pending = current =
          pending ? pending.then(doFetch) : doFetch();

    return current.always(function() { //always try to remove pending
        if(pending === current) { //otherwise another request was made
             pending = null;
        }
    });
}
function fetchActivites() {
    return $.ajax(/*...*/);//whatever you want it to do.
}

Now you can call enqueueFetchActivities the way you was calling fetchActivites before.

A: # if another ajax request comes when the previous request has not finished,
# just abort the previous one.
promise?.abort()
promise = $.ajax
  # some ajax params
promise.success = (data, textStatus, jqXHR) ->
  plotData(data, is_append)
promise.complete = ()->
  $('#checkbox_loader').hide()


text:
Q: Is there a way to preserve terminal tab history across computer restarts? I'm using Mac 10.9.5.  When I run a terminal with multiple tabs (using bash shell), I've noticed that when my computer restarts, the terminal will open up with the same number of tabs that were open in the previous session, but the commands I was running in the previous session (accessible via the "history" shell command) are no longer present in each tab.
Is there a way to preserve each session's history in the appropriate tab between computer restarts?

A: Try adding this to ~/.bash_profile:
HISTFILE=~/.bash_history.$(basename $(tty))

This creates a unique history file for the terminal associated with each tab.

A: The command history is saved by the shell when it closes, and by default this goes into ~/.bash_history.
So as the shell in each of your tabs is closed, they each append their own command history to that file.  When new shells/tabs are opened, they will load that file for their history.
So in a sense, each tab's history is saved, and you should be able to use ctrl-R to search for it (within limits of the history size limit), but when reloaded, each tab will see all the history, and in blocks corresponding to the order the previous tabs happened to close.
You might be able to configure the bash history more to your liking.


text:
Q: Convergence in Distribution Suppose $X_n$ are $\mathbb{R}$-valued random variables. Then how would I be able to show that $X_n\rightarrow^D X$ where $X$ is also a $\mathbb{R}$-valued random variable iff $F_n(x)\rightarrow F(x)$ for all $x\in A$ where $A$ is a dense subset of $\mathbb{R}$ and $F_n$ and $F$ are respective distribution functions.

A: We want to show that:
$$ \lim_{n\rightarrow \infty} F_n(x) = F(x), \ \forall x \in C_F \Longleftrightarrow  \lim_{n\rightarrow \infty} F_n(x) = F(x), \ \forall x \in D \subseteq \mathbb{R}, \text{ D is dense}$$
To show $\Rightarrow$, let $D=C_F$. We have proven earlier in the course that for any distribution function $F$, there are at most countable discontinuities. For any set $A \subseteq \mathbb{R}$, if $A^C$ is countable, then $A$ is dense in $\mathbb{R}$. By assumption, $\lim_{n\rightarrow \infty} F_n(x) = F(x), \ \forall x \in C_F = D$ so the first direction is proven.
To show $\Leftarrow$, we assume that $\exists D \subseteq \mathbb{R}$ where $D$ is dense in $\mathbb{R}$ such that $\lim_{n\rightarrow \infty} F_n(x) = F(x), \ \forall x \in D$. Take any $x \in C_F$ we want to look at sequences $l_i \subset D,\ u_i \subset D $ such that $l_i \uparrow x$ and $u_i \downarrow x$. Because $F_n$ is a nondecreasing function, $l_i \le x \le u_i \Rightarrow F_n(l_i) \le F_n(x) \le F_n(u_i)$. By assumption, we have $ \lim_{n\rightarrow \infty} F_n(l_i) = F(l_i)$ and $ \lim_{n\rightarrow \infty} F_n(u_i) = F(u_i)$. So, as $n\rightarrow \infty$, $ F(l_i) \le F_n(x) \le F(u_i)$. Because $x$ is a continuity point of $F$, we have $\lim_{y\rightarrow x} F(y) = F(x)$. Then $\lim_{i\rightarrow \infty} F(u_i) = F(x)$ and $\lim_{i\rightarrow \infty} F(l_i) = F(x)$. This means that as $i \rightarrow \infty$, $ F(x) \le F_n(x) \le F(x)$. So for $n \rightarrow \infty, \ i \rightarrow \infty$ we have $$\lim_{n\rightarrow\infty,\ i\rightarrow \infty}F_n(x) = \lim_{n\rightarrow\infty}F_n(x) = F(x)$$ Since this is true for any $x \in C_F$ we have $X_n \rightarrow^D X$.
Reference:
http://cmi.ac.in/~vinay/notes/measure-final.pdf


text:
Q: Select "N" consecutive groups of "X" records I need to filter "N" consecutive groups of "X" records from a list like this:
1
4
5
6
9
12

In the sample list the consecutive groups of "X" records when X=2 are:
4,5
5,6

Is there a way, using SQL Server 2008 window functions to get that result?.

A: How about this:
DECLARE @x int = 2;

WITH
  consecutive_groups (n, grp) AS (
    SELECT n, n - ROW_NUMBER() OVER (ORDER BY n)
    FROM NumbersTable
  ),
  groups_with_minmax (n, grp, nMin, nMax) AS (
    SELECT n, grp
      , MIN(n) OVER (PARTITION BY grp)
      , MAX(n) OVER (PARTITION BY grp)
    FROM consecutive_groups
  )
SELECT n AS SequenceStart, n+@x-1 AS SequenceEnd
FROM groups_with_minmax
WHERE n+@x-1 BETWEEN nMin AND nMax;

All of the window functions used should be available in SQL Server 2008.


text:
Q: Sanitizing errors sent thru url Ok quick question. I am sending errors through URL in intergers only
(../index?err=4)
then when it gets there I am filtering that error with
$errorget = filter_input(
    INPUT_GET, 'err', $filter = FILTER_SANITIZE_NUMBER_INT
);

I then use a switch to select appropriate echo.
switch ($errorget) {
    case "4":
        $error = 'Error1';
        break;
    case "61":
        $error = 'Error2';
        break;
    case "33":
        $error = 'Error3';
        break;
    case '51':
        $error = 'Error4';
        break;
    default:
        $error = null;
}
echo $error;

Ok so, is this a safe method and is there a vulnerability with this way to help avoid XSS?
Thank you in advance.

A: If you're seriously worried about it being a number, just cast it as such
$errorget = (int)$_GET['err']; //this is always a number

Next, this really isn't a candidate for XSS attacks because you're not outputting the data anywhere (i.e. echo $_GET['err']). Providing bad data in this case will simply do... nothing. As in $error = null; Providing a list of what should happen on the other end avoids XSS entirely.

A: In addition to what @Machavity writes about int case and XSS vulnerability, I would recommend not to use a switch/case for something as simple as printing an error message but to use an array instead:
$errorMessages = array(
    4  => 'Error1',
    61 => 'Error2',
    33 => 'Error3',
    51 => 'Error4',
);

echo $errorMessages[$errorget];

Output (with $errorget == 61):
Error2


text:
Q: Ack messages on receipt with Spring Integration I have a use case where I'd like to ack the message as soon as the application receives it rather than waiting for the flow to complete. Flow is below. Currently the simple message listener container is configured with AUTO acknowledgement mode.
    @Bean
    public IntegrationFlow processAggregateEventFlow(SimpleMessageListenerContainer messageListenerContainer,
                                                         @Qualifier("errorChannel") MessageChannel eventErrorChannel) {

            return IntegrationFlows
                    // Create message listener container and queueEvent error channel
                    .from(Amqp.inboundAdapter(messageListenerContainer).errorChannel(eventErrorChannel))
                    .transform(new JsonToObjectTransformer(Request.class, jacksonConfiguration.jsonObjectMapper()))
                    .filter(Request.class, e -> true)
                    .handle(requestMessageHandler)
                    .get();
        }

A: See AcknowledgeMode.NONE and read their JavaDocs:
public enum AcknowledgeMode {

    /**
     * No acks - {@code autoAck=true} in {@code Channel.basicConsume()}.
     */
    NONE,

    /**
     * Manual acks - user must ack/nack via a channel aware listener.
     */
    MANUAL,

    /**
     * Auto - the container will issue the ack/nack based on whether
     * the listener returns normally, or throws an exception.
     *
Do not confuse with RabbitMQ {@code autoAck} which is
     * represented by {@link #NONE} here.
     */
    AUTO;

With the MANUAL there are a couple headers added to the message from that AMQP Inbound Channel Adapter:
            headers.put(AmqpHeaders.DELIVERY_TAG, deliveryTag);
            headers.put(AmqpHeaders.CHANNEL, channel);

So you can have a .handle() just after that from(Amqp) to call  channel.basicAck(deliveryTag, false);. See more in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/amqp.html#amqp-inbound-ack


text:
Q: Is there a better way to manage a single subscription to a changing object's event in Reactive C#? I have a class ClassWithProperty that contains a property, SomeProperty, that is an instance of another class, ClassWithEvent, with an event, SomeEvent. The ClassWithEvent object will regularly change. I need ClassWithProperty to keep a single updated subscription to the event in ClassWithEvent.
I've come up with one way to do it so far:
public ClassWithProperty()
{
    IDisposable subscription = null;

    this
        .WhenAnyValue(x => x.SomeProperty)
        .Do(x => subscription?.Dispose())
        .Where(x => x != null)
        .Subscribe(x => subscription =
            Observable.FromEventPattern(x, nameof(x.SomeEvent))
            .Subscribe(y => SomeMethod()));
}

This solution does work but it somehow does not feel like idiomatic Reactive code, and it also seems somewhat verbose for what I think should be a fairly typical problem to solve. Is there a better way to solve this sort of issue in Reactive?

A: It's very simple with a Switch operator that switches to the latest produced inner observable of a IObservable<IObservable<T>>. It disposes of the previous subscriptions and only gives you values from the latest observable.
    IDisposable subscription =
        this
            .WhenAnyValue(x => x.SomeClass)
            .Select(x => Observable.FromEventPattern(x, nameof(x.SomeEvent)))
            .Switch()
            .Subscribe(x => SomeMethod());

If SomeClass can be null (which your original code suggests) then you can do this:
    IDisposable subscription =
        this
            .WhenAnyValue(x => x.SomeClass)
            .Select(x =>
                x == null
                    ? Observable.Never<EventPattern<object>>()
                    : Observable.FromEventPattern(x, nameof(x.SomeEvent)))
            .Switch()
            .Subscribe(x => SomeMethod());


text:
Q: How to use foldr to add variables to each other in a list? When given a list [x0, x1, x2, . . . , xn−1], the function
should return the list [y0, y1, y2, . . . , yn−1] where y0 = x0, y1 = x0 + x1, ...
So if you had [1,2,3] as input, you would get [1,3,6] as output
I don't completely understand foldr, so maybe if I could get some help in trying to figure out how to change that last line to get the right answer.
scan :: [Integer] -> [Integer]
scan [] = []
scan [x] = [x]

scan (x:xs) = x : foldr (/y -> y (+) x) 0 (scan xs)

My initial solution (that works) uses the map function.
scan :: [Integer] -> [Integer]
scan [] = []
scan [x] = [x]

scan (x:xs) = x : map (+x) (scan xs)

A: EDIT, I added this first section to better address your two implementations.
First, addressing your issue with your implementation using foldr, here are a few remarks:

*

*Lambdas start with a backslash in Haskell, not a slash. That's because backslashes kind of look like the lambda greek letter (λ).

*Functions named using only special characters, like +, are infix by default. If you use parens around them, it turns them into prefix functions:
$> (+) 1 5
$> 6

*The function passed to foldr takes two argument, whereas you're only supplying one in your lambda. If you really want to ignore the second one, you can use a _ instead of binding it to a variable (\x _ -> x).

I think this you're going down a rabbit hole with this implementation. See the discussion below for my take on the right way to tackle this issue.
Note: It is possible to implement map using foldr (source), that's one way you could use foldr in your working (second) implementation.

Implementing this with foldr is not optimal, since it folds, as the name implies, from the right:
foldr1 (+) [1..5]
--is equivalent to:
(1+(2+(3+(4+5))))

As you can see, the summing operation is done starting from the tail of the list, which is not what you're looking for. To make this work, you would have to "cheat", and reverse your list twice, once before folding it and once after:
scan = tail . reverse . foldr step [0] . reverse where
  step e acc@(a:_) = (e + a) : acc

You can make this better using a left fold, which folds from the left:
foldl1 (+) [1..5]
--is equivalent to:
((((1+2)+3)+4)+5)

This, however, still isn't ideal, because to keep the order of elements in your accumulator the same, you would have to use the ++ function, which amounts to quadratic time complexity in such a function. A compromise is to use the : function, but then you still have to reverse your accumulator list after the fold, which is only linear complexity:
scan' :: [Integer] -> [Integer]
scan' = tail . reverse . foldl step [0] where
  step acc@(a:_) e = (e + a) : acc

This still isn't very good, since the reverse adds an extra computation. The ideal solution would therefore be to use scanl1, which, as a bonus, doesn't require you to give a starting value ([0] in the examples above):
scan'' :: [Integer] -> [Integer]
scan'' = scanl1 (+)

scanl1 is implemented in terms of scanl, which is defined roughly like this:
scanl f init list = init : (case list of
                      []   -> []
                      x:xs -> scanl f (f init x) xs)

You can therefore simply do:
$> scanl1 (+) [1..3]
$> [1,3,6]

As a final note, your scan function is unnecessarily specialized to Integer, as it only requires a Num constraint:
scan :: Num a => [a] -> [a]

This might even lead to an increase in performance, but that's where my abilities end, so I won't go any further :)


text:
Q: How to use custom fonts on a input placeholder? I am using custom fonts (@font-face), and they show up properly on my entirely application except on input placeholders.
The font is not showing up and the placeholder is blank.
The input font (when I type something) is working fine.
Also, if I change the placeholder font for a system font (Arial, Tahoma...) it works too.
How can I use custom fonts for the placeholder?
Input:
<input placeholder="Search character" type="text" class="search-character">

CSS:
body { font-family: 'DIN', sans-serif; }
.search-character::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  font-family: 'DIN', sans-serif;
}
.search-character::-moz-placeholder { /* Firefox 19+ */
  font-family: 'DIN', sans-serif;
}
.search-character:-ms-input-placeholder { /* IE 10+ */
  font-family: 'DIN', sans-serif;
}
.search-character:-moz-placeholder { /* Firefox 18- */
  font-family: 'DIN', sans-serif;
}
.search-character::placeholder {
  font-family: 'DIN', sans-serif;
}

A: Apply the font-family property to the ::placeholder pseudo-class.
input::placeholder
{
    font-family: Helvetica;
}

Also, note that input does not inherit font-family by default due to user-agent stylesheets; look at this snippet:

body
{
  font-family: Impact, Haettenschweiler;
}

input::placeholder
{
  font-family: Impact, Haettenschweiler;
}
<input type="text" placeholder="hello" />

The placeholder is styled, but the text is not.

A: input::placeholder {
 font-family: Arial;
}

input:-ms-input-placeholder { /* Internet Explorer 10-11 */
  font-family: Arial;
}

input::-ms-input-placeholder { /* Microsoft Edge */
  font-family: Arial;
}


text:
Q: terraform beginner: where is my EC2 instance gone? I created a brand new (free) AWS account.
Using terraform, I created an EC2 instance but can't see it in aws console.
My terraform script is very simple
provider "aws" {
  region = "us-east-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "terraform-example"
  }
}

terraform apply completes successfully but when going to EC2 on the AWS Console, it tells me that there are no instances...
Even if I login as the AWS root account.
Out of curiosity, I created an EC2 instance manually through the AWS Console. I can see this one created manually.
If I run terraform plan again, it's still says everything is fine...
Should not it try to remove this new manual instance instead?
Does that confirm that my terraform instance is not looking at the account I think it is???

Later, I took the exact same credentials and main.tf file to another laptop
Initially terraform plan did not recognise my EC2 (or anything) created before (I suppose this is because i did not copy across the Terraform state file...).
Ran terraform apply which recreated the items... and this time I can see the instances I create...
Next step: try to find out whether this initial EC2 instance has been created in another region... which I am hoping to find out through billing / or activity...

A: It was because I was not using the credentials I thought...
I thought I had setup the 2 env variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY but I had made a typo when assigning AWS_SECRET_ACCESS_KEY and it was not set.
It happened that I had a "credentials" file hanging around in my ~/.aws folder with tests I had done on a different AWS account about a year ago (which I had all forgotten about).
Once I removed the .aws/credentials file AND assigned AWS_SECRET_ACCESS_KEY properly, everything behaved as expected.
I used a trick given to me by Laura M. (thanks) to show which user details were used by terraform
data "aws_caller_identity" "current" {}

output "account_id" {
  value = "${data.aws_caller_identity.current.account_id}"
}

output "caller_arn" {
  value = "${data.aws_caller_identity.current.arn}"
}

output "caller_user" {
  value = "${data.aws_caller_identity.current.user_id}"
}

A: Do you have the us-east-2 region (Ohio) selected in the AWS Console. By default I think it defaults to us-east-1 (Virginia) for new US accounts but your TF AWS provider is configured to deploy to us-east-2.


text:
Q: How do I change a specific MDB max-pool-size at runtime on Glassfish I'd like to be able to change the max-pool-size value at runtime. Currently I have to modify the xml and restart Glassfish.
Any ideas?

A: You should be able to do this with 'asadmin set'.  I do not know the particular name you needto use, though.
Use "asadmin get '*'" (after you have deployed your MDB) to find the name that you will need to use.


text:
Q: Quintessence: what are tracking and scaling models? I'm currently reading around the topic of dark energy, in particular quintessence, and I understand the idea of freezing and thawing models. In freezing models the potential is shallow at late times, causing the decrease in the equation of state parameter. Whereas in thawing models, w is frozen at -1 and deviates from this at late times.
However I have also read that freezing models can be categorised in tracking freezing models and scaling freezing models.
What is the difference between these two models?
Any help is greatly appreciated.


text:
Q: Problems with the Drivers for Ralink RT3290 Wi-Fi Adapter After upgrading to Ubuntu 13.10, Ralink RT3290 Wi-Fi Adapter in my laptop dosen't work. So I followed the guide in How do I get a Ralink RT3290 wireless card working? to compile the driver and load it manually. It seemed that the module was loaded successfully, for I got the following outputs:
forever41200@forever41200:~$ lsmod | grep -in rt3290sta
26:rt3290sta            1170462  0

forever41200@forever41200:~$ modinfo rt3290sta
filename:       /lib/modules/3.11.0-13-generic/kernel/drivers/net/wireless/rt3290sta.ko
version:        2.6.0.0_rev1
srcversion:     3D39532F027115378BDBC79
alias:          pci:v00001814d00003290sv*sd*bc*sc*i*
depends:
vermagic:       3.11.0-13-generic SMP mod_unload modversions
parm:           mac:rt28xx: wireless mac addr (charp)

But the driver used for Ralink RT3290 Wi-Fi Adapter didn't change. It still used "rt2800pci" instead of "rt3290sta".
forever41200@forever41200:~$ sudo lspci -v

02:00.0 Network controller: Ralink corp. RT3290 Wireless 802.11n 1T/1R PCIe
        Subsystem: Foxconn International, Inc. Device e055
        Flags: bus master, fast devsel, latency 0, IRQ 44
        Memory at f7d10000 (32-bit, non-prefetchable) [size=64K]
        Capabilities: [40] Power Management version 3
        Capabilities: [50] MSI: Enable+ Count=1/32 Maskable- 64bit+
        Capabilities: [70] Express Endpoint, MSI 00
        Capabilities: [100] Advanced Error Reporting
        Capabilities: [140] Device Serial Number 00-00-89-bc-3a-3f-76-b8
        Kernel driver in use: rt2800pci

02:00.1 Bluetooth: Ralink corp. RT3290 Bluetooth
        Subsystem: Foxconn International, Inc. Device e056
        Flags: bus master, fast devsel, latency 0, IRQ 3
        Memory at f7d00000 (32-bit, non-prefetchable) [size=64K]
        Capabilities: [40] Power Management version 3
        Capabilities: [50] MSI: Enable- Count=1/32 Maskable- 64bit+
        Capabilities: [70] Express Endpoint, MSI 00
        Capabilities: [100] Advanced Error Reporting
        Capabilities: [140] Device Serial Number 00-00-8a-bc-3a-3f-76-b8

So I add "rt2800pci" and "rt2x00pci" to blacklist, I had also updated initramfs. But it still didn't use "rt3290sta". It said the Wi-Fi adapter was using "rt2860".
forever41200@forever41200:~$ sudo lspci -v

02:00.0 Network controller: Ralink corp. RT3290 Wireless 802.11n 1T/1R PCIe
        Subsystem: Foxconn International, Inc. Device e055
        Flags: bus master, fast devsel, latency 0, IRQ 17
        Memory at f7d10000 (32-bit, non-prefetchable) [size=64K]
        Capabilities: [40] Power Management version 3
        Capabilities: [50] MSI: Enable- Count=1/32 Maskable- 64bit+
        Capabilities: [70] Express Endpoint, MSI 00
        Capabilities: [100] Advanced Error Reporting
        Capabilities: [140] Device Serial Number 00-00-89-bc-3a-3f-76-b8
        Kernel driver in use: rt2860

02:00.1 Bluetooth: Ralink corp. RT3290 Bluetooth
        Subsystem: Foxconn International, Inc. Device e056
        Flags: bus master, fast devsel, latency 0, IRQ 3
        Memory at f7d00000 (32-bit, non-prefetchable) [size=64K]
        Capabilities: [40] Power Management version 3
        Capabilities: [50] MSI: Enable- Count=1/32 Maskable- 64bit+
        Capabilities: [70] Express Endpoint, MSI 00
        Capabilities: [100] Advanced Error Reporting
        Capabilities: [140] Device Serial Number 00-00-8a-bc-3a-3f-76-b8

That's weird because I can't find the "rt2860" module in my system.
forever41200@forever41200:~$ lsmod | grep -in rt2860

forever41200@forever41200:~$ modinfo rt2860
ERROR: Module rt2860 not found.

Then I added "rt2860" to blacklist, however, nothing happened.
With the "rt2860" module, the Wi-Fi adapter do work at first, but a few minutes later the whole Linux system crash. Error messages I got were:

It mentioned "rt3290sta", and that makes me more confused about whether the driver in use   is "rt2860" or "rt3290sta".
By the way, After adding "rt2800pci" and "rt2x00pci" to blacklist, Ralink RT3290 Wi-Fi Adapter was no longer named "wlan0"; it was named "ra0".

A: Remove the  rt2800pci
sudo rmmod rt2800pci

Load the new one
sudo modprobe rt3290sta

Post any error messages.
If the new module, rt3290sta, does not load properly on boot, you will almost certainly need to then black list the rt2800pci module.
See:
How to blacklist kernel modules?
https://help.ubuntu.com/community/Loadable_Modules


text:
Q: Creating text files in Python Is it possible to create a variable in which I can store a list of products instead of using "lines" variable. when creating a text file
#creating a textfile

text_file= open("productlist.txt", "w")

lines = ("Bed","\n","Couch","\n","Mirror","\n","Television","\n"
         "Tables","\n","Radio")

text_file.writelines(lines)
text_file.close()

text_file = open("productlist.txt")
print(text_file.read())
text_file.close()

A: I believe what you're trying to accomplish is to not write a line break "\n" in there every time, right? Just throw your code into a loop:
#Create text file
text_file = open("productlist.txt", "w")

#Enter list of products
products = ["Bed", "Couch", "Mirror", "Television", "Tables", "Radio"] #Formerly "lines" variable

#Enter each product on a new line
for product in products:
    text_file.writelines(product)
    text_file.writelines('\n')

#Close text file for writing
text_file.close()

#Open text file for reading
text_file = open("productlist.txt")
print(text_file.read())

#Close text file
text_file.close()

If you ever decide you want to append to your document rather than overwrite it every time, just change
    text_file= open("productlist.txt", "w")
to
    text_file= open("productlist.txt", "a")
If a text document isn't the best format for your list, you might consider exporting to a csv file (which you can open in an excel spreadsheet)

A: Instead of writing each line, and the line breaks, individually using writelines, you can create a single string containing all the lines and the line breaks, and write that.
In order to create the combined string from a list of items, you can use join.
products = ["Bed", "Couch", "Mirror", "Television", "Tables", "Radio"]
text_file.write("\n".join(products))

(Note that (a, b, c) creates a tuple, while [a, b, c] creates a list. You may want to learn about the differences, but in this case it doesn't matter.)


text:
Q: Fundamental theorem of algebra using Cauchy's theorem Prove that a polynomial in $z$ without zeros is constant using Cauchy theorem.

Hint : If $P(z)$ is a polynomial that is not a constant, write $P(z)=P(0)+zQ(z)$, divide by $zP(z)$, and integrate around a large circle. This will lead to a contradiction if $P(z)$ has no zeros.

Consider $$\frac{P(z)}{zP(z)}=\frac{P(0)}{zP(z)}+\frac{zQ(z)}{zP(z)}$$
Integrating over circle of radius $R$
$$\int_R\frac{1}{z}dz=\int_R\frac{P(0)}{zP(z)}dz+\int_R\frac{Q(z)}{P(z)}dz$$
Assuming $P(z)$ has no zeros, we see that $\int_R\frac{Q(z)}{P(z)}dz=0$ using Cauchy theorem as $\frac{Q(z)}{P(z)}$ is analytic.
See that $\int_R\frac{1}{z}dz=2\pi i$ by considering parametrization $z(\theta)=Re^{i\theta}$.
I do not know how to compute $\int_R\frac{P(0)}{zP(z)}dz$ from basics but i can use Residue theorem here and assuming $P(z)$ has no zeros we see that $$\int_R\frac{P(0)}{zP(z)}dz=2\pi i\lim_{z\rightarrow 0}\frac{P(0)}{P(z)}=2\pi i$$
So, $$2\pi i=\int_R\frac{1}{z}dz=\int_R\frac{P(0)}{zP(z)}dz+\int_R\frac{Q(z)}{P(z)}dz=2\pi i$$
I do not see any contradiction.. What is wrong with my argument?

A: Starting from $$\int_R\frac{1}{z}dz=\int_R\frac{P(0)}{zP(z)}dz+\int_R\frac{Q(z)}{P(z)}dz$$
and using your facts that the LHS = $2 \pi i$ and $\int_R\frac{Q(z)}{P(z)}dz=0$ we have
$$2 \pi i=\int_R\frac{P(0)}{zP(z)}dz$$
we can get a contradiction by showing that the RHS $\to 0$ using the ML inequality, as suggested in comments.
$$\left|\int_R\frac{P(0)}{zP(z)}dz\right| \le 2 \pi R \cdot \frac{|P(0)|}{|R||P(R)|} = 2 \pi \frac{|P(0)|}{|P(R)|}$$
and clearly this tends to zero unless $|P(R)| = |P(0)|$, so we have a contradiction unless the polynomial is constant.


text:
Q: GWT 2.5 breaks RPC method - fine on 2.4, but not working after upgrade After upgrade from GWT 2.4.0 to 2.5.0 only one of many (many!) RPC methods is broken and I have no idea why. Here is what happens (and what does not):

*

*The program gets to async service object and calls its method.

*Underyling, generated by GWT proxy object exists and is called (I don't know its internals, though).

*The browser doesn't send any request to server (at least developer tools built into Google Chrome doesn't show anything like that happening. On the other hand... see 5.).

*The implementation on server is never called.

*If I stop the server, however, AsyncCallback.onFailure(Throwable) is executed immediately.

I'll repeat for sake of clarity: the very same code works like a charm on GWT 2.4.0 and other metods (most of them if not all) work just fine even on 2.5.0.
Now some code. Not sure if necessary, but...
Async interface
public interface BrokenServiceAsync {
    public void getData(int id, State state, AsyncCallback<Data> asyncCallback);
}

Both State interface (method param) and it's only implementation are declared in external module (added as jar package). I though this could be the case of that problem, but other methods are using these classes too. And there are no compile-time errors.
Data contains a String and an ArrayList of objects subclassing com.extjs.gxt.ui.client.data.BaseModelData. Most other methods use similar objects and it works.
Any ideas? Thanks!


text:
Q: trying to do a spreadsheet for work tomorrow i have 3000 graduation tickets that need to be entered into excel by number 001-004, 005-008, 009-012, 013-016- etc. What formula do i use to complete this task. I tried dragging the first 5 rows but it did not calculate properly.

A: In  A1 enter:
=TEXT(4*(ROW()-1)+1,"000") & "-" & TEXT(4*(ROW()-1)+4,"000")

and copy down:


text:
Q: How can I protect json data from "XHR finished loading […]"? Hello I'm doing a PWA and I use Google spreadsheet to store info and send emails.
When I use the app, in the console shows me the "XHR finished loading" message with an url with json data from my entire sheet.

What I want is that people don't have access to that URL or the JSON data, is this possible? or What should I do so that information is not visible in that way?

A: if your UI can access a URL, anyone could.
You can protect it though, deepening on your server side capability.
If your server side can authenticate the request to have proper credentials, then the protection can be implemented.
But you can't mask anything from UI to prevent users from seeing it. What goes to browser -> user have visibility. PWA wont change that fact.


text:
Q: Adding programmatically a span tag with an anchor inside innertext I have created a span element using:
ele= document.createElement(span);
ele.innerText = "bla bla ( ble ble ) blu blu";
divele.appendChild(ele); #divele is an div in the page

The problem is the  tag is not showed as a link, it is showed literally.

A: Should be innerHTML instead of innerText (since the sting contains HTML in it). The span should be enclosed with single quotes ('') or double quotes ("").

var ele= document.createElement('span');
ele.innerHTML = "bla bla ( ble ble ) blu blu";
var divele = document.getElementById('divele');
divele.appendChild(ele);


text:
Q: SailsJS policy on request method rather than route Is there any way I can trigger a policy on a specific request method (e.g. DELETE) rather than on specific routes?
I'd imagine something like this:
module.exports.policies = {
   'DELETE *': 'isAdmin'
}

My goal here is to expose the blueprint api to admins only, so that I can keep it in production, as it's a very useful tool for allowing third party scripts to add extra functionality.
I'm on Sails 1.0 right now.
One way to do that might be to add the check for the request method to the actual admin policy, however that doesn't quite seem like the best solution to me.

A: You can override the blueprint for all models for a particular method. You can do this for DELETE by creating a file destroy.js in /api/blueprints/ and then adding your code for what you want to do when a DELETE comes through:
module.exports = function(req,res, next) {
    if(ACLService.hasPermission(req.user.acl, 'admin')) {
        //Ok to allow delete here
    } else {
        return res.unauthorized();
    }
};

This is how I've done it in the past, but looking at the docs for the just released SailsJS 1.0:
https://sailsjs.com/documentation/reference/blueprint-api
You may need to add this hook for overriding blueprints in 1.0
https://www.npmjs.com/package/sails-hook-custom-blueprints

A: Here is one method that you can use, I am not claiming that it is the right way, but you can consider it:
You can write your own hook. How to do this: https://sailsjs.com/documentation/concepts/extending-sails/hooks/project-hooks
Basically here is the solution with a hook:
1 Create a hooks folder under your api folder.
2 In the hooks folder create another folder - the name will be the name of your hook (say my-hook).
3 In api/hooks/my-hook create a file index.js and in it put the following code:
module.exports = function myHook(sails) {
  return {
    routes: {
      before: {
        '/*': function (req, res, next) {
          if (req.method.toUpperCase() === 'DELETE') {
            return sails.hooks.policies.middleware.isadmin(req, res, next); // note - your policy function name must be called here with all lowercase, otherwise it will not work.
          }

          return next();
        }
      }
    }
  };
};

Then in your isAdmin.js policy you can check if your user is an admin and if not:
return res.forbidden();

if it is admin:
return next();


text:
Q: Using wp-cli through PHP Can I run WP-CLI https://wp-cli.org/ command through PHP script, so I can install user selected WordPress themes automatically with PHP script

A: As long as you can use the exec() or similar command. I use something like this to output the result of a wp-cli command:
<pre>
<?php
  exec("wp --info", $result);
  echo implode(PHP_EOL, $result); // join multi-line return result
?>
</pre>

Or simply:
<?php exec("wp --info");

See this answer: https://wordpress.stackexchange.com/questions/219230/utilize-wp-cli-from-inside-wordpress-not-ssh for further discussion.

A: You can do something like this:
exec('wp site list --field=url --archived=0', $output);

foreach($output as $url) {
    echo $url . "\n";
    echo exec("wp --url=$url plugin activate this-plugin");
}

Run it in a PHP script in your home directory.


text:
Q: Cannot generate ADO.NET Model classes I am using Visual Studio Express 2012 for Web.
I have created a new empty web site using .net framework 4.
I am using SQL Server 2008 R2 Service Pack 2, and I have a database with 4 tables there.
When I try to add a new ADO.NET data model into my website from this database, the Model.edmx, Model.tt, and Model.Context.tt files are all generated, but my Model.cs and Model.Context.cs files are missing. If I try to use the option 'update the model from database' nothing happens.
I have installed Visual Studio just two days ago, and initially I could work with a successfully generated model for another web site. But now I cannot generate the model in any website. I have tried with other databases, to no success.

A: Thanks to John Saunders for providing this answer as a comment.
Use the Build->Transform T4 Templates command if present, otherwise, right click the .tt files and do Run Custom Tool


text:
Q: Loading and accessing multiple ctype instances I have some existing C code that I am working with in Python.  I am able to load the library using the following commands:
library_path = '/full/path/to/my/library.dylib'
lib1 = cdll.LoadLibrary(library_path)

The problem is that I need to have multiple instances of this library, for example:
lib2 = cdll.LoadLibrary(library_path)

This creates a second instance, but both seem to have the same memory location (handles are the same).  I've tried copying and renaming library.dylib to library1.dylib and library2.dylib, but this doesn't change how they load.  The problem is that when I call function in lib1, global and state variables in lib2 are modified.  For example:
lib1.open('/path/to/myfile')  # open a file for processing
lib1.run()   # This will do something with the file

lib2.open('/path/to/anotherfile')  # open a file for processing
lib2.run()   # This will do something with the file

lib1.close() # Closes library 1

lib2.run()   # This fails because lib1.close() also closes lib2

Is there any way to load these library instances in way that they remain 'contained'?  The C code that I am trying to load is very large legacy software...do I need to do some rewriting?
Here is a link that I found addressing a similar problem, but doesn't help me that much: http://www.gossamer-threads.com/lists/python/python/826703
Any help is greatly appreciated.

A: As you noticed, some OS refuses to load several instances of the same DDL in the same process. If everything else failed, you might use the multiprocessing module to fork your program, and load each DLL in a different process. – Sylvain Leroux Jan 27 '15 at 22:20

A: An answer given to a question on circular imports may (or may not) hold a solution to your issue.
Here is the original thread: Circular Imports Hell
This is the relevant part that you may find interesting, as originally posted by Sebastian Wozny:

Begin Excerpt:
From David Beazleys excellent talk Modules and Packages: Live and Let Die! - PyCon 2015, 1:54:00, here is a way to deal with circular imports in python:
 try:
     from images.serializers import SimplifiedImageSerializer
 except ImportError:
     import sys
     SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']

This tries to import SimplifiedImageSerializer and if ImportError is raised, because it already is imported, it will pull it from the importcache.
End Excerpt:

I hope this is helpful. -Science_1


text:
Q: How can I use the covariant "Derived" in a base class's property where Type is needed? I have a BaseRepository class.  I want to use the Derived class from BaseRepository (call it JobSeekerRepository) in ILogger.
Example:
public abstract class BaseRepository<T>
{
     private readonly ILogger<Derived> _repositoryLogger;
}


text:
Q: Xubuntu 14.04 hangs while browsing using Chromium or Firefox My Xubuntu 14.04 hangs too much when i start to use browsers like chromium or firefox. I dont know the reasons,but i think i encounter this problem everytime i use a browser. I am using Xubuntu on my samsung netbook( 1gb ram).
I have already tried a few tweaks like decreasing the swap memory or something and it didnt solve my problem.
I have a feeling, this happens because i am always running into unresponsive pages in chromium or in firefox non-responsive scripts.
i have seen the browser support pages. They didnt help me either.
I would be very happy if somebody could tell me how to solve this problem.

A: maybe disabling the adobe flash player can solve it.
in the chrome enter= chrome://plugins (i dont have chromium,so if dosent work
replace chrome vs chromium)and disable flash player or ppapi flash)
and for firefox go to addons and plugins.

A: Here are some check points that I use to improve responsiveness.

*

*On Firefox, check the add-ons consumption with ... the addons-memory
addon (then disable any addon that shows high consumption.)

*If you use AdBlock (quite heavy), replace it with ublock origin or µblock (available on
Chromium as well)

*Optimize swappiness :
echo vm.swappiness=5 | sudo tee -a /etc/sysctl.conf
echo vm.vfs_cache_pressure=50 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

*If you use wifi, ensure that you
uses WPA2 AES encryption.

*Ultimately, on low RAM systems (<2Go) my experience is that 32bits OS are more responsive.(There, you can try to add RAM or.. to do a fresh install with a 32bits Xubuntu (or Lubuntu)


text:
Q: How can I rotate the output in 90 degrees? I have a code and from kladblok.txt there is a file with the following numbers:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

How can i get the output :
1111111111
2222222222

etc..
Can someone help me?

A: The algorithm is very simple:

*

*Open the file

*Allocate a 2 dimensional array which is big enough to contain the numbers

*Read the numbers to the array

*Close the file

*Print the array transposed

*Free the array

A: If you just want to print it rotated 90 degrees, then just change the start/end/increment of your loops.  Say you have int data[10][10] in the original rotation.
Then you want to start in the lower left and go up.  Move right one space, start again at the bottom and go to the top, etc:
int i, j;

for (i = ?; i ? ?; i??)
{
    for (j = ?; j ? ?; j??)
    {
        /* print element [i][j] (or perhaps [j][i]) */
    }

    /* do a carriage return here */
}

/* What should the question marks be? */


text:
Q: onReceive function not working to identify a particular phone number through my app I created a class called PhoneCallReciever.java which extends BroadcastReceiver
Anytime a user calls, a Toast should appear which is defined in CallReceiver.java. However this is not happening and there is no data being logged as well
PhoneCallReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Call;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import java.util.Date;

public abstract class PhoneCallReceiver extends BroadcastReceiver {

    private static int lastState = TelephonyManager.CALL_STATE_IDLE;
    private static Date callStartTime;
    private static boolean isIncoming;
    private static String savedNumber;  //because the passed incoming is only valid in ringing

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Entered onReceive", Toast.LENGTH_SHORT).show();
        //We listen to two intents.  The new outgoing call only tells us of an outgoing call.  We use it to get the number.
        if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
            savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
        } else {
            String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
            String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            int state = 0;
            if (stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                state = TelephonyManager.CALL_STATE_IDLE;
            } else if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                state = TelephonyManager.CALL_STATE_OFFHOOK;
            } else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                state = TelephonyManager.CALL_STATE_RINGING;
            }

            onCallStateChanged(context, state, number);
        }
    }

    //Derived classes should override these to respond to specific events of interest
    protected abstract void onIncomingCallReceived(Context ctx, String number, Date start);

    protected abstract void onIncomingCallAnswered(Context ctx, String number, Date start);

    protected abstract void onIncomingCallEnded(Context ctx, String number, Date start, Date end);

    protected abstract void onOutgoingCallStarted(Context ctx, String number, Date start);

    protected abstract void onOutgoingCallEnded(Context ctx, String number, Date start, Date end);

    protected abstract void onMissedCall(Context ctx, String number, Date start);

    //Deals with actual events

    //Incoming call-  goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
    //Outgoing call-  goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
    public void onCallStateChanged(Context context, int state, String number) {
        if (lastState == state) {
            //No change, debounce extras
            return;
        }
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                isIncoming = true;
                callStartTime = new Date();
                savedNumber = number;
                onIncomingCallReceived(context, number, callStartTime);
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                //Transition of ringing->offhook are pickups of incoming calls.  Nothing done on them
                if (lastState != TelephonyManager.CALL_STATE_RINGING) {
                    isIncoming = false;
                    callStartTime = new Date();
                    onOutgoingCallStarted(context, savedNumber, callStartTime);
                } else {
                    isIncoming = true;
                    callStartTime = new Date();
                    onIncomingCallAnswered(context, savedNumber, callStartTime);
                }

                break;
            case TelephonyManager.CALL_STATE_IDLE:
                //Went to idle-  this is the end of a call.  What type depends on previous state(s)
                if (lastState == TelephonyManager.CALL_STATE_RINGING) {
                    //Ring but no pickup-  a miss
                    onMissedCall(context, savedNumber, callStartTime);
                } else if (isIncoming) {
                    onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
                } else {
                    onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
                }
                break;
        }
        lastState = state;
    }
}

CallReceiver.java
import android.content.Context;
import android.widget.Toast;

import java.util.Date;

public class CallReceiver extends PhoneCallReceiver {

    @Override
    protected void onIncomingCallReceived(Context ctx, String number, Date start)
    {
        Toast.makeText(ctx, "Incoming Call", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onIncomingCallAnswered(Context ctx, String number, Date start)
    {
        //
    }

    @Override
    protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
    {
        //
    }

    @Override
    protected void onOutgoingCallStarted(Context ctx, String number, Date start)
    {
        //
    }

    @Override
    protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end)
    {
        //
    }

    @Override
    protected void onMissedCall(Context ctx, String number, Date start)
    {
        //
    }

}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.admin.xxxx">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".CallReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>

        <activity android:name=".DialogBoxActivity" />
        <activity android:name=".LocationActivity" />
    </application>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

</manifest>


text:
Q: Hibernate pulls up all child records of a parent, not just the constrained children I got Cat entity which is parent, CatDts which is one to many child collection.
I want to get all Cat which have CatDt.name='a'. The generated sql query is correct but when accessing the CatDts collection, all child recs are returned and not just those with name 'a'. Any help appreciated, thanks!
Tables
Cat         CatDt
id          id      name    cat_id
----        ---     ---     ---
1           100     a       1
2           101     a       2
            102     xyz     2

So I need just 1-100, 2-101 but it also gives me 2-102
Cat entity
private List<CatDt> catDts = new ArrayList<CatDt>();

@OneToMany(fetch = FetchType.LAZY, mappedBy = "cat", cascade=CascadeType.ALL)
public List<CatDt> getCatDts() {
    if(this.catDts==null){
        this.catDts = new ArrayList<CatDt>();
    }
    return this.catDts;
}

CatDt entity
private Cat cat;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
    @JoinColumn(name = "CAT_ID", nullable = false)
public Cat getCat() {
    return this.cat;
}

Service
public List<Cat>findAllByOption(CatOption options){
    QCat cat = QCat.cat;
    QCatDt catDt = QCatDt.catDt;
    List<Cat> cats = jpaQueryFactory.selectFrom(cat)
                .innerJoin(catDt).on(cat.id.eq(catDt.cat.id).and(catDt.name.eq("a")))
                .where(cat.status.eq(new BigDecimal(0))).fetch();
    return cats;
}

Test
@Test
public void testCatWithOptionsJpaQuery(){
    CatOption options = new CatOption();
    options.setStatus(new BigDecimal(0));
    options.setName("a");
    List<Cat> catList = catService.findAllByOption(options); //-->returns 2 rows
    for(Cat cat:catList){
        logger.info("--" + cat.toString()); //-->gets the child collection catDts and pulls out all rows, not just constrained ones
    }
    Assert.notNull(catList, "categories returned cannot be null!");
}

I check logs and find, at below line of Test, sql query & join is good, just returns 2 rows of Cat.
catService.findAllByOption(options)

But when I iterate those 2 Cat objects, Hibernate pulls out all correspoding CatDt child collection (total 3).
So how do I get just the child records with name='a'?
Update 1
When execution reaches below line within the loop in Test, it throws up the individual select statements, that's how the 3 records are being returned instead of 2. I think this is how orm is supposed to work but how to get just constrained children?
logger.info("--" + cat.toString())

A: So I got around the problem by creating a pojo to hold all joined resulting fields I needed.
My service/repo used querydsl to join & filter, returned List of the pojo.
I think Hibernate is great with one table crud, but for complex joins and results we can use custom objects and Querydsl.
Alternatively I could also loop thru parents and use Hibernate's @Filter.


text:
Q: How can I change the build-in toolchains in eclipse cdt mingw32 I am compiling on windows with cdt/mingw. I like to compile warning free. I get the following warning:
auto-importing has been activated without --enable-auto-import specified
on the command line.

The following page suggests the way to deal with it is to just adding that option to the command line of ld.
4.8 ld and WIN32 (cygwin/mingw)
The question is thus, how do you change the default command line switches for the built in toolchains?
I would also like to set the warning level of gcc.

A: You have to send the parameter to the linker via gcc's -Wl parameter:

-Wl,option
Pass option as an option to the linker. If option contains commas,
  it is split into multiple options at
  the commas. You can use this syntax to
  pass an argument to the option. For
  example, -Wl,-Map,output.map passes
  -Map output.map to the linker. When
  using the GNU linker, you can also get
  the same effect with
  -Wl,-Map=output.map.

So, you need (and me too :)) -Wl,--enable-auto-import.
For controlling warning levels, see the official docs.

A: Hi so far I have found a partial solution to this problem. I have not found how I can change the default toolchain options, but I have found how to change them on a project basis.
In project->properties->C++-build->settings
It seems to make more sense if it would be in tool chain editor, but it isn't.
There you have a tab called Tool Settings and looking down there is MinGW C++ Linker->Miscellaneous.
Here on the right you can add extra linker options. Above you also have the compiler and warning settings are implemented as checkboxes which is nice.
So far at least I have gotten started, only a pity I have to do that over for every project individually.
Oh for further confusion, this is not always there, and I have some old projects from before I installed MinGW and who thus have no real toolchain installed. In that case the settings pane only has the Binary Parsers and Error Parsers tabs, so it looks completely different. The secret is in having the Tool Settings Tab. Very dynamic and for the rainforest like settings dialog of eclipse also very confusing.


text:
Q: SQL: Find missing hierarchy Folders (Paths) in a table I have a table which contains Folders Paths.
I need to find all the "gaps" between those folders in the hierarchy.
I mean that, if the table contains these 3 folders:
'A'
'A\B\C'
'A\B\C\D\E\F\G'

I need to find the following missing folders in the hierarchy:
'A\B'
'A\B\C\D'
'A\B\C\D\E'
'A\B\C\D\E\F'

This table contains more than 250,000 records of folders, so we seek for the most efficient way to do so, otherwise the script will be stuck for long time, time we don't have.
Comment: I don't have list of all folders. What I have are the "root" folders and the "leafs" folders which I need to find the "gaps" between them in the hierarchy.
Second comment: The table can contains more than one hierarchy and we need to find the "gaps" in all of the hierarchies.
For that matter, There are 2 another int columns: "DirID" and "BaseDirID". The "DirID" column is the id column in our table. The "BaseDirID" contains the id of the first folder in the hierarchy. So all the folders (paths) from the same hierarchy share the same value in this column. Sample data for example:

DirID   BaseDirID   DisplayPath
1   1   'A'
2   1   'A\B\C'
3   1   'A\B\C\D\E'
4   4   'U'
5   4   'U\V\W'
6   4   'U\V\W\X\Y'

So we need to find the following data:

BaseDirID   DisplayPath
1   'A\B'
1   'A\B\C\D'
4   'U\V'
4   'U\V\W\X'

Thanks in advance.

A: Here is one approach using Recursive CTE and split string function
;WITH existing_hierachies
     AS (SELECT DirID,
                BaseDirID,
                DisplayPath
         FROM   (VALUES (1,1,'A' ),
                        (2,1,'A\B\C' ),
                        (3,1,'A\B\C\D\E' ),
                        (4,4,'U' ),
                        (5,4,'U\V\W' ),
                        (6,4,'U\V\W\X\Y' )) tc (DirID, BaseDirID, DisplayPath) ),
     folders_list
     AS (SELECT ItemNumber,
                item fol,
                BaseDirID
         FROM   (SELECT row_number()over(partition by BaseDirID order by Len(DisplayPath) DESC)rn,*
                 FROM   existing_hierachies) a
                 CROSS apply dbo.[Delimitedsplit8k](DisplayPath, '\')
                 Where Rn = 1),
     rec_cte
     AS (SELECT *,
                Cast(fol AS VARCHAR(4000))AS hierar
         FROM   folders_list
         WHERE  ItemNumber = 1
         UNION ALL
         SELECT d.*,
                Cast(rc.hierar + '\' + d.fol AS VARCHAR(4000))
         FROM   rec_cte rc
                JOIN folders_list d
                  ON rc.BaseDirID = d.BaseDirID
                  AND d.ItemNumber = rc.ItemNumber + 1)
SELECT rc.BaseDirID,
       rc.hierar AS Missing_Hierarchies
FROM   rec_cte rc
WHERE  NOT EXISTS (SELECT 1
                   FROM   existing_hierachies eh
                   WHERE  eh.BaseDirID = rc.BaseDirID
                     AND  eh.DisplayPath = rc.hierar)
Order by rc.BaseDirID

Result :
+-----------+---------------------+
| BaseDirID | Missing_Hierarchies |
+-----------+---------------------+
|         1 | A\B                 |
|         1 | A\B\C\D             |
|         4 | U\V                 |
|         4 | U\V\W\X             |
+-----------+---------------------+

Split string function code
CREATE FUNCTION [dbo].[DelimitedSplit8K]
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover NVARCHAR(4000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;
GO

Referred from http://www.sqlservercentral.com/articles/Tally+Table/72993/


text:
Q: Get the probabity of a specific word in Keras LSTM model I trained a w2v model and a keras LSTM model on top of it:
pretrained_weights = w2v_model.wv.syn0
vocab_size, emdedding_size = pretrained_weights.shape

keras_lstm_model = Sequential()
keras_lstm_model.add(Embedding(input_dim = vocab_size, output_dim = emdedding_size, weights = [pretrained_weights]))
keras_lstm_model.add(LSTM(units = emdedding_size))
keras_lstm_model.add(Dense(units = vocab_size))
keras_lstm_model.add(Activation('sigmoid'))
keras_lstm_model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['mae','acc'])

Now, I have a sentence

"This is my "

and I want to get the probability for the word

"Hat"

.
I can I do this?

A: Your output of the model has vocab_size neurons. If you call keras_lstm_model.predict you get the different probabilities for each word to succeed the sequence. The question is which probability do you need?  If you need one where the sum of all probabilities in a prediction is 1 then you should replace your last activation function with softmax.


text:
Q: How to pre-select values in select2 multi select? I am having a multiple select like this:
<select multiple="multiple" class="myList">
        <option value="1" selected="selected">Apple</option>
        <option value="2" selected="selected">Mango</option>
        <option value="3" selected="selected">Orange</option>
</select>

Now, apart from those options which must come selected in the select box, I wanted additional ajax functionality which would give values from a remote source.
Here is my code for select2
$(function(){
    $(".myList").each(function(){

                $(this).select2({
                placeholder: "Search for fruits",
                minimumInputLength: 2,
                multiple: true,
                id: function(e) {
                return e.id+":"+e.name; },
                ajax: {
                    url: "https://localhost:8443/fruit_search",
                    dataType: 'json',
                    data: function(term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function(data, page) {
                    var frts=[];
                        $.each(data,function(idx,Frt){
                            frts[frts.length]=Frt;
                        });
                        return {
                            results: frts
                        };
                    }
                },
                initSelection: function(element, callback) {
                    var data = [];
                },
                formatResult: formatResult,
                formatSelection: formatSelection
                });
        });

});

But I am getting the error:

Error: Option 'id' is not allowed for Select2 when attached to a
  <select> element.

But when I use <input type="hidden"> then where should I keep the pre-selected options? How do I show them up when the select2 box appears?

A: You can use the "data" function to set the initial values:
var PRESELECTED_FRUITS = [
    { id: '1', text: 'Apple' },
    { id: '2', text: 'Mango' },
    { id: '3', text: 'Orange' }
];

$('.myList').select2('data', PRESELECTED_FRUITS)

Note: The "val" function is another way to set the initial values, but you only specify the ids with that function. In that case you would have to supply an "initSelection" function that builds the objects from the ids.
Also note that the "id" option is not the only option that is forcing you to use a hidden input. You cannot use the "ajax" option with a select element either.
As for the "id" option, I don't think you need it. Just put logic in the ajax "results" function so it builds an array of objects that have the proper id and text properties, or have the server return objects with those properties.
jsfiddle demo

A: To preset values use the 'val' property to preset the selected values.
$(this).select2({
            val: ["1","2","3"]
    }

But why not remove the 'id' function? If possible you could return the correct 'id' from the server without the need of the id function.

A: You can also load the values into the HTML:
<select class="selector" multiple="multiple" >
    <option selected value="1">Apple</option>
    <option selected value="2">Mango</option>
    <option selected value="3">Orange</option>
</select>

And connect select2 to it:
$(".selector").select2({
    width: 'inherit',
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    placeholder: "Search for fruits",
    ajax: {
        delay: 1000,
        url: "/bla_foo",
        dataType: 'json',
        type: "GET",
    }
})

and select2 will prefill the form.

A: $('select').select2({
    multiple: true,
    data: [
        {id: 1, text: 'Foo', selected: true},
        {id: 2, text: 'Bar', selected: true}
    ]
})

A: If you only have values then you can use 'val' to get pre-selected values like this.
var PRESELECTED_FRUITS = [ '1','2','3'];

$('.myList').select2({}).select2('val', PRESELECTED_FRUITS);

A: $("#select2").select2('data', {id: '3', text: 'myText'});


text:
Q: Istio. How to add Virtual Host to Envoy? Using Istio EnvoyFilter https://istio.io/latest/docs/reference/config/networking/envoy-filter/ I want to add new VirtualHost inside Envoy in sidecar of pods.
How to do this?
I guess I should create and apply manifest something like:
apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: my-filter
  namespace: default
spec:
  workloadSelector:
    labels:
      run: mylabel
  configPatches:
  - applyTo: ???
    match:
      context: SIDECAR
    patch:
      operation: ADD
      value:
        ???


text:
Q: Can I simply isolate Ethernet ports from one another without the complexity of VLAN? I'm to set up Internet access for a building.  Each office-suite has a hardwired Ethernet cable.  I'm going to have each tenant bring their own WiFi/LAN router to plug into their Ethernet cable to service their suite.  Then I'd like to have an Ethernet switch that keeps each Ethernet port isolated, so that the tenants cannot access (or even detect) each others' devices.
I'd likely have my router assign IP address ranges to each tenant's router and let them run in router mode.  Or maybe I'd have a large DHCP server that assigns all the IP addresses while routers run in WAC mode.  Whichever works best for isolated Ethernet ports.

A: The concept you are looking for is
Private VLAN / Port Isolation,
described as:

Private VLAN, also known as port isolation, is a technique in computer networking where a VLAN contains switch ports that are restricted such that they can only communicate with a given "uplink". The restricted ports are called "private ports". Each private VLAN typically contains many private ports, and a single uplink. The uplink will typically be a port (or link aggregation group) connected to a router, firewall, server, provider network, or similar central resource.

You should ensure that whatever switch you buy supports this option.
See the descriptions for Port Isolation from
NETGEAR
and
CISCO.


text:
Q: Insert cells in Excel without updating adjoining formulas Sometimes I visually compare two datasets by pasting them side-by-side in Excel with a formula in the middle like =A1=C1.  This will return true or false based on whether the cells are an exact match.  When the datasets are missing a record, I can get them to line up again by simply inserting a new cell and shifting the existing ones down.  However, when I do this it updates the formulas to shift the referring cell down by the amount of cells I inserted, like this:

This causes problems because I have to redo all the formulas down the middle each time this happens.  On a long dataset, this gets very tedious.  Is there any way to "lock" the formulas in the comparison columns so it doesn't care if I insert or delete cells, they will always stay pointing to the original cells I set up?
BTW, I know that $A$1 will lock a reference, but that only works if you're moving that cell around, not moving the referenced cell.  If you put that in at the top and drag them down, they will all stay $A$1, no matter what row you drag to (plus, it still does the update after inserting a cell in the reference column).

A: Instead of inserting cells, you could copy the cells you want to shift down, and use paste-special-values to put them where you want them. In other words, moving the values instead of the cells will prevent the formulas from adjusting.

A: I put one set of data in column A and the other in column B.  Then I pasted the formula below in each cell in column C.  The ROW() function returns the current row number, so you can insert/delete data in column A or B without having to paste and repaste your formulas.  You can paste the formula in any column and it will still work – comparing column A and B in the row it is in.
=IF(INDIRECT(ADDRESS(ROW(),1)) = INDIRECT(ADDRESS(ROW(),2)), "ok", "***diff***")

I do agree – I wish there was some way to tell Excel not to change formulas when you insert and delete data in a column.

A: If I understand your question, I think this may work:
=OFFSET($B$1,ROW()-1,-1)=OFFSET($B$1,ROW()-1,1)

Where B1 is an arbitrary anchor for your formulas and you always calculate the offset to the cell on either side of your comparison.


text:
Q: DI with Repository and Services in different DLLs, keeping separation of concerns I have a layered application with the following projects:

*

*DAL (using EntityFramework with repositories)

*DAL.Model (contains the entities, and is referenced by all the others)

*Services

*UI (in wpf)

The base repository looks like this:
public abstract class RepositoryBase<T> where T : class
{
    private readonly MyContext context;
    private readonly IDbSet<T> dbSet;

    protected RepositoryBase(MyContext dataContext)
    {
        context = dataContext;
        dbSet = context.Set<T>();
    }

    protected MyContext Context
    {
        get { return context; }
    }

    **And a series of virtual methods for Add, Delete, etc.
}

All repositories extend this one, such as:
public class MarketRepository : RepositoryBase<Market>
{
    public MarketRepository(MyContext dataContext) : base(dataContext)
    {

    }

    public IEnumerable<Market> GetAllMarkets()
    {
        return this.Context.Markets.ToList<Market>();
    }
}

The services look like this:
public class MarketService
{
    IMarketRepository _marketRepository;

    public MarketService(IMarketRepository marketRepository)
    {
        _marketRepository = marketRepository;
    }

    public IEnumerable<Market> GetAllMarkets()
    {
        return _marketRepository.GetAllMarkets();
    }
}

What I would like to achieve is that the UI layer would only have a reference to the Services layer, the Services layer only with the DAL layer (and all of them to Model, where the entities live) using DI (right now I'm using Unity).
The problem is, in my container in the UI I only want to do this
unity.RegisterType<IMarketService, MarketService>();

and not have to do it as well for the repositories, because then the UI layer would have a dependency on the DAL layer.
I thought about adding a parameterless constructor to the Service classes, like:
public MarketService() : this(new MarketRepository(*What would I put here?)) { }

but then I'm loosing the abstraction that the interface gives, and also I don't know what to do with the MyContext that the repository needs as a parameter; if I pass a new one, then I need to reference the DAL.
Should I change my repositories to create a new MyContext in the constructor, rather than getting it as a parameter?
How can I refactor my architecture to make it work properly and with minimal dependencies?

A: Well, I belive it is up to the bootstrapper to configure dependencies, in the higher level of the application. As it is usually the UI project, if it needs to reference other assemblies, so be it. If you do not like your UI project managing that, than create a bootstrapper project responsable for getting your app running and separete your UI classes in another one.

A: Your IoC container should support Dependency Injection using a string from an external configuration file. This way you are not hardcoding the mapping. Structuremap does this quite well, so I am sure other IoCs will.

A: Adding external dependenices as a parameter when creating an instance is the way to go.
I think you should make yourself more familiar with the different ways to configure Unity, so that the dependencies are resolved.
Could you elaborate why you are creating a repository when using a dependency injection framework?

A: When configuring DI, you should follow the same pattern - UI bootstrapper initializes Services, Services initialize DAL. (With autofac or ninject you could achiece this using modules. With unity you should emulate modules).
In pseudocode something like
//ui
void UILayer.ConfigureUnity(unity)
{
    ServiceLayer.ConfigureUnity(unity)
}
//services
void ServiceLayer.ConfigureUnity(unity)
{
    DAL.ConfigureUnity(unity)
    unity.RegisterType<IMarketService, MarketService>();

}
//dal
void DAL.ConfigureUnity(unity)
{
    unity.RegisterType<IMarketRepository, MarketRespository>();
    unity.RegisterType<MyContext, MyContext>(); //not sure exact syntax - just register type for 'new Type()' activator.
}


text:
Q: Using EJML, is there a quick way to find mean of columns of a matrix? Was looking for a function which returns a one diamensional SimpleMatrix giving the mean.

A: Unfortunately there isn't a built in function to do that.  This should do the trick though:
SimpleMatrix ones = new SimpleMatrix(1,10);
ones.set(1);
SimpleMatrix m = SimpleMatrix.random64(10,20,-1,2,new Random());

SimpleMatrix sum = ones.mult(m);
SimpleMatrix mean = sum.divide(10);


text:
Q: Why are the correct values not displayed in my @Html.DropDownListFor()? I am a beginner at .NET MVC and trying to do a simple task such as displaying a list of items in a dropdown list. However my current code produces a dropdown list displaying the name of the type of the items instead of the actual values. Thanks for helping out. :)
DropDown not displaying the correct values
My code follows;
SelectArticleModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TheMakingOfAWebApplication.Models
{
    public class SelectArticleModel
    {
        public string Name { get; set; }
        public IEnumerable
 Articles { get; set; }
    }
}

Article.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TheMakingOfAWebApplication.Models
{
    public class Article
    {
        public string Name { get; set; }
    }
}

HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TheMakingOfAWebApplication.Models;

namespace TheMakingOfAWebApplication.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //List
 articles;

            SelectArticleModel model = new SelectArticleModel();
            model.Name = "";
            model.Articles = new List
{
                new Article { Name = "Bananas"},
                new Article { Name = "Apples"},
                new Article { Name = "Oranges"},
                new Article { Name = "Melons"},
                new Article { Name = "Grapes"},
                new Article { Name = "Sallad"},
                new Article { Name = "Potatoes"},
                new Article { Name = "Cucumber"},
                new Article { Name = "Beans"},
                new Article { Name = "Tomatoes"}
            };
            return View(model);
        }
    }
}

Index.cshtml
@model TheMakingOfAWebApplication.Models.SelectArticleModel

@{
    ViewBag.Title = "Index";
}

Index

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Article

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(m => m.Name, new SelectList(Model.Articles)))
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

A: Let your SelectList know what the Value and Text property names are.
@Html.DropDownListFor(m => m.Name,
                 new SelectList(Model.Articles, "Name", "Name", Model.Name)))

A: Since you are using a complex object to bind, you can specify the dataTextField and dataValueField as arguments to SelectList. Try following:
@Html.DropDownListFor(m => m.Name, new SelectList(Model.Articles,"Name","Name"))

If you have a List of primitive types like string, the overload of SelectList you are using would work without mentioning extra parameters.


text:
Q: Create subList of list, with increased performance Let's say we've got a few lists as follows:
list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
list2 = ['hi', 'bye', 1.0]
list3 = ['hi', 'bye', 'hello', 2.0]

I want to get it in this format:
newList1 = [['hi', 'hello'], ['hello', 'goodbye'], ['goodbye', 'caio'], ['caio', 1.0]]
newList2 = [['hi', 'bye'], ['bye', 1.0]]
newList3 = [['hi', 'bye'], ['bye', 'hello'], ['hello', 2.0]]

My current method is looping through the list based on len(), and appending [listN[i], listN[i+1], but this is running within another for loop of a huge dataset, so O(n^2) is brutal. Is there any way to increase the performance?
Thanks.

A: You can do like this,
list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]

newList1 = list(zip(list1, list1[1:]))
# Result
[('hi', 'hello'), ('hello', 'goodbye'), ('goodbye', 'caio'), ('caio', 1.0)]

Edit
If you want a list of list,
list(map(list, zip(list1, list1[1:])))
# Result
[['hi', 'hello'], ['hello', 'goodbye'], ['goodbye', 'caio'], ['caio', 1.0]]

A: I like the solution proposed by @Rahul K P, but here is another option. List comprehension is always almost faster than a loop, so you can do it like this:
list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
newList1 = [list1[i:i+2] for i in range(len(list1)-1)]

I would appreciate if you test all 3 solutions and share the results.


text:
Q: DB2 Building json using JSON_ARRAY I am  using DB2LUW 11.5.
I am building a JSON under usage of the below tables and want an output like this
I tried many things but I come not up to a solution.
 {
        "ID": 1,
        "NAME": "a",
        "B_OBJECTS": [{
                "ID": 1,
                "SIZE": 5
            },  {
                "ID": 2,
                "SIZE": 10
            },  {
                "ID": 3,
                "SIZE": 15
            }
        ],
        "C_OBJECTS": [{
                "ID": 1,
                "SIZE": 100
            }, {
                "ID": 2,
                "SIZE": 200
            }
        ]
    }

Table_A

ID
NAME

1
a

Table_B

ID
ID_A
SIZE

1
1
5

2
1
10

3
1
15

Table_C

ID
ID_A
SIZE

1
1
100

2
1
200

WITH
  TABLE_A(ID,NAME) AS
(
        VALUES (1, 'a')
)
, TABLE_B(ID, ID_A, SIZE) AS
(
        VALUES (1, 1, 5), (2, 1, 10), (3, 1, 15)
), TABLE_C(ID, ID_A, SIZE) AS
(
        VALUES (1, 1, 100), (2,1, 200)
)
, JSON_STEP_1 AS
(
  SELECT A_ID, A_NAME, B_ID, C_ID
  , JSON_OBJECT('ID' VALUE B_ID, 'SIZE' VALUE B_SIZE) B_JSON
  , JSON_OBJECT('ID' VALUE C_ID, 'SIZE' VALUE C_SIZE) C_JSON
  FROM
  (
        SELECT
          A.ID AS A_ID, A.NAME AS A_NAME, B.ID AS B_ID, B.SIZE AS B_SIZE, C.ID AS C_ID, C.SIZE AS C_SIZE
        FROM TABLE_A A
        JOIN TABLE_B B ON B.ID_A = A.ID
        JOIN TABLE_C C ON C.ID_A = A.ID
   )
   GROUP BY A_ID, A_NAME, B_ID, B_SIZE, B_ID, B_SIZE, C_ID, C_SIZE
)
, JSON_STEP_2 AS
(
 SELECT
 JSON_OBJECT
  (
    'ID' VALUE A_ID,
    'NAME' VALUE A_NAME,
    'B_OBJECTS' VALUE JSON_ARRAY (LISTAGG(B_JSON, ', ') WITHIN GROUP (ORDER BY B_ID) FORMAT JSON) FORMAT JSON,
    'C_OBJECTS' VALUE JSON_ARRAY (LISTAGG(C_JSON, ', ') WITHIN GROUP (ORDER BY C_ID) FORMAT JSON) FORMAT JSON
  ) JSON_OBJS
 FROM JSON_STEP_1
 GROUP BY A_ID, A_NAME
)
SELECT * FROM JSON_STEP_2

I get a mulitplication of the results
{
    "ID": 1,
    "NAME": "a",
    "B_OBJECTS": [{
            "ID": 1,
            "SIZE": 5
        }, {
            "ID": 1,
            "SIZE": 5
        }, {
            "ID": 2,
            "SIZE": 10
        }, {
            "ID": 2,
            "SIZE": 10
        }, {
            "ID": 3,
            "SIZE": 15
        }, {
            "ID": 3,
            "SIZE": 15
        }
    ],
    "C_OBJECTS": [{
            "ID": 1,
            "SIZE": 100
        }, {
            "ID": 1,
            "SIZE": 100
        }, {
            "ID": 1,
            "SIZE": 100
        }, {
            "ID": 2,
            "SIZE": 200
        }, {
            "ID": 2,
            "SIZE": 200
        }, {
            "ID": 2,
            "SIZE": 200
        }
    ]
}

A: You have to build arrays from table B and C in different queries.
By the way, since your version is 11.5 you will maybe sometime have JSON_ARRAYAGG available
So you can write :
WITH
  TABLE_A(ID,NAME) AS
(
        VALUES (1, 'a')
)
, TABLE_B(ID, ID_A, SIZE) AS
(
        VALUES (1, 1, 5), (2, 1, 10), (3, 1, 15)
), TABLE_C(ID, ID_A, SIZE) AS
(
        VALUES (1, 1, 100), (2,1, 200)
)
select
 JSON_OBJECT
  (
    'ID' VALUE A.ID,
    'NAME' VALUE A.NAME,
    'B_OBJECTS' VALUE (
      select json_arrayagg(
        JSON_OBJECT('ID' VALUE b.ID, 'SIZE' VALUE b.SIZE)
      ) from table_b b where b.id_a = a.id
    ) format json,
    'C_OBJECTS' VALUE (
      select json_arrayagg(
        JSON_OBJECT('ID' VALUE C.ID, 'SIZE' VALUE C.SIZE)
      ) from table_c c where c.id_a = a.id) format json
    absent on null
  )
from table_a a

gives
{
    "ID": 1,
    "NAME": "a",
    "B_OBJECTS": [{
            "ID": 1,
            "SIZE": 5
        }, {
            "ID": 2,
            "SIZE": 10
        }, {
            "ID": 3,
            "SIZE": 15
        }
    ],
    "C_OBJECTS": [{
            "ID": 1,
            "SIZE": 100
        }, {
            "ID": 2,
            "SIZE": 200
        }
    ]
}


text:
Q: Core Data Requests from Today Extension returning 0 results? I'm working on a simple app, and am looking to include some Core Data functionality from the Today Widget. It's giving me some trouble however, and I'm not sure what it is I'm missing.
Here's what I have done:

*

*I've added the widget target to the Core Data model

*I have NOT added my entity subclasses. This opens a can of worms with a bunch of sharedApplication references. I don't need to do much within the widget, so I think it will be much easier to just work with NSManagedObject instances.

*In viewDidLoad of the widget I create a persistent container:
NSPersistentContainer *myContainer = [[NSPersistentContainer alloc] initWithName:@"MyDataModelName"];
[myContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
    if (error != nil) {
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}];

So far so good, and no error is returned.
However, no results are returned when I call:
[myContainer.viewContext executeFetchRequest:request error:&error];

Entity Name and predicates don't seem to make a difference. No request error is returned. Identical requests work fine within the app proper.
It would seem that I am maybe initiating an empty container instead of grabbing the correct one? I'm sure this is a simple thing, but I'm at a loss. Any help is appreciated.


text: Q: Disable Video-Out on Galaxy Tab I'm trying to block the tv-out capabilities on a galaxy tab programatically and looking through the source code I have not been able to find anything that is available to do this.


text:
Q: $Z_{n,N}$ convergence to $N(0,1)$ in law for all N, how to find $N_n$ s.t. $Z_{n,N_n}$ also converges to $N(0,1)$ in law? I'm reading Terence Tao's blog on the central limit theorem.
When reducing the theorem to bounded random variables, let $$Z_{n, \leq N}:=\frac{S_{n, \leq N}-n \mu_{\leq N}}{\sqrt{n} \sigma_{\leq N}}$$ where $S_{n, \leq N}= (X_1+\cdots+X_n)_{\leq N}$, and ${\mu_{\leq N}, \sigma_{\leq N}^2}$ be the mean and variance of the bounded random variable ${(X_i){_{\leq N}}}$. Assuming the CLT in the bounded case, we know that $\forall N$, $Z_{n, \leq N}$ converges in distribution to $N(0,1)$. Now he uses the a diagonalization argument to conclude that there exists a sequence ${N_n}$ going to infinity with ${n}$, such that ${Z_{n,\leq N_n}}$ still converges in distribution to ${N(0,1)}$.
However, I don't see how the diagonalization argument works. Any suggestions will be greatly appreciated.


text:
Q: Converting call back to async/await functions I'm trying to concert a callback function to stand chained functions, but could not manage it,
the callback function is:
db.transaction(
 function(t){
  t.executeSql("SELECT * FROM cal_list where calories > ?" ,[min_cal_amount], function(t,r){
     for (var i=0; i < r.rows.length; i++){
      food = r.rows.item(i).food;
      amount_of_calories = r.rows.item(i).amount_of_calories;
      serving_size = r.rows.item(i).serving_size;

      list.innerHTML +="<li>"+food+" has "+amount_of_calories+" KCAL worth of calories.</li>";

        }
    },

    function(t,e){alert(e.message);})
}
);

How can I convert to to async..await or try..then..catch?

A: If your database library exposes db.transaction and t.executeSQL in a promise based api, it would look roughly like this:
async function getResults() {

    const transaction = await db.transaction();

    try {
        const result = await transaction.executSql(
            'SELECT * FROM cal_list where calories > ?',
            [min_cal_amount]
        );

        for (var i = 0; i < result.rows.length; i++) {
            // work with result data
        }
    }
    catch (e) {
        // rollback transaction, handle error as appropriate
    }
}

If your library does not expose those functions in a promise based api, you can use util.promisify to wrap those functions that expect a callback, and then use the above snippet.


text:
Q: WP - API - OAuth 1.0a Server, How to implement with AngularJS? I making an Angular WordPress theme and I want to add authentication to it using the WP REST API - OAuth 1.0a Server plugin, which isn't documented not very well.
I get oauth_token and oauth_token_secret using Postman, But I haven't got an idea on how to implement OAuth 1.0a in my AngularJS theme. I've googled a lot but can't get any results.
So is there any Example, Article or any other resources to get the idea?


text:
Q: Rewriting URL with .htaccess local in XAMPP My .htacces begins with
   RewriteEngine on
   RewriteBase /

(I tried it also without RewriteBase...)
I tried all of the following rewriting rules to rewrite the URL
index.php?page=news
to
/blog

*

*RewriteRule ^/?([-A-Za-z0-9]+)/([-A-Za-z0-9]+)/blog$
index.php?page=$1 [L]

*RewriteRule ^([^/]*)/blog$ /sites/blog/index.php?page=$1 [L]

*RewriteRule ([a-zA-z]+)/([a-zA-z]+)/blog$ index.php?page=$1 [L]

Nothing works - no error. Mod_rewrite is installed and working. I restarted Apache and MySQL everytime I changed something in my .htaccess.
I also want to change my URLs which looks like this... index.php?page=single_news&category=release&id=9&headline=Beastie%20Boys%20III
...into: blog/release/9-Beastie-Boys-III
I am lost. Hope you can help me.

A: First of all, upload your .htaccess and other files (whole project) to some working, ready hosting server. And check, if your rewriting works OK there. This will let you know, if this is problem with .htaccess or XAMPP itself. I had many strange problems with using .htaccess locally, under XAMPP, that were magically gone, after files were uploaded to Internet hosting.
For example, I don't have working autorization using .htaccess locally, because right after I provide correct login and password I see exactly the same error message as you mentioned. As for me, I'm more than sure that this problem is purely related to incorrect interpretation of .htaccess done by XAMPP (as everything works like a charm on production server), not by some mistakes in .htaccess contents.
I wasted (too) many hours on finding solution and left it. For right now, if I'm developing locally, I rename ".htaccess" to "htaccess", so it is ignored by XAMPP (Apache on-board of it) and re-enable it only when deploing files to production server. This approach maybe isn't to professional, but it saved me a lot of time and stress! :]
On the other hand, if your hosting also fail with the same symptoms, then you'll know, that this is not XAMPP releated problem and you have something wrong with your syntax.
Take a look here for a similar problem reported on StackOverflow.com, where (as I think) the cause is the same as in your issue.

A: Here's the solution to change links from http://www.domain.tld/index.php?page=blog to http://www.domain.tld/blog is:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+$ index.php?page=$0 [L]
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)$
RewriteRule ^index\.php$ /%1? [R=301,L]

and for links like: http://www.domain.tld/index.php?page=single_news&id=1&headline=This%20Is%20A%Headline
the solution is:
RewriteRule ^blog/(\d+)-([\w-]+)$ index.php?page=single_news&id=$1&headline=$2

After using this code, links looks like this: http://www.domain.tld/blog/2-this-is-a-headline

A: For your first question, try this:
RewriteEngine on
RewriteRule ^/blog$ /index.php?page=news


text:
Q: Failed to traverse DOM while rendered inside iframe with section tags I facing a situation which i can't traverse the dom inside iframe. My code is as follows. When i am trying to accessing childNodes of body tag, console will show there are no childNodes inside the body tag.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

c07.xhtml
<!DOCTYPE html>

The section element

History

The World Wide Fund for Nature (WWF)

Symbol

The Panda has become the symbol of WWF.

//index.js
const parentNode = document.querySelector("#container");
const iframeBody =  iframeRef(parentNode);
console.log(element.childNodes[0].getElementsByTagName('section')); //prints HTMLCollection[] and length is 0

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

How can i resolve this?

A: Try this its working for me. Access iframe dom elements inside setTimeout function.
const parentNode = document.querySelector("#container");
setTimeout(() => {
  const iframWindow = parentNode.contentDocument;
  console.log(iframWindow.getElementsByTagName("section")); //prints HTMLCollection[] and length is 0
}, 1000);


text:
Q: Making thread-safe calls to windows forms controls The MSDN article: How to: Make Thread-Safe Calls to Windows Forms Controls
says we should use async delegate to make the call. But why does the async delegate make the call safe?

A: Windows controls use the Component Object Model (COM) single-threaded apartment (STA) model because those underlying controls are apartment-threaded. Furthermore, many of the controls use the message pump for many operations. This model says that all function calls to each control must be on the same thread that created the control. Invoke (and BeginInvoke and EndInvoke) marshals method calls to the proper thread.
From Bill Wagner's  More Effective C#. Item 16. Understand Cross-Thread Calls in Windows Forms and WPF

A: You'll call control.BeginInvoke() or control.Invoke() and that method will take care of inserting your delegate in the GUI dispatch thread safely, so a bit later on your delegate will be processed and executed in the GUI thread and not the thread you'r in

A: The bottom line is this: You shouldn't update the UI Controls from a thread other than the one on which the control was created (UI / Main Thread). Otherwise you may see some unpredictable behavior.
If you need to update the UI from a worker thread (other than the main thread) you need to switch back to the UI Thread before updating the UI.
The article suggests using

*

*IsInvokeRequired (which returns true if the current thread is not the one in which UI was created.) and Invoke(delegate) which runs the delegate on the correct/UI thread. This is useful when you want to update the UI in between the async process. e.g. update progress on the UI.

*BackgroundWorker which executes registered handlers to its DoWork event async. on a worker thread and runs the registered handlers to its RunWorkerCompleted event on the calling thread. This is ideal if you want to update the UI with something after the async task has completed. e.g. post a Done indication on the UI

A: Because, windows forms controls are designed in that way, so they can be accessed only from within he thread, which owes them. And the async delegate, when used correctly, makes the call safe.
The actual answer to the given question is contained in the second paragraph of the given MSDN article =)

Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.

You should check whether you can access control immediately, without indirection ( checking the InvokeRequired property ), if you can't, you should access it asynchronously ( very simplified explanation: the system will wait until it can safely access a control )


text:
Q: A contents page displaying images I am creating a contents page in Word. For some reason, objects that I have pasted in from Visio are being shown in the page listing...
Why is this?
And more importantly, how can I stop this from happening?

A: OK, easy as. Just had the images set as a heading.
Soz ppl.