text:
Q: Getting value from IEnumerable collection There are some problems here:
1) Firstly, I've a property in Class1
class Class1
{
    IEnumerable itemSource;

    public IEnumerable ItemSource
    {
        set { itemSource = value; }
        get { return itemSource; }
    }
}

2) a class named TempClass
public class TempClass
{
    int a;
    public int A
    {
        set { a = value; }
        get { return a; }
    }

    public TempClass() { }
    public TempClass(int t) { A = t; }
}

3) In static void Main(string[] args), I tried to this:
ObservableCollection<TempClass> test = new ObservableCollection<TempClass>
{
    new TempClass(1),
    new TempClass(2),
    new TempClass(3)
}

Class1 class1 = new Class1();
class1.ItemSource = test;

foreach (var item in class1.ItemSource)
{
    Console.WriteLine(item);
}

4) Then, the console shows this:
testSolution.TempClass
testSolution.TempClass
testSolution.TempClass

where testSolution is my solution name, so is a name of the namespace.
I want to get values: 1, 2, 3.
Here, what I want to make is a property and method that show values of any collection or list of any class type.
In this case, ItemSource property and method that has:
foreach (var item in class1.ItemSource)
{
    Console.WriteLine(item);
}

How to do it?

A: This may need modification, am just laying out an idea on how to use reflection when the type and properties are unknown. I did not test this code,so feel free to modify
foreach(var objUnknown in ItemSource) {
    foreach(var prop in objUnknown.GetType().GetProperties()) {
        Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(objUnknown, null));
   }
}

A: Try this :
foreach (var item in class1.ItemSource)
{
    Console.WriteLine(((TempClass)item).A);
}

Second option is, Overriding as the other answer suggests, change the class definition as like this :
public class TempClass
{
   int a;
   public int A
   {
       set { a = value; }
       get { return a; }
   }
   public TempClass() { }
   public TempClass(int t) { A = t; }
   public override string ToString()
   {
       return A.ToString();
   }
}

And print the value like this:
foreach (var item in class1.ItemSource)
{
    Console.WriteLine(item.ToString());
}

Note : You need not to know about the class or properties when iterate over the class1.ItemSource use overrided .ToString() method in each class and print Return what you wished to print on the screen, Lets have another example here:
public class student
 {
     public int id { get; set; }
     public String fName { get; set; }
     public String lName { get; set; }

     public override string ToString()
     {
         return String.Format("Student ID : {0} \n Full Name : {1} {2}", id, fName, lName);
     }
 }

Here in this case the item.ToString() will prints the Student ID : 1
Full Name : suji vasuki

A: You would need this in TempClass:
        public override string ToString()
        {
            return A.ToString();
        }

For a generic solution, you would need constraint:
    public class Class1<T> where T : Temp
    {
        public IEnumerable<T> ItemSource
        {
            get;
            set;
        }

        public void WriteLine()
        {
            foreach (var item in ItemSource)
            {
                Console.WriteLine(item.A);
            }
        }
    }

    public abstract class Temp
    {
        public abstract int A { get; set; }
    }

    public class TempClass : Temp
    {
        public override int A
        {
            get;
            set;
        }

        public TempClass(int t) { A = t; }
    }

to write the property A:
        ObservableCollection<TempClass> test = new ObservableCollection<TempClass>
        {
            new TempClass(1),
            new TempClass(2),
            new TempClass(3)
        };

        Class1<TempClass> class1 = new Class1<TempClass>();
        class1.ItemSource = test;
        class1.WriteLine();


text:
Q: Symfony2 How to manipulative entity data inside model layer? Symfony2 How to manipulative entity data inside model layer? Can I use Entity Manager outside controller and how? How to get data from Database inside my model class?

A: First of all where you want to use your Entity Manager?
If you want to do some operation inside your entity, it's impossible.
You can use entity manager in:
 1. Controller - as you know
 2. Service - you have to set in your service. The best solition for some operation like crypt password for User entity
 3. Command - like in controller
Other way is using own Entity Repository
The question is: what you have to do?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Древовидная структура данных в django Имеется модель подразделений
class Subdivision(models.Model):
    name = models.CharField('Наименование', max_length = 200)
    parent = models.ForeignKey('self', null=True, blank=True)

Данные выводятся с помощью запроса subdivision = Subdivision.objects.all(), в не отсортированном виде. Например в базе есть данные:
+----+------------------------+--------+
| id |          name          | parent |
+----+------------------------+--------+
|  1 | Управление             | null   |
|  2 | Производственный отдел | 1      |
|  3 | Бухгалтерия            | 1      |
|  4 | Производственный цех   | 2      |
+----+------------------------+--------+
Все это выводится так:

*

*Управление

*Производственный отдел

*Бухгалтерия

*Производственный цех

А нужно так(сохраняя иерархию):

*

*Управление

*Производственный отдел

*Производственный цех

*Бухгалтерия

Т.е. первым идет подразделение с нулевым полем parent, потом идут дочерние подразделения, потом дочерние подразделения дочернего подразделения, и т.д. Можно ли такую сортировку реализовать с помощью django.

A: Можно, конечно:
subdivision = Subdivision.objects.all().order_by('parent')
order_by - сортирует по указанному полю. Если поставить минус вначале .order_by('-parent'), то отсортирует в обратном порядке.

A: Решил таким способом, добавил в модель поле order. При сохранении добавляю туда что-то подобии пути.
@receiver(pre_save, sender=Subdivision)
def pre_save_subdivision(sender, instance, **kwargs):
    if(instance.parent==None):
        instance.order='1'
    else:
        old = sender.objects.all().order_by('-id')[0].id
        instance.order = instance.parent.order + '.' + str(old+1)

Дальше сортирую Subdivision.objects.all().order_by('order'). В итоге:

+----+------------------------+--------+-------+
| id |          name          | parent | order |
+----+------------------------+--------+-------+
|  1 | Управление             | null   | 1     |
|  2 | Производственный отдел | 1      | 1.2   |
|  3 | Бухгалтерия            | 1      | 1.3   |
|  4 | Производственный цех   | 2      | 1.2.4 |
+----+------------------------+--------+-------+

И выводится так как мне нужно:

*

*Управление

*Производственный отдел

*Производственный цех

*Бухгалтерия


text:
Q: How can I format IANA timezone to US Standard timezone I have a use-case in which I need a user to enter an availability date on the browser (which will be saved in the database in UTC format) for example
July 2nd at 6:30PM,

i am getting IANA location string using momentjs
moment.tz.guess(); //'America/New_York'

now when I do the server side rendering, I would like to render the availability date as
July 2nd at 6:30 EST
or
July 2nd at 6:30 PMT

Is there a javascript library to do this for me? how can I convert 'America/New_York' to EST?
worth mentioning it is a reactjs application

A: we can achieve this by momentjs. get the IANA timezone with guess() function as explained above to set the timezone and then format it with as documented in moment documents
const date = user input date saved in the database
const z = value of moment.tz.guess() which saved in db
moment(date).tz(z).format('MM/DD/YYYY hh:mm A z');


text:
Q: i dont understand how the devise admin model work I am building a rails app, and i want users and a Admin (me), but i dont understand how the devise admin model work, because if i have have a admin model, cant anyone just go to the link (/admins/sign_up) and sign_up as a admin on my site?
I have already tried to look around on the internet but i just cant seem to find an answer.
If you can explain to me how i can get over this problem, i would love you :D
Thank you
- Peace

A: If you run rake routes | grep 'admin' you will see that there is no route like admin/sign_up. The admin user should be created on rails console or within the admin.
When you install devise (with the migrations and all) it creates for you a default admin user with email: "admin@example.com" and password: "password".
You should login with it to create your real admin user and them delete this default one.
And here is an excellent devise tutorial: http://www.gotealeaf.com/blog/how-to-use-devise-in-rails-for-authentication :)


text:
Q: Dependency resolution error in react native for android I am integrating react native into existing android app by following these steps  . I also install expo modules using this. In my android app,I have app compat version 1.5.1 implementation 'androidx.appcompat:appcompat:1.5.1'. Before integrating react native, the AppCompatActivity class was extended from ComponentActivity version 1.5.1. But after integrated, the ComponentActivity was downgrade to 1.1.0. I also added implementation 'androidx.activity:activity:1.5.0', but it didn't work. So how I can force AppCompatActivity depend with androidx.activity 1.5.0.
You can see three different dependencies version here.


text:
Q: Python script not launchable from C# or by running .py Before you flag this as a repost, please read my issue xD I haven't been able to find any answers to my paticular question.
I'm trying to launch a Python script from a C# program. Now I've made and tested my Python script, and when running it from my IDE (Visual Studio 2017) it works perfectly. Now when I try to execute it as a process from my C# program, a command prompt briefly appears (when I say briefly it's more like it flashes on screen), but my script has not run.
The code for my python script:
import os
import shutil
from pptx import Presentation
from pptx.table import Table
from pptx.text.text import TextFrame
from pptx.text.text import Pt
from pptx.dml.color import RGBColor

#Get ressources dir:
currentWorkingDir = os.getcwd()
ressourceDir = currentWorkingDir[:-31 ]

#Open files and read into variables
agendaInputFile = open(ressourceDir + "agendaInputs.txt", "r", encoding="utf8")

agendaInputs = agendaInputFile.readlines()

agendaTimesFile = open(ressourceDir + "agendaTimes.txt", "r", encoding="utf8")

agendaTimes = agendaTimesFile.readlines()

meetingTitleFile = open(ressourceDir + "meetingTitle.txt", "r", encoding="utf8")

meetingTitle = meetingTitleFile.readline()

presentersFile = open(ressourceDir + "presenters.txt", "r", encoding = "utf8")

presenters = presentersFile.readlines();

#Opens the template ppt-file
prs = Presentation(ressourceDir + "agendaTemplate.pptx")

#selects the first slide
slide = prs.slides[0]

#Sets the meetingtitle
title = slide.shapes[1]
title.text = meetingTitle[:-1]

#finds the table
graphicFrame = slide.shapes[2]
table = graphicFrame.table

#sætter agendapunkterne
i = 0
while i < len(agendaInputs):
    cell = table.cell(i+1,1)
    textFrame = cell.text_frame
    run = textFrame.paragraphs[0].add_run()
    font = run.font
    font.name = 'TSTAR PRO'
    font.size = Pt(16)
    run.text = agendaInputs[i][:-1]
    font.color.theme_color = 5
    i += 1

#Sætter agendatiderne
i = 0
while i < len(agendaTimes):
    cell = table.cell(i+1,0)
    textFrame = cell.text_frame
    run = textFrame.paragraphs[0].add_run()
    font = run.font
    font.name = 'TSTAR PRO'
    font.size = Pt(16)
    run.text = agendaTimes[i][:-1]
    font.color.theme_color = 5
    i += 1

#Sætter presenter
i = 0
while i < len(presenters):
    cell = table.cell(i+1,2)
    textFrame = cell.text_frame
    run = textFrame.paragraphs[0].add_run()
    font = run.font
    font.name = 'TSTAR PRO'
    font.size = Pt(16)
    run.text = presenters[i][:-1]
    font.color.theme_color = 5
    i += 1

#saves the ppt
prs.save("Agenda Slide.pptx")

#File is deleted from the desktop if present there
if os.path.exists("Agenda Slide.txt"):
    os.remove("Agenda Slide.txt")

#File moved to the desktop
shutil.move(os.getcwd() + "\\Agenda Slide.pptx", os.path.join(os.environ["HOMEPATH"], "Desktop") + "\\Agenda Slide.pptx")

Now, as I said, when I launch this from my IDE it works like a charm.
The files that I open and read in the python script is written to by my C# program. This is a lowtech way of transfering variables from my C# to my Python, not pretty, I know.. xD
From my c# programme this is how I launch the script:
private void runPythonScript()
        {
            Process p = new Process(); // create process (i.e., the python program
            p.StartInfo.FileName = @"C:\Python34\python.exe";
            p.StartInfo.RedirectStandardOutput = false;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.Arguments = getRessourcesDir() + "createAgendaPPT\\createAgendaPPT\\createAgendaPPT.py";
            p.Start();
            p.WaitForExit();
            p.Close();
        }

The function getRessourcesDir() just returns the directory for the Ressources folder in the solution.
So to sum up:

*

*Trying to launch a python script from C#

*Pythonscript will run correctly from my IDE but not by launching the .py file.

What I need help for:
How to make a python script launchable from it's .py file and how to launch it from C#.
If anything is unclear or missing, please let me know and I will edit my post and correct it.

A: Try running python script from a command window.
        Process cmdProcess;
        StreamWriter cmdStreamWriter;
        StreamReader cmdStreamReader;
        cmdProcess = new Process();
        cmdProcess.StartInfo.FileName = "cmd.exe";
        cmdProcess.StartInfo.UseShellExecute = false;
        cmdProcess.StartInfo.CreateNoWindow = true;
        cmdProcess.StartInfo.StandardOutputEncoding = Encoding.ASCII;
        cmdProcess.StartInfo.RedirectStandardOutput = true;

        cmdProcess.StartInfo.RedirectStandardInput = true;
        cmdProcess.Start();

        cmdStreamWriter = cmdProcess.StandardInput;
        cmdStreamReader = cmdProcess.StandardOutput;

        cmdStreamWriter.WriteLine("python xxxx.py");


text:
Q: Filter menu item  to add classes/attributes? How can I filter the presentation of menu items to add classes to anchors?
I already have the code below, in which I leverage the per-item "Description" field set in WordPress admin's Menus creator. But it's a bit of a hack, and it doesn't leverage the "CSS Classes (optional)" field available in the Menus creator.

*

*Other methods I have seen filter to add classes to <li>. Instead, I want to add classes to <a> - but not to replace the classes WordPress itself already applies to <a>.

*I want to know how to take those classes from the Menus creator field "CSS Classes (optional)".

*But I would also like to hard-set the additional classes in code, not from the "CSS Classes (optional)" field.
  /**
   * ==============================================================================
   *                       INSERT CLASSES IN TO NAV ITEMS
   * ==============================================================================
   */

  /**
   * Store class names in menu description field.
   * Used, eg. to make a nav item hidden
   */

  /**
   * Descriptions on Header Menu
   * @author Bill Erickson
   * @link http://www.billerickson.net/code/add-description-to-wordpress-menu-items/
   *
   * @param string $item_output, HTML outputp for the menu item
   * @param object $item, menu item object
   * @param int $depth, depth in menu structure
   * @param object $args, arguments passed to wp_nav_menu()
   * @return string $item_output
   */

  // Use menu item description field to store class name for output to link
  function be_header_menu_desc( $item_output, $item, $depth, $args ) {

    // Only if menu is footermenu1
    if( 'footermenu1' == $args->theme_location && ! $depth && $item->description )
        $item_output = str_replace( '<a ', '<a ' . $item->description .' ', $item_output );

    return $item_output;
  }
  add_filter( 'walker_nav_menu_start_el', 'be_header_menu_desc', 10, 4 );

Update:
This code seems relevant...
// via https://wordpress.stackexchange.com/a/241072/39300
  function menu_add_atts( $atts, $item, $args ) {
      $class = 'has-arrow waves-effect waves-dark nav-link'; // or something based on $item
      $atts['class'] = $class;
      return $atts;
  }
  add_filter( 'nav_menu_link_attributes', 'menu_add_atts', 10, 3 );

... however, that is imposes only the classes I specify (as opposed to any which WordPress also might). I would also like to extend it to add not just classes but also other attributes, eg. aria-expanded="false".


text:
Q: Why isn't a pseudo force considered for a block on an accelerating block?
I was going through an example where there is a system of blocks where two blocks A and B of mass $m$ are attached through a pully on another block C of mass $M$. The friction between the blocks is $\mu$, and the objective is to calculate the minimum or maximum force to keep the smaller blocks at rest with respect to C.
In the example, when A, B, and C are taken as a system, the total acceleration is said to be $\frac{F}{M + 2m}$, which I understand.
However, when A alone is taken as the system, the only forces considered are the tension $T$ towards the right, the frictional force $f$ towards the left, the weight $mg$ and the normal force $N$.
Why isn't a psuedo force opposite to F considered since we are in a non-inertial frame? When the forces on B are considered in the example, it accounts for a normal force $N'$ that acts towards the right because of the acceleration of the system caused by F, but I don't see it being a factor in the forces considered for block A as a system.
Also, the frictional force $f$ is taken to be $\mu mg$ and it states the horizontal net force is $T - \mu mg = ma$ since "the block moves towards the right with an acceleration a". Is this the same acceleration of the entire system caused by F? In that case, how is it being considered instead of the acceleration caused by block B attached to the rope?
I have not completely wrapped my head around the procedure for isolating and analyzing individual bodies in a system so I apologize if the question comes across as vague or convoluted.

A: $a$ is the acceleration of block A with respect to the reference frame $S$ in which the ground is at rest. We do not need to introduce a pseudo force because $S$ is an inertial frame. However, $a$ is not necessarily the same as the acceleration $\frac F {M+2m}$, which is the acceleration of the centre of mass of the whole system. We can only say that $a = \frac F {M+2m}$ if block A does not slip on block C.
If we work in a reference frame $S'$ in which block A is at rest, then $S'$  is accelerating to the right with acceleration $a$, so we need to include a horizontal pseudo force $-ma$. If we assume $\mu$ is the coefficient of static friction and block A is on the point of slipping then the horizontal equation of motion for block A becomes
$T - \mu m g - ma = 0$
The right hand side is zero because block A is at rest in frame $S'$. But if we re-arrange this equation we get
$T - \mu m g = ma$
which is exactly the same as the horizontal equation of motion for block A in frame $S$ - which is what we expect.
Note that block A is not moving vertically, so its vertical equation of motion (in both frame $S$ and in frame $S'$) is
$N - mg = 0$


text:
Q: How to Convert UTC time to local time In Swift 3? Here , I want to convert the UTC time to Local time formate in swift 3, but i'am not able to convert it. Please help me for this
let StrDate = "2018-03-06T13:32:57 +05:30" I want to Convert this Date into local time format.
 func convertStringDateFormateUTC(strDate: String,
     strCurrentFormateType:String, strFormateType:String) -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = strCurrentFormateType
            var strNewdate = NSDate()
            strNewdate = dateFormatter.date(from: strDate)! as NSDate
            dateFormatter.dateFormat = strFormateType;
            dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
            return dateFormatter.string(from: strNewdate as Date)
        }

A: Use TimeZone.current to detect local timezone and apply it.
let formatter = DateFormatter()
// initially set the format based on your datepicker date
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
//print(localTimeZoneAbbreviation)
formatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// convert your string to date
let yourDate = formatter.date(from: strDate)
//then again set the date format which type of output you need

In your function  :
func convertStringDateFormateUTC(strDate: String,
                                 strCurrentFormateType:String, strFormateType:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = strCurrentFormateType

    var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
    dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)

    var strNewdate = NSDate()
    strNewdate = dateFormatter.date(from: strDate)! as NSDate
    dateFormatter.dateFormat = strFormateType;
    dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
    return dateFormatter.string(from: strNewdate as Date)
}


text:
Q: AS3 vertical gradient incorrect when large This seems to be a very straight forward thing to do and there are loads of tutorials about the subject. None of them are helping me get this right though, and I can't for the life of me figure out what's wrong.
I'm trying to create a simple Flash AS3 GUI component that has a vertical gradient. I create the sprite, and draw the gradient with beginGradientFill and a matrix with a 90 degree radian angle on it. If you look at this output, you see that its not creating a black to white vertical gradient.
package
{
   import flash.display.GradientType;
   import flash.display.Shape;
   import flash.display.Sprite;
   import flash.geom.Matrix;

   public class Main extends Sprite
   {
      public function Main()
      {
          var theWidth : Number = 800;
          var theHeight: Number = 100;

          var shape1:Shape = new Shape();
          var matrix:Matrix = new Matrix();
          matrix.createGradientBox(theWidth , theHeight, Math.PI*0.5, 0, 0);
          var colors:Array = [ 0xffffff, 0x000000];
          var alphas:Array = [ 1, 1];
          var ratios:Array = [ 0, 255];
          shape1.graphics.lineStyle(2,0xa1b0b6);
          shape1.graphics.beginGradientFill(GradientType.LINEAR,colors, alphas, ratios, matrix);
          shape1.graphics.drawRect( 0.0, 0.0, theWidth , theHeight);
          shape1.graphics.endFill();
          addChild(shape1);
      }
   }
}
If I change
matrix.createGradientBox(800, 100, Math.PI*0.5, 0, 0);

to
matrix.createGradientBox(800, 100, Math.PI, 0, 0);

it works fine - but horizontally - why is it that applying 90 degrees the fill does not work?
Thanks for your help, I really don't know whats wrong with this

A: The solution would be to translate the Matrix in Y by the height of the box, it's silly working in FP9 worked fine for me without doing that, had the incubator build and looked bad, went back to 10.3 bad again.. might be that now the matrix it's rotated by the center or something that now translation is needed.

A: Without testing your code, it seems like you may be describing this issue that Mario Klingemann has a solution to (of course).
http://www.quasimondo.com/archives/000689.php

A: Just to confirm, this was a Flash player issue.


text:
Q: Is the Weierstrass function not Lipschitz continuous on any set of positive Lebesgue measure?
Find a measurable set $A \subset\mathbb R$ with positive Lebesgue measure $\mu(A)>0$ such that the Weierstrass function is Lipschitz continuous on $A$, or show that no such set exists.

Weierstrass function is the function $f:\mathbb R \to \mathbb R$ defined by the Fourier series
$$
  f(x) = \sum_{n=1}^\infty a^n cos(b^n \pi x),
$$
where $a \in (0,1)$, $b$ is a positive odd integer, and $ab>1+\frac 3 2 \pi$. It is known to be continuous but not differentiable at any point.
Let me demonstrate the emphasize that $A$ can be any measurable set, not necessarily an interval. For example, the indicator function of the rational numbers is not Lipschitz continuous on any interval, but it is Lipschitz continuous on the set of irrational numbers (as it is constantly 0 on that domain).
A closely related question: A continuous function $f:[0,1]\to \mathbb R$ that is not Lipschitz continuous on any subset of a positive measure.


text:
Q: Set of function of Bounded variation is complete A function $f:[a,b]\rightarrow\mathbb{R}$ is  said to be of bounded variation if $$V(f):=\text{sup }\lbrace \sum_{j=1}^{r}|f(t_j)-f(t_{j-1})|:r\in\mathbb{Z}^+\text{ and } a=t_0<t_1<\dots<t_r=b\rbrace$$
is finite. The set of all functions of bounded variation on the interval $[a,b]$ is denoted by $BV[a,b]$.
Prove that

*

*$|f|:=|f(a)|+V(f)$ defines a norm on $BV[a,b]$

*$BV[a,b]$ is compete with respect to the norm defined above

I have problem with the second bit. Any idea ?

A: Consider a Cauchy sequence $(f_n)$. If $|f_n-f_m|<\epsilon$ then they have to be $\epsilon$ uniformly close. So the Cauchy sequence converges pointwise (everywhere) to some $f$. Now, $V(f_n-f_m)<\epsilon$ for $n,m\geq N_\epsilon$, so for any fixed partition $P=(a=t_0<t_1<\cdots< t_r=b)$ we have
  $$V(f_n-f_m,P)=\sum_i |(f_n-f_m)(t_j)-(f_n-f_m)(t_{j-1})| <\epsilon$$
for every $n,m\geq N_\epsilon$. Taking the limit $m\rightarrow +\infty$ and using pointwise convergence:
  $$V(f_n-f,P)=\sum_i |(f_n-f)(t_j)-(f_n-f)(t_{j-1})| \leq \epsilon$$
which implies $V(f,P) \leq V(f_n,P)+\epsilon \leq V(f_n)+\epsilon< +\infty$.
Take now the sup over $P$ on the LHS to get: $V(f) \leq V(f_n)+\epsilon< +\infty$.


text:
Q: npm install socket.io hangs on node-gyp step I wanted to install socket.io via npm to use it in my node.js application. So I just entered npm install socket.io -g into my terminal and let it run.
> ws@0.5.0 install /usr/local/lib/node_modules/socket.io/node_modules/engine.io/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

After the last log message the regular progress spinner appears but it stops spinning after some seconds and starts to hang (indefinitely).
I can't imagine why this happens. No error message, no unusual resource usage in System Monitor, no whatever.
Does anyone of you know what it could be or where I could look for the reason?
I'm using Ubuntu 14.10 with Node v0.12.2 and npm v2.7.4. Further I have python 2.7.8 and node-gyp 1.0.3 installed.

A: I had the same problem on my ubuntu 12.04. Turns out I didnt have node-gyp installed on my system. I installed it using
sudo npm install -g node-gyp
and was then able to install socket.io succesfully. :)


text:
Q: Delete incoming header X-Forwarded-For from client within Ingress (Cloud HTTPS Load Balancer) How to delete / block header X-Forwarded-For coming from client for Ingress (Cloud HTTPS Load Balancer) within GKE?

A: In my opinion you can try to use Custom headers for External HTTP(S) Load balancer.

Custom request and response headers allow you to specify additional
headers that the external HTTP(S) load balancer adds to requests and
responses. These headers can include information that the load
balancer detects about the client connection, including the latency to
the client, the geographic location of the client's IP address, and
parameters of the TLS connection.

You can find the way to apply it on GKE ingress according to this example:
apiVersion: cloud.google.com/v1beta1
kind: BackendConfig
metadata:
  name: my-backendconfig
spec:
  customRequestHeaders:
    headers:
    - "X-Client-Region:{client_region}"
    - "X-Client-City:{client_city}"
    - "X-Client-CityLatLong:{client_city_lat_long}"


text:
Q: 4 GB limit on FAT32 flash drive I have created an iMovie slide show of about 20GB made up of slides and transitions but no music. Are the individual slides and transitions treated as separate files so it will work on FAT 32 format? Or will it be over the 4GB limit?

A: Format the flash drive as exFAT.
FAT32 does not support single large file
No, they wont be separate files and so it wont work with FAT32 if the size is large.


text:
Q: Win 10 doesn't upgrade to November update or Redstone I have an one year old ASUS laptop, which originally shipped with Win 8.1. When Windows 10 was released I upgraded without hassle to Windows 10.
Trying to update to November update (Threshold-2) or more recently Redstone just doesn't work.
The upgrade starts and finally Windows is restarting. Then after about 40% oin the upgrade process the upgrade is aborted and Windows is reverted to the previous edition.
In
C:\$WINDOWS.~BT\Sources\Panther\setuperr.log

the last entry is always:
2016-08-09 21:14:39, FatalError [0x090001] PANTHR Exception (code 0xC0000005: ACCESS_VIOLATION) occurred at 0x00007FFC83C9613C in C:\$WINDOWS.~BT\Sources\unbcl.dll (+000000000005613C).  Minidump attached (64405 bytes).

The last few entries in setupact.log are:
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Migrate boot settings
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Reserve space with file C:\$WINDOWS.~BT\Sources\Reserved.FirstApply (576716800)
2016-08-09 15:12:26, Info                  SP       AddSpace: add:       576716800, current:       786432000, peak:       786432000
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Reserve space with file C:\$WINDOWS.~BT\Sources\Reserved.SecondApply (157286400)
2016-08-09 15:12:26, Info                  SP       AddSpace: add:       157286400, current:       943718400, peak:       943718400
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Install Eula
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Orchestrate OS switch for NewOS with safe OS SafeOS and rollback OS ExternalRollback. DelayedSwitch: 0
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Copy log files from C:\$WINDOWS.~BT\Sources\Panther to C:\WINDOWS
2016-08-09 15:12:26, Info                  SP     DISKSPACEQUERY: Post-BOOT operations:
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Upgrade security
2016-08-09 15:12:26, Info                  SP       Operation (remaining): First boot apply
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Create file/registry on first boot
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Stop suspended services
2016-08-09 15:12:26, Info                  SP       Operation (remaining): OOBE boot apply
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Refresh localized strings
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Execute provisioning migration
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Gather end install, scope: EVERYTHING
2016-08-09 15:12:26, Info                  SP       AddSpace: add:       314572800, current:       314572800, peak:       314572800
2016-08-09 15:12:26, Info                  SP       Operation (remaining): Start suspended services
2016-08-09 15:12:26, Info                  SP     DISKSPACEQUERY: Final disk space needed estimate: 943718400 + 314572800 = 1258291200
2016-08-09 15:12:26, Info                  SP     Executing operation: Relocate OS from C:\$WINDOWS.~BT\NewOS to C:\
2016-08-09 15:12:26, Info                  SP     DISKSPACETRACK: Available    : 29226127360
2016-08-09 15:12:26, Info                  SP     DISKSPACETRACK: Needed total : 1258291200
2016-08-09 15:12:26, Info                  SP     DISKSPACETRACK: Needed for op: 0
2016-08-09 15:12:26, Info                  SP     Final list of source OS pieces:
2016-08-09 15:12:26, Info                  SP         Name: WINDOWS, Original path: C:\WINDOWS, Current path: C:\WINDOWS (do not allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: PROGRAMS, Original path: C:\Program Files, Current path: C:\Program Files (do not allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: PROGRAMSX86, Original path: C:\Program Files (x86), Current path: C:\Program Files (x86) (do not allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: USERS, Original path: C:\Users, Current path: C:\Users (allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: PROGRAMDATA, Original path: C:\ProgramData, Current path: C:\ProgramData (do not allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: INETPUB, Original path: C:\inetpub, Current path: C:\inetpub (do not allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: SKYDRIVETEMP, Original path: C:\SkyDriveTemp, Current path: C:\SkyDriveTemp (do not allow relocation)
2016-08-09 15:12:26, Info                  SP         Name: RECOVERY, Original path: C:\Recovery, Current path: C:\Recovery (do not allow relocation)
2016-08-09 15:12:26, Info                  SP     No source symblic mappings found
2016-08-09 15:12:26, Info                  SP     Final list of Windows.old roots:
2016-08-09 15:12:26, Info                  SP         C:\
2016-08-09 15:12:26, FatalError [0x090001] PANTHR Exception (code 0xC0000005: ACCESS_VIOLATION) occurred at 0x00007FFE2821613C in C:\$WINDOWS.~BT\Sources\unbcl.dll (+000000000005613C).  Minidump attached (68317 bytes).

I tried Windows Update, Media Creation Tool or Win 10 upgrade assistant without any luck.
Norton AV is uninstalled and Windows Defender is used.
So far I did not try a clean, new installation and I would like to avoid this, if possible.
Any hints or suggestions?
EDIT:
Complete setuperr.log:
2016-08-09 20:58:44, Error                 MOUPG  CDlpActionImpl<class CDlpErrorImpl<class CDlpObjectInternalImpl<class CUnknownImpl<class IMoSetupDlpAction> > > >::Suspend(1066): Result = 0xC1800104
2016-08-09 20:58:44, Error                 MOUPG  CSetupManager::ExecuteInstallMode(735): Result = 0x800705BB
2016-08-09 20:58:44, Error                 MOUPG  CSetupManager::ExecuteDownlevelMode(391): Result = 0x800705BB
2016-08-09 20:58:44, Error                 MOUPG  CSetupManager::Execute(236): Result = 0x800705BB
2016-08-09 20:58:44, Error                 MOUPG  CSetupHost::Execute(372): Result = 0x800705BB
2016-08-09 21:03:13, Error                 SP     Failed to create WIM handle for \\?\Volume{c5ef6f70-8ba0-47fa-9dae-62c3b55abf3d}\Windows Images\Install.wim. Error: 0x80070015[gle=0x00000015]
2016-08-09 21:03:13, Error                 SP     Failed to create WIM handle for \\?\Volume{c5ef6f70-8ba0-47fa-9dae-62c3b55abf3d}\Windows Images\custom.wim. Error: 0x80070015[gle=0x00000015]
2016-08-09 21:03:25, Error                 SP     Failed to create WIM handle for \\?\Volume{c5ef6f70-8ba0-47fa-9dae-62c3b55abf3d}\Windows Images\Install.wim. Error: 0x80070015[gle=0x00000015]
2016-08-09 21:03:25, Error                 SP     Failed to create WIM handle for \\?\Volume{c5ef6f70-8ba0-47fa-9dae-62c3b55abf3d}\Windows Images\custom.wim. Error: 0x80070015[gle=0x00000015]
2016-08-09 21:04:27, Error                 SP     pSPRemoveUpgradeRegTree: failed to delete reg tree HKLM\SYSTEM\Setup\Upgrade[gle=0x00000005]
2016-08-09 21:04:36, Error      [0x080831] MIG    CSIAgent: Invalid xml format: FormatException: "id" attribute is mandatory. void __cdecl Mig::CMXEMigrationXml::LoadSupportedComponent(class UnBCL::XmlNode *,int,class Mig::CMXEMigrationXml *,class Mig::CMXEXmlComponent *)
2016-08-09 21:04:51, Error                 CSI    00000001 (F) 80220008 [Error,Facility=FACILITY_STATE_MANAGEMENT,Code=8] #97586# from CWcmScalarInstanceCore::GetCurrentValue(options = 393216 (0x00060000), status = [6]"(null)", value = { type: 40972 (0x0000a00c), bytes ( 12 (0x0000000c) ): 640065002d00440045000000 })
[gle=0x80004005]
2016-08-09 21:05:29, Error                 CSI    00000002 (F) 80220008 [Error,Facility=FACILITY_STATE_MANAGEMENT,Code=8] #172943# from CWcmScalarInstanceCore::GetCurrentValue(options = 393216 (0x00060000), status = [6]"(null)", value = { type: 40972 (0x0000a00c), bytes ( 12 (0x0000000c) ): 640065002d00440045000000 })
[gle=0x80004005]
2016-08-09 21:05:41, Error      [0x080831] MIG    CSIAgent: Invalid xml format: FormatException: Component with display name: Plugin/{C939EC0F-2F56-4CE8-AF56-2336596A5FA7} already loaded __cdecl Mig::CMXEMigrationXml::CMXEMigrationXml(class Mig::CPlatform *,class UnBCL::String *,class UnBCL::XmlDocument *,class UnBCL::String *,class UnBCL::String *)
2016-08-09 21:07:09, Error      [0x0808fe] MIG    Plugin {526D451C-721A-4b97-AD34-DCE5D8CD22C5}: [shmig] Failed to get preferred homegroup with hr=0x80070490
2016-08-09 21:07:12, Error      [0x0808fe] MIG    Plugin {ff9c714f-b864-4f43-ae39-ec07d7385abe}: Skipping device 'SWD\PRINTENUM\WSD-0629E6A1-50D6-4C99-8F72-2112EA8AC266.0034' without driver.
2016-08-09 21:07:13, Error      [0x0808fe] MIG    Plugin {ff9c714f-b864-4f43-ae39-ec07d7385abe}: Skipping device 'SWD\PRINTENUM\WSD-AAA2298E-E65E-4116-A2D2-AC28C7D9D7A1.006E' without driver.
2016-08-09 21:07:14, Error      [0x0808fe] MIG    Plugin {ee036dc0-f9b7-4d2d-bb94-3dd3102c5804}: BRIDGEMIG: CBrgUnattend::CollectBridgeSettings failed: 0x1, 0
2016-08-09 21:07:21, Error      [0x0808fe] MIG    Plugin {D12A3141-A1FF-4DAD-BF67-1B664DE1CBD6}: WSLicensing: Failed to read machine binding, hr=0x80070002
2016-08-09 21:07:21, Error      [0x0808fe] MIG    Plugin {D12A3141-A1FF-4DAD-BF67-1B664DE1CBD6}: WSLicensing: Error reading Server Info hr=0x80070490
2016-08-09 21:07:24, Error                        CSetupAutomation::Resurrect: File not found: C:\$WINDOWS.~BT\Sources\Panther\automation.dat[gle=0x00000002]
2016-08-09 21:07:24, Error                 SP     CSetupPlatform::ResurrectAutomation: Failed to resurrect automation: 0x80070002[gle=0x00000002]
2016-08-09 21:14:39, FatalError [0x090001] PANTHR Exception (code 0xC0000005: ACCESS_VIOLATION) occurred at 0x00007FFC83C9613C in C:\$WINDOWS.~BT\Sources\unbcl.dll (+000000000005613C).  Minidump attached (64405 bytes).


text:
Q: Linux - Outgoing connections from process timeout after the process restarts banging my head against the wall with this one...
I have an Ubuntu Linux server, on top of which our own process which holds 40K persistent connections to external services.
When the process starts, it tries to reconnect to the 40K external endpoints. When I restart the process after long activity, and it tries to reconnect, most of the reconnects fail by timing out. About an hour after the initial restart, the connection attempts are suddenly succeeding again.
Here's what I know:

*

*Since the process restarts between the attempts, it cannot be the process' internal state

*The external services are available regardless of my restart.

*This leaves us with the server itself

My theory is that something in the Linux networking stack is being maxed out during steady state operation of our process, and only released after a significant timeout.

*

*Which resource could be maxed out, and how can I verify this scenario?

*Is there an alternative explanation?

Thanks!


text:
Q: Is it possible to add a post on a facebook page via the graph API without a Facebook App? I want to post updates automatically to my facebook page from my PHP website.
Facebook seems to force me to create an App where users can login and then post stuff.
But I don´t need all that stuff, I just want to post to the facebook page directly via code.
I went "Ok, I´ll create an App", but now for them to give my app the needed permissions, they want me to give them a login so they can test my app and stuff ... Is there no simple way to just autopost something to my own Facebook page?


text:
Q: Graph with multiple Y axes How do I create a graph multiple Y axes(more than 2) stacked one over the other with a common X axis?

See attached figure.   Each zero in y direction represents the beginning of new y axis.

A: A quick example with groupplots.
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.13}
\usepgfplotslibrary{groupplots}
\begin{document}
\begin{tikzpicture}
\begin{groupplot}[
 group style={
  group size=1 by 4,  % sets number of columns and rows in groupplot array
  vertical sep=0pt,   % vertical distance between axes
 },
 axis y line=left, % y axis line on left side only
 xmin=0,xmax=10,   % set axis
 ymin=0,           % limits
 domain=1:9,       % domain, just for example
 width=10cm,       % width
 height=3cm,       % and height for each axis
 scale only axis,  % disregard labels and ticks for scaling
 no markers,
 enlarge y limits=upper,
]

\nextgroupplot[
    ylabel=$y$,
    ylabel style={at={(rel axis cs:0,1)},above,rotate=-90}, %move ylabel a bit
    axis x line=none] % remove x-axis lines
 \addplot{x};

\nextgroupplot[axis x line=none]
 \addplot{-x + 10};

\nextgroupplot[axis x line=none]
 \addplot{x*x};

\nextgroupplot[
    axis x line=bottom, % only x axis line at bottom
    xlabel=$x$,
    xlabel style={at={(rel axis cs:1,0)},right}]
 \addplot+[samples=200] {abs(sin(x*180/pi))};

\end{groupplot}
\end{tikzpicture}
\end{document}


text:
Q: Reading the HTML viewed by the user Using R I would like to download the HTML generated by the following page:
https://digital.fidelity.com/prgw/digital/research/quote/dashboard/summary?symbol=AAPL
The page source does NOT correspond to the HTML that is seen by the user. When I use R functions like readLines or download.file I get the page source, which is not what I want. I want the HTML seen by the user, which I'd like to read into a character vector.
Can this be done? If so, please provide details.

A: I have been able to save the content of the webpage in a file with the following code :
library(RSelenium)
url <- "https://digital.fidelity.com/prgw/digital/research/quote/dashboard/summary?symbol=AAPL"
shell('docker run -d -p 4445:4444 selenium/standalone-firefox')
remDr <- remoteDriver(remoteServerAddr = "localhost", port = 4445L, browserName = "firefox")
remDr$open()
remDr$navigate(url)
Sys.sleep(10)
page_Content <- remDr$getPageSource()[[1]]
writeLines(page_Content, con = "C:\\test.html")

The variable page_Content contains the code of the webpage. Selenium will execute javascript code if the page contains javascript code.


text:
Q: Selectively Modify Indices Is there a shorter way to select elements and modify them? For example, in
y[y < 1] <- y[y < 1]*2

the object y is referenced 4 times in one line. Is it possible to reduce this repetition?

A: Try this
y <- y*{{y<1} + 1}

In general you can introduce a function f
f <- function(bool) ifelse(bool, 2, 1)
y <- y * f(y < 1)

This approach seems a bit faster than Josh's solution
n <- 10000
y <- sample(c(1,-1), n, replace = TRUE)
f1 <- function(y){y[i] <- y[i <- y < 1] * 10; y}
f2 <- function(y){y <- y*{{y<1} + 1}; y}
benchmark(f1(y), f2(y), replications = 50000)

  test replications elapsed relative user.self sys.self user.child sys.child
1 f1(y)        50000   30.29    2.398    27.427    3.146          0         0
2 f2(y)        50000   12.63    1.000     9.859    2.918          0         0

A: Here's a construct that reduces the number of references to y by 1:
y <- -2:2
y[i] <- y[i <- y < 1] * 10

y
# [1] -20 -10   0   1   2

In practice, though, I'm more likely to do this, which is maybe less "clever" but is certainly much easier to parse (for a human):
i <- y < 2
y[i] <- y[i] * 10

A: This does not reduce the number of references to y, but it does stop y>1 being calculated twice
y <- ifelse(y<1, y, y *2)

or you could predefine y <1
replacing <- y < 1

Then the line only contains two explicit references to y
y[replacing] <- y[replacing] *2

You could put y in a data.table, and then you can (almost) reduce the number of times y is repeated by 1
 library(data.table)
 Y <- data.table(y = y)

 Y[y <1, y := y*2]

I say almost, because if you want to access the atomic vector y, you will need to type Y[,y]


text:
Q: Refit Client using a dynamic base address I am using Refit to call an API using a Typed Client in asp.net core 2.2 which is currently bootstrapped using a single BaseAddress from our configuration Options:
services.AddRefitClient<IMyApi>()
        .ConfigureHttpClient(c => { c.BaseAddress = new Uri(myApiOptions.BaseAddress);})
        .ConfigurePrimaryHttpMessageHandler(() => NoSslValidationHandler)
        .AddPolicyHandler(pollyOptions);

In our Configuration json:
"MyApiOptions": {
    "BaseAddress": "https://server1.domain.com",
}

In our IMyApi interface:
public IMyAPi interface {
        [Get("/api/v1/question/")]
        Task<IEnumerable<QuestionResponse>> GetQuestionsAsync([AliasAs("document_type")]string projectId);
}

Example Current Service:
public class MyProject {
     private IMyApi _myApi;
     public MyProject (IMyApi myApi) {
        _myApi = myApi;
     }

    public Response DoSomething(string projectId) {
        return _myApi.GetQuestionsAsync(projectId);
    }
}

I now have the requirement to use different BaseAddresses based on data at runtime. My understanding is that Refit adds a single Instance of the HttpClient into DI and so switching BaseAddresses at runtime won't directly work in a multithreaded app. Right now it's really simple to inject an instance of IMyApi and call the interface method GetQuestionsAsync. At that point it is too late to set the BaseAddress. If I have multiple BaseAddresses, is there an easy way to dynamically select one?
Example config:
    "MyApiOptions": {
        "BaseAddresses": {
            "BaseAddress1": "https://server1.domain.com",
            "BaseAddress2": "https://server2.domain.com"
        }
}

Example Future Service:
public class MyProject {
     private IMyApi _myApi;
     public MyProject (IMyApi myApi) {
        _myApi = myApi;
     }

    public Response DoSomething(string projectId) {
        string baseUrl = SomeOtherService.GetBaseUrlByProjectId(projectId);

        return _myApi.UseBaseUrl(baseUrl).GetQuestionsAsync(projectId);
    }
}

UPDATE
Based on the accepted answer I ended up with the following:
public class RefitHttpClientFactory<T> : IRefitHttpClientFactory<T>
{
    private readonly IHttpClientFactory _clientFactory;

    public RefitHttpClientFactory(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public T CreateClient(string baseAddressKey)
    {
        var client = _clientFactory.CreateClient(baseAddressKey);

        return RestService.For<T>(client);
    }
}

A: Inject a ClientFactory instead of a client:
public class ClientFactory
{
    public IMyApi CreateClient(string url) => RestService.For<IMyApi>(url);
}

public class MyProject {
     private ClientFactory _factory;
     public MyProject (ClientFactory factory) {
        _factory = factory;
     }

    public Response DoSomething(string projectId) {
        string baseUrl = SomeOtherService.GetBaseUrlByProjectId(projectId);
        var client = _factory.CreateClient(baseUrl);

        return client.GetQuestionsAsync(projectId);
    }
}

A: Another option is to assign a fake base address in the configs and then override it using a DelegatingHandler
services
    .AddRefitClient<IMyApi>()
    .ConfigureHttpClient((sp, c) => c.BaseAddress = new Uri(MyDelegatingHandler.FakeBaseAddress))
    .AddHttpMessageHandler<MyDelegatingHandler>()

public class MyDelegatingHandler : DelegatingHandler
{
    public const string FakeBaseAddress = "http://fake.to.replace";

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var relativeUrl = request.RequestUri!.AbsoluteUri.Substring(FakeBaseAddress.Length);
        var newUri = Combine(GetDynamicBaseAddress(), relativeUrl);
        request.RequestUri = new Uri(newUri);
        return await base.SendAsync(request, cancellationToken);
    }

    private static string Combine(string baseUrl, string relativeUrl) =>
        return $"{baseUrl.TrimEnd('/')}/{relativeUrl.TrimStart('/')}";
}


text:
Q: How does Qt mobile work? in Qt 5.4 it is possible to develop Apps for Android and iOS. I want to understand the architecture behind it. There is nothing regarding this in the docu of Qt.

A: As to Android, you might start here.
Bogdan Vatra is the guy behind the Android Qt implementation:
http://www.kdab.com/qt-on-android-episode-1/


text:
Q: JQGrid-SetSelection Not working while edit cell is true I have created a grid as below.I want the first row to be selected programmatically after the grid is loaded. Also the cell should be editable. The first row selection works fine with the cellEdit:false. When I make the cellEdit:true , the selection will not change if I click on other rows . The first row remains selected even if I click on other rows. Could anyone help please? Thanks in advance
        $("#grid").jqGrid({
            url : 'getGridData',
            datatype : "json",
            colNames : colNamesArray,
            colModel : colModelArray,
            rowNum:'',
            shrinkToFit:false,
            cellEdit : true,
            hidegrid: false,
            //loadonce: true,
            gridview:true,
            autowidth: true,
            height : gridHeight,
            cellSubmit : "remote",
            cellurl : "saveCelldata",
            gridComplete: function () {
                $("#grid").setSelection(1);
            },
        });

A: http://jsfiddle.net/U4dcn/2
Try this Updated fiddle
 onSelectCell: function () {
        grid.resetSelection("83432a");
        }

I have added OnSelectCell Event to the code which will deselect the selected row,when u click any cell

A: http://jsfiddle.net/U4dcn/21/
Please add "editable:true".
colModel: [
        { name: 'PackageCode', index: 'PackageCode', width: "110",editable:true  },
        { name: 'Name', index: 'Name', width: "300",editable:true }
    ],


text:
Q: Need a program that can export flowcharts as xml for later use in JavaApp I want to develop a simple way to generate a flowchart for websites.
Here is why I would need something like that:
At first one draws a flowchart in < insert-program-here > and exports it as a xml-file.
This xml-file shall be imported and unmarshalled by another program, which in this case is a Java-application which is nothing more than a graphical interface which a user can use to find his/her way to a specific solution by following the flowchart.
I hope I got it right so far..
Does anybody know a simple program that would export a flowchart as a xml-file so I can use it as mentioned above? Or is there another way that is more comfortable to accomplish my needs?
Thanks for any help!
Best regards.

A: Personally I would recommend yEd because I have had good experiences with it. It uses the XML Format GraphML by default so your users will not have to use an export-Function but can use the files produced when saving their work.
But I don't think one can answer your question with a simple "I recommend program X." because nobody knows what you really need. Maybe one program does not give you all features you want to have for your flowcharts. Maybe others are not cheap enough.
I think you will have to find the right one by yourself. To determine which program can do it for you could check several drawing applications. A list of flowcharting programs can be found in this question. If that is not enough you may use google to find more.


text:
Q: Splitting a Web-Worker in several Typescript files in Angular2+ I run some Typescript code on a Web-Worker using the file-loader given on this page and it works as expected in my Angular 6 app.
For a better readability and maintainability of the code running on the Web-Worker, I need to split it in several Typescript (.ts) files.
I already tryied using require('worker!...') or importScripts('filename.js'), but i didn't manage to get them work with a Typescript (.ts) file. If possible, I would prefer an integrated build system the same way we import a Service in Angular2+.
Any help would be appreciated,
Regards.

A: I finally choose to implement platform-webworker in angular 6 using angular-cli-builders
Solution explained here: https://github.com/meltedspark/angular-builders/issues/13


text:
Q: Abrir arquivo em Python só funciona com pastas do Windows em inglês Eu tenho um programa de Python que pede um caminho de arquivo ao usuário e mostra os conteúdos do arquivo na tela. O problema é que o código só funciona quando eu coloco os nomes das pastas do Windows em inglês.
Por exemplo:
>>> print(open('C:\\Usuários\\usuario\\Documentos\\Gamepobre.txt').read())

retorna um erro:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Usuários\\usuario\\Documentos\\Gamepobre.txt'

Mas se eu trocar Usuários e Documentos por Users e Documents:
>>> print(open('C:\\Users\\usuario\\Documents\\Gamepobre.txt').read())

Ele mostra os conteúdos na tela como o esperado.
Como o programa vai usar input de usuário, existe alguma maneira de converter o caminho em português para o equivalente em inglês e evitar esse erro? Pesquisei mas não achei nada que menciona isso na internet.
Desculpe se isso for incrivelmente óbvio. Estou começando ainda. Também estou usando Pycharm, caso isso ajude.

A: O problema é que os nomes corretos, verdadeiros, das pastas que você citou, são os nomes em inglês mesmo, Users e Documents.
O que ocorre é que existe um gancho de visualização definido nos arquivos ocultos desktop.ini:
[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770
IconResource=%SystemRoot%\system32\imageres.dll,-112
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-235

Essa linha LocalizedResourceName chama uma função na shell32.dll exatamente no momento da exibição do nome da pasta. Essa função cria a ilusão de um nome traduzido.
Ou seja, no windows explorer e derivados, vai ser exibido um nome ilusório, diferente do verdadeiro nome que a pasta tem. Isso é apenas uma ilusão e não é o nome verdadeiro da pasta.
A forma mais direta de resolver o problema é a utilização de uma interface gráfica baseada no windows explorer para que o usuário selecione a pasta. Por exemplo:
from tkinter import filedialog as dlg
path = dlg.askopenfilename()

O código acima vai exibir uma janela gráfica para que o usuário selecione um arquivo graficamente. Como essa janela utilizará o windows explorer internamente, os nomes aparecerão traduzidos. Mesmo que o usuário selecione a pasta Documentos, a função retornará Documents, ou seja, a tradução ocorre automaticamente.

A: Para obtero caminho da pasta usuário em Windows ou user em Unix/Linux use a função de manipulação de caminhos expanduser (https://docs.os.path.html#os.path.expanduser) que substitui o ~ pelo caminho da pasta usuário.
from os.path import expanduser
print(open(expanduser("~\\Documentos\\Gamepobre.txt").read())


text:
Q: How does USB Power Delivery work with voltages above 5V without damaging 5V peripherals? I have a Qi wireless charging pad for my phone, powered via a micro-usb port. The markings on it indicate that it will accept the typical 5V that nearly every USB port provides, or it will accept 9V for "fast charge".
I was under the impression that USB standards allowed for no more than 5V.
My research shows that USB Power Delivery has several profiles (up to 20V), and Revision 2.0 Version 1.2 includes a 9V profile.
Now I'm wondering: How can voltages above the usual 5V be provided without worry of damaging an expensive phone when connecting them directly (no wireless pad)? If things are running at different voltages, wouldn't that cause an issue?
In this example, 9V is used for fast charging, but could that 9V be sent to my phone? Do phones have a safeguard for this? The USB standard allows for up to 20V. That's a lot when expecting only 5V. Some "dumb" devices are powered directly off of USB, like cheap LEDs and fans that have no IC. Surely they would blow upon 20V!
I'm guessing there is data exchanged between the power source and the peripheral, ultimately telling the power source whether or not it's okay to provide more than 5V. Some USB charging cables don't have data pins though, which can allow for faster charging. In this case, it seems that not having data pins would be a restriction. Maybe the power source would have to default to 5V?. Unfortunately I cannot find an explicit protocol/explanation of how the different potentials are managed.

A: Your initial guess is correct, ICs such as the TPS65982 handle the negotiation of power, and that one in particular handles the entire voltage spec of 5-20V.
Update
For USB-PD through micro-usb, it needs to be done through a PD aware cable. USB-OTG added an additional pin to the micro connectors (the ID pin) which is left floating on the micro-b connector. A USB-PD device uses that pin to negotiate the power profile determine if the cable is PD aware.
Your 'dumb' devices don't get damaged because USB-PD has a 'start up profile', by default it's 5V/2A (in the 1.0 version):

As the sidenote says, if you're using a 'dumb' cable (even if it's connected to a smart device), then all you'll get is 5V/1.5A.
Once a smart device is connected, however, it can negotiate a higher PD profile through the Vbus by using the PD communication protocol, which is a 24MHz BSFK protocol.
The PD 2.0 specification is a bit different. The fixed power outputs of 1.0 have been deprecated, and there are 4 nominal voltage levels with varying current abilities:

It has also been updated to include type C connectors, which as you mentioned have the CC pin, and use BMC encoding to communicate on that pin. It is important to note however that this protocol is backward compatible with the USB 2.0 devices that implement 1.0 as well.

Update 20170206
Adding new information based on Ali Chen's answer. Your device may make use of the Qualcomm Quick Charge protocol, which uses the data lines to negotiate. Specifically, the portable device puts a pair of voltages on the D+ and D- lines, and the Quick Charge IC applies a different voltage depending on whether or not the IC is configured to connect to class A or B devices. For Quick Charge 3.0, the negotiation table is as follows:

To determine if this applies to you, simply connect a USB cable that does not have data lines inside to your wireless charger or to your phone. If it reads 9V, then it's not using the Quick Charge protocol to negotiate voltage (or, at the very least, it's not negotiating over the data lines, since there could be other protocols in use). Also, and probably more effective, You could also put the D+ and D- lines on a scope, and observe the voltage changes. Here is also a state diagram for reference, taken from a Quick Charge 3.0 IC, the NCP4371:

Sources:
https://en.wikipedia.org/wiki/USB_On-The-Go
https://electronics.stackexchange.com/a/165808/17582
https://doc.xdevs.com/doc/Standards/USB%203.1/usb_31_030215/USB%20Power%20Delivery/USB_PD_R2_0%20V1.0%20-%2020140807.pdf
http://www.st.com/content/ccc/resource/sales_and_marketing/presentation/product_presentation/group0/5a/b1/8e/6c/2b/0d/46/3c/Apec/files/APEC_2016_USB_Power.pdf/_jcr_content/translations/en.APEC_2016_USB_Power.pdf
http://www.onsemi.com/pub_link/Collateral/NCP4371-D.PDF

A: For the sake of accuracy, I feel that I need to refine a bit the BigHomie answer.
The main worry of OP is about not damaging devices that do not tolerate VBUS above 5V. The answer is simple: by default, a USB port initially provides the same safe 5V power, and nothing more.
The higher voltages and capabilities of power providers are only available upon mutual negotiations between a device (consumer) and a port (provider). If the device does not support this intelligence, no elevated power will be delivered, and no problem will occur. [ADDENDUM: details of identification of Power Delivery capabilities and mechanisms of negotiations are cumbersome and still evolving, and are beyond the scope of a single stackexchange article]
Now about the current state of PD: unfortunately, specifications appears to evolve slightly faster than wikipedia contributors bother to check. In the new Rev.3.0 of PD specifications (V1.0a, March 25, 2016, + ECNs of August 2, 2016) the BFSK negotiations over VBUS are depreciated.
In reality, the PD v1.0 with PD negotiation over VBUS with BFSK data coding did never take off, maybe one or two devices were ever made in the entire world. So, currently going forward, the only way to negotiate Power Delivery is through Type-C CC pin.
[ADDENDUM2: there are also proprietary types of PD, like Qualcomm "Quick Charge", protocol details are unknown]
[ADDENDUM3: upon further research out of sheer curiosity, it looks like the QCOM QCharge technology already captured most of the mobile market, while the official PD standard is lagging way behind, and could be a flop, as all previous BC1.1, BC1.2, PD1.0, PD2.0 "standards" were]


text:
Q: Getting data from Fragment upon parent activity Button Click my android app main activity contains two fragments.The main activity also contain two buttons-save and cancel.The fragments contain EditTexts and Spinners.i want to take data from these EditTexts and Spinner upon Save button click event(Event occur in parent activity).Is it Possible?

A: You are able to get the current fragment by doing getFragmentManager().findFragmentById(R.id.fragmentId) that will return the current fragment. You can then check its type by calling getClass() or by checking its instance as such if(getFragmentManager().findFragmentById(R.id.fragmentId) instanceof MyFragment){
//Code goes here
} You can then type cast it if it is the correct class and call whatever methods you want
MyFragment fragment=(MyFragment)getFragmentManager().findFragmentById(R.id.fragmentId);
fragment.getSomeData();


text:
Q: Intent without second activity name I know that intents are used to to start a new activity from another one, and pass data from activity to another. But in the documentation http://developer.android.com/reference/android/content/Intent.html there are also constructors of Intent to which we only pass an action (no parameter of a second activity class), so I was wondering in which case this kind of intent can be used ?

A: An Intent provides a facility for performing late runtime binding between the code in different applications.
Intent
Two Primary form of Intents implicit and explicit
You are Talking about implicit Intents

Implicit Intents have not specified a component; instead, they must include enough information for the system to determine which of the available components is best to run for that intent.

Suppose if Your app need to ask the User to enable GPS in his mobile for finding his Latitude and Longitude co-ordinates.In that Case We need to navigate him to GPS Settings automatically
Here is the example to move to the GPS(Launch Settings) of the phone
 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
 startActivity(intent);


text:
Q: Is it a right way to response when query database? I use express and MySql with node-orm2.
There is a GET request to get some data from database.
var loginFormChecker = function (phone, pwd, cb) {
    var ret = {};

    userBaseModel.exists({
        phone: phone,
        password: pwd
    }, function (err, exists) {
        if (err) {
            // database error
            ret = new returnData({
                error: error.database,
                type: 0
            });
        } else {
            ret = new returnData({
                data: exists,
                type: 1
            });
        }

        cb(ret);
    });
};

router.route('/login')
.get(function (req, res) {
    var query = req.query;

    var output = function (ret) {
        if (ret) {
            res.send(ret);
        } else {
            res.status(500).send('something broken!');
        }
    };

    userService.loginFormChecker(query.p, query.k, output);
});

I pass the output function to loginFormChecker, and call it in the callback of querying data.
I do not know whether it is a right way to do it. Is there a better way to do, maybe promise or something?
Thanks.


text:
Q: Azure CLI aks install cli permission denied and sudo does not work I'm trying to run
az aks install-cli
 but I get an error that says
Downloading client to "/usr/local/bin/kubectl" from "https://storage.googleapis.com/kubernetes-release/release/v1.14.0/bin/linux/amd64/kubectl"
Connection error while attempting to download client ([Errno 13] Permission denied: '/usr/local/bin/kubectl')

If I use sudo I get:
bash: sudo: command not found

Not sure how to elevate permissions other than using sudo

A: You do not need to install the kubectl for AKS if you use the Azure Cloud Shell, that's a default tool installed in it. See all the default tools installed in Azure Cloud Shell.
So you should take a look at the list if you want to install a tool in the Azure Cloud Shell.
And permissions are set as regular users without sudo access. Any installation outside your $Home directory is not persisted. So you cannot execute the sudo command in it.

A: Apparently, this is expected. It tries to install it in /usr/local/bin which isnt user writable.
You need to either use: sudo aks kubernetes install-cli
OR
use the --install-location to install to another location.
There is an issue similar to this reported on azure-cli repo: https://github.com/Azure/azure-cli/issues/2558

A: I still get error when I run it in Azure Portal Cloud Shell Powershell window -

but as it is specified above kubectl is already installed. I ran kubectl commands directly after switching to BASH - it ran fine.


text:
Q: Compare Network logs with const using Testcafe I'm trying to see if request is triggered when I scroll down the page.
I cannot use RequestURL because of timestamp. I know that there is RequestLogger.
What I'm trying to do is:

*

*create const which contains part of request URL, get specific log

*from Network tab in Dev-Tool in Chrome (maybe filter them) compare

*log with const to see if it contains the same pattern.

And if they begin with the same pattern pass the test

A: Ok guys. Here is a workaround:
const logger = RequestLogger(new RegExp(`somestring`));

Then I use
await t.expect(logger.requests.length).eql(1);


text:
Q: How to execute php code after html page load after full html page load want to execute some php api's & script and display response
<html>
<body>
content
<?php
//some php script execute after full page load
?>
</body>
</html>

A: To do so you could make use of the Ajax calls after the page is rendered ,
$(window).load(function(){ /*This allows to execute your code after the  page is rendered fully */
    $.get("<path to php file>", function(data){
     /* you can then process the ajax response as needed */
    });
})

You can this (Javascript that executes after page load) ,to be helpful to load your script after page load

A: PHP is a server-side programming language. It gets executed when you request a page. So you cannot execute it after the page has been loaded.
If you need to check if something has loaded on the client side, you'll have to use a client-side programming language like JavaScript.
That way you can make a request to a PHP file (which will be executed) and get process everything that is returned by the file.
You can do this using JavaScript or jQuery (a JavaScript library):
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
    // Check if the page has loaded completely
    $(document).ready( function() {
        $('#some_id').load('php-file.php');
    });
</script>


text:
Q: React Native Pressable has to be clicked twice to be executed I am using react native and firebase v9. When I click to add a chatroom, an alert prompt pops up, the user enters a room name and firebase should automatically roll it out to the UI. But what happens is when the modal is closed, I then have to click the add button again and then the chat room will roll out. How can I fix this so when the user enters a name, presses ok it automatically shows on the UI? Thanks!
My state:
 const [rooms, setRooms] = useState([]);
 const [input, setInput] = useState("");

Here is my JSX:
      <ScrollView horizontal showsHorizontalScrollIndicator={false}>
        <Pressable onPress={handleAddRoom}>
          <View style={styles.addRoom}>
            <MaterialCommunityIcons
              name="plus-circle"
              color="black"
              size={42}
            />
            <Text style={styles.nameText}>Add</Text>
          </View>
        </Pressable>

Here are my functions for uploading to firebasev9:
  const handleAddRoom = () => {
    Alert.prompt("Add New Chat Room", "Please enter a name", [
      { text: "CANCEL", onPress: null },
      { text: "OK", onPress: (text) => setInput(text) },
    ]);

    if (input) {
      const colRef = collection(db, "rooms");
      addDoc(colRef, {
        image: inputData,
        roomName: input,
      });
    }
    setInput("");
  };

  const fetchRooms = async () => {
    try {
      const colRef = query(collection(db, "rooms"), orderBy("roomName", "asc"));
      onSnapshot(colRef, (snapshot) => {
        setRooms(
          snapshot.docs.map((doc) => ({
            id: doc.id,
            roomName: doc.data().roomName,
            image: doc.data().image,
          }))
        );
      });
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    fetchRooms();
  }, []);


text:
Q: Help Solve a Circuit Using Mesh Current Analysis I'm Trying To Solve This Circuit Using Mesh Current Analysis But I'm getting that the currents are unsolvable (Matrix is wrong ) .
Question :

Find The Power of Each Source in :

$$ \Downarrow  $$My Try At Solving This  :

I Randomly Chose Current Flow Directions , Then Using Mesh Current Analysis  I Got :
$$\begin{aligned}\left( 1\right) I_{1}\left( R_{2}+R_{1}+R_{1}\right) +I_{2}R_{2}+I_{3}R_{6}=V_{G}\\
\left( 2\right) I_{2}\left( R_{2}+R_{3}+R_{5}\right) +I_{1}R_{2}+I_{4}R_{5}=V_{S1}\\
\left( 3\right) I_{3}\left( R_{4}+R_{6}\right) +I_{1}R_{6}+I_{4}R_{4}=V_{G}\\
\left( 4\right) I_{4}\left( R_{0}+R_{4}+R_{5}\right) +I_{3}R_{4}+I_{2}R_{5}=V_{s2}\end{aligned}$$
Using KVL for \$i_{x}\$ We Get:
$$\begin{aligned}\begin{cases}i_{x}=I_{1}+I_{2}\\
V_{0}=5\cdot i_{x}=5\cdot \left( I_{1}+I_{2}\right) \end{cases}\\\end{aligned}
$$
And :
$$\begin{aligned}\begin{cases}V_{Y}=-I_{1}\cdot R_{1}=-15\cdot I_{1}\\
I_{3}=i_{G}=0.4\cdot V_{Y}=-6I_{1}\end{cases}\end{aligned} $$
Hence We Get :
$$ \begin{gathered}\left( 1\right) I_{1}\cdot 30+I_{2}\cdot 10+I_{1}\cdot  -30 & = 5 I_{1}+I_{2}\ \\  -I_{1}\cdot 5+I_{2}5 & = 0\\
\left( 2\right) I_{1}\cdot 10+I_{2}\cdot 35+I_{4}\cdot 5-25 & =0\\
\left( 3\right) I_{1}\cdot 5-I_{1}\cdot 180+I_{4}\cdot 25 & =5\left( I_{1}+I_{2}\right) \\
-I_{1}\cdot 180-I_{2} \cdot 5 +I_{4}\cdot 25 & =0\\
\left( 4\right) -I_{1} \cdot 150+I_{2}\cdot 5+I_{4}\cdot 40-50 & =0\end{gathered}$$
A Cleaner Look :
$$ \begin{gathered}\left( 1\right)-I_{1}\cdot 5+I_{2}\cdot5 & = 0\\
\left( 2\right) I_{1}\cdot 10+I_{2}\cdot 35+I_{4}\cdot 5 & =25\\
\left( 3\right)-I_{1}\cdot 180-I_{2} \cdot 5 +I_{4}\cdot 25 & =0\\
\left( 4\right) -I_{1} \cdot 150+I_{2}\cdot 5+I_{4}\cdot 40 & =50\end{gathered}$$
Yet , there is NO SOLUTION to these Set of Equations (The system is inconsistent):
$$
  \begin{pmatrix}
    -5 & 5 & 0 &\bigm|& 0\\
    10 & 35 & 5 &\bigm|& 25 \\
    -180 & -5 & 25 &\bigm|& 0\\
    -150 & 5 & 40 &\bigm|& 50\\
\end{pmatrix} \longrightarrow ... \longrightarrow   \begin{pmatrix}
    1 & 0 & 0 &\bigm|& \frac{25}{82}\\
    0 & 1 & 0 &\bigm|& \frac{25}{82} \\
    0 & 0 & 1 &\bigm|& \frac{185}{82}\\
    0 & 0 & 0 &\bigm|& \frac{325}{82}\\
\end{pmatrix} $$
- I Really Don't know why my solution is not working , I'd Appreciate Any Kind Of Help !

A: Quick summary of your problem statement
First off, here's a labeled schematic drawn up in LTspice (free from Linear Tech):

I placed a ground at the intersection, since that's where I decided to start all of the loops you have. I then went around the loop in the direction indicated.
KVL development
My equations are:
$$\begin{align*}
i_G&=i_3=0.4\,i_1 R_1
\\
V_G &= 5\left(i_1+i_2\right)
\\
0\:\text{V}-R_6\left(i_1+i_3\right)+V_G-R_1\, i_1-R_2\left(i_1+i_2\right)&=0\:\text{V}
\\
0\:\text{V}-R_5\left(i_2+i_4\right)-R_3\, i_2+V_{S_1}-R_2\left(i_2+i_1\right)&=0\:\text{V}
\\
0\:\text{V}-R_6\left(i_3+i_1\right)+V_G+V_{i_{_\text{G}}}-R_4\left(i_3+i_4\right)&=0\:\text{V}
\\
0\:\text{V}-R_5\left(i_4+i_2\right)+V_{S_2}-R_0\, i_4-R_4\left(i_4+i_3\right)&=0\:\text{V}
\end{align*}$$
I assigned a voltage across the dependent current source, of course, to solve for. And note the sign for \$i_3\$ that I used. It's different from what I saw in your question.
Solver solution
Using SymPy, I find:
var('r0 r1 r2 r3 r4 r5 r6 i1 i2 i4 vs1 vs2 vig')
vg = 5 * ( i1 + i2 )
i3 = 0.4 * i1 * r1
eq1 = Eq( 0 - r6*(i1+i3) + vg - r1*i1 - r2*(i1+i2), 0 )
eq2 = Eq( 0 - r5*(i2+i4) - r3*i2 + vs1 - r2*(i2+i1), 0 )
eq3 = Eq( 0 - r6*(i3+i1) + vg + vig - r4*(i3+i4), 0 )
eq4 = Eq( 0 - r5*(i4+i2) + vs2 - r0*i4 - r4*(i4+i3), 0 )
ans = solve( [ eq1, eq2, eq3, eq4 ], [ i1, i2, i4, vig ] )

ans[ i1 ].subs({r0:10,r1:15,r2:10,r3:20,r4:25,r5:5,r6:5,vs1:25,vs2:50})
     -0.0484652665589661
ans[ i2 ].subs({r0:10,r1:15,r2:10,r3:20,r4:25,r5:5,r6:5,vs1:25,vs2:50})
      0.533117932148627
ans[ i4 ].subs({r0:10,r1:15,r2:10,r3:20,r4:25,r5:5,r6:5,vs1:25,vs2:50})
      1.36510500807754
ans[ vig ].subs({r0:10,r1:15,r2:10,r3:20,r4:25,r5:5,r6:5,vs1:25,vs2:50})
      22.7382875605816

That's what I get for answers.
Comparison vs Spice simulation
Here's what LTspice says:

I think that's a match.
Summary
It's now your job to examine your own development and compare it with what I did.
Keep in mind that you can construct, out of whole cloth, voltage differences and currents where you need them. In this case, as I was walking around the loop for \$i_3\$ I found I needed a "voltage difference" for the dependent current source. So I just made one up on the spot.
As you can see, it either works out (as it should for a problem you are given) or else it doesn't because you've either over-specified or under-specified the problem. In this case, it worked out fine because the problem is, in fact, solvable. Which is a good thing.

A: Your equation 3 doesn't include a term for the dependent current source, \$i_G\$. You can't just ignore the voltage across that source or assume that it is zero.


text:
Q: My Magic 8 ball My magic 8 ball code won't work for some reason. The basic code works but it wont give one answer, it starts some never ending loop. Any help?
import sys
import random

ans = True

while ans:
    question = input("Ask the magic 8 ball a question: (press enter to quit) ")

    answers = random.randint(1,8)

    if question == "":
        sys.exit()

    elif answers == 1:
        print ("It is certain")

    elif answers == 2:
        print ("Outlook good")

    elif answers == 3:
        print ("You may rely on it")

    elif answers == 4:
        print ("Ask again later")

    elif answers == 5:
        print ("Concentrate and ask again")

    elif answers == 6:
        print ("Reply hazy, try again")

    elif answers == 7:
        print ("My reply is no")

    elif answers == 8:
        print ("My sources say no")

Generally I would figure this out myself but I have been looking at it for two years

A: Try add ans = False at the end like this:
import sys
import random

ans = True

while ans:
    question = input("Ask the magic 8 ball a question: (press enter to quit) ")

    answers = random.randint(1,8)

    if question == "":
        sys.exit()

elif answers == 1:
    print ("It is certain")

    elif answers == 2:
        print ("Outlook good")

    elif answers == 3:
        print ("You may rely on it")

    elif answers == 4:
        print ("Ask again later")

    elif answers == 5:
        print ("Concentrate and ask again")

    elif answers == 6:
        print ("Reply hazy, try again")

    elif answers == 7:
        print ("My reply is no")

    elif answers == 8:
        print ("My sources say no")
    ans = False

A: If you don't want a loop, don't use a while.
For a 1 shot response, try this :
import random

answers = ("It is certain","Outlook good","You may rely on it",\
           "Ask again later","Concentrate and ask again",\
           "Reply hazy, try again","My reply is no","My sources say no")

if input("Ask the magic 8 ball a question: (press enter to quit) "):
    print( answers[random.randint(0,len( answers )-1)] )


text:
Q: OpenCL Memory Buffer not passing the right values to kernel I am trying to learn OpenCL by writing a simple program to add the absolute value of a subtraction of a point's dimensions. When I finished writing the code, the output seemed wrong and so I decided to integrate some printf's in the code and kernel to verify that all the variables are passed correctly to the kernel. By doing this, I learned that the input variables were NOT correctly sent to the kernel, because printing them would return incorrect data (all zeros, to be precise). I have tried changing the data type from uint8 to int, but that did not seem to have any effect. How can I correctly send uint8 variables to the memory buffer in OpenCL? I really cannot seem to identify what I am doing wrong in writing and sending the memory buffers so that they show up incorrectly and would appreciate any opinion, advice or help.
Thank you in advance.
EDIT: Question is now solved. I have updated the code below according to the kind feedback provided in the comment and answer sections. Many thanks!
Code below:
#include <iostream>
#include <chrono>
#include <CL/cl.hpp>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
#define USE_PLATFORM_NR  0

#define SIZE 100*1024*1024UL

//SAD DEFINES
#define NUM_DIM_SAD         5
#define NUM_POINTS_SAD      10
//#define NUM_LOOPS_SAD       20
#define SAD_SEED            2014
//NUM_LOOPS * NUM_POINTS should be 75M

//SSD DEFINES
#define NUM_DIM_SSD         128
#define NUM_POINTS_SSD      150000
//#define NUM_LOOPS_SSD       1000
#define SSD_SEED            2048
//NUM_LOOPS * NUM_POINTS should be 150M

// Threadblock sizes (e.g. for kernels )
#define TS 5

// =================================================================================================

// Set the kernel as a string
const char* kernelstring =
"__kernel void SAD(const int num_points_sad, const int num_dim_sad,"
"                      const global unsigned char* m1_set,"
"                      const global unsigned char* m2_set,"
"                      global unsigned char* sad_gpu) {"
"    const int Point = get_global_id(0);"
"    unsigned char acc = 0;"
"    printf(\" POINT: %d \\n \", Point); "
"    for (int s=0; s<num_dim_sad ; s++) {"
"        printf(\"GPU: i = %d | m1_set = %d| m2_set = %d \\n \",Point*num_dim_sad + s,m1_set[Point*num_dim_sad+s],m2_set[Point*num_dim_sad+s]);}"
"    for (int k=0; k<num_dim_sad; k++) {"
"        acc += abs( m1_set[Point*num_dim_sad + k] - m2_set[Point*num_dim_sad + k] );"
"    }"
"    printf(\"ACC: %d \\n \",acc);"
"    sad_gpu[Point] = acc;"
"}";

// =================================================================================================

// Matrix-multiplication using a custom OpenCL SGEMM kernel.
int main() {

    cout << "Computing naive SAD & SSD for result checking" << endl;
    //naive implementation on CPU for result checking
    uint8_t* m1_set;// [NUM_POINTS][NUM_DIM];
    uint8_t* m2_set;// [NUM_POINTS][NUM_DIM];

    m1_set = (uint8_t*)malloc(sizeof(uint8_t*) * NUM_POINTS_SAD * NUM_DIM_SAD);
    m2_set = (uint8_t*)malloc(sizeof(uint8_t*) * NUM_POINTS_SAD * NUM_DIM_SAD);

    uint8_t* sad;    //   [NUM_POINTS];
    uint8_t* sad_gpu;//   [NUM_POINTS];
    sad =     (uint8_t*)malloc(sizeof(uint8_t) * NUM_POINTS_SAD);
    sad_gpu = (uint8_t*)malloc(sizeof(uint8_t) * NUM_POINTS_SAD);

    srand(SAD_SEED);
    for (int i = 0; i < NUM_POINTS_SAD * NUM_DIM_SAD; i++)
    {
        sad[i/NUM_DIM_SAD] = 0;
        m1_set[i] = rand() / (uint8_t)RAND_MAX;
        m2_set[i] = rand() / (uint8_t)RAND_MAX;
        cout << "CPU: i = " << i << "| m1_set = " << (unsigned int)m1_set[i] << "| m2_set = " << (unsigned int)m2_set[i] << endl;
    }

    for (int i = 0; i < NUM_POINTS_SAD * NUM_DIM_SAD; i++)
         sad[i/NUM_DIM_SAD] += abs(m1_set[i] - m2_set[i]);

    cl_int err;

    // Configure the OpenCL environment
    printf(">>> Initializing OpenCL...\n");
    cl_platform_id platform = USE_PLATFORM_NR;
    err = clGetPlatformIDs(1, &platform, NULL);
    if (err != CL_SUCCESS) { cout << err << "clGetPlatformId"; return -1;}
    cl_device_id device = 0;
    err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
    if (err != CL_SUCCESS) { cout << err << "clGetDeviceIDs"; return -1; }
    cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
    if (err != CL_SUCCESS) { cout << err << "clCreateContext"; return -1; }
    cl_command_queue queue = clCreateCommandQueue(context, device, 0, &err);
    if (err != CL_SUCCESS) { cout << err << "clCreateCommandQueue"; return -1; }
    char deviceName[1024];
    err = clGetDeviceInfo(device, CL_DEVICE_NAME, 1024, deviceName, NULL);
    if (err != CL_SUCCESS) { cout << err << "clGetDeviceInfo"; return -1; }
    cl_event event = NULL;

    // Compile the kernel
    cl_program program = clCreateProgramWithSource(context, 1, &kernelstring_sad, NULL, &err);
    if (err != CL_SUCCESS) { cout << err << "clCreateProgramWithSource"; return -1; }
    err = clBuildProgram(program, 0, NULL, "", NULL, NULL);
    if (err != CL_SUCCESS) { cout << err << "clBuildProgram"; return -1; }

    // Check for compilation errors
    size_t logSize;
    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
    if (err != CL_SUCCESS) { cout << err << "clGetProgramBuildInfo"; return -1; }
    char* messages = (char*)malloc((1 + logSize) * sizeof(char));
    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, logSize, messages, NULL);
    if (err != CL_SUCCESS) { cout << err << "clGetProgramBuildInfo2"; return -1; }
    messages[logSize] = '\0';
    if (logSize > 10) { printf(">>> Compiler message: %s\n", messages); }
    free(messages);

    // Prepare OpenCL memory objects
    cl_mem buf_m1 = clCreateBuffer(context, CL_MEM_READ_ONLY, NUM_DIM_SAD * NUM_POINTS_SAD * sizeof(uint8_t), NULL, &err);
    if (err != CL_SUCCESS) { cout << err << "clCreateBuffer_m1"; return -1; }
    cl_mem buf_m2 = clCreateBuffer(context, CL_MEM_READ_ONLY, NUM_DIM_SAD * NUM_POINTS_SAD * sizeof(uint8_t), NULL, &err);
    if (err != CL_SUCCESS) { cout << err << "clCreateBuffer_m2"; return -1; }
    cl_mem buf_sad = clCreateBuffer(context, CL_MEM_READ_WRITE, NUM_POINTS_SAD * sizeof(uint8_t), NULL, NULL);
    if (err != CL_SUCCESS) { cout << err << "clCreateBuffer_sad"; return -1; }

    // Copy matrices to the GPU
    err = clEnqueueWriteBuffer(queue, buf_m1, CL_TRUE, 0, NUM_DIM_SAD * NUM_POINTS_SAD * sizeof(uint8_t), m1_set, 0, NULL, NULL);
    if (err != CL_SUCCESS) { cout << err << "clEnqueueWriteBuffer_m1"; return -1; }
    err = clEnqueueWriteBuffer(queue, buf_m2, CL_TRUE, 0, NUM_DIM_SAD * NUM_POINTS_SAD * sizeof(uint8_t), m2_set, 0, NULL, NULL);
    if (err != CL_SUCCESS) { cout << err << "clEnqueueWriteBuffer_m2"; return -1; }
    err = clEnqueueWriteBuffer(queue, buf_sad, CL_TRUE, 0, NUM_POINTS_SAD * sizeof(uint8_t), sad_gpu, 0, NULL, NULL);
    if (err != CL_SUCCESS) { cout << err << "clEnqueueWriteBuffer_sad"; return -1; }

    // Configure the kernel and set its arguments
    int num_points_sad = NUM_POINTS_SAD;
    int num_dim_sad =    NUM_DIM_SAD;
    cl_kernel kernel = clCreateKernel(program, "SAD", &err);
    if (err != CL_SUCCESS) { cout << err << "clCreateKernel"; return -1; }
    err = clSetKernelArg(kernel, 0, sizeof(int), (void*)&num_points_sad);
    if (err != CL_SUCCESS) { cout << err << "clCreateKernel_arg0"; return -1; }
    err = clSetKernelArg(kernel, 1, sizeof(int), (void*)&num_dim_sad);
    if (err != CL_SUCCESS) { cout << err << "clCreateKernel_arg1"; return -1; }
    err = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&buf_m1);
    if (err != CL_SUCCESS) { cout << err << "clCreateKernel_arg2"; return -1; }
    err = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void*)&buf_m2);
    if (err != CL_SUCCESS) { cout << err << "clCreateKernel_arg3"; return -1; }
    err = clSetKernelArg(kernel, 4, sizeof(cl_mem), (void*)&buf_sad);
    if (err != CL_SUCCESS) { cout << err << "clCreateKernel4"; return -1; }

    // Start the timed loop
    printf(">>> Starting SAD GPU run...\n");
    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();

 //   const size_t local[1] = { TS };
    const size_t global[1] = { NUM_POINTS_SAD };
    err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global, NULL, 0, NULL, &event); //local
    if (err != CL_SUCCESS) { cout << err << "clEnqueueNDRangeKernel"; return -1; }
    // Wait for calculations to be finished
    clWaitForEvents(1, &event);

    // End the timed loop
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    // Copy the output matrix C back to the CPU memory
    clEnqueueReadBuffer(queue, buf_sad, CL_TRUE, 0, NUM_POINTS_SAD * sizeof(uint8_t), sad_gpu, 0, NULL, NULL);
    auto us = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();
    std::cout << "Time difference = " << us << " us " << std::endl;
    // Free the OpenCL memory objects
    clReleaseMemObject(buf_m1);
    clReleaseMemObject(buf_m2);
    clReleaseMemObject(buf_sad);

    // Clean-up OpenCL
    clReleaseCommandQueue(queue);
    clReleaseContext(context);
    clReleaseProgram(program);
    clReleaseKernel(kernel);

    for (int i = 0; i < NUM_POINTS_SAD; i++)
    {
        cout << "i: " << i;
        cout << " | CPU: " << (unsigned int)sad[i];
        cout << " | GPU: " << (unsigned int)sad_gpu[i];
        cout << endl;
    }
    // Free the host memory objects
    free(m1_set);
    free(m2_set);
    free(sad);
    free(sad_gpu);

    // Exit
    return 0;
}

A: There is an error in function where the context is being created - one of the parameters is being passed at wrong position.
Instead:
cl_context context = clCreateContext(NULL, 1, &device, NULL, &err, NULL);

Should be:
cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
                                                             ^^^^^^^^^^

Also the way the error are output is still not much helpful. Should be something like this:
cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
if (err != CL_SUCCESS)
{
    cout << err << "clCreateContext";
    return -1;
}

This way we stop the code execution when the error occurred and we know for which function it happened.
======= UPDATE ========================================================
There is wrong type being used in kernel: uint8 type in OpenCL is a vector type meaning array of 8 values of type int.
To fix the problem use uchar/unsigned char type in the OpenCL kernel which is an equivalent of uint8_t/unsigned char from c++.
See OpenCL data types and Scalar data types.


text:
Q: How to add the content of two files with Ruby Hello there I have two files in CSV format before processing I need to have the content of the two in a single file.
I do this in ms-dos like this
d:\project\>copy file?.csv file3

File1.csv

File2.csv

1 archivo(s) copiado(s).

then
rename file3 file.csv

but I need to do this in Ruby, the files have only text in tabulated format.
Thanks in advance.

A: Run this from your project folder or change "file.csv" etc. with full paths.
 File.open("file.csv", "w") do |f|
   f.puts(File.read("File1.csv"), File.read("File2.csv"))
 end


text:
Q: Calling PFXExportCertStoreEx in Go does not return data I'm working in Go 1.6 on Windows and trying to export a certificate container to a PFX (the ultimate goal here is to access an exportable private key from the certificate store).
I have opened a memory store and inserted a certificate into the store:
var storedCertCtx *syscall.CertContext
storeHandle, err := syscall.CertOpenStore(syscall.CERT_STORE_PROV_MEMORY, 0, 0, syscall.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, 0)
err = syscall.CertAddCertificateContextToStore(storeHandle, certenum, syscall.CERT_STORE_ADD_ALWAYS, &storedCertCtx)

Now I want to generate a PFX of that store. I have defined a struct for containing the data blob and want to use PFXExportCertStoreEx to get a PFX of the store:
var (
    crypt32                  = syscall.NewLazyDLL("crypt32.dll")
    procPFXExportCertStoreEx = crypt32.NewProc("PFXExportCertStoreEx")
)

type CRYPTOAPI_BLOB struct {
    DataSize uint32
    Data     *byte
}

var pfxBlob CRYPTOAPI_BLOB
err = PfxExportCertStore(storeHandle, &pfxBlob, syscall.StringToUTF16Ptr("MyPassword"), 0, 0)

syscall.Syscall6(procPFXExportCertStoreEx.Addr(), 5,
        uintptr(storeHandle),                //hStore
        uintptr(unsafe.Pointer(&pfxBlob)),   //*pPFX
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("password"))), //szPassword
        0,   //*pvPara
        0,   //dwFlags
        0)

And this half works.
DataSize is populated with what looks like an appropriate value (i.e. if I add more certificates to the store, it grows bigger), however Data is always <nil>.
Seeing as it's meant to be populated with a pointer, I have tried declaring it as *uintptr and uint32 (just to see if anything gets populated), but nothing. The value is always untouched (if I manually put junk data in there, the junk data stays after the syscall is executed).
Have I defined the struct incorrectly? There is precious few examples to go for getting this done in Go, but from what I can see from the numerous C examples, this should be working.

A: This is the expected behavior.
According to this: https://msdn.microsoft.com/en-us/library/windows/desktop/aa387313(v=vs.85).aspx, the pPFX struct requires a pre-allocated buffer, with the size in the cbData field, which will be updated with the size of the data copied in.
If the call is made with pbData equal to NULL, only the cbData field is updated to reflect the size needed for the output buffer.

A: JimB's answer is most certainly correct, but I want to add this for followup in case anyone else is going down this path. The actual code that I had to use to get the PFX file into CRYPTOAPI_BLOB was:
var (
    crypt32                  = syscall.NewLazyDLL("crypt32.dll")
    procPFXExportCertStoreEx = crypt32.NewProc("PFXExportCertStoreEx")
    procCryptMemAlloc        = crypt32.NewProc("CryptMemAlloc")
    procCryptMemFree         = crypt32.NewProc("CryptMemFree")
)

type CRYPTOAPI_BLOB struct {
    cbData uint32
    pbData *byte
}

func (b *CRYPTOAPI_BLOB) ToByteArray() []byte {
    d := make([]byte, b.cbData)
    copy(d, (*[1 << 30]byte)(unsafe.Pointer(b.pbData))[:])
    return d
}

func PfxExportCertStore(storeHandle syscall.Handle, password string, flags uint32) (returnData []byte, err error) {

    var pfxBlob CRYPTOAPI_BLOB

    r1, _, _ := syscall.Syscall6(procPFXExportCertStoreEx.Addr(), 5,
        uintptr(storeHandle),                                        //hStore
        uintptr(unsafe.Pointer(&pfxBlob)),                           //*pPFX
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(password))), //szPassword
        0,              //*pvPara
        uintptr(flags), //dwFlags
        0)

    r2, _, _ := syscall.Syscall(procCryptMemAlloc.Addr(), 1, uintptr(unsafe.Pointer(&pfxBlob.cbData)), 0, 0)

    p := unsafe.Pointer(&r2)
    q := (*byte)(p)
    pfxBlob.pbData = q
    defer syscall.Syscall(procCryptMemFree.Addr(), 1, uintptr(unsafe.Pointer(pfxBlob.pbData)), 0, 0)

    r3, _, _ := syscall.Syscall6(procPFXExportCertStoreEx.Addr(), 5,
        uintptr(storeHandle),                                        //hStore
        uintptr(unsafe.Pointer(&pfxBlob)),                           //*pPFX
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(password))), //szPassword
        0,              //*pvPara
        uintptr(flags), //dwFlags
        0)

    returnData = pfxBlob.ToByteArray()
    return
}

(I have stripped the error handling to make it easier to read). The first call to PFXExportCertStoreEx just returns the size, and once we have the size we can do a call to PFXExportCertStoreEx to allocate a buffer, and then we pass the same pointer to PFXExportCertStoreEx, but this time it has the allocated buffer, and we get the full PFX file returned.


text:
Q: Why isn't Hapi matching this path when I set the HTTP method to * My goal is to create a route to proxy requests to a specific path to a remote API. I'm having trouble making this route match GET requests. POST requests are matched and the call is passed through. For example, a POST request from the browser to /api/document proxies to the destination successfully. Hapi responds to GET /api/document with a 404, though. I can create two identical routes with different values for the method key but that doesn't seem DRY.
    server.route({
    path: '/api/{path*}',
    method: '*',
    config: {
        handler: {
            proxy: {
                passThrough: true,
                mapUri: function (request, callback) {
                    var baseUri = 'https://remote/services/v1';
                    var resourceUri = request.path.replace('/api', '');
                    var destinationUri = baseUri + resourceUri;

                    server.log('Proxying to: ' + destinationUri);
                    callback(null, destinationUri);
                }
            }
        }
    }
});

    server.route({
        method: 'GET',
        path: '/{path*}',
        handler: {
            file: '../build/index.html'
        }
    });

A: According to the docs, when you use the '' wildcard for the method in your route it will only match when an exact match isn't found.  Your 'catchall' route's method matches the route and the method is more specific so it appears to be going through the /{path} route instead.

method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually.

You can probably fix this by either using a wildcard for your catch all or passing an array for the proxy route instead of using the wildcard.


text:
Q: VirtualBox not exporting disk image in OVA I have a VM I am attempting to export. When I attempt to export it (OVF 2.0), the OVA file is a mere ~12kb and does not contain the disk image. The only potentially relevant difference I see compared to other VMs which export successfully is that this has a .vmdk on a SCSI controller rather than a .vdi on a SATA controller.
I am aware of the "copy the entire folder" method, but this is less than ideal for my application.
I am running VirtualBox 5.0.30 on Windows 10.

A: The VMDK was using an SCSI controller. Once I moved it to the SATA controller, exporting the VM included the disk image.

A: You can try below things. I checked on Virtualbox on Ubuntu host.

*

*Shutdown the vm

*Detach disk

*Convert disk to .vdi using "VBoxManage clonehd"

*Attach new disk to SATA storage on your vm

*Power on and verify everything is working

*Shutdown vm and try to export again