text:
Q: fetching rows without any filtered child row The application manages (for the sake of simplicity) Topic and Messages posted to it by Users. Its structure is rather simple, and enforced by Foreign keys:
There are 3 tables, Topics, Users and Messages.
The Topic and User entities are linked through an (,) cardinality link embodied by the Message Entity.
Message: (IdTopic,IdUser,Message)

The other entities aren't of any interest by themselves.
Now the question:
I need to return every topics for which a specific user hasn't made any reply (Message). As you imagine, the database diagram is constitued of 3 tables.
How do I do it without a complex query? I am quite sure the answer is easy... But it's far too late in the night for me to think straight.

A: Using NOT EXISTS
SELECT t.*
  FROM TOPICS t
 WHERE NOT EXISTS(SELECT NULL
                    FROM MESSAGES m
                   WHERE m.idtopic = t.idtopic
                     AND m.isuser = @userid)

Using NOT IN
SELECT t.*
  FROM TOPICS t
 WHERE t.idtopic NOT (SELECT m.idtopic
                        FROM MESSAGES m
                       WHERE m.isuser = @userid)

Using LEFT JOIN / IS NULL
   SELECT t.*
     FROM TOPICS t
LEFT JOIN MESSAGES m ON m.idtopic = t.idtopic
                      AND m.isuser = @userid
    WHERE m.message IS NULL

Performance Concerns
NOT IN and NOT EXISTS perform better than LEFT JOIN / IS NULL if the columns being compared (idtopic, isuser) are not nullable.  See this link for details.

A: From what you've described I believe that this query will work. I'm sure that it can be made to be more efficient, but I wanted it to work and be simple and then you could figure out how to improve it if you want.
SELECT t.IdTopics
FROM Topics t
WHERE t.IdTopics NOT IN (SELECT m.IdTopics
                          FROM Messages m
                          WHERE m.IdUser = @SpecificUser
                         )


text:
Q: Selecting items in a list based on multiple conditions This question has been solved. Thanks for all your help!
I have data that looks like this.
{{{1,3}},{{2,3},{5,2},{2,3},{4,1}},{{4,3},{1,1},{3,2},{5,4},{7,6}},{{2,6},{3,3}}}

These represent the position of objects and their trajectories at different times. So, that the first object {{1,3}} only stayed at that one position with coordinates {1,3}. But, the second object {{2,3},{5,2},{2,3},{4,1}} was in 4 positions.
I would like to delete only the objects that moved more than 2 times, and that have the same position at times 1 and 3. So, an example would be:
{{2,3},{5,2},{2,3},{4,1}}

And I would like to keep all the other data.
I would appreciate if some could help with figuring this out.
Thanks!

A: @Runnykine pointed out corectly that I only address 1 criterion.
Corrected Answer
DeleteCases[d, _?(Length@# > 2 && #[[1]] == #[[3]] &)]
Pick[d, Or[Length@# < 3, #[[1]] != #[[3]]] & /@ d]
Select[d, Or[Length@# < 3, #[[1]] != #[[3]]] &]

Original Answer
Just some variants:
Pick[d, Length /@ d, _?(# < 3 &)]
Select[d, Length@# < 3 &]
Cases[d, _?(Length@# < 3 &)]

where d is list

A: This works as well
Select[
 list,
 If[Length[#] > 2,
   If[#[[1]] == #[[3]],
    False,
    True
    ],
   True
   ] &
 ]

And i think it's easier to understand how it works (well, at least for me).

A: This should do it:
DeleteCases[list, {x_, _, x_, ___}]

or equivalently
list /. {x_, _, x_, ___} -> Nothing

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I repeat a printf() every 1 second, but toggle it on and off with a specific user input? I need to write a program that begins by accepting a user input, either "poke" or "quit". If the user types "poke", the program begins to print "Go Tigers" every 1 second, and at any time "poke" can be typed again to toggle the printing on or off. If "quit" is typed at any time, the program should exit.
Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAXLEN 4

int main()
{
    char line[MAXLEN], input[MAXLEN];
    fgets(line, sizeof(line), stdin);
    sscanf(line, "%s", input);

    int flag = 0;

    if (input[0] == 'p')
        flag = 1;
    else if (input[0] == 'q')
        exit();

    while (flag == 1)
    {
        printf("Go Tigers\n");
        sleep(1);
    }
}

The printing is working fine, but I'm not sure how to allow input during the while loop to toggle it on/off. I think I have to use wait() and write another function, but I haven't had any luck with that yet.
Thanks in advance!


text:
Q: Hierarchical model in Tensorflow probability using JointDistributionSequential I'm trying to understand how to implement the following model in Tensorflow probability.

*

*An angle, theta, has uniform prior probability in the range [-pi / 2, +pi / 2];

*A direction-flip probability, beta, has uniform prior probability in range [0, 1];

*theta' is set to either:

*

*theta' = theta + pi with probability beta; or

*theta' = theta with probability (1 - beta);

*Concentration c has a HalfCauchy prior probability; and

*An observation, alpha is drawn from the von Mises distribution, centred on theta' with concentration c.

So far what I've tried is
import tensorflow_probability as tfp
import numpy as np
tfd = tfp.distributions

model = tfd.JointDistributionSequential(
    [
        tfd.Uniform(-np.pi / 2, +np.pi / 2, name='theta'), # theta
        tfd.Uniform(0.0, 1.0, name='beta'), # beta
        tfd.HalfCauchy(loc=0, scale=1), # c
        lambda c, beta, theta: tfd.VonMises(
            loc=theta + np.pi * tfd.Binomial(probs=beta),
            concentration=c,
            name='observed'
        ), # Observation, alpha
    ]
)

Calling this gives an error on the binomial part: TypeError: __init__() missing 1 required positional argument: 'total_count'.  What am I doing wrong?
Updated 2020-03-17
Latest code is as follows. I'm still trying to find out how to implement part (3) of my model, i.e. flip the direction of my angle, theta, by adding pi with probability beta.  Any help on this would be appreciated! What I have so far doesn't work because I can't multiply the Bernoulli object by a float.
model = tfd.JointDistributionSequential(
    [
        tfd.Uniform(-np.pi / 2, +np.pi / 2, name='theta'), # theta
        tfd.Uniform(0.0, 1.0, name='beta'), # beta
        tfd.HalfCauchy(loc=0, scale=1), # c
        lambda c, beta, theta: tfd.VonMises(
            loc=theta + np.pi * tfd.Bernoulli(probs=beta, dtype=tf.float32),
            concentration=c,
            name='observed'
        ), # Observation, alpha
    ]
)

A: The problem of multiplying a number by a distribution in the loc parameter calculation can be fixed by sampling from the Bernoulli distribution i.e.
...
loc=theta + np.pi*tfd.Bernoulli(probs=beta, dtype=tf.float32).sample(),
...

This allows sampling from the joint distribution but I'm not sure that it's correct.
Another approach is to pull out the flip random variable and scale using a bijector i.e.
tpb = tfp.bijectors
model = tfd.JointDistributionSequential(
[
    tfd.Uniform(-np.pi / 2, +np.pi / 2, name='theta'), # theta
    tfd.Uniform(0.0, 1.0, name='beta'), # beta
    lambda beta, theta: tfb.Scale(np.pi)(tfd.Bernoulli(probs=beta, dtype=tf.float32)), #flip
    tfd.HalfCauchy(loc=0, scale=1), # c
    lambda c, flip, beta, theta: tfd.VonMises(
        loc=theta + flip ,
        concentration=c,
        name='observed'
    ), # Observation, alpha
]

)
This also allows sampling from the joint dictribution and has the advantage of being able to see when flips happen.

A: Swap out Bernoulli for Binomial. Binomial is the sum of a total_count number of bernoulli draws.


text:
Q: Number of solutions of the equation $z^\alpha=1$ where $\alpha$ is real. I was just studying complex analysis by myself, and I got stuck with this problem. The problem is essentially just asking about the number of solutions of $z^\alpha=1$ where $\alpha$ is real and $z$ is complex.
If $\alpha$ is an integer, all possible $z$'s are given as the nth root of unity, so there are $n$ of them.
If $\alpha$ is rational, then I can write $\alpha=\frac{q}{p}$, and take the power of $p$ in each side, so we get $z^{q}=1$. Not all of $q$-roots of unity satisfy the original solution, so we would need to delete some of them.
If $\alpha$ is irrational, suppose $\alpha=\pi$, then how would I know the number of the solutions of $z^\pi=1$?
This might be a really dumb question, and I'm new to complex analysis, so help me please. Thanks in advance.

A: The number of solutions is actually infinity. It is actually trivial, when $\alpha$ is 0.
For the $z^\pi=1$ answer, look here: How many solutions has $z^\pi = 1$?


text:
Q: Nested Web Worker in Chrome I am trying to spin up a Web Worker from inside a Web Worker using Chrome. Historically, this has been a problem space with the Chrome Host API, but:
According to ChromeStatus,as of 2018-10-22

Dedicated workers can create nested workers, but shared workers and service workers cannot.
Creating a nested dedicated worker from a shared worker is not yet supported.
Nested shared workers are also in the spec, but there is no plan to support them at this time.

Lucky me; I'm using a dedicated worker.
I can find no information available that formally contradicts this declaration of support in Chrome for desktop release 69 (I am using Chrome 72) and my nested Worker just sits on his duff and refuses to get Janice her Coffee.
I have three moving parts at play: a SlaveDriver, a Minion, and a Peon.  The SlaveDriver delegates to the Minion. The Minion delegates to the Peon, the Peon does the work, and each receiver takes the credit.
SlaveDriver
(
function(){
     var minion = new Worker('./Features/Work/Work.Minion.js');
     let crackTheWhip= ()=>
     {
        let message = {ID: 1};
        minion.postMessage(
           JSON.stringify(message)
        );
        console.log(message.ID);
     };
     let take_the_credit = (message)=>
     {
        let work = JSON.parse(message.data);
        console.log("Hot Coffee!");
        console.log(JSON.stringify(work));
     };
     minion.onmessage = take_the_credit;

     return {
        GetJaniceHerCoffee: crackTheWhip
     };
})();

Minion ./Features/Work/Work.Minion.js
(
   function(){
      var self = this;
      var peon = new Worker('./Features/Work/Work.Peon.js');
      let receiveWorkOrder = (message)=>
      {
          console.log('Delegating to a Peon');
          peon.postMessage(
              message.data
          );
      };
      let take_the_credit = (message)=>
      {
          console.log('Taking the credit');
          let work = JSON.parse(message.data);
          self.postMessage(JSON.stringify(
             work
          ));

      };
      peon.onmessage = take_the_credit;
      self.onmessage = receiveWorkOrder;
   }
)();

Peon   ./Features/Work/Work.Peon.js
(
   function(){
       var self = this;
       let receiveWorkOrder = (message)=>
       {
           console.log("surfing LinkedIn.");
           console.log("surfing stackoverflow");
           console.log("...wth is this? *sigh*");

           let work_result = {Value: "Coffee"};
           self.postMessage(JSON.stringify(
               work_result
           ));
       };
       self.onmessage = receiveWorkOrder;
   }
)();

If I stop delegating at the minion and have him do all of the work of the peon, everything processes fine. But, as soon as I try to have the minion delegate to the peon, it gets squirrely on me.  In DevTools, I can see the minion activate in my Threads list when I postMessage to it. My debugging context jumps to the worker thread and when I postMessage to the peon, the Peon thread gets added to the Threads list but all propagation seems to stop. The logs to the console do not happen. The debugging context does not jump to the Peon thread. My minion's take_the_credit callback does not receive a response.
The Peon just sits there and does not do his work.
Why is my peon refusing to get Janice her coffee?

A: The answer to my question is currently found in the Spawning Subworkers subsection of the MDN documentation on Using Web Workers

Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.

Ultimately, the problem that I experienced was rooted in the fact that when my minion worker attempted to spawn its peon, it attempted to make reference to a file that was relative to document root rather than from the context of the worker but nothing was output to the console indicating that the file did not exist.
To tie this simple example out:
Slavedriver
<script type="application/javascript">
        var slave_driver = (
            function(){
                let minion = new Worker('/Features/Work/minion.js');
                let crackTheWhip = ()=>
                {
                    minion.postMessage(
                        JSON.stringify({SERVICE: "get"})
                    );
                };
                let take_the_credit = (message)=>
                {
                    console.log("It's about time");
                    alert(message.data);
                };
                minion.onmessage = take_the_credit;
                return {
                    GetJaniceHerCoffee: crackTheWhip
                }
            }
        )();

        slave_driver.GetJaniceHerCoffee();
    </script>

Minion ./Features/Work/Work.Minion.js
(
   function(){
      var self = this;
      let home = location;
      let peon = new Worker('/peon.js');
      let receiveWorkOrder = (message)=>
      {
         console.log("Delegating to a Peon");
         peon.postMessage(
            message.data
         );
      }
      let take_the_credit = (message)=>
      {
         console.log("It's about time!");
         console.log("Minion Taking the Credit");
         let work = JSON.parse(message.data);
         self.postMessage(JSON.stringify(work));
      };

      peon.onmessage = take_the_credit;
      self.onmessage = receiveWorkOrder;
   }
)();

Peon ./Features/Work/Work.Peon.js
(
 function(){
     var self = this;
     let receiveWorkOrder = (message)=>
     {
       console.log("Peon surfing stackoverflow");
       console.log("Peon surfing ebay for beanie babies, cuz they're coming back, yo");
       console.log("...wth is this? *sigh*");

       let work_result = {Value: "Coffee"};
       self.postMessage(JSON.stringify(
           work_result
       ));
     };
     self.onmessage = receiveWorkOrder;
  })();

Notice the small change to the file reference made when the minion spawns the peon.
If you drop the "slavedriver" script into the body of an index.html file and the relevant modules into their identified locations, you should get an alert that displays {"Value":"Coffee"} when you open index.


text:
Q: How to assign privileges on a postgresql schema to a user? pg_hba.conf contains:
...
host 10.10.10.10 service_db admin md5
...
Logged in as root, executed the following commands:
###CREATE DB ADMIN
sudo -u postgres psql -p 5432 -d postgres -c "CREATE USER 'admin' ENCRYPTED PASSWORD 'admin_pwd';"
###CREATE DB
sudo -u postgres psql -p 5432 -d postgres -c "CREATE DATABASE service_db OWNER 'admin' ENCODING 'UTF-8' TABLESPACE service_ts LC_COLLATE 'en_US.UTF-8' LC_CTYPE 'en_US.UTF-8' LIMIT -1;"
###CREATE SCHEMA
sudo -u postgres psql -p 5432 -d service_db -c "CREATE SCHEMA 'service_schema';"
###REVOKE PREVILEGES ON service_schema from public
sudo -u postgres psql -p 5432 -d service_db -c "REVOKE ALL ON SCHEMA 'service_schema' FROM 'public';"
###GRANT PREVILEGES ON TABLES OF service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT ALL ON TABLES IN SCHEMA 'service_schema' TO 'admin';"
###GRANT PREVILEGES ON SEQUENCES OF service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT ALL ON SEQUENCES IN SCHEMA 'service_schema' TO 'admin';"
###GRANT PREVILEGES ON FUNCTIONS OF service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT ALL ON FUNCTIONS IN SCHEMA 'service_schema' TO 'admin';"

and all commands were executed successfully.
Observed that:
a) Got permission denied error while selecting from a table in that schema in cli, as follows:
sudo -u postgres psql -H 10.10.10.10 -p 5432 -d service_db -U admin
service_db=#
service_db=#select * from service_schema.customers;
permission denied

While connecting and executing the command from Netbeans:
select * from service_schema.customers;

throws error:
Exception, Error Code 0, SQL State 42501
ERROR permission denied for schema admin

Please guide me in resolving the above issue.
Thanks in Advance!
Update:
GRANT USAGE ON SCHEMA... just before GRANT PRIVILEGES... resolved the problem. ie.
###CREATE DB ADMIN
sudo -u postgres psql -p 5432 -d postgres -c "CREATE USER "admin" ENCRYPTED PASSWORD 'admin_pwd';"
###CREATE DB
sudo -u postgres psql -p 5432 -d postgres -c "CREATE DATABASE service_db OWNER "admin" ENCODING 'UTF-8' TABLESPACE service_ts LC_COLLATE 'en_US.UTF-8' LC_CTYPE 'en_US.UTF-8' LIMIT -1;"
###CREATE SCHEMA
sudo -u postgres psql -p 5432 -d service_db -c "CREATE SCHEMA "service_schema";"
###REVOKE PREVILEGES ON service_schema from public
sudo -u postgres psql -p 5432 -d service_db -c "REVOKE ALL ON SCHEMA "service_schema" FROM 'public';"
###GRANT USAGE ON service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT USAGE ON SCHEMA "service_schema" TO "admin";"
###GRANT PREVILEGES ON TABLES OF service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT ALL ON TABLES IN SCHEMA "service_schema" TO "admin";"
###GRANT PREVILEGES ON SEQUENCES OF service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT ALL ON SEQUENCES IN SCHEMA "service_schema" TO "admin";"
###GRANT PREVILEGES ON FUNCTIONS OF service_schema TO admin
sudo -u postgres psql -p 5432 -d service_db -c "GRANT ALL ON FUNCTIONS IN SCHEMA "service_schema" TO "admin";"

works fine for me!

A: You don't mention which user created service_schema.customers and what permissions were given, if any, to the admin user for that table.
That user is presumably not admin and it presumably gave no permission at all to admin, so that would explain the error.
After creating the schema, the script does that:
GRANT ALL ON TABLES IN SCHEMA service_schema TO admin;

(BTW I've removed the single quotes around the schema name and user name. It's an error to put single quotes around identifiers, only double quotes or no quotes at all are allowed).
Anyway that command doesn't really affect anything because there are no tables yet in a schema that has just been created.
What you probably want is to (quoting the doc here) set the privileges that will be applied to objects created in the future with
ALTER DEFAULT PRIVILEGES IN SCHEMA service_schema GRANT ALL ON TABLES TO admin;

See ALTER DEFAULT PRIVILEGES in the documentation.


text:
Q: SSIS 2008 sql task returning a variable I have a problem when trying to retrieve a value from a sql task and pass it to an integer variable. I configure the sql task with resultSet in a single row  and Result Name = "0" , Variable Name ="Myvar"
Here is the code I use in the sql statement:
select max(runid) from table

with this query, using the max function, my variable get always the default value.
However when using the code:
select runid from table

, my variable get the correct data.
Can you see what wrong is?
Thanks a lot

A: Try adding an alias?
select max(runid) as runid from table


text:
Q: Why does trying to access an attribute in LINQ-to-XML give me an error? According to my LINQ book, this slightly altered example should work.
Why does it tell me "Object reference not set to an instance of an object"?
using System;
using System.Xml.Linq;

namespace TestNoAttribute
{
    class Program
    {
        static void Main(string[] args)
        {

            XDocument xdoc = new XDocument(
                new XElement("employee",
                    new XAttribute("id", "23"),
                    new XElement("firstName", new XAttribute("display", "true"), "Jim"),
                    new XElement("lastName", new XAttribute("display", "false"), "Smith")));

            XElement element = xdoc.Element("firstName");
            XAttribute attribute = element.Attribute("display"); //error

            Console.WriteLine(xdoc);

            Console.ReadLine();

        }
    }
}

Partial Answer:
I figured out if I change XDocument to XElement, then it works. Could anyone explain why?

A: You are accessing a child element of xdoc that doesn't exist. Try one level down:
XElement element = xdoc.Element("employee").Element("firstName");

or
XElement element = xdoc.Descendants("firstName").FirstOrDefault();

A: See this on MSDN as to why.  It explicitly explains their 'idiom' on why they felt returning a null element when the name is not found was beneficial.


text:
Q: What is the language used in this script? I have some code that i am supposed to work on as an assignment.But i am having trouble figuring out what it is written on.I normally code in c# but this is like nothing i've ever seen.
<cust_name "Reservations Cancelled Report">

<start_form "CANCRESV">

< t = 51>
<set_field n = 50>
<set_field o = 200>
<set_field h = 1300>

<set_print_lines = 55>

<loop>
  <concat {t[1]} = {3}>
  <box 10,10,14,70>
  <writpos 0,12,20, "Reservation cancellations for : ">
  <getfield 5,2,12,52,9,1>
  <if {20[{t[1]}]} >= 0>
    <calc {n[1]} = {20[{t[1]}]}>
    <break_loop>
  <end_if>
  <error "Invalid date">
<end_loop>

<concat {t[2]} = "16,'" + {26[{20[{t[1]}]}]} + "'">
<exec {h2[{t[2]}]}>              ! Init for Reservation history search

<loop until_last_page>

A: It's a rarely used language call Splud.
It is mainly used to wind-up students and trainees, and annoy online communities.
On occasion, it has been identified with other random (hitherto unknown) programming languages but these classifications are rarely accurate and are usually cynical intentions to illicit reputation points, or other virtual currency.
Hope this helps.


text:
Q: How is Task.Delay awaitable if it's not marked async? I'm looking at Task.Delay(int) decompiled in ILSpy:
// System.Threading.Tasks.Task
[__DynamicallyInvokable]
public static Task Delay(int millisecondsDelay)
{
    return Task.Delay(millisecondsDelay, default(CancellationToken));
}

This method is used like await Task.Delay(5000);, and the intellisense even says "(awaitable)":

So how is it that Task.Delay(int) isn't marked async (public static async Task Delay(int millisecondsDelay))?

A: What's awaitable is the Task Task.Delay returns. Each method returning a Task/Task<TResult> is awaitable. async is just an implementation detail allowing you to use await in that method and the whole state machine it generates.
More generally, every thing that has a GetAwaiter method (extension methods count as well) that return something that has IsCompleted, OnCompleted and GetResult can be awaited.
For example, Task.Yield returns YieldAwaitable which isn't a Task and looks like this:
public struct YieldAwaiter : ICriticalNotifyCompletion, INotifyCompletion
{
    public void OnCompleted(Action continuation);
    public void UnsafeOnCompleted(Action continuation);
    public void GetResult();
    public bool IsCompleted { get; }
}

*UnsafeOnCompleted here is just an optimization, await would work without it.
It's important to note that the compiler in this case (same as in other cases like GetEnumerator for foreach) doesn't expect an interface or a base class. It basically uses duck typing (i.e. "if it walks like a duck...") and simply looks for a GetAwaiter method that returns anything (doesn't matter what type or interface or if it's a class or a struct) that has the other 3 members (IsCompleted, OnCompleted and GetResult)
For example, this is how you can make await "bar" compile (it will fail in runtime of course):
public static Awaiter GetAwaiter(this string s)
{
    throw new NotImplementedException();
}
public abstract class Awaiter : INotifyCompletion
{
    public abstract bool IsCompleted { get; }
    public abstract void GetResult();
    public abstract void OnCompleted(Action continuation);
}

In conclusion, you don't need async to return an awaitable and moreover most Task-returning methods in the .Net framework don't use it and explicitly return a Task.


text:
Q: VIM: navigating xdebug traces The xdebug traces look like this, :
1 TRACE START [2011-12-06 12:50:29]
2     0.0018     350384   -> {main}() /index.php:0
3     0.0019     350464     -> error_reporting() /index.php:4
4     0.0019     350704     -> define() /index.php:8
5     0.0021     370136     -> require_once(/forum/global.php) /index.php:43
6     0.0022     370216       -> error_reporting() /forum/global.php:13
7     0.0020     353760       -> chdir() /index.php:42
8     0.0019     350704     -> define() /index.php:9
9     0.0019     353760     -> dirname() /index.php:42

Each time a function or include() is called, the third column indents another place. For instance, in line 5 we see a require_once(/forum/global.php) in which the error_reporting() and chdir() functions are called, and then code flow returns to the original file (/index.php).
How can I jump down from a line for a file (say line 5 which is in /index.php) over the include()ed files to the next line of the file (which would be line 8 in the above example).
One solution that I could think of would be to overload "j" to look check that it is not on a space character, and if it is then to run "j" again. If there is a better solution then I would love to know about it.

A: In the file you gave, you can jump around the lines with the specific position of "->" you're interested in (at columns 29-30) using the following search by regular expression:
Search pattern:  /^.\{28\}-
Here are the details:

*

*/ is the search key

*^ means start of line

*.\{28} means 28 random characters

*- just matches "-" as the next (29th) character

After typing this search once, you can navigate around the lines you're interested in using n (forwards) and N(backwards).
-- edit --
Based on the comments below, here's another version closer to what the O.P. was looking for:
Ex command: :exe '/^.\{'.(col(".")-1).'\}->'
This builds on the previous search pattern, using the value of the column right before the cursor instead of a fixed value.

A: Not totally related, but I use debugger.vim for debugging PHP code, and find it invaluable.
You can ge the script here, or a slightly modified version at my github
http://www.vim.org/scripts/script.php?script_id=1929
https://github.com/richo/richo-vim/tree/master/plugin


text:
Q: Clusters squeeze nodes in GraphViz I have several related sub-graphs that I want to draw together in GraphViz. When I draw simple nodes it looks quite pretty:

Source:
digraph {
  rankdir=LR;

  A1 -> A21;
  A1 -> A22;
  A1 -> A23;
  A1 -> A24;

  B1 -> B21;
  B1 -> B22;
  B1 -> B23;
  B1 -> B24;

  A21 -> A31;
  A22 -> A31;
  A23 -> A31;

  A23 -> A32;

  B21 -> B31;

  B21 -> B32;
  B22 -> B32;

  B21 -> B33;
  B23 -> B33;
}

As the nodes in the same level across the several sub-graphs are related, I want to group them and give it a label.
I tried to do it using clusters, but it "squeezes" the nodes:

Source:
digraph {
  rankdir=LR;

  subgraph cluster_level1 {
    label = "Level 1";
    style=filled;
    color=lightgrey;

    A1;
    B1;
  }

  subgraph cluster_level2 {
    label = "Level 2";
    style=filled;
    color=lightgrey;

    A21;
    A22;
    A23;
    A24;

    B21;
    B22;
    B23;
    B24;
  }

  subgraph cluster_level3 {
    label = "Level 3";
    style=filled;
    color=lightgrey;

    A31;
    A32;

    B31;
    B32;
    B33;
  }

  A1 -> A21;
  A1 -> A22;
  A1 -> A23;
  A1 -> A24;

  B1 -> B21;
  B1 -> B22;
  B1 -> B23;
  B1 -> B24;

  A21 -> A31;
  A22 -> A31;
  A23 -> A31;

  A23 -> A32;

  B21 -> B31;

  B21 -> B32;
  B22 -> B32;

  B21 -> B33;
  B23 -> B33;
}

With just two sub-graphs, it's bad, but still not horrible. However, if I add more sub-graphs, it becomes uglier and uglier.
Is there a way to group nodes with some shadowing and labels, while keeping the original nodes layout using GraphViz?

A: This is probably not a good answer since it implies a lot of trial and error but at least you get what you want (I guess) with invisible nodes:
digraph {
  rankdir=LR;

  subgraph cluster_level1 {
    label = "Level 1";
    style=filled;
    color=lightgrey;
    A01[ style = invis ];
    A1;
    A02[ style = invis ];
    A03[ style = invis ];
    A06[ style = invis ];
    A05[ style = invis ];
    B1;
    A04[ style = invis ];
  }

  subgraph cluster_level2 {
    label = "Level 2";
    style=filled;
    color=lightgrey;

    A21;
    A22;
    A23;
    A24;

    B21;
    B22;
    B23;
    B24;
  }

  subgraph cluster_level3 {
    label = "Level 3";
    style=filled;
    color=lightgrey;

    A07[ style = invis ];
    A31;
    A32;
    A08[ style = invis ];

    B31;
    B32;
    B33;
    A01[ style = invis ];
    A09[ style = invis ];
  }

  A1 -> A21;
  A1 -> A22;
  A1 -> A23;
  A1 -> A24;

  B1 -> B21;
  B1 -> B22;
  B1 -> B23;
  B1 -> B24;

  A21 -> A31;
  A22 -> A31;
  A23 -> A31;

  A23 -> A32;

  B21 -> B31;

  B21 -> B32;
  B22 -> B32;

  B21 -> B33;
  B23 -> B33;
}

yields


text:
Q: How can I take every 3rd line in a text file, then after taking the value of line 3, take the next one? I am new to Python, so please help me...
I want to take out every 3rd, 4th and 5th line in a text file. There are 22 lines in the text file
Here is just an algorithm
For i in range (0,16):

    Name = Extract line 3 from text file.

    Distance= Extract line 4 from text file.

    Time = Extract line 5 from text file.

    Calculations = (Distance/Time )

    Print (Name,Calculations, Time)

    Name = ''

    Distance = ''

    Time = ''

My problem is that I want the for loop to repeat, but next time name should extract line 6, distance line 7 and time line 8. The next time the loop repeats, it should change name into line 9 and so on...
Hopefully my problem is clear enough, I am not sure how to phrase it.
Thanks for all the help in advance... I am clueless
By the way I am using python 3.3

A: f = open('file.txt')
count = 0  #where in the file we are
entry = 3  #the first line we want to write, e.g Name
for line in f:
    count += 1
    if count == entry: name = line.strip() #name
    elif count == entry+1: distance = line.strip() #distance
    elif count == entry+2:
        time = line.strip() #time
        entry += 3  #now we've hit time, lets set entry to line 6 for the next iteration
        calculation = float(distance) / float(time)
        print name, calculation, time
#do calculations

A: If you always know that you will only ever need those three lines, you simply need to do:
values   = list()
state    = 0 # 0 is name, 1 is distance, 2 is time
line_num = 0
with open(filename) as ifile:
    name, distance, time = '',0,0 # the null set
    for line in ifile:
        if line_num < 3:
            line_num += 1
        else:
            if state == 0:
                name  = line.strip()
                state = 1
            elif state == 1:
                distance = float(line.strip())
                state = 2
            elif state == 2:
                time = float(line.strip())
                state = 0
                values.append((name, distance, time))

for name, distance, time in values:
    # do calculations on name, distance, time

A: Using the grouper recipe from itertools:
from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

with open('file.txt') as ff:
    data = ff.read().split('\n')[2:]
data = grouper(data, 3, None)
for name, distance, time in data:
    print(name, int(distance)/int(time), time)

A: You file is not very large(only a few lines), so memory seems not to be a problem for you. Said that, you can try a different approach:
lines = []

with open("file.txt") as input:
    lines = input.readlines()    # If file is large is not a good idea load it all into memory.

thirds  = lines[2:-1:3]  # Select from third element to the end and step by 3
fourths = lines[3:-1:3]  # Select from fourth element to the end and step by 3
fifths  = lines[4:-1:3]  # Select from fifth element to the end and step by 3

for (name, distance, time) in zip(thirds, fourths, fifths):
    calculations = distance / time
    print(name, calculations, time)

A: The following code opens your file, uses the lines #1 and #2 by a reasonable guess of your description and then proceed to scan the file

*

*the method readline returns a single line from the file, with a newline at the end (that's why we use the method strip when we want to use the file content as a name...) and returns a null string '' only (only) when the EOF is reached.

*we use an infinite loop to scan the rest of the file, but when the file is over we want to stop... that's why we do something different when we read the activity name, first we test for a null string (meaning: we reached EOF) and possibly break out of the loop.
.
with open('data.txt') as data:
    person = data.readline().strip()
    age =  int(data.readline())
    while True:
        activity = data.readline()
        if not activity:
            break
        activity = activity.strip()
        distance = float(data.readline())
        time = float(data.readline())
        velocity = distance/time
        format_output()

A: I think something like this would be a fast and simple way to do it:
# create test file
with open('3_lines_test.txt', 'wt') as file:
    for i in range(1, 22):
        file.write('line{:>2}\n'.format(i))

# read test file
with open('3_lines_test.txt', 'rt') as file:
    for _ in range(3): next(file)  # skip first 3 lines
    while True:
        try:
            name = next(file).rstrip()  # read next 3 lines
            dist = next(file).rstrip()  #        "
            time = next(file).rstrip()  #        "
        except StopIteration:
            break

        # do calculations or whatever...
        print('values: ({name!r}, {dist!r}, {time!r})'.format(**locals()))

print('done')

Output:
values: ('line 4', 'line 5', 'line 6')
values: ('line 7', 'line 8', 'line 9')
values: ('line10', 'line11', 'line12')
values: ('line13', 'line14', 'line15')
values: ('line16', 'line17', 'line18')
values: ('line19', 'line20', 'line21')
done

For such a short file, you could just read each line explicitly and calculate the values 6 times without any loop at all. This would require more code, but most of it would be boiler-plate and it would likely be the fastest possible approach.


text:
Q: Customize reset password form redirect problem I would like to create my own reset password form and page, I mean this page:

I have already created a page template for the reset password form, the code:
<?php
/*
 * Template Name: Page - Reset Password
 */
if( !is_user_logged_in() ) {
    wp_redirect( site_url( 'login' ) );
}
get_header();
?>

Reset your password

            <form id="form-reset-password" name="resetpassform" class="form-reset-password" action="<?php echo site_url( '/wp-login.php?action=resetpass', 'https' ); ?>" method="post" autocomplete="off">
                <input type="hidden" id="user_login" value="<?php echo $_GET['login']; ?>" autocomplete="off">

                    New password
                    <input type="password" name="user_pass" id="user_pass">

                    Confirm new password
                    <input type="password" name="user_pass_confirm" id="user_pass_confirm">

                    <input type="submit" id="reset-password-btn" class="reset-password-btn" value="Submit"/>

            </form>

<?php get_footer(); ?>

This is how it looks:

On form submit I fire a function using Ajax to validate these passwords and change them if everything goes well, so far so good.
How do people get to see this page? basically there is the request a password reset using email address form that looks like this:

After the email is received the user can click on a link that looks similar to this:
https://example.com/wp-login.php?action=rp&key=tkFUnvcJmhu30nRxqjpt&login=example%gmail.com

Now, in functions PHP I used this function to redirect users to my custom page with the $_GET variables but it's not working, I need your help please! here is the code:
/*
 * Redirect to custom reset password page
 */
function override_reset_password_form_redirect() {
    $action = isset( $_GET['action'] ) ? $_GET['action'] : '';
    $key = isset( $_GET['key'] ) ? $_GET['key'] : '';
    $login = isset( $_GET['login'] ) ? $_GET['login'] : '';

    if ( 'wp-login.php' === $GLOBALS['pagenow'] && ( 'rp' == $action  || 'resetpass' == $action ) ) {
        wp_redirect( site_url( '/reset-password/' ) . '?key=' . $key . '&login=' . $login );
        exit;
    }
}
add_action( 'init', 'override_reset_password_form_redirect' );

A: You can add the following to your functions.php to achieve what you are after. The action init doesn't seem to fire in time for what you are looking for.
if($_GET['action']==='rp' && strpos($_SERVER['REQUEST_URI'],'wp-login.php')) {
    $key = isset( $_GET['key'] ) ? $_GET['key'] : '';
    $login = isset( $_GET['login'] ) ? $_GET['login'] : '';
    wp_redirect( site_url( '/reset-password/' ) . '?key=' . $key . '&login=' . $login );
    exit;
}


text:
Q: Using Google Maps static tiles with Leaflet? I am trying to use tiles generated with the Google static API with Leaflet and I am facing issues because the generated tile seems to be displayed "off-centred".
My original question has been posted on Stack Overflow.
I am asking the question here in case this site is more suitable (I will also move the question here if the answer is given in this site).

A: Use the leaflet-google plugin that orchestrates the gmaps api to get the images and provides a custom layer to leaflet
https://gist.github.com/crofty/2197042

A: I know this is too late to answer this question. But I want to share my knowledge in this question. For the static purpose you can freely add the google map tiles inside your leaflet. For the static tiles, you can add following code,
for street,
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

Hybrid,
googleHybrid = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

satellite,
googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

Terrain
googleTerrain = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

Note that difference in the "lyrs" parameter in the URL:
Hybrid: s,h;
Satellite: s;
Streets: m;
Terrain: p;

A: If someone is trying to get Google Maps under Leaflet and through proxy (like Nginx proxy server), you can use it like this:
    L.tileLayer('https://example.com/mygoogle/vt/lyrs=m&z={z}&x={x}&y={y}', {
                minZoom: 5,
                maxZoom: 19,
                attribution: 'ThanksToGoogleMap' })
    .addTo(map);

And to save it to your server or cache it in Nginx (Both server side and client side): I do not know that cache is illigal or not !!
proxy_cache_path  /tmp/googlecache levels=1:2 keys_zone=googlecache:10m inactive=3650d  max_size=3g use_temp_path=off;

upstream google {
    server  mt0.google.com;
    server  mt1.google.com;
    server  mt2.google.com;
    server  mt3.google.com;
}

location / mygoogle /
{
proxy_pass http://google/;
#proxy_pass http://mt1.google.com/;
proxy_set_header  Host     mt1.google.com;

proxy_cache googlecache;
proxy_cache_valid 200 302 3650d;
proxy_cache_valid 404 1m;
proxy_redirect off;
proxy_read_timeout 12;
proxy_connect_timeout 12;

access_log off;
add_header Cache- Control public;
add_header Pragma public;
add_header Vary Accept - Encoding;
expires 30d;
}


text:
Q: How to access req.user from session cookie using passport.js I am trying to store the current user in a react state in order to better manage getting data for the logged in user. In the backend, creating and authenticating a user works properly and I am able to access req.user, however, when I try to create a specific route to return the current user, req.user is undefined. The cookies for the two calls also look different where one has the passport attribute attached to it but the other doesn't.
Session setup:
app.use(session({
  secret: process.env["SECRET"],
  resave: false,
  saveUninitialized: true,
  store: MongoStore.create({mongoUrl: process.env["MONGO_URI"]
}), //Connects session store to cookie
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 31 //Setting cookie to last around a month
  }
}));

Initializing passport:
require("./config/passport");
app.use(passport.initialize());
app.use(passport.session());

config/passport file:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("../config/database").user;
const validatePassword = require("../lib/passwordUtils");

const verifyUserCallback = (email, password, done) => {
  User.findOne({email: email})
    .then((user) => {
      if(!user){
        return done(null, false); //Returns 401. Should be handled
      }
      const isValid = validatePassword(password, user.hash, user.salt);

      if(isValid){
        return done(null, user)
      } else{
        return done(null, false); //Credentials are not valid
      }
    })
      .catch((err) => {
        done(err);
      });
};

const strategy = new LocalStrategy({usernameField: "email"}, verifyUserCallback);
passport.use(strategy);

passport.serializeUser((user, done) => { //Persists data after session
  done(null, user.id)
});

passport.deserializeUser((userId, done) => {
  User.findById(userId)
    .then((user) => {
      done(null, user);
    })
  .catch((err) => done(err));
})

Accessing req.user from the login file works properly:
router.post(
  "/login",
  passport.authenticate("local"),
  (req, res) => {
    if(req.user){
      console.log(req.user)
      console.log(req.session)
      res.status(200).json({user: req.user})
    } else{
      res.status(401).json({error: "Username and password do not match"})
    }
  }
);

Registering user:
router.post("/register", (req, res) => {
  const saltHash = genPassword(req.body.password);
  const salt = saltHash.salt;
  const hash = saltHash.hash;

  //Going to see if user exists
  User.findOne({email: req.body.email}).then((user) => {
    if(!user){ //If there is no current user make a new one
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        age: req.body.age,
        salt: salt,
        hash: hash
      });
      newUser.save().then((user) => {
        req.isAuthenticated = true; //Pretty sure this works
        res.status(200).json({user: user})
      });
    } else{
      //User exists
      req.isAuthenticated = false;
      res.status(401).json({error: "User already exists"})
    }
  }).catch(err => console.log(err));
});

But the checkAuthentication file is the issue. It does not properly return req.user instead saying that it is undefined.
router.get("/checkAuthentication", (req, res) => {
  console.log(req.user) //Undefined
  if(req.isAuthenticated){
    res.status(200).json({user: req.user})
  } else{
    res.status(401).json({user: "User is not logged in"})
  }
});

The cookies for the two also look different. Here is an example cookie of when the user has just been logged in:
Session {
  cookie: {
    path: '/',
    _expires: 2022-06-23T23:14:13.366Z,
    originalMaxAge: 2678400000,
    httpOnly: true
  },
  passport: { user: '628bf9107d0bbe14b560609d' }
}

When authenticated but not just logged in or registered:
Session {
  cookie: {
    path: '/',
    _expires: 2022-06-23T23:15:04.343Z,
    originalMaxAge: 2678400000,
    httpOnly: true
  }
}


text:
Q: assertText on span with dynamic div Trying to find out how could I insert some text inside the span that has a dynamic div as a parent. the span has the price that is calculated after initial steps. I am really stuck with this.
I check the value of that span with regexp:."*[1-9].*"
span inside a dynamic div
This option does not really work
//div[@class='gatsby-focus-wrapper']/main/div/div[4]/div/div/div[3]/div[3]/div/div/div[2]/div[2]/div/div[3]/span

Thanks a lot in advance!

A: Seems that I can use "// *[@amount]". Cannot really use //span[@amount='14.03'] as the price is changing for every single user. But, suggestion did help. Thanks for the lift up folks :)


text:
Q: Page Not Found for urls - openwisp-radius I'm new to Django, I am following this guide to setup openwisp-radius
https://openwisp-radius.readthedocs.io/en/stable/developer/setup.html
When I go to the browser for any path from urlpatterns I get Page not found (404).
My django version is 3.0, os is Ubuntu 20.04, I installed openwisp-radius-0.2.1
I created a new django project with django-admin startproject testapp, and added code from the guide to settings.py and urls.py
this is my settings.py:
"""
Django settings for testapp project.

Generated by 'django-admin startproject' using Django 3.0.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$_u-k638-9hprxb8lhx96+q+yo97be1uriik_86*t3my(s8ux3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # openwisp admin theme
    'openwisp_utils.admin_theme',
    # all-auth
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    # admin
    'django.contrib.admin',
    # rest framework
    'rest_framework',
    'django_filters',
    # registration
    'rest_framework.authtoken',
    'dj_rest_auth',
    'dj_rest_auth.registration',
    # openwisp radius
    'openwisp_radius',
    'openwisp_users',
    'private_storage',
    'drf_yasg',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
PRIVATE_STORAGE_ROOT = os.path.join(MEDIA_ROOT, 'private')

AUTH_USER_MODEL = 'openwisp_users.User'
SITE_ID = 1

OPENWISP_RADIUS_FREERADIUS_ALLOWED_HOSTS = ['127.0.0.1']

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'testapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'testapp.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

this is my urls.py:
from django.urls import path,include
from openwisp_radius.urls import get_urls

urlpatterns = [
    # ... other urls in your project ...
    # openwisp-radius urls
    path('accounts/', include('openwisp_users.accounts.urls')),
    path('', include('openwisp_radius.urls', namespace='radius'))
]
]

after adding code, I executed ./manage.py migrate
My folder structure looks like this:
testapp
-manage.py
-db.sqlite3
-testapp
--init.py
--asgi.py
--settings.py
--urls.py
--wsgi.py

A: Try the following:

*

*Access http://localhost:8000/admin/ and http://localhost:8000/api/v1/docs/

*Run ./manage.py show_urls to know all the available URL paths


text:
Q: Bitscope DC Offset I had an old Tektronix scope for a few years that finally gave out. I recently purchased a Bitscope, but it seems to be having some problems.
I have connected the function generator to channel A, and have attempted to generated and measure a sine wave.
However, when channel A offset is set to "REF" which is described in the manual as "Zero reference voltage (i.e. no input offset)", it appears that an offset voltage does indeed appear. Please see screenshot:
http://i.imgur.com/110PH8h.png
As you can see, channel A offset is set to "REF", and note that the waveform generator panel shows the sine wave with zero offset, and is also set for zero offset. However, the actual measured sine wave appears to have a bit of DC offset voltage.
This tool is useless if I can't trust the measurements that it makes. Anyone have one of these and can shed some light on what I am seeing here?
Bitscope support is unresponsive.
Thank you!

A: You can adjust the DC offset by grounding the probe and clicking 'Assign Input Offset'. This option is reached by right-clicking on the small circle (yellow for channel A, green for channel B) that signifies that the channel is active - to the left of where it says 'CHA' or 'CHB'. This should zero the DC reading and if you then select REF the trace should be centred.
You may need to repeat this process if you change voltage display range and for each probe individually.


text:
Q: How to make an activity background transparent and blur the background When I launch my app, it launches an Activity which should have transparent header and whatever is the currently shown in background should be blurred.

I am able to get the transparency. But I am not able to figure out how to blur the background. For example if I launch app from home screen, then home screen should be visible but blurred out.
I have an idea to use Framebuffer to get current displayed data, but how to convert that to bitmap which I can use to draw an image without saving the image and directly using data.
I also know that We can take screenshot by pressing power and volume button. Does anyone has an idea where is the code in android to do that? My app will have system access.

A:
how to blur the background?

You can use RenderScript available in support library
public class BlurBuilder {
    private static final float BITMAP_SCALE = 0.4f;
    private static final float BLUR_RADIUS = 7.5f;

    public static Bitmap blur(Context context, Bitmap image) {
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        RenderScript rs = RenderScript.create(context);
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);

        return outputBitmap;
    }
}

see this link for more details
Or you can use Blurry

Does anyone has an idea where is the code in android to do that?

For taking screenshot of your app screen see this link

A: I used this to give a blur effect to my edit text background, you can modify it according to your preference, play around with opacity:
<?xml version="1.0" encoding="utf-8"?><!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:centerColor="#33FFFFFF"
        android:endColor="#33FFFFFF"
        android:gradientRadius="270"
        android:startColor="#33FFFFFF"
        android:type="radial" />
    <corners
        android:bottomLeftRadius="25dp"
        android:bottomRightRadius="25dp"
        android:topLeftRadius="25dp"
        android:topRightRadius="25dp" />
</shape>

alternatively, you might be interested in this  or this
As one more alternative you can use a small blur bitmap and repeat it:
    <xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    android:id="@+id/MainLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/backrepeat"
    >

Then prepare:
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/back"
        android:tileMode="repeat" />


text:
Q: Why does it take 100 seconds to delete a blob? I have code like this
BlobDownloadInfo blob = Client.GetBlockBlobClient(filePath).Download().Value;
...
Client.GetBlockBlobClient(filePath).DeleteIfExists();

And DeleteIfExists() reliably takes 00:01:42 (about 100 seconds) to delete my blob. Why?

A: BlobDownloadInfo is an IDisposable. By not disposing it, we appear to be keeping open the connection and forcing DeleteIfExists() to wait for that connection to timeout. Updating the code to
using (BlobDownloadInfo blob = Client.GetBlockBlobClient(filePath).Download().Value)

causes DeleteIfExists() to return in about 00:00:00.15


text:
Q: Using tsconfig-paths-webpack-plugin gives "Module not found" error for "fs" and other standard modules I have spent half a day looking for a solution and trying everything I came across.
What I want is to use imports relative to my src folder by using an @src alias. Eg.
import { GmailMgr } from '@src/google-api/GmailMgr';
The most popular way to achieve this seems to be using https://www.npmjs.com/package/tsconfig-paths-webpack-plugin
Editing tsconfig.json like this makes vs code happy:
{
  "compilerOptions": {
    "outDir": "./dist/",        // path to output directory
    "sourceMap": true,          // allow sourcemap support
    "strictNullChecks": true,   // enable strict null checks as a best practice
    "module": "CommonJS",       // specify module code generation
    "jsx": "react",             // use typescript to transpile jsx to js
    "target": "es5",            // specify ECMAScript target version
    "allowJs": true,            // allow a partial TypeScript and JavaScript codebase
    "baseUrl": "./src",
    "paths": {
      "@src/*":["*"]
    }
  },
  "include": [
      "./src/"
  ]
}

To inform webpack about the paths in tsconfig.js, I then added the TsconfigPathsPlugin to webpack.config.js as described in the readme:
const path = require("path");
const webpack = require("webpack");

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  entry: "./App.tsx",
  context: path.resolve(__dirname, "src"),
  mode: "development",
  module: {
    rules: [
      {
        test: /\.(t|j)sx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/
      },
      {
        enforce: "pre",
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "source-map-loader"
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  },
  resolve: {
    // changed from extensions: [".js", ".jsx"]
    extensions: [".ts", ".tsx", ".js", ".jsx"],
    alias: {
      'react-dom': '@hot-loader/react-dom',
    },
    plugins: [new TsconfigPathsPlugin()]
  },
  output: {
    path: path.resolve(__dirname, "dist/"),
    publicPath: "/dist/",
    filename: "bundle.js"
  },
  devServer: {
    contentBase: path.join(__dirname, "public/"),
    port: 45011,
    publicPath: "http://localhost:45011/dist/",
    hotOnly: true,
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  devtool: "source-map"
};

When I run webpack --mode production, I can see that the files that don't use node_modules but use this @src import style are compiled so it works but I use the google api packages in one file (GmailMgr.ts in the errors) and those rely on things like fs, child_process, net and tls and for each of them, I get an error like this:
ERROR in ../node_modules/https-proxy-agent/dist/agent.js
Module not found: Error: Can't resolve 'tls' in 'D:\MartijnFiles\Documents\Programming\0502-crew\youtube4me\node_modules\https-proxy-agent\dist'
 @ ../node_modules/https-proxy-agent/dist/agent.js 16:30-44
 @ ../node_modules/https-proxy-agent/dist/index.js
 @ ../node_modules/gaxios/build/src/gaxios.js
 @ ../node_modules/gaxios/build/src/index.js
 @ ../node_modules/google-auth-library/build/src/transporters.js
 @ ../node_modules/google-auth-library/build/src/index.js
 @ ./google-api/GmailMgr.ts
 @ ./components/YTNotifications.tsx
 @ ./App.tsx

It looks like it's trying to find fs, etc. inside the folder of the module instead of looking for it by starting in the node_modules root. If I remove the tsconfig-paths-webpack-plugin and paths, everything is fine but I have to stick to imports like import { GmailMgr } from '../../../google-api/GmailMgr';
P.S. I have tried webpack-node-externals and it works for the errors but this is for a website so I then get errors in the browser that require doesn't exist.

A: I encounter the same problem, but I don't think it's related to certain api.
I think it's a bug when using tsconfig-paths-webpack-plugin with webpack5.(I suppose you are using webpack5)
I submitted a issue here: https://github.com/dividab/tsconfig-paths-webpack-plugin/issues/60

A: It has started to dawn on me that webpack only has trouble with modules that require node to perform (eg. fs) and a browser won't be able to do. I suppose the google api modules are intended purely for backend (while you are able to use them perfectly if you include them using  in the html). I guess I'll have to split my app into front and back end.
Update: I was right in this and split it up. However, I did still use webpack for both, just with different configs. In the backend webpack, I then used target: 'node' which prevents anything that should come from node_modules from being packed.

A: You may need to specify the full path to src/. Rather than using TsconfigPathsPlugin, I was able to resolve the issue by using the Webpack alias property in resolve, and using path.resolve(...) to my source directory.
In webpack.config.js:
resolve: {
    extensions: [ '.ts', '.js' ],
    alias: {
        '@src': path.resolve( __dirname, 'src' )
    },
},

For some reason using the full path worked, whereas using relative paths in webpack.config.js like @src: './src' did not. I suspect this is why TsconfigPathsPlugin didn't work as it was pulling the relative path from tsconfig.json.


text:
Q: How to detect an exist element in an array with one or more elements Here is the code in Jsfiddle
It's a simple form to create a new form : label and it's input
I already did four validations :

*

*if input is empty

*if there in no label before adding an input

*if the input id is not matched the label

But there is a new problem : if I enter an input id which already exist, it will add a second input for the same label,
For example :

I created two labels and their inputs

if I enter "a" in "input id" again, it will add a second input to label "a"

And if I add a same label again, then for adding the input is the same problem, it will add to both of them.
To avoid this problem, I think that I need to check : if the input value is matched any existing input id, so don't add the input, the same for label
I try to do this :

*

*create an empty array
var inputExist = [];

*push the id in this array every time I add an new input inputExist.push($('#input_id').val());

*do a loop for in the else to detect if the input value matched any element in the array
for (var i = 0; i < inputExist.length; i++){
  if($('#input_id').val() == inputExist[i]){}
}
Scince the if condiction is based on the loop, I have to put the if inside the loop, which means the else too, so that will cause the adding input order do array.length times, not good!
I have no idea how to separer the detection and the instruction followed.
Any ideas?

A: Create an array where you store the labels you already added (or the values);
var labelsArray = [];
var valuesArray = [];

Then when you handle the button click, add the following check:
var currentLabel = $('#lable_name').val();
if(labelsArray.indexOf(currentLabel) > -1){
    return;
}

In alternative you can use the jQuery function:
$.inArray(currentLabel, labelsArray)

Do the same with the values and you will be able to avoid duplication.
In alternative you can use jQuery to search for an input


text:
Q: Show that $a_{k-1}a_{k+1}\le a_k^2$ where $P(x) = \sum_{k=0}^n a_k X^k$ is a real polynomial with real roots, and $0the question is in the title.
I know that this is a direct consequence of Newton's inequalities but I'm looking for a proof without using it. A hint was given to solve it :
Show that

$$ P'^2 - P''P\ge 0$$

To show the given identity, let
$$P(X) = \lambda\prod_{k=0}^{r} (X-\alpha_k)^{m_k} = \sum_{k=0}^{n} a_k x^k$$
The identity :
$$ \dfrac{P'}{P} = \sum \dfrac{m_k}{X-\alpha_k}$$
Shows that $\dfrac{P'}{P}$ is decreasing, but :
$$ \left(\dfrac{P'}{P}\right)' = \dfrac{P''P - P'^2}{P^2}$$
Therefore, $P''P - P'^2\le 0$
To prove that $a_{k-1}a_{k+1}\le a_k^2$ for $0< k<n$, I don't really know how to start. I thought of using Vieta's formulas to express $a_{k-1}a_{k+1}$ and $a_k^2$ but I don't think it will really help me use the fact that $P'^2 - P''P\ge 0$. Any thoughts ?
Thanks for reading.

A: Here's a solution :
Let $$P(X) = \sum_{k=0}^{n} a_kX^k$$ $$Q(X) = (P'^2 - P''P)(X) = \sum_{k=0}^{2n-2} c_kX^k$$
The first observation is that $c_0 = a_1^2 - 2a_0a_2$. Therefore, if $P$ has real roots, $Q(0)\ge 0$ so that $a_1^2\ge 2a_0a_2$. if $a_0a_2<0$, $a_1^2\ge a_0a_2$, otherwise, $a_0a_2\le 2a_0a_2\le a_1^2$ and the result follows for $k=1$.
For other values of $k$, apply the same reasoning to $P^{(k-1)}$ which also has real roots :
Let $P^{(k-1)} = \sum_{j=0}^{n-k+1} c_j X^j$. We know that $c_1^2\ge 2c_0c_2$.
But $c_0 =(k-1)!\cdot a_{k-1}$, $c_1 = k!\cdot a_k$ and $c_2 =(k+1)!a_{k+1}/2$. So that :
$$ k!^2a_k^2\ge (k-1)!(k+1)! a_{k-1}a_{k+1}$$
$$ \implies ka_k^2\ge (k+1)a_{k-1}a_{k+1}$$
$$ \implies a_k^2\ge \dfrac{k+1}{k} a_{k-1}a_{k+1}$$
And the result follows.


text:
Q: Combining two lists into a sentences(python) I have two lists in a list:
t = [['this','is','a','sentence'],['Hello','I','am','Daniel']]

I want to combine them in order to get two sentences:
'this is a sentence. Hello I am Daniel.'

I quickly came up with the following solution:
text = ''
for sent in t:
  text = text + ' '.join(sent) + '. '

But maybe there is more readable(better styled) solution for this task?

A: You can shorten it to a single list comprehension, with another "." at the end:
text = '. '.join(' '.join(sent) for sent in t) + '.'

A: You could also use list comprehensions:
In [584]: ''.join([' '+ ' '.join(sent) + '. ' for sent in t])
Out[584]: ' this is a sentence.  Hello I am Daniel. '


text:
Q: Command raised an exception: AttributeError: 'TextChannel' object has no attribute 'message' I am making a discord and i am working on its clear message command but it shows this
Command raised an exception: AttributeError: 'TextChannel' object has no attribute 'message'

Here's the full code
from discord.ext import commands
class Clear(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount=2):
        await ctx.channel.message.purge(limit=amount)
def setup(bot):
    bot.add_cog(Clear(bot))

A: Don't add the .message attribute to it as it doesn't exist within TextChannel. ctx.channel.purge() will work
from discord.ext import commands
class Clear(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount=2):
        await ctx.channel.purge(limit=amount)
def setup(bot):
    bot.add_cog(Clear(bot))


text:
Q: multiple bars and dual monitor not working after driver installation Installed the drivers acording to the manual setup in the Ubuntu help wiki, ran amdcccle and setup the dual display, enabled Xinerama so I can move stuff between monitors and now my desktop looks like

and the second monitor is white. I can move the mouse to it, but not the windows.
I use Ubuntu 12.04.


text:
Q: Current noise as spectral density from given RMS noise I want to know the current spectral density of a Keithley 6221 current source.

The datasheet above provides values in RMS for a given Bandwidth from \$10~\text{Hz} - \text{BW}\$, not clearly specifying the bandwidth \$\text {BW}\$. I am not exactly sure what Output Response Bandwidth (BW) into Short means, but figuring from the \$\text {BW}\$ in brackets I used it as bandwidth.
In a first approximation the RMS value can be calculated from the spectral density \$\text {SD}\$ by
$$X_{RMS}=SD\cdot\sqrt{\text{BW}}\cdot\sqrt{\text{ENBW}}~~~~~~~~~~~(1)$$
with the equivalent noise bandwidth \$\text {ENBW}\$ (rectangular approximation valid for high bandwidths).
Assuming the above values for the 100 mA range this yields
$$\frac{20e^{-6}\text{A}_{\text{RMS}}}{\sqrt{1e^6~\text{Hz}}\sqrt{\text{ENBW}}}=20\frac{\text{nA}}{\sqrt{\text{Hz}}},~~~~~~~~~~~(2)$$
which seems a lot to me. Note that a \$\text{ENBW}\$ anywhere from 1 (brick wall filter) to 1.57 (1 Pole) does not change the result significantly and can thus be neglected.
Is this the correct way to determine the spectral density?

I read through the thread Determining noise spectral density, which states that the spectral density cannot be calculated due to lack of information. If the bandwidth I used is correct, this is not the case here.
Sideinformation: I feed a 3 Ohm inductance with the current source and I can measure the voltage density over the inductance with a spectrum analyzer. I would like to get the calculation and the measurement into accordance. The voltage noise can be calculated from the current noise and the resistance, once the current noise is known.

A: From my point of view, the calculated \$20~\mathrm{nA}/\sqrt{\mathrm{Hz}}\$ in the original question are calculated correctly as a first estimate. Some time ago I measured the current noise of the Keithley 6221 current source indirectly by measuring the resulting voltage noise across a known impedance at a current of 100 mA. This resulted in a value of \$5~\mathrm{nA}/\sqrt{\mathrm{Hz}}\$ between 50 Hz and 4 kHz:

Please note that the utilized FFT analyzer (SR785) dominates the measured noise floor below 50 Hz (black curve). The complete article with further details about this measurement can be found here: https://arxiv.org/abs/2006.08515

A: What current noise will you get from a 10Meg Ohm resistor in 1MHz bandwidth?
1KOhm is 4 nanoVolts/rtHz
100Kohm is 40 nanoVolts/rtHz
10Meg Ohm is 400 nanoVolts/rthz
Current noise density is 400nanoVolts/10MegOhm = 400 e-9/1e+7 = 400 e-16
or 40 e-15 or 40 femtoAmps/rtHz.
Scale up by sqrt(1 MHz), and find 40fA * 1000 = 40 picoAmps.
But............this is the current noise for a single resistor.
That Keithley has numerous circuits involved in implementing a programmable current source.

A: Spectral density is a function. You have a total integrated over a bandwidth (stated as 'typical' so it is not dependable anyway).
There is not enough information to determine the PSD function from a single number. For example, here is the typical noise of a real op-amp showing the PSD (the top one showing the nasty peak is hidden deep within the datasheet, the bottom one is what they show on the front page).

You can see the 1/f noise in the lower graph, the white noise and the excess noise caused by the circuit design that causes the peak at ~400kHz.
In the case of your current source there may also be significant shot noise at low currents.


text:
Q: Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.Button' I am getting this error: Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.Controls.TextBox
foreach(Control x in this.Controls)
{
 Button btn = (Button)x;
 btn.Enabled = true;
}

A: Some of your controls are not buttons. If you try to cast them to a button you will get this error.
You can remove non-buttons from the list with a bit of LINQ and the OfType() method. Using OfType() will also automatically cast the result so you don't need the intermediate variable.
//using System.Linq;
foreach(Button btn in this.Controls.OfType<Button>())
{
    btn.Enabled = true;
}

If you want to do it the old-fashioned way here it is:
foreach(Control x in this.Controls)
{
    Button btn = x as Button;
    if (btn != null)
    {
        btn.Enabled = true;
    }
}


text:
Q: Autocomplete in CodeIgniter is not working (jQuery UI ) jQuery code:
    $(function(){
      $("#birds").autocomplete({
        source: "http://localhost/codeigniter/learning/autocomplete"
      });
    });

View:
    <label>Normal Autocomplete</label>
    <input type="text" id="birds" />

Controller:
public function autocomplete()
{
    if (isset($_GET['term']))
    {
        $q = strtolower($_GET['term']);
        $this->learning_model->get_bird_string($q);
    }
}

Model:
public function get_bird_string($q)
{
    $this->db->select('bird');
    $this->db->like('bird', $q);
    $query = $this->db->get('birds');
    if($query->num_rows > 0)
    {
      foreach ($query->result_array() as $row)
      {
        $row_set[] = htmlentities(stripslashes($row['bird']));
      }
      echo json_encode($row_set);
    }
}

this are the code i'm using for a normal autocomplete suggestion in textbox search the js files i am including in the view are:
<link href="<?php echo base_url()?>js/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php echo base_url()?>js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url()?>js/jquery-ui.js"></script>

the problem is the code is not working. What i am doing wrong ??

A: I think you are getting error in your model function as Num_rows is a function not a variable so try it like,
if($query->num_rows() > 0) //num_rows() is a function
{
    foreach ($query->result_array() as $row) {
         $row_set[] = htmlentities(stripslashes($row['bird']));
    }
    echo json_encode($row_set);
} else { // you can use elese part if no data found
   echo json_encode(array());// return json message
}


text:
Q: Unable to search a string using more pager I opened a file using the more pager,i was trying to find a string in this file using / as shown in the figure below,but it is saying that pattern not found even though the string i have searched is present in the file,in the second case when i tried to find and string ,it is not showing any thing on hitting enter,and just showing the next page on screen.Again the and string is present in the file,still it is not found on hitting enter. What wrong am i doing here and why there are two different results with these two different strings

A: I got it,it was actually finding the string but the main difference between more and less is that the string when found in more is not highlighted,that's why i was getting confused.For more explanation check the comment section.


text:
Q: Wordpress Align sidebar to the main container I question whether it is possible to sidebar is aligned to my main content without using margin-top? If so, how?
So it is now

And so it should be

A: you would need to move your html and you can also try position and top


text:
Q: require.js synchronous loading I'd like to define a module which computes a new dependancy, fetches it and then returns the result. Like so:
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
    var name = get_config_name();
    var config;
    require.synchronous([configs / '+name'], function(a) {
        config = defaults.extend(a);
    });
    return config;
});

Is there a way to do this or a better way to attack this problem?

A: *

*You may try to use synchronous RequireJS call require('configs/'+get_config_name()), but it will load a module synchronously only if it is already loaded, otherwise it will throw an exception. Loading module/JavaScript file synchronously is technically impossible.
UPD: It's possible (see Henrique's answer) but highly unrecommended. It blocks JavaScript execution that causes to freezing of the entire page. So, RequireJS doesn't support it.

*From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously.
AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously. The solution may be in using loader plugin (details here and here):
// config_loader.js
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
    return {
        load: function (resourceId, require, load) {
            var config_name = 'configs/' + get_config_name();
            require([config_name], function(config) {
                load(defaults.extend(config));
            })
        }
    }
});

// application.js
define(['config_loader!'], function(config) {
    // code using config
});

*If get_config_name() contains simple logic and doesn't depend on another modules, the better and simpler is calculating on the fly paths configuration option, or in case your config depends on context - map configuration option.
function get_config_name() {
    // do something
}
require.config({
    paths: {
        'config': 'configs/' + get_config_name()
    }
});
require(['application', 'defaults', 'config'], function(application, defaults, config) {
    config = defaults.extend(config);
    application.start(config);
});

A: Loading JavaScript synchronously is NOT technically impossible.
function loadJS(file){
   var js = $.ajax({ type: "GET", url: file, async: false }).responseText; //No need to append
}

console.log('Test is loading...');
loadJS('test.js');
console.log('Test was loaded:', window.loadedModule); //loadedModule come from test.js


text:
Q: Многопоточность для обработки файла Есть много огромныйх файлов(по 4-6gb), мне нужно запустить примерно 100 потоков, чтобы каждый поток брал следующую строку из файла и обрабатывал.
        List<Thread> _threads;
        int countThr;

        public void Run(int count)
        {
            Globals.threadAlive = 0;
            _threads = new List<Thread>();
            _threads.Clear();
            countThr = count;
            for (int i = 0; i < count; i++)
            {
                var thread = new Thread(multiThread);
                thread.IsBackground = true;
                _threads.Add(thread);
                _threads[i].Start();
            }
        }

        public void Abort()
        {
            Globals.threadAlive = 1;
            foreach (Thread thr in _threads)
            {
                thr.Abort();
            }
            _threads.Clear();
            Globals.threadAlive = 0;
        }

        private void multiThread()
        {
            for (int c = 0; c < Globals.lines.Length; c++)
            {
                //обработка строки
            }
            Globals.threadAlive = 1;
            Abort();
        }

Это будет правильное решение моей задачи?

A: Если у вас доминирует чтение файла, просто читайте каждый из файлов в одном отдельном потоке. Сотня потоков не нужна и только всё испортит.
Да, и потоки устарели уже давно, применяйте TPL.
void ProcessFile(string path)
{
    foreach (var line in File.ReadLines(path))
    {
        // обработать строку
    }
}

IEnumerable<string> paths = ...;
var processTasks = paths.Select(p => Task.Run(() => ProcessFile(p));
await Task.WhenAll(processTasks);

Ленивое чтение файла позволяет не грузить гигабайты текста в память.
Заодно убрали ненужную (и ошибочную) ручную работу с потоками.

Если у вас обработка строки занимает ощутимое время, вам пригодится PFX:
void ProcessFile(string path)
{
    Parallel.ForEach(File.ReadLines(path), line =>
    {
        // обработать строку
    });
}

A: Я предлагаю вычитывать с помощью File.ReadLines, это позволяет не загружать весь файл в память.
Разбирать отдельные строки в отдельных задачах для потоков - нерентабельно, скорее всего, зависит от того, как долго занимает обработка одной строки.
Поэтому предложенный вариант разбивает все строки на пакеты небольшого размера (batches) и обрабатывает их параллельно.
void Main()
{
    var filePath = Path.GetTempFileName();
    File.WriteAllText(filePath, string.Join(Environment.NewLine, Enumerable.Range(0, 100001)));

    var batchSize = 1000;

    var allLines = File.ReadLines(filePath);

    var processedCount = 0;

    GetLinesInBatches(allLines, batchSize).AsParallel().ForAll(batch =>
    {
        foreach (var line in batch)
        {
            Interlocked.Increment(ref processedCount);
            // Do something with the line.
        }
    });

    Console.WriteLine("Total: {0}", processedCount);
}

IEnumerable<List<string>> GetLinesInBatches(IEnumerable<string> allLines, int batchSize)
{
    using (var e = allLines.GetEnumerator())
    {
        bool more = false;
        do
        {
            var batch = new List<string>(batchSize);
            for (var i = 0; i < batchSize && (more = e.MoveNext()); i++)
            {
                batch.Add(e.Current);
            }
            yield return batch;
        }
        while (more);
    }
}


text:
Q: How to let a C-array always to be accessed from disk directly instead of remaining in memory? I'm trying to embed binary media resources into source code. I will going to use plain C-array (char[]) to store binary. (with something like this: Embedding binary blobs using gcc mingw) Because managing media files resource separately is very annoying work because the symbol it is hard to determined at compile time, and makes my customers annoying too.
Anyway what I'm concerning is memory consuming. If I store a PNG image, actually, I don't need the persistent binary anymore after I loaded live image instance (UIImage*) from it. But I think the persistent binary will remain in memory because

*

*it's part of code

*and it's constant.

I don't know any option to remove it from memory.
How can I let a C-array always to be accessed from disk directly instead of remaining in memory?
PS.
I can limit my build and execution environment strictly. I will use Clang and the program will be run on iOS. Anyway I don't mind to use any of extra build tool :)

A: I don't fully understand what you are saying or trying to solve, but it sounds like you are looking for memory mapping. See man mmap.
ps reading again, if I understand your question correctly, you want to make a fat binary containing all resource data. In that case, the OS will probably page out unused parts of it, so the memory is "freed" automatically. ("freed" in the sense of releasing physical memory that can be used for other purposes) So the persistant binary will remain in virtual memory, but not in physical memory.
update to explain a little further
On your Mac, in the terminal, run
$ vmmap -resident $$

This will show the virtual memory mapping for your shell, showing total memory and resident memory. You will see this line:
==== Non-writable regions for process 7139
__TEXT 0100000000-00100099000 [  612K   460K] r-x/rwx SM=COW  /bin/bash

This says, that in this region of memory the file /bin/bash is to be found (memory mapped, again, see man mmap) and that it is not fully paged in; only 460kb of the binary is actually present in memory. Which is interesting because this is the binary actually running. The other lines are interesting as well, but beyond the scope of this question.
so if the OS of choice (iOS) has sane memory management, your problem does not really exist. Just don't touch memory you don't need to use; every time you touch it, the pages are read in memory.

A: By storing them as resource files on disk instead of as source files. You can't have it both ways.

A: If you were able to load a shared library you could load an unload the shared library, (for C-arrays) but you can't since it's iOS which is all about the static libraries. Unfortunately, I don't think there's a solution like you want on that platform.

A: With a UIImage, you may be able to accomplish this -- I've never tried it. What you would need to do is create the UIImage with a CGImage which provides a custom CGDataProvider which used file read or mmap to access data. Not sure it would work -- the UIImage may make a copy along the way for one reason or another, and you've no control over that implementation detail.
You don't want the image in your binary if you also want to free it from memory. Creating a UIImage from a resource in binary could double your memory requirements.
It's hard to tell what you're trying to accomplish, but I sense UIImage's default behavior with bundled images would seem the ideal for your needs as-is…


text:
Q: Posted notifications showing date 'Thu, 1 Jan 1970' after a while I am the developer of an application which is strong on the notifications department. I've recently upgraded to the HTC One X running Android 4.0.3 and noticed a problem that I never noticed on my previous phone running Android 2.1.
The notifications posted by my app do not set a date and a date has never been shown on my previous phone notifications. On my new phone, when the notifications are posted the date doesn't appear, but after a while, the 'Thu, 1 Jan 1970' date appears and I can't understand why.
When I say "after a while" I don't mean you keep staring at the screen for a few seconds/minutes and see the date appear. What I mean is after using the phone for a while, put it down, use it again, whatever, eventually, all the notifications posted by my app will have that date.
I've seen this happen a few times but I cannot find a pattern and understand when this happens to see if I can find a fix. Does anyone have any ideas why this might be happening on ICS?
I don't how relevant it can be but there's the whole code of my postNotification method:
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

Intent intent = NoteEditorSingleActivity.createIntent(mContext);
intent.putExtra(AgendaNotesAdapter.KEY_ROW_ID, notifyId);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

builder.setContentIntent(PendingIntent.getActivity(mContext, (int)notifyId, intent,
        PendingIntent.FLAG_CANCEL_CURRENT));

builder.setContentTitle(noteTitle);
builder.setContentText(noteDescription);
builder.setSmallIcon(iconId);
builder.setTicker(noteTitle.length() > 0 ? noteTitle : null);
builder.setWhen(0);

Notification notification = builder.getNotification();

long noteSortOrder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD ? 1 : -1;

notification.flags = Notification.FLAG_NO_CLEAR;
notification.when = noteSortOrder * notifyId;

mNotificationManager.notify((int)notifyId, notification);

I know I'm setting the when to 0 with the builder and to a different value by changing the when value directly in the notification object. I can't remember why I did this initially but it's there for a reason.
What I don't understand is that the moment right after calling the notify() method and look at the notification in the status bar, there is no date. Why does it appear after some time of using the phone.
That's what I want to know and fix.

A: Your notification's when should be set to the time you  want it display (in milliseconds since the UNIX epoch: January 1, 1970 00:00:00 UTC).  Setting it to 0 is a popular but undocumented (and therefore not guaranteed to work) way to not show any timestamp.
You don't show where notifyId is set, but you're presumably setting when to a low number of milliseconds since the epoch here:
notification.when = noteSortOrder * notifyId;

The reason you're setting it to 0 first and then changing it later is that you're using another undocumented hack, trying to affect how the system places your notification in relation to others. By building the notification (with builder.getNotification()) with when set to 0, you're getting its View laid out without a timestamp.  Then you're changing the timestamp to affect the sort order before calling notify().
The fact that ICS happens to actually end up showing your notification with the very low timestamp you set is something that may or may not be fixable. It might just be that ICS ends up re-laying-out your notification after some time, which of course would use the last timestamp you gave it.
Personally, I think the best option is to remove the hacks.  (Well, I think you could probably get away with setting the timestamp to 0 to hide the timestamp altogether, but the sort order hack seems like asking for trouble.)


text:
Q: Proving Equivalence of TM and DFA I'm trying to prove that TM = DFA is undecidable using reduction from Halting Problem
Theoretically I understand that Turing Machine captures all the computable functions and DFA only capture the functions that can be computed in constant space therefore TM = DFA is undecidable.
Here are my steps:
Suppose that R that decide L(M)=L(D)
EQ_DM = { [D,M] | L(M) = L(D) }
and we create a turing machine
HALT_TM = { [M,w]  |  (M halt on input w→Accept
                M did not halt on input w→Reject)}
How do I construct a D & M so R[D,M] tells if M halt on w?

A: Suppose that it is decidable whether a TM and a DFA accept the same language. You can use this to solve the halting problem for a general TM.
Given any TM M and word w, construct M' so that whenever M enters the halt-reject state, M' enters the halt-accept state. Now, M' is a TM that accepts every string that causes M to halt. Now construct M'' from M' so that L(M'') is the intersection of L(M') and {w}, where w is any word. You can always construct M'' using the Cartesian product machine construction given a DFA for {w} and M'.
Since it is decidable whether L(M'') is equal to that of a DFA - say, the DFA for {w} - we can say whether M'' accepts {w}. If it accepts w, then L(M') contains w and if L(M') contains w, M halts on w. If M'' does not accept w, L(M') does not contain w and, therefore, M does not halt on w.


text:
Q: Element not being found with property.find .Webscappy issues I'm trying to scrape data from this site enter link description here but I'm encountering a problem with pricing. Can you tell me if I'm seeing the documentation wrong?

import requests
from bs4 import BeautifulSoup
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

def extract_data():
    url = "https://www.vivareal.com.br/venda/rj/rio-de-janeiro/apartamento_residencial/"
    response = requests.get(url)
    return BeautifulSoup(response.text, "html.parser")

soup = extract_data()
property_list = soup.find_all("div", class_="property-card__main-content")

# Created a dataframe with the extracted data
data = {"title": [property.find("h2", class_="property-card__title").text for property in property_list],
        "price": [property.find("div", class_="property-card__price").text for property in property_list],
        "location": [property.find("div", class_="property-card__address").text for property in property_list]}
df = pd.DataFrame(data)

and then i was preprocessing the data
df["price"] = pd.to_numeric(df["price"].str.replace("R$ ", "").str.replace(".", "").str.replace(",", ".").str.extract('(\d+)').astype(float))

but i got this error: Can only use .str accessor with string values! , which i think is that the element is not being found by the find() method.


text:
Q: Implementation of AutoBrightness I want to add an auto-brightness feature to my android framework.currently the auto-brightness feature is by default disabled in the JB source code.
The actual scenario is,when i check the checkbox from

Settings>Display>Brightness>AutoBrightness

the light sensor should returns the current lux value,and depending on the lux value returned, my screen brightness should adjust.
I went trough several docs and Stack-Overflow questions,but got confused on whether i use AsyncTask or a Service to implement such functionality. Any Solution or guidence would appreciated.

A: You can do a service that listens for light sensor changes and changes the screen brightness in response. There is at least one app I've seen that does this, I think, but I am not sure it checks the system AutoBrightness setting.


text:
Q: How to avoid repeatedly recalculating a function that is used multiple times in another function Example as following
g[x_]:=NIntegate[......];

f[x_]:=g[x]^2+g[x];

I need to have define f[x] through g[x], Does mathmetica NIntegrate g[x] twice when calculating f[x]?
How to rewrite it to reduce calculation?
My idea is to give the value of g[x] at some x to a variable and use it in f[x].
value=g[x];
f[x_]=value^2+value;

The value giving should be done inside f[x_]. How to build up the function definition in mathematica in such way?
Update:
After a bit of study myself, the new code I write is:
g[x_] := NIntegate[......];
f[x_] = #^2 + # &[g[x]]

The function definition gives correct answer. Does it calculate g[x] once or twice in this way?

A: This is one of the situations that With is designed to handle.
g[x_] := NIntegrate[u/(1 + u), {u, 0, x}]
f[x_] := With[{u = g[x]}, u^2 + u]

Then
Plot[f[x], {x, 0, 5}]

A: You could also use memoization (Memoization/Caching)
When you define g as
g[x_]:=g[x]=<definition of g in terms of x>

you can make use of the fact that Mathematica 'remembers' the values of g that are already evaluated.
In the context of the question, the output of a-possibly-computationally costly function like NIntegrate will be evaluated only once for a given input.
In the following code RandomReal will be used as a substitute for the output of some costly function like NIntegrate and Pause is used to simulate the time consuming nature of g.
g[x_]:=g[x]=(Pause[1];RandomReal[])
f[x_]:=g[x]^2+g[x]

Now, the first time eg f[2] is executed, Mathematica will evaluate g[2] and then assign the value of g[2]^+g[2] to f[2].
The next time Mathematica encounters f[2], it will no longer need to evaluate the costly g[2] again because it will already have  a rule saved that associates the expressiong[2] with the value that was calculated, the first time g[2] was encountered.
In short, the costly function g will be calculated once, only the first time Mathematica encounters f[value]. In all subsequent evaluations where f[value] is relevant, there will be no need to re-evaluate the costly g[value].


text:
Q: Fastest way to store medium term data I am posed with a problem where I need to store an Time variable for a medium amount of time after the current activity has been Finish();.
Once the activity has been started again (only a few seconds later) I need to be able to retrieve the Time variable set in the previous activity.
What I want to know is what is the quickest and most efficient way to store the Time variable just before the activity has finished and then retrieve it once the activity has been started again.

A: You should take a look at SharedPreferences. It's an easy and simple way to store small amounts of data.
http://developer.android.com/guide/topics/data/data-storage.html#pref

A: If its really only for a view seconds, i recommend using a singelton. SharedPreferences would be an option, too


text:
Q: SQL SERVER 2012 error am trying to restore a backup, the backup is from a database in the current instance, want to restore the backup with a different name for test purposes, this was possible in 2008 R2 but in 2012 its not possible, anybody know a work around

A: You may use t-sql for restore. Make sure that you create new files instead of replacing your existing database.
Try someting like this:
    USE [master]
    RESTORE DATABASE [new database name] FROM
    DISK = N'path to your full backup' WITH
    MOVE N'logicaldatafilename' TO N'path to your mdf file',
    MOVE N'logicallogfilename' TO N'path to your ldf file',
    NOUNLOAD,  STATS = 5

GO

I hope it helps.
Janos


text:
Q: Can I say that domain doesn't exist if Socket.Connect fails? I want to check if some email domain exist.
When Dns.GetHostEntry(domain) throw an exception I know for sure that the domain doesn't exist.

*

*Can I say that if Dns.GetHostEntry(domain) succeeded then the domain does exists or even if Dns.GetHostEntry(domain) succeeded that doesn't mean (yet) that domain exists?

*Can I say the same when s.Connect fails to connect? I mean if connect throw an exception can I say that such domain doesn't exist?

If (1) is true, so in order to check if domain exists (1) will be enough, right?
public static bool Lookup(string domain)
{
    if (domain == null) throw new ArgumentNullException("domain");

    try {
       IPHostEntry ipHost = Dns.GetHostEntry(domain);
       var endPoint = new IPEndPoint(ipHost.AddressList[0], _dnsPort);

       return Transfer(endPoint);
    }
    catch (SocketException ex)
    {
          ++attempts;
    }
    return false;
}
public static bool Transfer(IPEndPoint endPoint)
{
    int attempts = 0;
    while(attempts <= _attempts)
    {
        try
        {
             var s = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
             s.Connect(endPoint);
        }
        catch (SocketException ex)
        {
            ++attempts;
        }
        finally
        {
            s.Close();
        }
    }
}

A: When trying to connect with a socket you're saying a few things:

*

*There is a network path from my machine to the target machine

*The network path is clear of firewall and other restrictions

*The target machine is hosting a service on the target port

*The target machine is accepting my connections on that target service

All of these occur after the hostname has been resolved to an IP.
So the answer to your question is no. If Socket.Connect fails it could be that the domain doesn't exist, or any of the above reasons (and perhaps more).

A: after some research I found out that checking mx records against dns will tell me if domain can receive emails or not. If DNS server do return mx records for the domain it only means that domain can receive emails. If no mx records are returned, so domain can not receive emails == such domain doesn't exist


text:
Q: 2 questions on Page 6 of Hoffman Kunze ( Linear Algebra) While studying Linear Algebra from Hoffman Kunze I have following two questions :

I.3. Matrices and Elementary Row Operations
One cannot fail to notice that in forming linear combinations of linear equations there is no need to continue writing the "unknowns' $x_{1}, \ldots, x_{n},$ since one actually computes only with the coefficients $A_{i j}$ and the scalars $y_{i} .$ We shall now abbreviate the system (1-1) by
$$AX=Y$$
where
$$A=\begin{bmatrix}A_{11}&\cdots&A_{1n}\\\vdots&&\vdots\\A_{m1}&\cdots&A_{mn}\end{bmatrix}\\X=\begin{bmatrix}x_1\\\vdots \\x_n\end{bmatrix}\text { and }Y=\begin{bmatrix}y_1\\\vdots\\y_m\end{bmatrix}$$
We call $A$ the matrix of coefficients of the system. Strictly speaking, the rectangular array displayed above is not a matrix, but is a representation of a matrix. An $m \times n$ matrix over the field $F$ is a function $A$ from the set of pairs of integers $(i, j), 1 \leq i \leq m, 1 \leq j \leq n,$ into the field $F$. The entries of the matrix $A$ are the scalars $A(i, j)=A_{i j},$ and quite often it is most convenient to describe the matrix by displaying its entries in a rectangular array having $m$ rows and $n$ columns, as above. Thus $X$ (above) is, or defines, an $n \times 1$ matrix and $Y$ is an $m \times 1$ matrix. For the time being, $A X=Y$ is nothing more than a shorthand notation for our system of linear equations. Later, when we have defined a multiplication for matrices, it will mean that $Y$ is the product of $A$ and $X$

Questions->
(1) Why in 2nd paragraph author wrote that the rectangular array displayed above is not a matrix?
(2) In 2nd line of 2nd paragraph author wrote the definition of matrix. How is a matrix a function from set of pair of integers into the field?
To me this definition given contradicts the definition given on Wikipedia and I can't understand it.
Definition on Wikipedia: https://en.m.wikipedia.org/wiki/Matrix_(mathematics)
Can kindly anyone explain why I am confused .