text:
Q: humanize in django/python, how to translate i only need a quick way to translate days in italian in django.
Using humanize it works properly but obviously always in english

{{ h.datainserimento|date:"d M Y"  }} | {{ h.nomegiorno }}

def nomegiorno(self):
   pio = self.datainserimento.strftime("%A")
   return pio

to:

21 May 2014 | Wednesday

thanks!

A: Try to use hard-coded, for a test, translation.activate(language) just before sending it:
def nomegiorno(self):
   old = translation.get_language()
   print('old', old)
   translation.activate('it')
   pio = self.datainserimento.strftime("%A")
   translation.activate(old)
   return pio

And tell me what you have, this should help anyway


text:
Q: Howdo I use MATPOWER only for power flow? Here is my question. I´m developing a genetic algorithm to optmize a distribution net by reducing it´s power losses, I´ve been trying to use Matpower since this "matlab´s plugin" already calculate the power flow, but my problem is that matpower tries to optimize it. I´d like to know if it is possible to use it only for power flow calculation and how could I do it.
Thank you.

A: I´ve just find the answer. It is quite simple, instead of using runopf() you can use runpf() for power flow analyses.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Cloudflare SSL certificate for Subdomain with www I am looking to have a solution for using Cloudflare Dedicated SSL certificate for my website subdomains. I have purchased the $10/month package with the expectation that I could setup a wildcard hostname with the www.
I want my subdomains to load with the SSL certificate and I have more than 100 subdomains available for my domain. I don't want to add each subdomain with www as a hostname but use a wildcard format.
I am inspired after reading the following posts -
https://community.cloudflare.com/t/page-rule-forwarding-with-subdomain-and-wildcards/136977
https://community.cloudflare.com/t/subdomain-too-deep/81872
My current hostnames are -
.example.com, example.com,  .www.example.com
I added *.www.example.com to work for subdomains like www.sub.example.com but it seems not working! I think the wildcard format is incorrect.
I want my SSL certificate works for all addresses like below. -
example.com
www.example.com
sub1.example.com
www.sub2.example.com
sub2.example.com
www.sub2.example.com

I am quite confused if it's really possible with Cloudflare!
Thanks for the help!

A: As reported on the Cloudflare Support article

Dedicated certificates with Custom Hostnames can cover additional levels of subdomains (ex: test.dev.www.example.com instead of just www.example.com)

So you should be able to create a Dedicated Certificate which covers
example.com *.example.com *.sub1.example.com *.sub2.example.com, which should work for:
example.com
www.example.com
foo.example.com
www.sub1.example.com
bar.sub1.example.com
baz.sub2.example.com
www.sub2.example.com
[...]

And so on. In your message, you mention adding *.www.example.com to the certificate to cover for subdomains like www.sub.example.com - but this does not look correct, as you would need *.sub.example.com added instead.


text:
Q: How to select records not on log table using Laravel 4 Eloquent hasMany relation? My table schema
+rules
 -id
 -title
 -description

+log
 -id
 -rules_id
 -date  MYSQL(YYYY-mm-dd)

I execute rules daily and update on logs table. How do I fetch rules that did not execute today?
Rule module
public function log()
{
    return $this->hasMany('Log');
}

A: Use whereDoesntHave:
$rules = Rules::whereDoesntHave('log', function($q){
    $q->where('date', Carbon::now()->toDateString());
})->get();

whereDoesntHave has only been added recently (Dec 2014) You might have to update Laravel. If you can't use this:
$rules = Rules::whereHas('log', function($q){
    $q->where('date', Carbon::now()->toDateString());
}, '<', 1)->get();

A: you can use simple query without eloquent if you don't know much about Carbon::now() mention by @lukasgeiter
$today = DATE('Y-m-d');
$rules = DB::table('rules')
        ->select('rules.id','rules.title','rules.description','log.date')
        ->join('log', 'rules.id', '=', 'rules.rules_id')
        ->where('DATE(log.date)', '!=', $today)
        ->first();


text:
Q: How do I add add device timestamp when ion-checkbox is set to true I am presently using check boxes to track when tasks have been completed in my ionic 2 App.  Is there a way save the date/time from the mobile device when this checkbox is selected.
<ion-list>
  <ion-item>
    <ion-label>Task 1</ion-label>
    <ion-checkbox [(ngModel)]="data.task1"></ion-checkbox>
  </ion-item>
</ion-list>

A: You could use the Date object from Javascript to do so, like you can see in this plunker.
Your Component:
import { Component } from "@angular/core";

@Component({
     templateUrl:"home.html"
})
export class HomePage {

  public data: any;
  public dateTime : string = '';

  constructor() {
    this.data = {
      task1 : false
    }
  }

  public changeCheckBox() {
    if(this.data.task1) {
      this.dateTime = new Date();
    }
  }
}

Your view:
<ion-content>
  <ion-list>
    <ion-item>
      <ion-label>Task 1</ion-label>
      <ion-checkbox [(ngModel)]="data.task1" (ionChange)="changeCheckBox()"></ion-checkbox>
    </ion-item>
    <ion-item>
      <ion-label>Timestamp: {{ dateTime }}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>

Of course you can obtain detailed information by using some of the get methods:
Date.prototype.getDate()
Date.prototype.getDay()
Date.prototype.getFullYear()
Date.prototype.getHours()
Date.prototype.getMilliseconds()
Date.prototype.getMinutes()
Date.prototype.getMonth()
Date.prototype.getSeconds()
Date.prototype.getTime()
Date.prototype.getTimezoneOffset()
Date.prototype.getUTCDate()
Date.prototype.getUTCDay()
Date.prototype.getUTCFullYear()
Date.prototype.getUTCHours()
Date.prototype.getUTCMilliseconds()
Date.prototype.getUTCMinutes()
Date.prototype.getUTCMonth()
Date.prototype.getUTCSeconds()
Date.prototype.getYear()


text:
Q: Unable to write a CSV into Dropbox APP V2 - CSV appears blank I'm trying to upload my script's output (pandas df) into a Dropbox folder, but the csv file created in Dropbox appears blank.
dbx.files_upload(cvd_tracker.to_csv("Trial.csv"),'/Trial.csv')

I'm guessing the .to_csv() doesn't apply here, but I couldn't figure out how to do it. I've checked, and the "cvd_tracker" dataframe does have data in it.
Using the StringIO also failed.
from io import StringIO
csv_buffer = StringIO()
cvd_tracker.to_csv(csv_buffer)

dbx.files_upload(csv_buffer.getvalue(),'/Trial3.csv')

A: dbx.files_upload has two required parameters, the first is a file-like object or a bytes-like object, the second is a path in the user's dropbox in which to save the file. Your second parameter looks ok, but your first parameter is incorrect - pandas.Dataframe.to_csv returns a string if the first parameter passed to it is None, or it returns None if the first parameter is not None. The first (and only) parameter you pass to cvd_tracker.to_csv is "Trial.csv", so cvd_tracker.to_csv("Trial.csv") returns None. This means essentially you are doing dbx.files_upload(None, "/Trial.csv").
To get the desired result, simply remove the argument passed to cvd_tracker.to_csv, so that it returns a string. You then need to turn the string into a bytes-like object by using str.encode, so that dbx.files_upload can accept it. It would look like this:
dbx.files_upload(cvd_tracker.to_csv().encode(), "/Trial.csv")


text: Q: Tangent space of the $z$ axis I want to find the tangent space of the $z$-axis a some point $p\in \mathbb{R^3}$. If $(0,0,c)$ is some point on the $z$ axis, is $T_pZ=\{(0,0,zc)|z\in R\}$? $Z$ here is for the $z$ axis. I know this is a very basic question but any help is very very much appreciated!


text:
Q: Debug Backbone Javascript using Visual Studio I've website developed in VS 2010 which is using MVC framework & backbone javascript.
I want to know how to debug backbone javascript step by step by putting a debugger in JS file within Visual Studio.
When I put a breakpoint in JS, it says no symbol will be loaded.
Any clue how to debug backbone JS via visual studio or any other alternatives?
Thanks!

A: I recommend using the developer tools in the browser of your choice.
However, I have been able to debug JS in Visual Studio by temporarily adding a debugger; statement in the javascript. This will attach the debugger in Visual Studio. Just remember to remove it afterwards though.


text:
Q: SPARQL: Bind value to variable based on another value I have a SPARQL query that returns the triples shown in the attached table. Is it by any chance possible to assign the value of "new_arg_val" to variables ?arg1 and ?arg2 based on their "position"-value? The position is from an rdf:Seq, and it should work with an arbitrary length of the rdf:Seq.

Edit:
So I am working on an approach to handle the inferencing of calculated properties, ie. properties that are derived from the values of other properties. I am using the seas evaluation ontology and the structure of my data is the following:
<resourceURI> seas:fluidTemperatureDiffeence <propertyURI> .
<propertyURI> seas:evaluation <evaluationURI> .
<evaluationURI> seas:evaluatedValue "33 Cel"^^cdt:ucum ;
              prov:wasGeneratedAtTime "2017-06-13T21:51:26.706+02:00"^^xsd:dateTime ;
              seas:calculation "abs(?arg1-?arg2)"^^xsd:string ;
              prov:wasDerivedFrom _:c0 .
 _:c0 a rdf:Seq ;
      rdf:_1 <evaluationURIa> ;
      rdf:_2 <evaluationURIb> .

A property can have multiple evaluation as properties can change over time. Hence I also have several calculations. So far my query looks like this:
SELECT  *
WHERE
  { #Get the time of the latest calculation
    { SELECT  ?calculatedProperty (MAX(?_tc) AS ?tc)
      WHERE
        { GRAPH ?g
            { ?resource seas:fluidTemperatureDifference/seas:evaluation _:b0 .
              _:b0 ^seas:evaluation ?calculatedProperty .
              _:b0  prov:wasGeneratedAtTime  ?_tc
            }
        }
      GROUP BY ?calculatedProperty
    }
    #Get calculation data
    GRAPH ?gi
      { ?calculatedProperty
                  seas:evaluation       _:b1 .
        _:b1      prov:wasGeneratedAtTime  ?tc ;
                  seas:calculation      ?calc ;
                  seas:evaluatedValue   ?old_res .
        _:b1     (prov:wasDerivedFrom)+ _:b2 .
        _:b2  ?position  ?old_arg
      }
    #Get the time of the latest input values
    { SELECT  ?old_arg (MAX(?_t) AS ?t)
      WHERE
        { GRAPH ?g
            { ?old_arg ^seas:evaluation/seas:evaluation ?arg .
              ?arg  prov:wasGeneratedAtTime  ?_t
            }
        }
      GROUP BY ?old_arg
    }
    #Get argument data
    GRAPH ?g
      { ?old_arg ^seas:evaluation/seas:evaluation ?new_arg .
        ?new_arg  prov:wasGeneratedAtTime  ?t ;
                  seas:evaluatedValue   ?new_arg_val
      }
    #Bind values to arguments (WIP)
    BIND(IF(?position = rdf:_1, ?new_arg_val, "") AS ?arg1)
    BIND(IF(?position = rdf:_2, ?new_arg_val, "") AS ?arg2)
    #Should do the calculation based on ?calc
    BIND(str("newResultHere") AS ?_res)
    #Get datatype of existing result
    BIND(datatype(?old_res) AS ?datatype)
    #Get unit of existing result
    BIND(strafter(str(?old_res), " ") AS ?unit)
    #Define datatype and unit for result
    BIND(strdt(concat(str(?_res), " ", ?unit), ?datatype) AS ?res)
    #Make a guid (struuid() bug in stardog)
    BIND(replace(str(uuid()), "urn:uuid:", "") AS ?guid)
    BIND(uri(concat("https://host/proj", "/Evaluation/", ?guid)) AS ?evaluationURI)
    BIND(now() AS ?now)
  }

I would like to get a calculation result so I can construct the new triples.


text:
Q: overwrite php loop while looping it, then break? I was wondering if this code snippet is considered legal:
$arr = array(123,456,789,123,456,789);
foreach($arr as $a) {
    $arr = $a;
    break;
}
//prints 123
echo $arr;

It executes, but are there any pitfalls i should know using this method?

Update: Here is the actual problem
You have an array as follows from the database query (select * from table where code = $code)

Array
(
    [0] => Array
        (
            [id] => 1
            [code] => 1234567
            [member_id] => 7
        )

    [1] => Array
        (
            [id] => 5
            [code] => 1234567
            [member_id] =>
        )

    [2] => Array
        (
            [id] => 67
            [code] => 1234567
            [member_id] => 43
        )

)

all you care about is finding the first (if any) row that has an empty member_id (this means the code has not been claimed).
So how do you go about doing this?
According to Felix Kling using the variable to hold the array of codes and then overwriting it with the row that you want is not the best solution, so what do you propose.
Also, bonus credit:
 How many different 7 digit codes can you generate using 32 characters (duplicate characters allowed)?
is it 32^32*7 or ((((((32^32)^32)^32)^32)^32)^32)^32)?

A: As others explained, there is no reason to reuse the variable. Is there a reason for it? Why not create a new one?
$resultId = 0;

foreach ($result as $row) {
   if ($row["member_id"] == "") {
      $resultId = $row["id"];
      break;
   }
}

But here is the big question - why don't you simply do that in SQL? You're already creating an SQL query. What's wrong with select * from table where code = $code and member_id = null?
Btw, to answer your other question: Number of permutations with seven characters, each one with 32 different possibilities = 32^7.

A: So,
using this method works fine as long as you are only using  a copy of the array.
If you were to pass in the array by reference foreach($code_info as &$code) then you will receive a Invalid argument supplied for foreach() error.

A: This might work, but it is definitely bad coding style and makes your code harder to understand. Because if you use more meaningful variable names, it makes no sense anymore:
$scores = array(123,456,789,123,456,789);
foreach($scores as $score) {
    $scores = $score;
    break;
}
//prints 123
echo $scores;

In this case, $scores suggests to hold something like a list, not a single element (or imagine you use $score_list... even worse). And it won't improve if you start giving your variables names that fit for different types of values ;)

Remember: Not everything that is possible should be done. I would definitely avoid this.

A: $empty_number=-1;
foreach($arr as $a=>$b)
{
  if($b['member_id']!='')
  {
    $empty_number=$a;
    break;
  }
}

The index for the empty number is stored in the $empty_number variable.. if there is no row with an empty member_id tag, the value of $empty_number is -1.
EDIT:
For your bonus question, the maximum would be 32^7 = 34 359 738 368


text:
Q: Update or insert field from table into another table VBA sql First this is my first post so I apologize for the layout or any other errors with presentation.
I have two tables.
tempWkEndHrs: Is created when the user selects a weekending date and their name from two comboboxs. The result is 5 fields: Name1, Task, Closed Date, Initiated Date and #xx/xx/xxxx# <--the same date as chosen by the user from the combobox to create the table. This is done to limit the number of date fields returned and built into the temp table.
The purpose of this table is so the user can populate as many values under the #xx/xx/xxxx# field/column to show/see the distribution of hours taken on tasks for that week. (its also used as a check to make sure entered values sum up as expected)
I would like to save the new values entered underfield #xx/xx/xxxx# in tempWkEndHrs to the same field #xx/xx/xxxx# in tblHrs.
tblHrs: has fields... Task , #xx/xx/xxxx#, #xx/xx/xxxx#, #xx/xx/xxxx#, #xx/xx/xxxx#, etc.. <--Same dates available within combobox.
I have having difficulty finding an example of updating multiple records from one table to another to fit my situation.
Below is my last attempt from several variations.
Dim strITEM As String
Dim strWkEnd As String

strWkEnd = Me.cmbWkEnd
strSQL = "UPDATE tblHrs SET " & _
        "[" & strWkEnd & "] = [" & strWkEnd & "] " & _
        "FROM tempWkEndHrs " & _
        " WHERE [Task] = [Task]"

*Update 10-24-2017 5:37pm
Dim strITEM As String
Dim strWkEnd As String

strWkEnd = Me.cmbWkEnd
strSQL = "UPDATE tblHrs " & _
       "SET tempWkEndHrs.[" & strWkEnd & "] = tblHrs.[" & strWkEnd & "] "& _
       "FROM tempWkEndHrs " & _
       " WHERE tempWkEndHrs.[Task] = tblHrs.[Task]"

Result:
UPDATE tblHrs SET tempWkEndHrs.[9/30/2017] = tblHrs.[9/30/2017] FROM tempWkEndHrs WHERE tempWkEndHrs.[TASK] = tblHrs.[TASK]
***Run-Time error '3075
***Syntax error(missing operator) in query expression 'tblHrs.[9/30/2017] FROM tempWkEndHrs'.
If this is clear as mud please let me know.

enter image description here

A: BIG SHOUT OUT TO
Oscar Anthony and Parfait
https://stackoverflow.com/a/34910889/8797058
5.You don't need the FROM tblTemp clause in the SQLReplace String.
6.EDIT: As @Parfait pointed out, tblTemp does not exist in scope of the SQLReplace statement. You should do an INNER JOIN to fix that: <--AWESOME!!
strWkEnd = Me.cmbWkEnd
strSQL = "UPDATE tblHrs INNER JOIN tempWkEndHrs ON tblHrs.TASK = tempWkEndHrs.TASK SET tblHrs.[" & strWkEnd & "] = tempWkEndHrs.[" & strWkEnd & "] "

Works! >:P
I didn't receive any answers to this post so obviously I need to write better questions, I figured it was mud...Thanks for the ~21 Views ?lol.


text:
Q: How to find the clockwise angle between two vectors in python? I want to find the clockwise angle between two vectors in python
the angle should be in range of (-90,90)
what is the equation/code to calculate the angle ?
class Vect:
  def __init__(self, a, b):
    self.a = a
    self.b = b

  def findClockwiseAngle(self, other):
    ## how to compute ??
    pass

vector1 = Vect(a1,b1)  ## a1*i + b1*j
vector2 = Vect(a2,b2)  ## a2*i + b2*j
angle = vect1.findClockwiseAngle(vect2)

A: Vector geometry provides (at least) two useful formulas for finding the angle between two vectors:

*

*the dot product formula

where a · b can be computed using

*

*and the cross-product formula:

where

and since our vectors are two dimensional, we can take a3 and b3 (the components in the z-axis direction) equal to 0. This simplifies the formula even further:
|a x b| = |a1 * b2 - a2 * b1| = |a| * |b| * sin(ϴ)

The ϴs is these two formulas, however, have different interpretations.
With the dot product, the angle is the included angle between the two vectors -- and thus always a value between 0 and pi.
With the cross product, the angle is measured in the counterclockwise direction from a to to b. Since you are looking for the angle measured in the clockwise direction, you would simply reverse the sign of the angle obtained using the cross product formula.
In Python, math.asin returns values in the range [-pi/2, pi/2], whereas math.acos returns values in the range [0, pi]. Since you want angles in the range [-pi/2, pi/2] (in radians), the cross-product formula seems to be the more promising candidate:
import math

class Vect:

   def __init__(self, a, b):
        self.a = a
        self.b = b

   def findClockwiseAngle(self, other):
       # using cross-product formula
       return -math.degrees(math.asin((self.a * other.b - self.b * other.a)/(self.length()*other.length())))
       # the dot-product formula, left here just for comparison (does not return angles in the desired range)
       # return math.degrees(math.acos((self.a * other.a + self.b * other.b)/(self.length()*other.length())))

   def length(self):
       return math.sqrt(self.a**2 + self.b**2)

vector1 = Vect(2,0)

N = 12
theta = [i * 2 * math.pi / N for i in range(N)]
result = []
for t in theta:
    vector2 = Vect(math.cos(t), math.sin(t))  ## a2*i + b2*j
    angle = vector1.findClockwiseAngle(vector2)
    result.append((math.degrees(t), angle))

print('{:>10}{:>10}'.format('t', 'angle'))
print('\n'.join(['{:>10.2f}{:>10.2f}'.format(*pair) for pair in result]))

prints
     t     angle
  0.00     -0.00
 30.00    -30.00
 60.00    -60.00
 90.00    -90.00
120.00    -60.00
150.00    -30.00
180.00     -0.00
210.00     30.00
240.00     60.00
270.00     90.00
300.00     60.00
330.00     30.00

Above, t is the angle from vector1 to vector2 measured in the counterclockwise direction in the range (0, 360) degrees. angle is the angle from vector1 to vector2 measured in the clockwise direction and in the range (-90, 90) degrees.

A: In this case, you want to find the angle in range of (-90,90).
More infomation, you can get the angle in range of (-180,180).
Shown bellow.
From unutbu'answer
You can get cos(theta), sin(theta) of target angle theta.
cosTh1 = np.dot(a,b)/(np.linalg.norm(a)*np.linalg.norm(b))
sinTh1 = np.cross(a,b)/(np.linalg.norm(a)*np.linalg.norm(b))

You can get tan(theta) = sin(theta)/cons(theta).
In Python, numpy.arctan2 returns values in the range [-pi, pi]. So,
print (np.rad2deg(np.arctan2(sinTh1,cosTh1)),end=",")

More simple, (cause np.linalg.norm(a)*np.linalg.norm(b) is common.)
cosTh = np.dot(a,b)
sinTh = np.cross(a,b)
print (np.rad2deg(np.arctan2(sinTh,cosTh)))


text:
Q: Non-const implicit "converting" constructor Hi guys I'm working on a messaging system where there are 3 types: Streams (memory), Taps (const view type), Sink(mutable view type). Now constructing a tap from a stream is very easy because it can implicitly convert from a stream to a tap by using the standard const ref conversion constructor. But for sinks I can't seem to figure out how to make it implicitly convert. Implicit conversion is something that saves me a lot of headaches (I'm not trying to get into the whole implicit conversion is evil discussion here) working with tuple and constexpr code here, would it be possible to implicitly construct a sink from a stream, maintaining const correctness?
#include <tuple>

template<typename T>
struct Stream
{
};

template<typename T>
struct Tap
{
    Tap(const Stream<T>& stream)
    {}
};

template<typename T>
struct Sink
{
    Sink(Stream<T>&)
    {}
};

int main()
{
    Stream<float> stream;
    Tap<float> tap = stream;
    //Sink<float> sink = stream;

    std::tuple<Stream<float>, Stream<int>> streams;
    std::tuple<Tap<float>, Tap<int>> taps = streams;
    //std::tuple<Sink<float>, Sink<int>> sinks = streams;
}

A: This fails because tuple needs to use its converting constructor for the sinks variable.
constexpr tuple(const tuple<_U1, _U2>& __in)

However, this fails because it adds const qualification onto the streams which then means they cannot be used with the constructor of the Sink class.  For this to work then std::tuple would need a converting constructor that did not add const qualification, i.e.
constexpr tuple(tuple<_U1, _U2>& __in)

Or you would need to pass it through the equivalent move constructor as such as this gotbolt example show: https://godbolt.org/z/woF__K
Do you need to copy here, would moving suffice?


text:
Q: Measuring custom statistics with sar I have a server application which I think is leaking file handles.
I want to track the usage of file descriptors over time on my Linux (ubuntu) server.
I've figured out that I can track the number of file descriptors in use by a process with
lsof -p `pgrep the-process-name` | wc -l

Since I'm already using sysstat and sar to track various metrics, I thought it'd be nice to display with sar.  I want to measure this every 10 minutes.   Is it possible to add a custom metric to sar?  Then I can easily report it out.
If not, I'll write a simple cron job to collect this data and store it separately in a log file.

A: It's not possible to add another metric without modifying the source code of sar.


text:
Q: Project file contains ToolsVersion="4.0" (old thread did not help) I get this
Project file contains ToolsVersion="4.0", which is not supported by this version of MSBuild
when trying to build from VS2008 my setup project.  Now, I've edited all csproj files by replacing 4.0 with 3.5 to no avail!

A: You can set current target framework to .net 4.0 in Nant by adding the following line to your nant script.
<property name="nant.settings.currentframework" value="net-4.0" />


text:
Q: Accessor methods and Java Reflection This is a question about how Java does reflection internally.
I have a abstract class say
SuperClass

and two chlid classes from SuperClass,
ChildClass1 and ChildClass2.
SuperClass defines a accesor method getValue() although it dosen't define the attribute value.
ChildClass1 and ChildClass2 override the method getValue() and both add an annotation @MyAnnotation to the method, @MyAnnotation is kept in runtime (It's the OneToOne annotation).
In my program I have an instance of ChildClas1 and an instance of ChildClass2. I used reflection to obtain all methods from both objects.
As expected I got two getValue() methods in the resulting array, (one for the SuperClass and one for the ChildClass).
For the instances of ChildClass1 the getValue() method that had @MyAnnotation was marked as a accessor (methodAccessor property != null) but for instances of ChildClass2 the method marked as an accessor didn't have the annotation (was the getValue() method of the parent class).
I couldn't understand why, eventually I changed the order in which methods were declared in ChildClass2 (There were more methods than just the accessors), namely I put all getters and setters at the begginging and ChildClass2 was behaving as ChildClass1.
My question is, how does Java qualify methods as accessors in reflection, and further does the order in which methods are declared change the behavior of reflection?

A:
how does Java qualify methods as accessors in reflection,

It doesn't JavaBean is a convension which the Reflections library is not aware of.  If you use the Beans Introspector, this does make assumptions about getters and setters by names and number fo arguments.

and further does the order in which methods are declared change the behavior of reflection?

The order the methods is defined tends to be the order they are retrieved e.g. getMethods() but you cannot rely on this behaviour.

A: Java reflection does not distinguish accessor methods from other - all are just methods. The order in which methods are declared does not matter.


text:
Q: LinkedList subList returns List instead of LinkedList? I have a function f that gets a sublist of a LinkedList and passes it to g, which also takes a LinkedList:
public static <T> void g(LinkedList<T> l) {
}

public static <T> void f() {
    LinkedList<T> l = new LinkedList<T>();
    ...
    LinkedList<T> l2 = l.subList(i,j);
    ...
    g(l2);
}

But this doesn't compile, because apparently LinkedList.subList returns List instead of LinkedList. So I have to change it to this:
LinkedList<T> l2 = (LinkedList<T>)l.subList(i,j);

Why?

A: subList is defined in the List interface and returns a List. And if you check the implementation in LinkedList, which is actually in one of the parent classes (AbstractList), you will see that it does not return a LinkedList but a SubList and your cast will throw an exception.
Unless you use methods specific to LinkedList, the easiest way to fix this would be to change g to:
public static <T> void g(List<T> l) {

A: if g() doesn't use the method of LinkedList but only the List interface is preferable to define g() as follow:
public static <T> void g( List<T> l ) {
}

and the main becomes:
public static <T> void f() {
    List<T> l = new LinkedList<T>();
    ...
    List<T> l2 = l.subList(i,j);
    ...
    g(l2);
}

For a justification, please consult this post.

A: The method sublist is declared in the List interface which is implemented by LinkedList. The signature of the sublist method in the List interface is:
 List<E> subList(int fromIndex, int toIndex)

Thus whenever you call this method from a LinkedList class, the object will be of LinkedList, but return type of the method is List, thus it will be given in the form of List. However, you can cast the variable to LinkedList and use it.

A: You can't instantiate 'Objects' such List. List is an interface, not a concrete class.
An interface is just a set of functions that a class can implement; it doesn't make any sense to instantiate an interface.
Hope it helps.
Clemencio Morales Lucas.

A: Java wants as much polymorphism as you can get, so subList returns List, and you have to cast it to what you want.


text:
Q: react navigation define drawer navigation with custom components using redux I am creating a React Native app wherein I have a SwitchNavigator which takes me either to a LoginStack or a Drawer (depending on the loginState, post-login also the user reaches the Drawer).
After Logging the user in, I have a requirement wherein depending on the user's details fetched through a login (account etc), I fetch the projects from that account.
My requirement is to display these projects in the Drawer NavBar. (I have a screen that will cater to the navigation, displaying the selected project's details on clicking a project entity in the drawer. Which, again, are fetched through related APIs and so on.) I also want to have my customComponent of logout to empty my state, so that logging in a different account/user does not cause any overlap on the store which is presently happening.

Hence, I want a way to connect my Drawer declaration to redux.

I am using redux-thunk as my middleware and stated below are the relevant code files.
AppNavigationView.js

let DrawerNavigation = allProjects => {
    return createDrawerNavigator(
        {
            Dashboard: {
                screen: DashboardStack,
                navigationOptions: ({ navigation }) => {
                    return {
                        drawerIcon: () => <Icon name="chart" fontSize={12} />,
                    };
                },
            },
            Workspaces: {
                screen: ProjectNavigator,
                navigationOptions: {
                    // This is the title that displays in the side Drawer
                    title: 'Workspaces',
                    drawerIcon: () => <Icon name="home" fontSize={12} />,
                },
            },
            MyProfile: {
                screen: MyProfileStack,
                navigationOptions: {
                    title: 'Profile',
                    drawerIcon: () => <Icon name="user" fontSize={12} />,
                },
            },
            About: {
                screen: AboutStack,
                navigationOptions: {
                    drawerIcon: () => <Icon name="info" fontSize={12} />,
                },
            },
        },
        {
            // let allProjectObjects = this.allProjects;
            contentComponent: props => (
                <View style={{ flex: 1 }}>
                    <SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
                        <DrawerItems {...props} />
                        <View
                            style={{ flexDirection: 'row', alignItems: 'center', paddingLeft: 25 }}
                        >
                            <Icon name="info" fontSize={12} />
                            <TouchableOpacity
                                onPress={() => handleLogoutClick(props)}
                                style={{ paddingLeft: 15 }}
                            >
                                <Text style={{ margin: 16, fontWeight: 'bold', color: 'black' }}>
                                    Logout
                                </Text>
                            </TouchableOpacity>
                        </View>
                        // THIS SAFEAREAVIEW IS COMMENTED OUT, BUT I WANT TO DISPLAY MY
                        // PROJECTS FROM HERE!!
                        {/* <SafeAreaView>
                            <FlatList
                                data={this.allProjects}
                                renderItem={({ item }) => {
                                    return (
                                        <View
                                            style={{
                                                flexDirection: 'row',
                                                alignItems: 'center',
                                                paddingLeft: 25,
                                            }}
                                        >
                                            <Icon name="home" fontSize={12} />
                                            <TouchableOpacity style={{ paddingLeft: 15 }}>
                                                <Text
                                                    style={{
                                                        margin: 12,
                                                        color: 'black',
                                                    }}
                                                >
                                                    {item.name}
                                                </Text>
                                            </TouchableOpacity>
                                        </View>
                                    );
                                }}
                                keyExtractor={item => item.id}
                            />
                        </SafeAreaView> */}
                    </SafeAreaView>
                </View>
            ),
            drawerOpenRoute: 'DrawerOpen',
            drawerCloseRoute: 'DrawerClose',
            drawerToggleRoute: 'DrawerToggle',
        },
    );
};

export const createRootSwitchNavigator = (signedOut = false, allProjectObjects = {}) => {
    return createSwitchNavigator(
        {
            SignedIn: {
                screen: DrawerNavigation(allProjectObjects),
            },
            SignedOut: {
                screen: Login,
            },
        },
        {
            initialRouteName: signedOut ? 'SignedOut' : 'SignedIn',
        },
    );
};

AppScreen.js (this calls the Switch Navigator)
    render() {
        if (this.state.isLoading || _.isEmpty(this.props.allProjectObjects)) {
            return <SplashScreen />;
        }

        let Layout = createRootSwitchNavigator(
            this.state.isSignedOut,
            this.props.allProjectObjects,
        );
        let AppContainer = createAppContainer(Layout);
        return <AppContainer />;
    }

I have redux connected in this case and fetch projects by dispatching an action.
But this is only the case wherein the user is already logged in
In case we take the logging in route and then navigating to the drawerNavigator, I am clueless.
Any help is appreciable. Thanks!


text:
Q: Add certain words to a file I am using this code to read the line number 2 from files has the same name and included in folders (the name of those folders included in list.txt):
#!/bin/bash
in=/au/cl/tr/129/
inlist=/1/2/3
g=/1/5/file.txt

for i in $(cat $inlist/list.txt); do
 echo ${i}
 sed '2q;d' ${in}/${i}/${g};
 done > newfile.txt

the output of this code (the content of newfile.txt) is as the following:
 folder 1
 a
 folder 2
 b
 folder 3
 c
 .
 .
 .
 .

a, b, c are the value of the second line in the files
how can I add "i" which is the name of the folder (included in list.txt) to the output of the code so I will have the value in line 2 and the name of the folder in the same row as the following
 folder1 (a)
 folder2 (b)
 folder3 (c)
   .
   .
   .
   .

A: #!/bin/bash
in=/au/cl/tr/129/
inlist=/1/2/3
g=/1/5/file.txt

for i in $(cat $inlist/list.txt); do
 echo -n "$i ("
 sed '2q;d' ${in}/${i}/${g};
 echo ")"
done > newfile.txt

-n switch tell echo not to print newline character.
Ref: http://wiki.bash-hackers.org/commands/builtin/echo

A: If you don't have to do it in sed, Perl can help. It stores the name of the file it's reading from in the special variable $ARGV and the line number in the special variable $., so this should work:
...
for i in $(cat $inlist/list.txt); do
    perl -nle 'print "$ARGV ($_)" and last if ($.==2)' "${in}/${i}/${g}"
done

To grab multiple lines:
...
for i in $(cat $inlist/list.txt); do
    perl -nle '
        BEGIN{
            @lines = (2,3,5);
            print "$ARGV: "
        }
        print "Line $.: $_" if grep { $. == $_ } @lines;
        last if $. == $lines[-1];
    ' "${in}/${i}/${g}"
done

The above will print lines 2, 3 and 5. This assumes that the last entry in the array @lines is the very last line you want printed.


text:
Q: nginx makes own html folder/file I have just setup my virtual machine setup with vagrant.
The virtual machine config i configured on https://puphpet.com.
Everything is fine and works (I can ssh to the VM, ...). But I can't seem to connect to the right folder in my application.
My application is a Symfony 3.2 app, so the default connect folder and file are: /web/app.php (or /web/app_dev.php).
When I run vagrant, it automatically creates a html with index.html folder in the root folder of the shared folder (so in ./ ) although I have not setted it up that way.
I know it's just tweaking of the settings (I guess?), but I can't seem to get it working.
This is my config.yml:
vagrantfile:
target: local
vm:
    provider:
        local:
            box: puphpet/ubuntu1604-x64
            box_url: puphpet/ubuntu1604-x64
            box_version: '0'
            chosen_virtualizer: virtualbox
            virtualizers:
                virtualbox:
                    modifyvm:
                        natdnshostresolver1: false
                    showgui: 0
                vmware:
                    numvcpus: 1
                parallels:
                    linked_clone: 0
                    check_guest_tools: 0
                    update_guest_tools: 0
            machines:
                vflm_yo94xzj3amtb:
                    id: IDOFMACHINE
                    hostname: machine1.puphpet
                    network:
                        private_network: 192.168.56.101
                    memory: '512'
                    cpus: '1'
    provision:
        puppet:
            manifests_path: puphpet/puppet/manifests
            module_path:
                - puphpet/puppet/modules
                - puphpet/puppet/manifests
            options:
                - '--verbose'
                - '--hiera_config /vagrant/puphpet/puppet/hiera.yaml'
    synced_folder:
        vflsf_4nfi36d4rw19:
            source: ./
            target: /var/www
            sync_type: nfs
            smb:
                smb_host: ''
                smb_username: ''
                smb_password: ''
                mount_options:
                    dir_mode: '0775'
                    file_mode: '0664'
            rsync:
                args:
                    - '--verbose'
                    - '--archive'
                    - '-z'
                exclude:
                    - .vagrant/
                    - .git/
                auto: 'true'
            owner: www-data
            group: www-data
    usable_port_range:
        start: 10200
        stop: 10500
    post_up_message: ''
ssh:
    host: 'false'
    port: 'false'
    private_key_path: 'false'
    username: vagrant
    guest_port: 'false'
    keep_alive: '1'
    forward_agent: 'false'
    forward_x11: 'false'
    shell: 'bash -l'
    insert_key: 'false'
vagrant:
    host: detect
proxy:
    http: ''
    https: ''
    ftp: ''
    no_proxy: ''
server:
    install: '1'
    packages:
        - vim
users_groups:
    install: '1'
    groups:
        - USERGROUP
    users:
        - USERNAME
locale:
    install: '1'
    settings:
        default_locale: en_US.UTF-8
        locales:
            - en_GB.UTF-8
            - en_US.UTF-8
        timezone: Europe/Brussels
firewall:
    install: '1'
    rules: {  }
cron:
    install: '1'
    jobs: {  }
nginx:
    install: '1'
    settings:
        version: present
        default_vhost: 1
        proxy_buffers: '4 256k'
        proxy_buffer_size: 128k
        proxy_connect_timeout: 600s
        proxy_send_timeout: 600s
        proxy_read_timeout: 600s
        names_hash_bucket_size: 128
    upstreams: {  }
    vhosts: {  }
    proxies: {  }
letsencrypt:
    install: '1'
    settings:
        email: ''
    domains: {  }
php:
    install: '1'
    settings:
        version: '7.1'
    modules:
        php:
            - cli
            - intl
            - xml
        pear: {  }
        pecl: {  }
    ini:
        display_errors: 'On'
        error_reporting: '-1'
        session.save_path: /var/lib/php/session
        date.timezone: UTC
    fpm_ini:
        error_log: /var/log/php-fpm.log
    fpm_pools:
        phpfp_fo0v12pi60wc:
            ini:
                prefix: www
                listen: '127.0.0.1:9000'
                security.limit_extensions: .php
                user: www-user
                group: www-data
    composer: '1'
    composer_home: ''
ruby:
    install: '1'
    versions:
        rv_3wwtzfmr5ph7:
            default: '1'
            bundler: '1'
            version: 2.3.1
            gems:
                - deep_merge@1.0.1
                - activesupport@4.2.6
                - vine@0.2
python:
    install: '1'
    packages: {  }
    versions: {  }
mysql:
    install: '1'
    settings:
        version: '5.7'
        root_password: PASSWORD
        override_options: {  }
    adminer: 0
    users:
        mysqlnu_dhshopbnzmjt:
            name: DBNAME
            password: DBPASSWORD
    databases:
        mysqlnd_cgzy7ctnghxn:
            name: dbname
            sql: ''
    grants:
        mysqlng_176bhrghj78b:
            user: dbuser
            table: '*.*'
            privileges:
                - ALL

Thank you very much

A: You don't actually have any vhosts set up.
For example, here's the default Nginx section:
nginx:
install: '1'
settings:
    version: present
    default_vhost: 1
    proxy_buffers: '4 256k'
    proxy_buffer_size: 128k
    proxy_connect_timeout: 600s
    proxy_send_timeout: 600s
    proxy_read_timeout: 600s
    names_hash_bucket_size: 128
upstreams: {  }
vhosts:
    nxv_g7clf38t8tsy:
        server_name: awesome.dev
        server_aliases:
            - www.awesome.dev
        www_root: /var/www/awesome
        listen_port: '80'
        client_max_body_size: 1m
        ssl: '0'
        ssl_cert: ''
        ssl_key: ''
        ssl_port: '443'
        ssl_protocols: ''
        ssl_ciphers: ''
        rewrite_to_https: '1'
        spdy: '1'
        locations:
            nxvl_1anmyow0cd4b:
                www_root: ''
                location: /
                index_files:
                    - index.html
                    - index.htm
                    - index.php
                try_files:
                    - $uri
                    - $uri/
                    - /index.php$is_args$args
                fastcgi: ''
                fastcgi_index: ''
                fastcgi_split_path: ''
                proxy: ''
                proxy_redirect: ''
            nxvl_yhk6qxrhfjqr:
                www_root: ''
                location: '~ \.php$'
                try_files:
                    - $uri
                    - $uri/
                    - /index.php$is_args$args
                fastcgi: '127.0.0.1:9000'
                fastcgi_index: index.php
                fastcgi_split_path: '^(.+\.php)(/.*)$'
                fast_cgi_params_extra:
                    - 'SCRIPT_FILENAME $request_filename'
                    - 'APP_ENV dev'
                set:
                    - '$path_info $fastcgi_path_info'
                proxy: ''
                proxy_redirect: ''
proxies: {  }

Your config is missing the whole vhosts: block.
Recreate your config.


text:
Q: Am I programming too slow? I've only been a year in the industry and I've had some problems making estimates for specific tasks. Before you close this, yes, I've already read this: How to respond when you are asked for an estimate? and that's about the same problem I'm having. But I'm looking for a more specific gauge of experiences, something quantifiable or probably other programmer's average performances which I should aim for and base my estimates.  The answers range from weeks, and I was looking more for an answer on the level of a task assigned for a day or so. (Note that this doesn't include submitting for QA or documentations, just the actual development time from writing tests if I used TDD, to making the page, before having it submitted to testing)
My current rate right now is as follows (on ASP.NET webforms):

*

*Right now, I'm able to develop a simple data entry page with a grid listing (no complex logic, just Creating and Reading) on an already built architecture, given one full day's (8 hours) time.

*Adding complex functionality, and Update and Delete pages add another full day to the task.

*If I have to start the page from scratch (no solution, no existing website) it takes me another full day.

*(Not always) but if I encounter something new or haven't done yet it takes me another full day.

Whenever I make an estimate that's longer than the expected I feel that others think that I'm lagging a lot behind everyone else. I'm just concerned as there have been expectations that when it's just one page it should take me no more than a full day. Yes, there definitely is more room for improvement.  There always is. I have a lot to learn. But I would like to know if my current rate is way too slow, just average, or average for someone no longer than a year in the industry.

A: You might be a little "slow" compared to someone who has been programming for 5 or 10 years, but it all comes with time. You are probably doing things now in 1/10th of the time as when you were first learning, and it will continue to become easier. That's just the way most things in life are... you are slow when you first learn it, and you gradually get better, faster, more efficient. If you practice long enough, you might become "masterful".

A: If you're programming for a job, and your superiors are happy with the rate you're turning stuff out at, then I'd say you're doing fine.  As you've lasted a year, they're clearly not outraged with your output.  Also, you've only been there a year, and assuming they've been managing people for more than a day, they know that there's a learning curve when you're still green.
As for estimates... I've been in the industry for 5 years now (certainly not veteran territory, I know!), and my personal estimates still suck.  I overestimate almost as often as I underestimate, and I do both far more than I get it right.  Something will come up, somewhere, and bite you.  Sometimes you'll find a library that does everything you thought you had to do yourself, and a week's work disappears in half a day.  Other times a stupid bug will stretch a day's work out to 2, 3, 4...
If you're repeating a lot of the same work over and over, and you feel like you've maxed out your throughput on it, maybe you should ask to be moved to another task. 'Cross-pollination' and other PHB-friendly terms are definitely of benefit to devs.  If you spend a month or more on something else, maybe you'll find something you're better suited to.  If not, or you're not able to stay away from webforms, the change won't do you any harm, and you might come back with a bit more knowledge and experience that will help you.

A: If you are doing things that are somewhat unique each time getting down to fine detail tasks or getting a very accurate estimate is always going to be difficult.
I personally like the challenge, but sometimes it can make you look a bit silly if you are just looking at a task list or a time line.
If you are doing tests as you go sometimes I would say that the examples you gave are fairly quick depending on the complexity of what you are doing.  I have worked on projects where each item, even some if the items inside your bullet points, had at least a day assigned to them.

A: Lucky you, if you've managed 1 year as a green programmer. I was moved to another unit after just 9 months (of which 3 months was actually programming), for not being productive enough. And I was learning more and more each day, enjoying the process and delivering things at a steady pace. It was the first time I had been working in corporate programming at all, ah well...
Perhaps it would just be better to do the dirtiest, least reliable code with zero testing that barely stays together with bubblegum when doing the task, so the managers will get enough "producitivity" for their benchmarks.

A:
Whenever I make an estimate that's longer than the expected I feel
  that others think that I'm lagging a lot behind everyone else.

This is all to common, if no-one will every give a longer estimate when looking at a problem in detail, then all estimate will tend to be too short.


text:
Q: Paypal Express Checkout Timeout Integrated with Paypal Express Checkout, the PHP SDK, tested in sandbox and worked fine, tested on live, worked fine.
Just got some notifications that payments were failing. As far as I was concerned things were working fine, nothing has changed, but now its stopped working :(
When I try it out I get a fatal error, and debugging returns:
[url:PPConnectionException:private] => https://api-3t.paypal.com/2.0/
[message:protected] => connect() timed out!

It is failing on SetExpressCheckout(), I have checked the API password and signature, which haven't changed since it was working. Nor has the code itself.
Bit annoyed as its NYE, my other halves birthday, and only a week ago we had our second child, so I am enjoying paternity leave and now have to deal with this :( I am stumped, any ideas?


text:
Q: Can't install the sherrif mod for Among us I have Among us v2020.12.5 under windows 10. I want to install the Sherriff mod, but I have no steam/steamapps folder anywhere on the machine. The docs and screenshots say it should be in my programs (x86), but it absolutely isn't. What is going on?

A: Go to your library on Steam, then right click Among Us. Go to Properties > Local Files. Click on Browse. It will open the folder where Among Us is installed, anywhere it is.
Steam/Steamapps is the usual place where Steam installs games, but if you switched the configuration it could be anywhere.
Microsoft Store:
If you bought the game via the Microsoft Store, your files are still there, just behind some Microsoft BS.

Installation Folder
Your Store downloads are in a hidden folder in Program Files > WindowsApps.
Open File Explorer and click on the Program Files folder. Click on the View tab. Check the box next to Hidden items.

https://www.majorgeeks.com/content/page/how_to_find_your_microsoft_store_downloads.html#:~:text=Your%20Store%20downloads%20are%20in,box%20next%20to%20Hidden%20items.
In fact, maybe you could make it work by right clicking the shortcut on the desktop, go to Properties, and the location might be in the Target field. Then copy the whole URL (Starting by a capital letter like C or E) until the last / before the .exe file, and paste that in Run. (Open the start menu, type run then enter). It should open the folder.


text:
Q: How to change HSV color to normal color code android? I need to set color to view background and created Gradient view, here I'm getting only hsv color value and I need convert that rgb. converted rgb but its always gives me black color only.
How can I change hsv color to rgb color code? its not applying to views in android. Please any suggestions?
public static String hsvToRgb(float H, float S, float V) {

    float R, G, B;

    H /= 360f;
    S /= 100f;
    V /= 100f;

    if (S == 0)
    {
        R = V * 255;
        G = V * 255;
        B = V * 255;
    } else {
        float var_h = H * 6;
        if (var_h == 6)
            var_h = 0; // H must be < 1
        int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
        // floor( var_h )
        float var_1 = V * (1 - S);
        float var_2 = V * (1 - S * (var_h - var_i));
        float var_3 = V * (1 - S * (1 - (var_h - var_i)));

        float var_r;
        float var_g;
        float var_b;
        if (var_i == 0) {
            var_r = V;
            var_g = var_3;
            var_b = var_1;
        } else if (var_i == 1) {
            var_r = var_2;
            var_g = V;
            var_b = var_1;
        } else if (var_i == 2) {
            var_r = var_1;
            var_g = V;
            var_b = var_3;
        } else if (var_i == 3) {
            var_r = var_1;
            var_g = var_2;
            var_b = V;
        } else if (var_i == 4) {
            var_r = var_3;
            var_g = var_1;
            var_b = V;
        } else {
            var_r = V;
            var_g = var_1;
            var_b = var_2;
        }

        R = var_r * 255; // RGB results from 0 to 255
        G = var_g * 255;
        B = var_b * 255;
    }

    String rs = Integer.toHexString((int) (R));
    String gs = Integer.toHexString((int) (G));
    String bs = Integer.toHexString((int) (B));

    if (rs.length() == 1)
        rs = "0" + rs;
    if (gs.length() == 1)
        gs = "0" + gs;
    if (bs.length() == 1)
        bs = "0" + bs;
    return "#" + rs + gs + bs;
}


text:
Q: Hybrid Pagination (Client + Server) side pagination using Backbone Backgrid I have a Marionette application which is using Backgrid control to fetch records from a backend API.
My requirement :

*

*While Bootstrapping fetch 100 records and split them into 5 pages of 20 each.

*For the first 5 pages implement Client side pagination i.e no call to backend.

*To load the next 100 records on the 6th page make a backend call to fetch the records.

Can this be achieved using the "infinite" mode setting in backgrid paginator?
Any suggestions will be helpful.


text:
Q: Is $x\in\{\{x\}\}$ Is $x\in\{\{x\}\}$. I understand that $x\in\{x\}\in\{\{x\}\}$ does this mean $x\in\{\{x\}\}$?
Very simple just unsure about the properties of $\in$, not looking for an extravagant answer, thanks in advance for the help.

A: The answer is no. $\{\{x\}\}$ has exactly one element, namely $\{x\}$.
In general, to test if $a\in b$, we do the following:

*

*Is $b$ a set?

*If so, is $a$ one of the elements in the set $b$?
$a$ can be a set itself, or not, doesn't matter.

A: The answer is no. Good analogy is list in programming language Python.


text:
Q: Excel Array Filter I have data in four columns in Excel. Column three ("C") contains a string which has a country name, e.g "The name of the country is China". The string is not standardized hence I am unable to use string functions like left/right/mid. I am creating a macro to filter six countries (Egypt, USA, China, Russia, Japan and Uganda). So far I can get two countries using the following macro:
Sub Countries ()
   Activesheet.Range("A1:D1000").Autofilter Field:=3, Criteria1:=Array("*Japan*","*China*"),Operator:=xlFilterValues
End Sub

This is working and I am able to get the two countries filtered. However when I add more countries the Excel does not bring up the countries and returns no rows.
I am not sure what I am not doing right and I am hoping someone can help me please

A: you could loop through countries:
Option Explicit

Sub main()
    Dim filter As Variant
    Dim countriesRng As Range

    Set countriesRng = Range("A1") ' initial dummy range to use Union() without checking for 'countriesRng' being 'Nothing'
    With Range("A1:D" & cells(Rows.Count, "C").End(xlUp).row) ' reference columns A:D from row 1 down to column C last not empty row
        For Each filter In Array("Egypt", "USA", "China", "Russia", "Japan", "Uganda") ' loop through countries
            .AutoFilter Field:=3, Criteria1:="*" & filter & "*" ' filter current country
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then Set countriesRng = Union(countriesRng, .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible)) ' if any filtered cells other than header then add them to 'countriesRng'
        Next
       .parent.AutoFilterMode = False

        Set countriesRng = Intersect(countriesRng, Range("C:C")) ' get rid of the initial dummy range
        If Not countriesRng Is Nothing Then ' if any filtered country
            .Resize(.Rows.Count - 1).Offset(1).EntireRow.Hidden = True ' hide all records
            countriesRng.EntireRow.Hidden = False ' unhide ones with filtered countries
        End If
    End With
End Sub


text:
Q: Multiple apps in one project or one project per app in Firebase? I have, at the moment 2 android apps in which I want to add notifications and maybe ads and analytics, using Firebase, since it's free and easy to implement.
I see that I have 2 options:

*

*Create a new project with my company's name and add the 2 apps in there

*Create 2 projects, each with app's name and on each of them add the related apps.

Which one would be the correct approach and why?
Thank you.

A: Don't mean to be flippant, but the answer is "it depends" :-)
A canonical way of setting up a Firebase project is to have it correspond to a "logical app", and create separate Firebase apps for the Android or iOS or web versions.
I'd not personally put a grab bag of unrelated apps into the same Firebase project, but your mileage may vary.
Depending on what you want to do, it might make sense to group related (but logically different apps) under the same Firebase project. But note that that has implications on how your apps would interact with the Firebase features.
For example, all apps in the same Firebase project would share the same logical Firebase database instance (with the same hostname / end-point).
You would probably want to go through the various features that you plan to use and make sure that the organizational structure satisfies the way you plan to use the platform features.


text:
Q: Countability of the continuum I googled the word countability of continuum and the first result (Ok, second to this thread!) was from Arxiv.
I was wondering how valid this argument is.
I would also appreciate any additional comments on this paper.
Thank You.

A: Not to put too fine a point on it, the paper is rubbish.
In Proposition 2.2 the author confuses the set of nodes of his tree, which has cardinality $\aleph_0$, with the set of branches through the tree, which has cardinality $10^{\aleph_0}$; because he mistakenly thinks that these are the same set, he mistakenly concludes that $\aleph_0=10^{\aleph_0}$. Proposition 2.3 is merely a restatement of the same error in a very slightly different guise.
In his argument for Proposition 3.1 he (mostly) establishes an injection from the set of real numbers to the set of branches of his tree, but (as he himself acknowledges in the argument for Lemma 3.1) this is not a bijection, since a real number may correspond to more than one branch of the tree. (The assertion on page $4$ that $3.1415926$ 'is the number $\pi$' is of course false, since $\pi$ is irrational and therefore does not have a finite decimal expansion.)
Proposition 3.2 is yet another instance of his inability to distinguish the nodes of a tree from its branches. The rest of the paper is just more of the same.

A: The arguments given in the paper for the claims supposedly proved are nonsense. Moreover, as the author says in the beginning, Cantor proved that $\mathbb N$ and $\mathbb R$ have different cardinalities. So, in fact, if the author did prove what he claims (which he did not, but never mind) then unless he can demonstrate that all of the proofs of the uncountability of the reals (and there are several, essentially different ones) then the author establishes the inconsistency of mathematics by proving a contradiction. Needless to say, he did not do that.

A: This is one of the common false proofs that $\mathcal P(\Bbb N)$ is countable, we forget that there are subset of $\Bbb N$ which are infinite, and that their complement is infinite as well.
If we think of the full binary tree of height $\omega$ (i.e. every finite height is realized, and no point has infinitely points below it), then $\mathcal P(\Bbb N)$ corresponds to the branches of the tree, and not the vertices of the tree.
The paper constructs a rooted tree where every point has $10$ successors, and the tree has height $\omega$. Then he claims that the real numbers correspond to the vertices, rather than the branches (do note that some numbers can be represented by two branches, but that's not a big deal for now).
Of course this is false, as Brian points out, $\pi$ cannot be represented by a vertex and only by a branch.


text:
Q: How to use awk to print specific string n time? For example:
cat file.txt| awk -F "\t" '{print $1}' | tr '\n' '\t' | awk -F "\t" '{print "Data_type" "\t" "Fraction \t" "Read \t" $1}'

I wanted to print "Fraction\t" "Reads \t" five times before $1.
Thanks!!!

A: Don't use cat + awk, simply use awk See Useless Use of cat
What is wrong with awk '{print "Fraction\t Reads \t Fraction\t Reads \t Fraction\t Reads \t Fraction\t Reads \t Fraction\t Reads \t" $1}' file.txt ?


text:
Q: Making the nao robot say something that is stored in a variable using python I am making a Luis (Microsoft AI) and Nao linkage so when I ask my Nao robot something he can send the request to Luis and tell me an answer. But for that I have an answer that I store in a variable (lets call it answerL) and I want Nao to say what is in this answer with a python script since all the program is in Python. I didn't found anything in the Aldebaran documentation to do that with the "say" command from the ALTextToSpeechProxy. Is there another way or did I miss something ?
Thanks
L

A: From documentation Making NAO Speak
from naoqi import ALProxy
tts = ALProxy("ALTextToSpeech", "<IP of your robot>", 9559)
tts.say("Hello, world!")

You simply pass the words you want spoken as a string to tts.say
So assuming that Microsoft Luis bot gives you some result/answer as a string, just call the say method with that string as an argument.
answer = MadeUpLiusAPI.get_answer("some question")
tts.say(answer)


text:
Q: How do I get a single level of object details from php? When I retrieve a stacktrace in php using debug_backtrace, I can have it include the object it was called from. Being able to see both the public and private properties of the object is extremely useful to me, however the object is too big to be usable. Due to some of the variables in it containing other objects, simply printing it out is not feasible - I tried writing the output of debug_print_backtrace to a file, and it reached 23G before something broke and it stopped outputting.
What I really need, is to get this output to limit itself to going one level deep - that is, to output all the properties of the object, but if one of those is another object, instead of further listing out that one all I need is the class name for it.
I know I can use get_object_vars to get the public properties of the object, but how do I get the private ones? print_r, var_export, var_dump, etc. are all useless, because I can't stop them recursing.

A: You can iterate through object simply with foreach loop, as:
foreach($object as $property => $value)
   if (is_object($value))
      echo(get_class($value)."
");
   else
      echo($property." => ".$value."
");

Bear in mind though, that this will not show private properties.
A broader explanation on how you can got over that can be found here: http://www.php.net/manual/en/language.oop5.iterations.php

A: You can cast objects to arrays, then iterate over the array. Private and protected properties are available too, prefixed with the class name enclosed with null-bytes. You can test this behaviour like so:
Test:
class Test
{
    private $parent;
    public function __construct($parent) {
        $this->parent = $parent;
    }
}

$test = new Test(new Test(new Test(null)));
var_dump((array)$test);

Output:
array(1) {
  ["�Test�parent"]=>
  object(Test)#2 (1) {
    ["parent":"Test":private]=>
    object(Test)#3 (1) {
      ["parent":"Test":private]=>
      NULL
    }
  }
}

Now that you have an array you can do a simple foreach, stripping the prefixes and differentiating between objects and other variables:
foreach((array)$test as $name => $property) {
    if (ord($name[0]) === 0) {
        $name = substr($name, strrpos($name, "\x0")+1);
    }
    echo $name, ":";
    if (is_object($property)) {
        echo "(object)", get_class($property);
    } else {
        echo var_export($property, true);
    }
    echo "\n";
}

I'll leave the pretty-printing up to you.


text:
Q: How can I resolved Unresolved inclusion: ? I am a green hands about mongoc. My mongo-c-driver is 1.6.3, and I want to do some operation to mongodb database, like create, update, insert and delete. But there are problems as shown below. My eclipse CDT contains the header file (path:/usr/local/include), but the IDE still cannot find them:
unresolved inclusion:<mongoc.h>

Can somebody give me some advice?
I installed the mongo-c-driver manually, without using the package manager.

A: The command pkg-config outputs a flag to search at the path where the header is (not sure about the library name you must provide: check with your package manager):
$ pkg-config --cflags libmongoc
-I/usr/local/include/libmongoc-1.0/

If you use gcc, your compilation line must look like:
gcc `pkg-config --cflags libmongoc` file.c

If you use an IDE, find the way to provide this for the compilation. This is the best way to do it because if you update the library, or if you give the project to someone with a different emplacement of the headers, your project will keep to compile correctly.
Because you installed the library manually, you must

*

*either install the libmongoc.pc file into the right place (man pkg-config for more information);

*either put the flag manually: gcc -I/usr/local/include/libmongoc-1.0 file.c. The syntax -I/some/path given to the compiler means: search the header files in this place. Modify the project configuration in the IDE accordingly.

A: The include file is in "/usr/local/include/libmongoc-1.0/" but you've told Eclipse to look in "/usr/local/include/", so naturally it won't find it.
You can either add "/usr/local/include/libmongoc-1.0/" as an include path or change what you include to <libmongoc-1.0/mongoc.h>. The former is probably the more sensible option as it'll be easier to change the include path in the future than all the places where you do the include.

A: Thanks goodness! I have solved it.  No matter where you configure the mongo-c-driver, like /usr, /usr/local, or /usr/local/xxx(any name), you can find that the mongoc.h and others header files are all under libmongoc-1.0 folder, you should copy all the header file(xxxx.h)out of the libmongoc-1.0 folder and under include folder and that is will be ok. Good luck to everyone who encounter the same problem with me.


text:
Q: What does master tag mean in history for Git in Visual Studio 2019? I am using Visual Studio 2019 Community Edition for an asp.net project with Azure DevOps Git as the source control. I have been using this source control without issues for the past month.
But today, when I clicked on Commit and Push drop-down button in the Changes tab of Team Explorer then on viewing the history of project it showed a master tag for most recent commit/push that I had just made as shown in the screenshot below.

Question
Why did the master tag suddenly appear for most recent commit/push and what does it mean? I had not input any tag for this commit/push but this was added by Azure DevOps automatically. Such a master tag never shows for any of the prior commits in the past month.
I have only 2 Git branches in my project -  a local branch origin/master and a remote branch origin/master as in the screenshot below.

A: This is not a tag.  It is letting you know that's the commit to which the master branch currently points.
The toolbar in the History window has three buttons on it where you can toggle seeing local branches, remote tracking branches, and tags labeled onto the corresponding commits.  By default, branches are rendered red and tags are green.  Hovering the mouse over the label should also tell you if it's a branch or tag.  In your example above, I believe the tooltip would say "Head for branch master".
Hope this helps.

A: A tag named master does not mean anything.  But by the same token, the branch name master does not mean anything either.  The meaning, if there is one, is whatever you think it is.
It's unwise to use the same name for a branch and a tag.  Git handles this just fine, but humans get confused.
Lightweight tags have no additional information, but annotated tags record the person who creates them, in much the same way that commits record the person who creates them.  If this is an annotated tag, inspect it—git show refs/tags/master will do the trick for instance1—and then ask the person who created it what they thought they were doing and what name they'd like you to use instead, and then rename or delete the tag.  (If the person turns out to be you, ask yourself why you did that. :-) )

1Actually, so will git show master: some Git commands, including git show, "prefer" the tag when it's ambiguous like this.  Note that git checkout effectively prefers the branch though.  That's why people get confused: they don't know whether master means refs/heads/master or refs/tags/master.


text:
Q: Unable to update appRoles in azure manifest I'm unable to add new roles to my application manifest file in azure. Getting some random error
"Error detail: The client ID provided could not be found. [LLn0W]".
After some research, I came to know that only global/directory admins can update manifest file. My question is, why is it restricted to only admins? Why not enabled for application owners?

A:
After some research, I came to know that only global/directory admins
  can update manifest file.

If you are the owner of the app and not an admin in the Azure AD, you also have the privilege to edit the approle in the manifest. For normal users, not an owner or admin, they will have no sufficient privilege to make it.

A:
My question is, why is it restricted to only admins? Why not enabled
  for application owners?

If you are owner of the application, you are able to add new roles to your application manifest.
I am in my AD with User role.

When I try to edit the manifest of an application which I am not an owner of it. It told me that I do not have insufficient permission.

Then I use admin account grant me the owner role for this application. Now I can add approles successfully.


text:
Q: Get raw data from Http Request? I want to save the raw, full data of an HttpRequest. At the moment I have this:
Request.ContentEncoding.GetString(Request.BinaryRead(int.MaxValue));

But this only gets the body of the HttpRequest. I also want to get the headers. In the raw form, http requests are transfered as header fields followed by the body, so it should be possible to get the raw text representation of the whole request, but I can't work out how.

A: You can pull them out of the Headers property (Apologies for this being kind of an obvious suggestion). It may not be as convenient as "give me everything in raw format", but it's code you will only have to write once.


text:
Q: How is the data generated for a double in webassembly? In Webassembly the following:
double x = 1;

Is analog to this WAST:
(module
  (table 0 anyfunc)
  (memory $0 1)
  (data (i32.const 16) "\00\00\00\00\00\00\f0?")
  (export "memory" (memory $0))
)

I already figured out how it works with integers (by using hex numbers) but what I see for doubles isnt the usual hex im familiar with.
For example an integer of 15 is equivalent to: "\0f\00\00\00" which I understand but how does it work for doubles. What kind of hex is it and what defines the offset inside the data section?
I am using https://mbebenita.github.io/WasmExplorer/ for testing purposes.

A: WebAssembly uses IEEE-754 to encode f32 and f64.
The data section is being initialized with "\00\00\00\00\00\00\f0?" which is ASCII-encoding. That's just what the author of s-expressions chose to use, in the actual binary it's encoded as 4 or 8 bytes (for f32 versus f64). We could also use hex-float as C / C++ support, we just need a lossless encoding (and hex-float is lossy with NaNs). Another option is base64, or raw hex, or whatever. The data section doesn't care what datatype it contains: in the binary format it's all just bytes. So we're not really encoding floating-point values or integers, just bytes.
This decodes to hex 3FF000000000. Why? There's a ? at the end, its ASCII value is 3F. Then you have all the escaped ASCII values which don't have nicer representations so the escape encoding is used. It's really not a great representation!
What does this mean? Try out this tool to understand IEEE-754 encoding!
Binary64: 3FF0000000000000
Status  Sign [1]    Exponent [11]   Significand [52]
Normal  0 (+)       01111111111 (0) 1.0000000000000000000000000000000000000000000000000000 (1.0)

So sign is positive, exponent is 0, and significand is 1.0. That's value 1.0 in IEEE-754.


text:
Q: Choropleth boundary colour change in QGIS? How do you change the colour of the boundaries between areas on a choropleth map in QGIS 2.18 Mac version?

A: In the "symbology" tab, you can select all of the classes and select "change symbol". There you can change the color and size of the outline for all of the classes.


text:
Q: Getting the number of arrays within an Object I have an object which contains multiple arrays. I need to know the number of arrays in this object.
This is the code which creates the map object:
function parseXML(xData, Status){
  var map = {}; //init the map
  var web = $(xData.responseXML).find("Web");
  for (var i = 0; i < web.length; i++) {
  //we create a index for our links based on the depth of them by `/`
    var m = web[i].attributes['Url'].value.substring(23, web[i].attributes['Url'].value.length).split('/').length;

    map[m] = map[m] || []; //make sure we leave alone the old values if there is none init with new array
    map[m].push(web[i].attributes['Url'].value); //push new value to node
  }
  console.log(map);
  createNav(map);
}

I've tried:
console.log('there are '+map.length+"levels in this site"); but I get map.length = undefined.

A: map.length = 0;
for (item in map) {
    if (map.hasOwnProperty(item) && map[item] instanceof Array) {
        map.length++
    }
}


text:
Q: Use a UIView as the background of a UIButton? I have a UIButton.  Rather than giving it a background Image, I want to use a custom UIView object as the background.  I realize I could do this by rendering the UIView into an image, then using that.  But is there a better way?
I've looked at playing with the Button's view tree, but that seems to have undesirable side effects.

A: To achieve the same, I usually do this:
Add subview to the parentView
Add a UIButton with clearColor to the parentView, with the same frame as the subview.
You can achieve the same by creating a custom UIView class that has this view and button as its properties.

A: If you want to use a UIView as a button, you should just add a tap gesture recognizer to the UIView and use that.  Is there something specific you're looking for?


text:
Q: chainsubstitution: which rule can detect the last character? In the following MWE, I want to replace all ſ by s if they are at the last position of a line or document or some place where there is no next character.
I added two rules to show that it works for other places, but I can't think of a rule when the ſ is at the end. The rule having after = {{ 0x0000 }}, was my guess, but it doesn't work.
Here is a reference for chainsubstituion.
Compilation using lualatex mwe.tex
\documentclass[a4paper]{article}
\usepackage{fontspec}

\directlua
{
    fonts.handlers.otf.addfeature {
        name = "chainrounds",
        type = "chainsubstitution",
        lookups = {
            {
                type = "substitution",
                data = {
                    [0x017F] = "s",
                },
            },
        },
        data = {
            rules = {
                {
                    before = {{ "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "t", "v", "w", "x", "z" }},
                    current = {{ 0x017F }},
                    after = {{ 0x017F }},
                    lookups = { 1 },
                },
                {
                    current = {{ 0x017F }},
                    after = {{ "b", "d", "f", "g", "h", "j", "k", "l", "m", "n", "q", "r", "v", "w", "x", "z", 0x00DF, 0x0020 }},
                    lookups = { 1 },
                },
                {
                    current = {{ 0x017F }},
                    after = {{ 0x0000 }},
                    lookups = { 1 },
                },
            },
        },
    }

}

\begin{document}

    \setmainfont[
        RawFeature={+chainrounds},
    ]{XITS-Regular.otf}

    OK: gſſe eſg

    For the following I cannot find a rule:
    wanted is a \texttt{s} when a \texttt{ſ} is typed but the character is the last in the line/document: ſ

\end{document}

A: General answer

*

*From my tests, I assume that a general way to detect first and last character using such rules is not possible. In complex cases it requires multiple font features in a row, each one added in order like RawFeature={+featurename1,+featurename2,+featurename3} to get the wanted result, where each possible type is defined in the manual linked in the question and where the chained features can be of same or different type.

*A complex rule would be to check all expected neighbours of ſ like eſ, iſ, oſ, sſ and create a specfic rule that matches before the more general rule "match only ſ". The more general rule would then in praxis be the end of the string/start of string if the rules are good enough.

*Since I'm not sure if this is the correct answer, I let it open.

Workaround for my use case
Thanks to the hint by Jasper (replacing first all the ſ by s so we then have the impossible positions already correct) I could make up a solution by combining

*

*substitution

*chainsubstitution
the order probably matters.

*

*replace all ſ by s without limitations.

*replace all s by ſ but with limitations (where it is possible)

*now we still have too many ſ in the string so filter out some more with checking before, current and after.

*filter out some more ſ by checking only current and after.

The current code needs some tweaking but the main problem is fixed.
\documentclass[a4paper]{article}
\usepackage{fontspec}

\directlua{
    fonts.handlers.otf.addfeature
    {
        name = "subfirststep",
        type = "substitution",
        data =
        {
            [0x017F] = "s",
        },
    }

    fonts.handlers.otf.addfeature {
        name = "chainrounds",
        type = "chainsubstitution",
        lookups = {
            {
                type = "substitution",
                data = {
                    [0x017F] = "s",
                },
            },
            {
                type = "substitution",
                data = {
                    ["s"] = 0x017F,
                },
            },
        },
        data = {
            rules = {
                {
                    current = {{ "s" }},
                    after = {{ "a", "c", "e", "i", "o", "p", "t", "u", "y", 0x00E4, 0x00F6, 0x00FC }},
                    lookups = { 2 },
                },
                {
                    before = {{ "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "t", "v", "w", "x", "z" }},
                    current = {{ 0x017F }},
                    after = {{ 0x017F }},
                    lookups = { 1 },
                },
                {
                    current = {{ 0x017F }},
                    after = {{ "b", "d", "f", "g", "h", "j", "k", "l", "m", "n", "q", "r", "v", "w", "x", "z", 0x00DF, 0x0020 }},
                    lookups = { 1 },
                },

            },
        },
    }

}

\begin{document}

    \setmainfont[
        RawFeature={+subfirststep,+chainrounds},
    ]{XITS-Regular.otf}

    OK: gſſe eſg

    ſa

    ſ ſ

\end{document}


text:
Q: Count number of tails since the last head Consider a sequence of coin tosses: 1, 0, 0, 1, 0, 1 where tail = 0 and head = 1.
The desired output is the sequence: 0, 1, 2, 0, 1, 0
Each element of the output sequence counts the number of tails since the last head.
I have tried a naive method:
def timer(seq):
    if seq[0] == 1: time = [0]
    if seq[0] == 0: time = [1]
    for x in seq[1:]:
        if x == 0: time.append(time[-1] + 1)
        if x == 1: time.append(0)
    return time

Question: Is there a better method?

A: Using NumPy:
import numpy as np
seq = np.array([1,0,0,1,0,1,0,0,0,0,1,0])
arr = np.arange(len(seq))
result = arr - np.maximum.accumulate(arr * seq)
print(result)

yields
[0 1 2 0 1 0 1 2 3 4 0 1]

Why arr - np.maximum.accumulate(arr * seq)? The desired output seemed related to a simple progression of integers:
arr = np.arange(len(seq))

So the natural question is, if seq = np.array([1, 0, 0, 1, 0, 1]) and the expected result is expected = np.array([0, 1, 2, 0, 1, 0]), then what value of x makes
arr + x = expected

Since
In [220]: expected - arr
Out[220]: array([ 0,  0,  0, -3, -3, -5])

it looks like x should be the cumulative max of arr * seq:
In [234]: arr * seq
Out[234]: array([0, 0, 0, 3, 0, 5])

In [235]: np.maximum.accumulate(arr * seq)
Out[235]: array([0, 0, 0, 3, 3, 5])

A: Step 1: Invert l:
In [311]: l = [1, 0, 0, 1, 0, 1]

In [312]: out = [int(not i) for i in l]; out
Out[312]: [0, 1, 1, 0, 1, 0]

Step 2: List comp; add previous value to current value if current value is 1.
In [319]: [out[0]] + [x + y if y else y for x, y in zip(out[:-1], out[1:])]
Out[319]: [0, 1, 2, 0, 1, 0]

This gets rid of windy ifs by zipping adjacent elements.

A: Using itertools.accumulate:
>>> a = [1, 0, 0, 1, 0, 1]
>>> b = [1 - x for x in a]
>>> list(accumulate(b, lambda total,e: total+1 if e==1 else 0))
[0, 1, 2, 0, 1, 0]

accumulate is only defined in Python 3. There's the equivalent Python code in the above documentation, though, if you want to use it in Python 2.
It's required to invert a because the first element returned by accumulate is the first list element, independently from the accumulator function:
>>> list(accumulate(a, lambda total,e: 0))
[1, 0, 0, 0, 0, 0]

A: The required output is an array with the same length as the input and none of the values are equal to the input. Therefore, the algorithm must be at least O(n) to form the new output array. Furthermore for this specific problem, you would also need to scan all the values for the input array. All these operations are O(n) and  it will not get any more efficient. Constants may differ but your method is already in O(n) and will not go any lower.

A: Using reduce:
time = reduce(lambda l, r: l + [(l[-1]+1)*(not r)], seq, [0])[1:]

A: I try to be clear in the following code and differ from the original in using an explicit accumulator.
>>> s = [1,0,0,1,0,1,0,0,0,0,1,0]
>>> def zero_run_length_or_zero(seq):
    "Return the run length of zeroes so far in the sequnece or zero"
    accumulator, answer = 0, []
    for item in seq:
        accumulator = 0 if item == 1 else accumulator + 1
        answer.append(accumulator)
    return answer

>>> zero_run_length_or_zero(s)
[0, 1, 2, 0, 1, 0, 1, 2, 3, 4, 0, 1]
>>>


text:
Q: vba - copy first row from another sheet, and put it as a dropdown menu in current I would like to make something like that:
in one file I have a table, with many columns, and the first cell of each column is the title.
now, I want to grab those column's titles, and put them in another file as a dropdown menu, which the user can select (so he can select which column he would like to see).
any ideas on how can I do it?
Thanks

A: ok I did something, isn't most elegant but works fine, with a bit of tweeking:
    Set s_wbk = Workbooks.Open(strFile)
    For i = 1 To 4
        strData = strData & "," & s_wbk.Sheets("Sheet1").Cells(1, i).Value
    Next i
    s_wbk.Close

    formattedData = Split(strData, ",")
    firstCell = "E1"
    lastCell = "E" & (UBound(formattedData) - 1)
    For i = 1 To UBound(formattedData)
        Cells(i, 5).Value = formattedData(i)
    Next i

    ActiveSheet.Shapes.Range(Array("Drop Down 3")).Select
    With Selection
        .ListFillRange = firstCell & ":" & lastCell
        .LinkedCell = ""
        .DropDownLines = 8
        .Display3DShading = False
    End With
    Range("D8").Select


text:
Q: issue when invoking findObjectsInBackGroundWithBlock() with Parse in iOS Using Parse in my project, i have this line
query.findObjectsInBackgroundWithBlock({ (objects:[PFObject], error:NSError) -> Void in      })

But Xcode keeps telling me :
cannot invoke this method with an argument list `([PFObject],NSError)`.

Any idea why??

A: Instead of at the end of each parameter having an exclamation point at the end of it, change the ! to a ? So it would be
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in

That was what I tried and it seemed to work.

A: The 2 closure parameters are both optionals, declared as implicitly unwrapped:
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]!, error: NSError!) -> Void in
                                                              ^                ^

Also, I think that the first argument should be [AnyObject]! and not [PFObject]! - not sure, so I suggest you to verify that.


text:
Q: Notification addAction creates button with no behavior I am trying to add a button to my notification in android.
I use the addAction method in order to add an intent which supposes to open up the main activity (same as clicking the entire notification) but with an extra bundle with data.
this is what I have done so far:
notificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

//regular intent to view main activity
PendingIntent contentIntent = PendingIntent.getActivity(this,Constants.MAIN_ACTIVITY,
                              new Intent(this, MainActivity.class), 0);

//intent for viewing transaction dialog, within main activity using PURCHASE_DIALOG request code
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.LIST, (java.util.ArrayList<? extends android.os.Parcelable>) list);
PendingIntent purchaseIntent = PendingIntent.getActivity(
                               this, Constants.PURCHASE_DIALOG,
                               new Intent(this, MainActivity.class), 0, bundle);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(Constants.NOTIFICATION_TOPIC)
                        .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(watchResponse.toString()))
                        .setAutoCancel(true)
                        .addAction(R.drawable.ic_launcher, "Buy", purchaseIntent)
                        .setContentText(message);

mBuilder.setContentIntent(contentIntent);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());

I simply expect that my onResume in MainActivity class will be called once clicking the extra action, and there i'll be able to get the bundle trough getIntent(), yet nothing happens when I click on it. the button is clicked, but the activity remains open and my application activity wont start.

A: I had a very similar issue but a very different solution. Pending intent is also not fired if you have declared <service android:enabled="false"></service> in your manifest.xml file.
Replace from android:enabled="false" to android:enabled="true"
This might not be a direct issue of the problem. But if you create the service in android studio using default template it automatically adds these properties to the service.
If this does not work there is a similar question you can find here:
Android Notification Action is not fired (PendingIntent)


text:
Q: Creating a sparse matrix from a TermDocumentMatrix I've created a TermDocumentMatrix from the tm library in R. It looks something like this:
> inspect(freq.terms)

A document-term matrix (19 documents, 214 terms)

Non-/sparse entries: 256/3810
Sparsity           : 94%
Maximal term length: 19
Weighting          : term frequency (tf)

Terms
Docs abundant acid active adhesion aeropyrum alternative
  1         0    0      1        0         0           0
  2         0    0      0        0         0           0
  3         0    0      0        1         0           0
  4         0    0      0        0         0           0
  5         0    0      0        0         0           0
  6         0    1      0        0         0           0
  7         0    0      0        0         0           0
  8         0    0      0        0         0           0
  9         0    0      0        0         0           0
  10        0    0      0        0         1           0
  11        0    0      1        0         0           0
  12        0    0      0        0         0           0
  13        0    0      0        0         0           0
  14        0    0      0        0         0           0
  15        1    0      0        0         0           0
  16        0    0      0        0         0           0
  17        0    0      0        0         0           0
  18        0    0      0        0         0           0
  19        0    0      0        0         0           1

This is just a small sample of the matrix; there are actually 214 terms that I'm working with. On a small scale, this is fine. If I want to convert my TermDocumentMatrix into an ordinary matrix, I'd do:
data.matrix <- as.matrix(freq.terms)

However the data that I've displayed above is just a subset of my overall data. My overall data has probably at least 10,000 terms. When I try to create a TDM from the overall data, I run an error:
> Error cannot allocate vector of size n Kb

So from here, I'm looking into alternative ways of finding efficient memory allocation for my tdm.
I tried turning my tdm into a sparse matrix from the Matrix library but ran into the same problem.
What are my alternatives at this point? I feel like I should be investigating one of:

*

*bigmemory/ff packages as talked about here  (although the bigmemory package doesn't seem available for Windows at the moment)

*the irlba package for computing partials SVD of my tdm as mentioned here
I've experimented with functions from both libraries but can't seem to arrive at anything substantial. Does anyone know what the best way forward is? I've spent so long fiddling around with this that I thought I'd ask people who have much more experience than myself working with large datasets before I waste even more time going in the wrong direction.
EDIT: changed 10,00 to 10,000. thanks @nograpes.

A: The package qdap seems to be able to handle a problem this large.  The first part is recreating a data set that matches the OP's problem followed by the solution.  As of qdap version 1.1.0 there is compatibility with the tm package:
library(qdapDictionaries)

FUN <- function() {
   paste(sample(DICTIONARY[, 1], sample(seq(100, 10000, by=1000), 1, TRUE)), collapse=" ")
}

library(qdap)
mycorpus <- tm::Corpus(tm::VectorSource(lapply(paste0("doc", 1:15), function(i) FUN())))

This gives a similar corpus...
Now the qdap approach.  You have to first convert the Corpus to a dataframe (tm_corpus2df) and then use the tdm function to create a TermDocumentMatrix.
out <- with(tm_corpus2df(mycorpus), tdm(text, docs))
tm::inspect(out)

## A term-document matrix (19914 terms, 15 documents)
##
## Non-/sparse entries: 80235/218475
## Sparsity           : 73%
## Maximal term length: 19
## Weighting          : term frequency (tf)


text:
Q: Why do explosive rockets claim to do less damage? According to the in-game stats and all the wikis I've found, the two types of rockets are:

Rocket
   Damage: 60 Explosion
Explosive rocket
   Damage: 40 Explosion

Why would I want to research and craft explosive rockets, if they do less damage? It sounds like perhaps explosive rockets have a bigger blast radius, but nobody's actually said that.

A: Regular rockets do their 60 damage to a single target. Explosive rockets do 40 damage to everything in a circle centered on the target (there is no falloff). While this allows doing much more total damage, it can hit things you don't want to hit, and is not more effective against a single enemy.
The pictured test (current "stable" version, 0.10.12) shows that that the radius of the explosion is apparently 6 tiles. All of the pipe sections took exactly 40 damage.

(Note that unlike the shotgun, rockets cannot be fired in an arbitrary direction; you must target an object.)


text:
Q: Random binary matrix with row and column sum constraints My objective is to create:

*

*a randomly populated matrix with entries either 0 or 1. In this particular case, the matrix is 4x24.

*The row sum of each of the 4 rows is exactly 6.

*The column sum of each of the 24 columns is exactly 1
Call the desired matrix M.
Another way of looking at M:

*

*There are exactly 24 entries equal to 1.

*No column has more than one 1 entry.

Progress:
There are 6 spots on each row with a 1 entry.  The rest are zero, the matrix is sparse. With 4 rows, this means that M can be uniquely determined by a matrix of indices that stores the locations of the 1 entries. Call this matrix of indices indexM.
I populated indexM with the numbers 1:24 sampled without replacement:
set.seed(30592)
colNum <- 24
rowSum <-6
numZeros <- colNum-rowSum

OneRow<-c(rep(1,rowSum),rep(0,numZeros))

indexM<-matrix(sample(1:24,replace=FALSE),
                    nrow=4,ncol=6,byrow=TRUE)

For the given seed, the matrix is: https://pastebin.com/8T21MiDv .
How do I turn indexM into the desired sparse matrix?
I found the sparseMatrix in the Matrix library, but it wants a vector or row indices and another vector of column indices, which is not what I have.
Thank you.

A:
I found the sparseMatrix in the Matrix library, but it wants a vector or row indices and another vector of column indices, which is not what I have.

The constraints impose that...

*

*row indices are rep(1:4, 6)

*col indices are 1:24
The match between row and col indices is randomized. We can...
library(Matrix)

# fix rows, jumble cols
sparseMatrix(rep(1:4, each=6), sample(1:24))

# fix cols, jumble rows
sparseMatrix(sample(rep(1:4, each=6)), 1:24)

# jumbl'm all
sparseMatrix(sample(rep(1:4, each=6)), sample(1:24))

any of which will return something like
4 x 24 sparse Matrix of class "ngCMatrix"

[1,] . . . . | | . . | . . . | | . | . . . . . . . .
[2,] . | | . . . | . . | . . . . . . . . | . . . | .
[3,] . . . | . . . | . . | | . . . . | . . . | . . .
[4,] | . . . . . . . . . . . . . | . . | . | . | . |


text:
Q: Connecting to Oracle from ASP.NET I am on a Windows 8.1 x64 machine and trying to connect to my locally installed Oracle 11g database through an ASP.NET WebForms 4 application that I am running from Visual Studio 2013 and IIS Express.
I downloaded ODP.NET from this NuGet package. But I keep getting the error Could not load file or assembly or one of its dependencies. An attempt was made to load a program with an incorrect format.
Someone please help me troubleshoot this problem. There so little source code and sample out there regarding Oracle and .NET that is up to date.

A: This usually happens when referencing an assembly that is either 32-bit from a 64-bit application or the inverse.  Please make sure you're WebForm project is targeting the same platform as the referenced Oracle assembly.

A: Quote from the page you downloaded your Oracle.DataAccess.dll:

Oracle will still need to be installed on the production or development machine in order to connect to Oracle (those libraries are greater than 100MB in size, so it didn't make sense to include them in a NuGet package), but this package will at least allow the project to be successfully built

So now you can only build your code, not run it. To run it you should get: 64-bit ODAC 11.2 Release 5 (11.2.0.3.20) for Windows x64 from this Oracle page: http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html
Your ASP.NET if installed so after your download and install it run command like this:
C:\oracle\product\11.2.0\client_1\odp.net\bin\4> OraProvCfg  /action:gac  /providerpath:"C:\oracle\product\11.2.0\client_1\odp.net\bin\4\Oracle.DataAccess.dll"

(assuming your install directory will be C:\oracle\product\11.2.0\client_1\)


text:
Q: Asking about sufficiency of a document I want to ask about sufficiency of a document. Is this sentence applicable?

Can an English abstract be enough?

Is it better to use "could" instead of "can"?

A: It depends on what you are trying to get at. Either "can" or "could" are basically saying the same thing. They are asking if there is any possible situation in which an abstract is enough. That is, is there some set of circumstances that might or might not apply to the current situation when the abstract is enough?
Possibly you want to ask if an abstract is sufficient in this particular case. In that case,  you want to say "Would an English abstract be enough?"