text:
Q: I keep getting this error in python3 "TypeError: an integer is required (got type str)" so basically i have been working on a project that makes a login and signup system with python3 using tkinter
ive come to the point where i have to save the things inputed into a file with open()
but it keeps giving me this error
    File "C:\Users\Kirill Rodionov\AppData\Local\atom\app-1.45.0\login.py", line 19, in storeData
    passwordFile = open("Passwords.txt", "a")
TypeError: an integer is required (got type str)

this is my code
from tkinter import *
from os import *

nameFile = open("Names.txt", O_APPEND)
passwordFile = open("Passwords.txt", O_APPEND)

def SignUp():

    def storeData():

        name = signupNameEntry.get()
        password = signupPasswordEntry.get()
        rpassword = signupRPasswordEntry.get()

        print(name)
        print(password)
        print(rpassword)
        print(type(name))
        print(type(password))

        if password == rpassword:
            print("passwords match")
            nameFile = open("Names.txt", "a")
            passwordFile = open("Passwords.txt", "a")
            passwordFile.write(password)
            nameFile.write(name)
            passwordFile.close()
            nameFile.close()

        else:
            print("passwords don't match")

    signup = Toplevel()
    signup.title("Sign Up")

    Label(signup, text="Name", pady=5, padx=5).grid(row=1, column=1)
    Label(signup, text="Password", pady=5, padx=5).grid(row=2, column=1)
    Label(signup, text="Repeat\nPassword").grid(row=3, column=1)
    signupNameEntry = Entry(signup)
    signupNameEntry.grid(row=1, column=2)
    signupPasswordEntry = Entry(signup)
    signupPasswordEntry.grid(row=2, column=2)
    signupRPasswordEntry = Entry(signup)
    signupRPasswordEntry.grid(row=3, column=2)
    signupButton = Button(signup, text="Sign Up", command=storeData, pady=5, padx=5).grid(row=4, column=2)

    signup.mainloop()

the other part is the main loop i hope you get the code is the main loop i cant post the whole code because it says "your post is mostly code"
btw im new to stackoverflow

A: Are you using from os import *? In this case, it may be trying to use os.open. See An integer is required? open().


text:
Q: Does the following integral converge? Let $a\in(-1,1)$, let:
$$ P(x,y)=C_{n,a}\frac{y^{1-a}}{(|x|^2+y^2)^{(n+1-a)/2}},\quad\forall (x,y)\in \mathbb{R}^n\times(0,\infty),$$
let $f\in \mathcal{S}(\mathbb{R}^n)$, i.e. $f$ is a Schwartz function, let:
$$ u(x,y)=\int_{\mathbb{R}^n}P(x-\xi,y)f(\xi)\,d\xi,\quad\forall (x,y)\in \mathbb{R}^n\times(0,\infty),$$
is true that:
$$\int_0^\infty\int_{\mathbb{R}^n}y^a|u(x,y)|^2\,dx\,dy<\infty?$$
I heve no idea on how to proceed, any help is appreciated.

A: In dimension one, this is false even when $a = 0$. In higher dimensions, however, the integral is indeed finite.
The proof involves just Plancherel's theorem: when $a = 0$ , the double integral is equal to
$$\int_0^\infty \int_{\mathbb R^n} |\hat u(\xi, y)|^2 d\xi dy = \int_0^\infty \int_{\mathbb R^n} |e^{-|\xi| y} \hat f(\xi)|^2 d\xi dy = \int_{\mathbb R^n} (2 |\xi|)^{-1} |\hat f(\xi)|^2 d\xi.$$
(Here $\hat u$ is the Fourier transform with respect to $x$ alone.)
Now $|\hat f(\xi)|^2$ is bounded and integrable. In dimension 2 and higher, $|\xi|^{-1}$ is a sum of a bounded function and an integrable function; hence the integral converges. In dimension 1, however, $|\xi|^{-1}$ is not locally integrable, and hence the integral diverges, unles $\hat f(0) = 0$, that is, $f$ has integral zero.
When $a \ne 0$, the argument is essentially the same, but the Fourier transform of $P(x, y)$ is no longer $e^{-|\xi| y}$, but rather $c_a (y |\xi|)^{(1-a)/2} K_{(1-a)/2}(y |\xi|)$  (or something very similar), where $K$ is the Bessel function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TabbedPage renders multiple times in Xamarin Forms using shell I have a problem using TabbedPages in my Xamarin.Forms mobile app (Shell).
When I navigate to a TabbedPage containing 3 tabs, the 3 tabs are crunched up and repeating themselves all down the page.
To replicate it I:

*

*Created a standard Xamarin Forms Shell app in Visual Studio 2019 Version 16.4.5

*Upgraded to Xamarin Forms 4.4.0.991640

*Added a TabbedPage and changed the navigation of the About button to navigate to the TabbedPage instead.

Here is a photo of how it looks on my android phone
If I remember correctly it also happened when I deployed to my iPhone.
Update due to Jason's comment
All the code is automatically generated by Microsoft, my only interaction was to add an empty TabbedPage and change a line of code in AppShell.xaml.
(Note - while not relevant to this particular demo, I also got the same issue when navigating from a ListView in a ContentPage in my Xamarin.Forms app.)
Added TabbedPage1.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    x:Class="App1.Views.TabbedPage1">
    <!--Pages can be added as references or inline-->
    <ContentPage Title="Tab 1" />
    <ContentPage Title="Tab 2" />
    <ContentPage Title="Tab 3" />
</TabbedPage>

Added TabbedPage1.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App1.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TabbedPage1 : TabbedPage
    {
        public TabbedPage1()
        {
            InitializeComponent();
        }
    }
}

Amended AppShell.xaml (all I did was change the line from DataTemplate local:AboutPage to DataTemplate local:TabbedPage1):
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:local="clr-namespace:App1.Views"
    Title="App1"
    x:Class="App1.AppShell">

<!--
Styles and Resources
-->
<Shell.Resources>
    <ResourceDictionary>
        <Color x:Key="NavigationPrimary">#2196F3</Color>
        <Style x:Key="BaseStyle" TargetType="Element">
            <Setter Property="Shell.BackgroundColor" Value="{StaticResource NavigationPrimary}" />
            <Setter Property="Shell.ForegroundColor" Value="White" />
            <Setter Property="Shell.TitleColor" Value="White" />
            <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
            <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
            <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
            <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
            <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
            <Setter Property="Shell.TabBarTitleColor" Value="White"/>
        </Style>
        <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
    </ResourceDictionary>
</Shell.Resources>

<!-- Your Pages -->
<TabBar>
    <Tab Title="Browse" Icon="tab_feed.png">
        <ShellContent ContentTemplate="{DataTemplate local:ItemsPage}" />
    </Tab>
    <Tab Title="About" Icon="tab_about.png">
        <ShellContent ContentTemplate="{DataTemplate local:TabbedPage1}" />
    </Tab>
</TabBar>

<!-- Optional Templates
// These may be provided inline as below or as separate classes.

// This header appears at the top of the Flyout.
<Shell.FlyoutHeaderTemplate>
<DataTemplate>
<Grid>ContentHere</Grid>
</DataTemplate>
</Shell.FlyoutHeaderTemplate>

// ItemTemplate is for ShellItems as displayed in a Flyout
<Shell.ItemTemplate>
<DataTemplate>
<ContentView>
Bindable Properties: Title, Icon
</ContentView>
</DataTemplate>
</Shell.ItemTemplate>

// MenuItemTemplate is for MenuItems as displayed in a Flyout
<Shell.MenuItemTemplate>
<DataTemplate>
<ContentView>
Bindable Properties: Text, Icon
</ContentView>
</DataTemplate>
</Shell.MenuItemTemplate>

-->

</Shell>


text:
Q: How to retrieve data in chunks using Pagination(Limit/offset) from a select query in this following example code? I have an select sql query statement that returns 900000+ rows.But i want data to be retrieved in small chunks using limit/offset clause,so that it can be easily inserted into another table.
public class Snomedinfo {
    public void snomedinfoinsert()
    {
    Root oRoot = null;
    ResultSet oRsSelect = null;
    PreparedStatement oPrStmt = null;
    PreparedStatement oPrStmt2 = null;
    PreparedStatement oPrStmtSelect = null;
    String strSql = null;
    int count=0;
    int batchSize=1000;

    ResultSet oRs = null;
    String refid = null;
    String id = null;
    String effectivetime = null;
    String active = null;
    String moduleid = null;
    String conceptid = null;
    String languagecode = null;
    String typeid = null;
    String term = null;
    String caseSignificanceid = null;

    try{
    oRoot = Root.createDbConnection(null);

    strSql = "SELECT d.* FROM snomed_conceptdata c, snomed_descriptiondata d WHERE c.active = 1 and conceptid = c.id AND d.active = 1 ";//this is the query that returns 900000 rows
    oPrStmt2 = oRoot.con.prepareStatement(strSql);

    oRs = oPrStmt2.executeQuery();
    String sql = "INSERT INTO snomedinfo_date (refid,id,effectivetime,active,moduleid,conceptid,languagecode,typeid,term,caseSignificanceid) VALUES( ?, ?, ?,?,?,?,?,?,?,?)";
    oPrStmt = oRoot.con.prepareStatement(sql);

        while (oRs.next())
        {
            refid = Root.TrimString(oRs.getString("refid"));
            id = Root.TrimString(oRs.getString("id"));
            effectivetime = Root.TrimString(oRs.getString("effectivetime"));
            active = Root.TrimString(oRs.getString("active"));
            moduleid = Root.TrimString(oRs.getString("moduleid"));
            conceptid = Root.TrimString(oRs.getString("conceptid"));
            languagecode = Root.TrimString(oRs.getString("languagecode"));
            typeid = Root.TrimString(oRs.getString("typeid"));
            term = Root.TrimString(oRs.getString("term"));
            caseSignificanceid = Root.TrimString(oRs.getString("caseSignificanceid"));

            oPrStmt.setString(1, refid);
            oPrStmt.setString(2, id);
            oPrStmt.setString(3, effectivetime);
            oPrStmt.setString(4, active);
            oPrStmt.setString(5, moduleid);
            oPrStmt.setString(6, conceptid);
            oPrStmt.setString(7, languagecode);
            oPrStmt.setString(8, typeid );
            oPrStmt.setString(9, term);
            oPrStmt.setString(10, caseSignificanceid);
            oPrStmt.addBatch();
            if (++count % batchSize == 0) {
                oPrStmt.executeBatch();
                oPrStmt.clearBatch();
            }

        }

        oPrStmt.executeBatch();

    System.out.println("done");
    }

    catch (Exception e) {
        e.printStackTrace();

    }

    finally {

        oRs = Root.EcwCloseResultSet(oRs);
        oPrStmt = Root.EcwClosePreparedStatement(oPrStmt);
        oPrStmt = Root.EcwClosePreparedStatement(oPrStmt2);

        oRoot = Root.closeDbConnection(null, oRoot);
    }
}

How do i implement the logic for setting limit/offset in my program ??
I have an select sql query statement that returns 900000+ rows.But i want data to be retrieved in small chunks using limit/offset clause,so that it can be easily inserted into another table.

A: SELECT d.* FROM snomed_conceptdata c, snomed_descriptiondata d WHERE c.active = 1 and conceptid = c.id AND d.active = 1 limit offset,limit;
Offset - The row from which you want to start reading data.
Limit - The number of rows you want to read.
For example-
SELECT d.* FROM snomed_conceptdata c, snomed_descriptiondata d WHERE c.active = 1 and conceptid = c.id AND d.active = 1 limit 10,20;
If you are using this in a web page then you need pagination.
Otherwise use a simple loop like this -
for(int i=0;i<=(90000/100);i+=10){
strSql = " SELECT d.* FROM snomed_conceptdata c, snomed_descriptiondata d WHERE c.active = 1 and conceptid = c.id AND d.active = 1 limit "+i+",10";
// run other code
}
This offsets the pointer by 10 rows with each iteration.


text:
Q: jQuery check if BootstrapValidator passed I want my Laravel's login page to show a spinning circle and a message "You're being logged in" inside the "Login" button after it was pressed. OK so far, however, I'd need to validate first whether bootstrap validator passes all input. This is my JS:
$("#loginSubmit").click(function()
    {
        $("#button_login_content").replaceWith("You're being logged in  ");
        $("#loginSubmit").prop("disabled", true);
        $("#authentication").submit();
    });
loginSubmit is the submit button's id. button_login_content is a div inside the button which then is altered by $("#button_login_content").replaceWith("You're being logged in  ");. authentication is the form's name. So far, it does what I want. However, entering nothing or invalid data and hitting submit leads to red warnings shown beneath the input fields (which is also what I want) but doesn't prevent the button from changing its content and so on. This is why I thought that I needed to check something like this [pseudocode]:
if(!bootstrapValidator.checked()) return;
before actually running the rest of $("#loginSubmit").click(). I actually googled and didn't find anything. I tried myself various things such as the code above. Is there a way to check this? This is my validator:
$("#authentication").bootstrapValidator({
        fields: {
            username: {
                validators: {
                    notEmpty: {
                        message: 'The email address is required'
                    },
                    regexp: {
                        regexp: /^\S+@\S{1,}\.\S{1,}$/,
                        message: 'Please enter valid email format'
                    }
                }
            },
            password: {
                validators: {
                    notEmpty: {
                        message: 'Password is required'
                    }

                }
            }

        }
    });

A: This is the solution:
var validator = $("#authentication").data("bootstrapValidator");
 validator.validate();
 if(!validator.isValid()) { return; }


text:
Q: Daisy chain two monitors on a single thunderbolt port I currently have 3 monitors (Asus VN247H) connected to a mid 2014 15" MBP Retina. Two connections are on thunderbolt (with TB->HDMI adaptors) and one on the HDMI port. I would like to use one of the thunderbolt ports for another peripheral. Is there a way to daisy chain two monitors on a single TB port?

A: You can chain up to 12 thunderbolt devices of any kind. If you want to connect a non-thunderbolt device, make sure you put it at the end of the chain.
Also keep in mind that Apple, for some reason, doesn't allow 3rd party-non-thunderbolt-displays chained directly after their own Thunderbolt Display. However it will work if another thunderbolt-device is inbetween.


text:
Q: Compare two json objects and return another JSON Object with only changes in c# I would like to compare two JSON Objects and return another object with only the properties missing in one JSON Object. For example:
json1 = {
   "name": "ABCD",
   "hobbies": [
     {
       "water_hobby1": "Rafting",
       "water_hobby2": "swimming",
     },
     {
       "hobby3": "Singing",
       "hobby4": "Drawing",
     }
    ]
}

json2 = {
   "name": "ABCD",
   "hobbies": [
     {
       "hobby3": "Singing",
       "hobby4": "Drawing",
     }
    ]
}

Expected output:
json = {
  "hobbies": [
     {
           "water_hobby1": "Rafting",
           "water_hobby2": "swimming",
         },
   ]
}

Lets say I write json1.getDiff(json2); I want the resulting json to contain only the properties that are missing in json2 and present in json1. The nesting of properties and properties themselves is dynamic.
My actual JSOn is like below:

{
  "property1": 0,
  "property2": "value1",
  "property3": [
    {
      "name": "value2",
      "property4": [
        {
          "property5": 0,
          "name": "value3",
          "porperty6": 0,
          "property7": [
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            },
            {
              "name": "",
              "property": 0,
              "property": value,
              "property": "value",
              "property": "value",
              "property": "value"
            }
          ]
        },
  {
   Many Such Objects With nested array and objects
  }]
 },
 {
  "name": "value",
        "property4": []
 }
}

Suppose my source JSON Contains Property7[0] Object but my another JSON object does not contain Property7[0] object. I want to only return Property7[0] as my output. The code I am following returns the whole Property7 array which obviously does not contain property7[0] object. But that is not I want. The code is not looping through the objects in the array Property7. some help for me to  achieve this is what I seek.

A: 1st you have to define for yourself this "diff". E.g.: What should be returned when both objects have some property, but have a different value?
Shouldn't be very difficult to write some code based on your definition that just compares the properties of two objects. I think this post can help you: Find and return JSON differences using newtonsoft in C#?


text:
Q: Mod rewrite redirect every subdirectory to the same file I have a website with a products.html file. Now, inside this file, I will have some Javascript code that checks the url to show the correct products/categories. This are some examples of the urls:
example.com/products
example.com/products/
example.com/products/shoes
example.com/products/shoes/
example.com/products/shoes/adidas
example.com/products/shoes/adidas/
example.com/products/shoes/adidas/adidas-predator-20.3
example.com/products/shoes/adidas/adidas-predator-20.3/

So basically, I want that everytime someone goes to the any of the above urls, I want to get the file products.html, I'll manage the rest with JS.
Also I want to be able to test this on my local machine. In this case, my URLs will be:
localhost/websites/myWebsite/products
localhost/websites/myWebsite/products/
localhost/websites/myWebsite/products/shoes
localhost/websites/myWebsite/products/shoes/
localhost/websites/myWebsite/products/shoes/adidas
localhost/websites/myWebsite/products/shoes/adidas/
localhost/websites/myWebsite/products/shoes/adidas/adidas-predator-20.3
localhost/websites/myWebsite/products/shoes/adidas/adidas-predator-20.3/

So I think we would need two htaccess files right?

A: You may use this single rule that will work on localhost and on production host as well:
RewriteEngine On

RewriteRule (?:^|/)products(?:/|$) products.html [L,NC]

A: With your shown samples could you please try following, you should place .htaccess file on same level where folder products is present. Also place the products.html in same level too.
RewriteEngine ON
RewriteCond %{REQUEST_URI} ^/(?:products)/?((?:shoes)/?((?:adidas)/?((?:adidas-predator-20\.3)/?)?)?)?$ [NC]
RewriteRule ^(.*)$ products.html [L]

If these are the only rules you will have then change L to END as an additional note here.


text:
Q: Catch/Modify (Message)/Rethrow Exception of same type I want a central place to extract information from an exception, set all the information I need to its message parameter and then rethrow that information as an Exception of the same type.
The better solution probably would be to do this at the place where the exception is finally being handled (and its message logged), but.. I have control over the place throwing the exception, and not over the place that receives the exception and only logs its Message content.
Apart from that design decision and given that message is a readonly property, I would have (?) to create a new Exception object in some way, is there a way to make the new exception object the same type as the original one?
Here is my code, which does not compile - it stumbles over the throw line (where I try to dynamically cast the object).
public static void RethrowExceptionWithFullDetailInMessage(string msg, Exception ex)
{
    Exception curEx = ex;
    int cnt = 0;
    while (curEx != null)
    {
        msg += "\r\n";
        msg += cnt++ + " ex.message: " + curEx.Message + "\r\n";
        msg += "Stack: " + curEx.StackTrace;
        curEx = curEx.InnerException;
    }
    object newEx = Convert.ChangeType(new Exception(msg), ex.GetType());
    throw (ex.GetType())newEx;
}

Does this
throw (Exception)newEx;

preserve the type? (It compiles.)
Does the Convert.ChangeType make sure I get an Exception of the correct type?

A: You could do this to dynamically call the constructor of the exception type:
object newEx = Activator.CreateInstance(ex.GetType(), new object[] { msg });

Your original code would fail at runtime, because for Convert.ChangeType towork, the exception type would have to implement IConvertible and support conversion to the other exception type, which i doubt.

A: May be it's a bit late, but would this work for you?
catch (Exception ex)
{
    throw new Exception("New message", ex);
}

A: What you are trying to do here is not as easy as it seems and there are lots of pitfalls to consider.
Remember, that Convert.ChangeType() will convert one type to another (assuming such a path exists, like converting a string to an int for example).  Most exceptions wont do this (Why would they?)
IN order to pull this off, you would have to examine the exception type at runtime with the GetType() method and locate a constructor that has requirements you can satisfy and invoke it.  Be careful here, since you don't have control over how all exceptions are defined there is no guarantee you will have access to "standard" constructors.
That being said, if you feel like being a rule breaker you could do something like this...
void Main()
{
    try
    {
        throw new Exception("Bar");
    }
    catch(Exception ex)
    {
        //I spit on the rules and change the message anyway
        ex.GetType().GetField("_message", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ex, "Foo");
        throw ex;
    }
}

A: You can change the exception message via reflection like this...
Exception exception = new Exception("Some message.");
var type = typeof(Exception);
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
var fieldInfo = type.GetField("_message", flags);
fieldInfo.SetValue(exception, message);

So you can create an extension method...
namespace ExceptionExample
{
    public static class ExceptionExtensions
    {
        public static void SetMessage(this Exception exception, string message)
        {
            if (exception == null)
                throw new ArgumentNullException(nameof(exception));

            var type = typeof(Exception);
            var flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var fieldInfo = type.GetField("_message", flags);
            fieldInfo.SetValue(exception, message);
        }
    }
}

And then use it...
...
using static ExceptionExample.ExceptionExtensions;

public class SomeClass
{
    public void SomeMethod()
    {
        var reader = AnotherClass.GetReader();
        try
        {
            reader.Read();
        }
        catch (Exception ex)
        {
            var connection = reader?.Connection;
            ex.SetMessage($"The exception message was replaced.\n\nOriginal message: {ex.Message}\n\nDatabase: {connection?.Database}");
            throw; // you will not lose the stack trace
        }
    }
}

You have to keep in mind that if you use "throw ex;" the stack trace will be lost.
To avoid this you must use "throw;" without the exception.

A: Supplemental comment.
These all work in supplementing the exception message, but I found that using "throw" did NOT preserve the StackTrace - the last trace pointed to the actual "throw" statement (dropping the root cause location).
From discussions elsewhere, it's clear there are some circumstances that throw doesn't preserve due to CLR stack limitations
Throw and preserve stack trace not as expected as described by Code Analysis
Solution: dump the StackTrace in each exception (e.g. and add to the error message) and/or dump to logging


text:
Q: go fiber http functions On the home page of "gofiber.io" they show this code
package main

import (
    "log"

    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    app.Get("/", func (c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    log.Fatal(app.Listen(":3000"))
}

In the code, the function inside the second argument of the "Get" function says it is returning an error but returns a c.SendString("Hello, World!"). What do I not understand about this that makes it ok to say you're returning an error but you are returning something else?
I admit I am new to Golang and even newer to Go Fiber so please help me understand this better.

A: The resulting error is returned from SendString (nil, if no error)
See https://docs.gofiber.io/api/ctx#send
The signature for is:
func (c *Ctx) SendString(body string) error


text:
Q: Blow-up of a Pencil of Cubic Curves (Miranda's basic theory of elliptic surfaces) In Rick Miranda's "The basic theory of elliptic surfaces" the Example (I.5.1) see page 7 on a pencil of plane curves contains an argument Inot understand yet:
Let $C_1$ be a smooth cubic curve in $\mathbb{P^2}$ and let $C_2$ be any other cubic. By intersection theory and Bezout's theorem the intersection number $C_1 \cdot C_2$ is $9$. We form a pencil $P \subset \mathbb{P^2} $ generated by $C_1$ and $C_2$; in english that is a $\mathbb{P^1}$-family of curves (or more generally divisors) $[ \lambda C_1 + \mu C_2 ]$, which has $9$ base points $x_1,..., x_9$ . This gives only a rational map to $\mathbb{P^1}$. After blowing them up the fundamental locus of this rational map is resolved and we obtain a honest morphism $\pi: X \to \mathbb{P^1}$ where $X= Blowup(P)_{x_1,..., x_9}$ is the blowup of the pencil $P$ in these $ 9 $ points.
Then it is claimed that the canonical class of $X$ is $-C_1$ and in particular that this implies that $K_X^2= (-C_1)^2 =0$.
How to check that the canonical class of $X$ equals $-C_1$ and why does it have as consequence self-intersection number zero? The divisor $-C_1$ is definietely not vertical and therefore I not see why it's interesection with itself should vanish.

A: Note that such a blow-up $X$ can be represented by a degree $(1,3)$ hypersurface in $\mathbb{P}^1\times\mathbb{P}^2$, so you can see $K_X=-C$ by adjunction formula. We have $K_X^2=0$ because $X$ is a minimal elliptic surface (see  III.21 in Beauville's Complex Algebraic Surfaces).


text:
Q: operator implementations in swift In the following shift playground with operator += I get a compile error:
protocol Value {
    func get() -> Float
    mutating func set(to:Float)
}

func += (a:inout Value, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}

struct S : Value {
    var t:Float
    func get() -> Float {
        return t
    }
    mutating func set(to:Float) {
        t = to
    }
}

var s1 = S(t:3)
let s2 = S(t:4)
s1 += s2 // Compiler error: Binary operator '+=' cannot be applied to two 'S' operands

Now if I redefine my operator as
func += (a:inout S, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}

it works just fine. Why can I not define += with the left hand side as a Value?

A: As @Hamish stated in the comments, you can't use the protocol Value for the inout variable because the called function is free to assign an instance of some other Value conforming type to it.
Instead, you should make it generic like this:
func +=<T: Value>(a:inout T, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}


text:
Q: Reboot into USB stick on insert I would like to be able to insert a USB drive that, on insert, would reboot the computer into an operating system housed on the USB drive. The OS would be Linux-based. I would also like this to be cross-platform so it will work on any OS. I have considered a autorun setup as mentioned here, but it is Windows-only and as far as I can tell it doesn't work on the latest version of Windows.
P.S. I am new to Stack Exchange and if I posted this on the wrong site please move it (I think that's possible).

A: The stated scenario would need the fastboot or whatever they call it in windows to be disabled. Windows 10 guide here Then the next step you'll be doing is to change the boot order of the devices from BIOS.
I'm presuming from the question that you already have created a bootable USB stick, If you haven't then you'll have to create it first using a tool like Rufus or UUI(Universal USB Installer).
Now comes the last and most important step, for automatic reboot when the stick is plugged in, you'll need to create an autorun script for windows and allow it to execute by default when USB is plugged in to your system.
That's all for now, PM me if you have any troubles.
PS- I'll add the scripts later I'm currently on a trip.

A: I would try creating a separate drive built into your existing hard drive. U will have to create a new file path and download the software in the new drive. Then try autorun


text:
Q: protractor showing wrong chromedriver version and unable to run e2e tests I'm working with an angular2 web application were we have setup protractor for e2e testing but my all tests are keep failing for some ambiguous error.
The error is get is
× Full amount can be tendered to card via scanning the device
  - Failed: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=59.0.3071.115)
  (Driver info: chromedriver=2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 10.0.10586 x86_64)
  - Failed: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
 (Session info: chrome=59.0.3071.115)
 (Driver info: chromedriver=2.26.436362(5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 10.0.10586 x86_64)

My environment is windows 10, node version is 6.9.1, npm version is 3.8.6, chrome version is 59.xx, chromedriver version is 2.30 but don't know why its showing 2.26 in console along with error. I've tried to update it through npm install chromedriver (both locally and global) and it shows that 2.30 is installed but when I try to run protractor its show chromedriver=2.26.436362 (as you can see in output). I've tried many solution found on internet but nothing worked for me (included upgrading chrome to latest version + chromedriver to latest version, downgrading chrome to 58 and chromedriver to 2.28 etc).
Anything I'm missing in setting up my environment ? Any help would be appreciated. Thanks
*******UPDATE*******
I've upgraded chromedriver version to 2.30 and now started getting different error, it doesn't even start now, error is following
e2e/app/framework/element-functions.ts(43,29): error TS2349: Cannot invoke an expression whose type lacks a call signature.
e2e/app/framework/wait-functions.ts(45,18): error TS2345: Argument of type 'Function' is not assignable to parameter of type 'Promise<{}> | Condition<{}> | ((driver: WebDriver) => {})'.
Type 'Function' is not assignable to type '(driver: WebDriver) => {}'.
Type 'Function' provides no match for the signature '(driver: WebDriver): {}'
node_modules/blocking-proxy/built/lib/angular_wait_barrier.d.ts(43,43): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/blockingproxy.d.ts(40,13): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/client.d.ts(11,39): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/client.d.ts(18,42): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/client.d.ts(19,22): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/highlight_delay_barrier.d.ts(17,43): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/simple_webdriver_client.d.ts(14,47): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/simple_webdriver_client.d.ts(21,52): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/simple_webdriver_client.d.ts(29,56): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/simple_webdriver_client.d.ts(37,52): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/webdriver_proxy.d.ts(14,90): error TS2304: Cannot find name 'Promise'.
node_modules/blocking-proxy/built/lib/webdriver_proxy.d.ts(23,43): error TS2304: Cannot find name 'Promise'.
node_modules/protractor/built/plugins.d.ts(31,22): error TS2304: Cannot find name 'Promise'.
node_modules/protractor/built/plugins.d.ts(48,26): error TS2304: Cannot find name 'Promise'.
node_modules/protractor/built/plugins.d.ts(62,25): error TS2304: Cannot find name 'Promise'.
node_modules/protractor/built/plugins.d.ts(76,28): error TS2304: Cannot find name 'Promise'.
node_modules/protractor/built/plugins.d.ts(94,55): error TS2304: Cannot find name 'Promise'.

A: Yeah, I've seen this. Webdriver-manager gets confused, and grabs the wrong version. To fix, run this on both local (node_modules) and global (if you have it there too) Protractor installs.

*

*node_modules/.bin/webdriver-manager clean // removes all older versions

*node_modules/.bin/webdriver-manager update // get the latest


text:
Q: One or more errors occurred (an error occurred while sending the request) - Xamarin.Forms I'm currently in development to create an application with Xamarin.Forms to manage notifications in an intranet.
So I have a button "Connection" on the main page which connects to a webservice to verify the login and the password of the user first.
My problem is the connection to the webservice always failed.
I tested the webservice with postman and it's ok ; I get a response, but when I try it with the app in visual studio (UWP or Droid projects), an exception occurres each time and I don't know why.
This is my code :
private string WebServiceAuthentication()
{
    string url = "https://chlevinatier.agiir-portail.com/api/jsonws/AlertesPortail-portlet.portal/check-authentication";
    string login = "test";
    string password = "test";`

    using ( HttpClient client = new HttpClient() )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", "tjhGjfM1" );

        try
        {
            return client.GetAsync( $"{url}?login={login}&password={password}" ).Result.Content.ReadAsStringAsync().Result;
        }
        catch ( AggregateException ae )
        {
            ae.Handle( ( x ) =>
            {
                if ( x is HttpRequestException )
                {
                    HttpRequestException hre = x as HttpRequestException;
                    Debug.WriteLine( $"Data : {hre.Data}\nHelpLink : {hre.HelpLink}\nHResult : {hre.HResult}\nInnerException : {hre.InnerException}\nMessage : {hre.Message}\nSource : {hre.Source}\nStackTrace : {hre.StackTrace}" );
                }

                return false;
            });

            return string.Empty;
        }
        catch ( Eception e )
        {
            Debug.WriteLine( $"Data : {e.Data}\nHelpLink : {e.HelpLink}\nHResult : {e.HResult}\nInnerException : {e.InnerException}\nMessage : {e.Message}\nSource : {e.Source}\nStackTrace : {e.StackTrace}" );
            return string.Empty;
        }
    }
}

When I clicked on the button "Connection", I get this result on the debug screen on visual studio :
*******************************************************************************
>Data : System.Collections.ListDictionaryInternal
>HelpLink :
>HResult : -2147012851
>InnerException : System.Runtime.InteropServices.COMException (0x80072F0D): Le texte associé à ce code d'erreur est introuvable.

>L'autorité de certification n'est pas valide ou correcte

>   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>   at System.Net.Http.HttpHandlerToFilter.<SendAsync>d__4.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

>   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>   at System.Net.Http.HttpClientHandler.<SendAsync>d__86.MoveNext()

>Message : An error occurred while sending the request.
>Source : System.Net.Http
>StackTrace :
>at System.Net.Http.HttpClientHandler.  <SendAsync>d__86.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

>   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>   at System.Net.Http.HttpClient.<FinishSendAsync>d__58.MoveNext()
*******************************************************************************

A: The problem is that the domain https://chlevinatier.agiir-portail.com/ doesn't use a valid SSL/TLS certificate so the request doesn't work because connecting with a server with an untrusted certificate isn't safe (in the majority of cases).
Solutions:

*

*Download the certificate, add this to the app and import it for example following this answer. I have been looking for a solution with HttpClient but I didn't find it. This is the right way.

*Avoid the validation of certificates, following this answer
I hope this can help you.


text:
Q: How do I get the number of elements from a list which is in a map? I'm programming a student administration so far and want to sort courses by their number descending and ascending.
The student.class wields a list which I store my students in. Should look like this.
    public class courses{
        Coursenumber coursenumber;
        int grade;
        Teacher teacher;

        List<Student> listOfStudentsInCourse = new ArrayList<>();
}

And I'm putting that list in a map for easier access to the key-value pairs.
TreeMap<Coursenumber, Course> showAllCoursesMap = new TreeMap<>();

        Course testCourse1 = new Klasse(
                new Coursenumber("XYZ"),
                grade 5,
                mrLee);

        Course testCourse1 = new Klasse(
                new Coursenumber("XYZ"),
                grade 5,
                mrSmith);

I added both of them in the showAllCoursesMap by using the put-method. The output should look like
testcourse1 number of students: 2
testcourse2 number of students: 1

A: You can use the Stream API for Java >= Java 8.
Essentially what you want to do is some sorting based on Map values. Therefore we stream the map using sorted and compare based on the value using Map.Entry.comparingByValue(). This method takes a Comparator which we can provide by using Comparator.comparingInt(). We then only have to tell comparingInt() what the key is we want to compare on. In your case that's the length of the List so you need to get the list and its size. Last but not least collect the results in a list.
If you want the List sorted in reversed order add Collections.reverseOrder().
Here a minimal example that shows how you can could do it. The result will be of type List<Map.Entry<Integer, Application.Wrapper>> in my case. If you just want a list of the actual values (List<Application.Wrapper> in my case) you need to insert .map(Map.Entry::getValue) before toList()
import java.util.*;

public class Application {
    public static void main(String[] args) {

        var test = new TreeMap<Integer, Wrapper>();
        test.put(1, new Wrapper(List.of(1, 2, 3, 4, 5, 6)));
        test.put(2, new Wrapper(List.of(1, 2, 3, 4)));
        test.put(3, new Wrapper(List.of(1, 2)));
        test.put(4, new Wrapper(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9)));

        // sort in ascending order (default)
        var resultAscending = test
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(wrapper -> wrapper.getSomeList().size())))
                .toList();

        // sort in descending order
        var resultDescending = test
                .entrySet()
                .stream()
                // only change here: Collections.reverseOrder()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue(Comparator.comparingInt(wrapper -> wrapper.getSomeList().size()))))
                .toList();

        System.out.println(resultAscending);
        System.out.println(resultDescending);
    }

    static class Wrapper {
        List<Integer> someList;

        public Wrapper(List<Integer> someList) {
            this.someList = someList;
        }

        public List<Integer> getSomeList() {
            return someList;
        }

        @Override
        public String toString() {
            return someList + " (Size: %d)".formatted(someList.size());
        }
    }
}

Expected output
[3=[1, 2] (Size: 2), 2=[1, 2, 3, 4] (Size: 4), 1=[1, 2, 3, 4, 5, 6] (Size: 6), 4=[1, 2, 3, 4, 5, 6, 7, 8, 9] (Size: 9)]
[4=[1, 2, 3, 4, 5, 6, 7, 8, 9] (Size: 9), 1=[1, 2, 3, 4, 5, 6] (Size: 6), 2=[1, 2, 3, 4] (Size: 4), 3=[1, 2] (Size: 2)]

Please note: The toString() method uses formatted() which is available starting from Java 15, so if you do not have that use String.format(" Size: (%d)", someList.size()) instead of " (Size: %d)".formatted(someList.size()) or drop that formatting completely as it was only added for demo purposes here.


text:
Q: Increment character in string I have the following code:
string str="A";

I want to get the next alphabetical character programmatically (so B, C, D, E etc.)
Can anyone suggest a way of doing this?

A: If you are looking for something like "A".. "Z"..."AA", "AB"..."ZZ"..."AAA"...
, here is the code,
  public static string IncrementString(this string input)
    {
        string rtn = "A";
        if (!string.IsNullOrWhiteSpace(input))
        {
            bool prependNew = false;
            var sb = new StringBuilder(input.ToUpper());
            for (int i = (sb.Length - 1); i >= 0; i--)
            {
                if (i == sb.Length - 1)
                {
                    var nextChar = Convert.ToUInt16(sb[i]) + 1;
                    if (nextChar > 90)
                    {
                        sb[i] = 'A';
                        if ((i - 1) >= 0)
                        {
                            sb[i - 1] = (char)(Convert.ToUInt16(sb[i - 1]) + 1);
                        }
                        else
                        {
                            prependNew = true;
                        }
                    }
                    else
                    {
                        sb[i] = (char)(nextChar);
                        break;
                    }
                }
                else
                {
                    if (Convert.ToUInt16(sb[i]) > 90)
                    {
                        sb[i] = 'A';
                        if ((i - 1) >= 0)
                        {
                            sb[i - 1] = (char)(Convert.ToUInt16(sb[i - 1]) + 1);
                        }
                        else
                        {
                            prependNew = true;
                        }
                    }
                    else
                    {
                        break;
                    }

                }
            }
            rtn = sb.ToString();
            if (prependNew)
            {
                rtn = "A" + rtn;
            }
        }

        return rtn.ToUpper();
    }

A: var str = "A";
char firstChar = str[0];
char nextChar = (char)((int)firstChar + 1);
var newStr = nextChar.ToString();

A: Instead of whole strings, use Char.
char aChar = 'A';

aChar++; // After this line executes, `aChar` is `B`

A: I am looking for the same thing, and I am using string so I need to cast it.
You can do this if your variable is string:
string foo = "b";
char result = Convert.ToChar(foo[0] + 1); //Will result to 'c'


text:
Q: Concatenar endereço no Objeto Range VBA Excel Preciso concatenar um endereço no Objeto Range do Excel e não estou conseguindo.
O valor é uma variavel do tipo Integer.
Segue a linha de código:
Range("O10").Formula = "=SUM(O12:O" & "valor)"

A: Public Sub Teste()
  Dim Valor As Integer
  Valor = 3000
  Range("A1").Formula = "=SUM(D1:D" & Valor & ")"
End Sub


text:
Q: Issue with JS from fields obtained through Ajax response I use DataTables In order to create nicely displayed and managable table. To get data I use Ajax data source and prepared php script which connect to database and echo on screen date in JSON format.
assign.php
$q = "select o.id, a.id as aid, o.starttime,o.scid, count(case when v.severity = '0' then 1 else null end) as zero,
        count(case when v.severity = '1' then 1 else null end) as one,
        count(case when v.severity = '2' then 1 else null end) as two,
        count(case when v.severity = '3' then 1 else null end) as three, o.starttime as start
        from topic a, project v, person o
        where a.id = v.topic_id and a.id = o.topic_id and o.starttime = '".$_GET['date']."'
        group by o.id,o.starttime,o.scid,a.id order by id desc";
$result = $db->query($q)->fetchall(PDO::FETCH_ASSOC);
$arr = array();
foreach ($result as $row){
    if ($row['scid']==1){
        $button="<button     id=\"opener_".$row['aid']."\" class ='opener pure-button'  >Edit</button>";
    }
    else{
        $sys="";
        $button="<button id=\"opener_".$row['aid']."\" class ='opener pure-button'  >Assign</button>";
    }
    array_push($arr, array($button,$row['zero'],$row['one'],$row['two'],$row['three'],$row['starttime']));
}
$str = json_encode($arr);
$str= "{\"aaData\":".$str."}";
echo $str;

page displaing the table:

                    Button
                    Low
                    Medium
                    High
                    Critic

                    Button
                    Low
                    Medium
                    High
                    Critic

echo "

Select Person to link it with project

          <form action='/?page=test' id='persontoproject' method='post' class='asholder'><input id='existing' name='existing' value='' class='txt' style='width: 125px;' /><input type='submit' name='saveperson' value='Assign'></form>

";

Problem is that when user click on the button displayed in table (loaded from ajax) the JS which handle the click is not being executed. Is there a way to solve this issue?

A: I'm assuming the click event using $(.open) in your posted code is for the button.

Delegate Bindings

You might need to delegate the event binding to the closest static element on your page instead of on the buttons directly.
If the bindings scripts are executed before the buttons are in the DOM the events will not be bound.
In that case, using jQuery 1.7 or later you can use on() with delegation, similar to this:
$('#asset').on('click', '.opener', function(event) {

I'm assuming that the element with the id asset is already on the page, otherwise use $(document) or $('body') instead.
This will bind the event to the static element (#asset) but delegate it to the '.opener' selector.
For versions of jQuery pre 1.7 delegate() to bind the event instead, similar to this:
$('#asset').delegate('.opener', 'click', function(event) {

Note the parameter order between on() and delegate() differs!

A: Give the submit button an id like this--
<input type='submit' name='saveperson' value='Assign' id="submit">

and then in jquery code put--
 $("#submit").click(function(event) {
      //// code
     });


text:
Q: Concrete5 Content Block content into pagelist i'm building this website where i have event list on frontpage. I do this by using
pagelist block. Now my customer also want to show date of current event. I have created my own
event page template where i have this "date" block (ordinary content block) where user just types date he/she wants. Now i want this "date" to be part of pagelist..like so

12.10.2014 - Lorem ipsum

How do i do this ? I'm not php coder..
At first i tried Simple Event add-on but it did not work out because language of Concrete5 (finnish)..
// Mika

A: Pages and their attributes are easy to search and list in many different formats. Blocks are not.
If the date associated with each page was a page attribute, then it would be easy to list it with the page using many of the various page list addons or templates (including my own Uber List). So start by looking for a page list addon/template that includes dates or attributes, then work back from that to decide how you need to attach the date attribute to each event page.
Within the event pages, you can then either edit the date using the usual page attribute dialog and then revise your date block to just show that attribute, or revise your date block to save its data in that attribute, so editing the block edits the date (or use my Front End Attribute Editor block).
You don't really need your date block as there are already addons that can display page attributes (including my own Magic Data addon).
While I have given examples using my own addons, there are plenty of other page listing and attribute displaying blocks available. The thing they all have in common is making the date an attribute of the page.

A: You could make the date a page attribute instead of a block, then it is very easy to retrieve it in the PageList (using $date = $page->getAttribute('your_date_attribute_handle') within the foreach loop of the page list template).


text:
Q: An integral to compute the volume of the spherical shell by rotating an annulus about the $x$-axis?
Question: How do I construct the integral to compute the volume of a spherical "shell" via rotation of an annulus about the $x$-axis.

The set up: I have an annulus, $A$ which is centered at the origin of $\mathbb{R}^2$ and has an outer radius equal to $1$ and inner radius equal to $1/2.$ I want to spin $A$ all the way around the  $x$-axis and construct a spherical shell and write an integral to compute its volume. I am not certain how to do this. Note the integral set up is more important than the actual computation of the volume.
Very similiar Question

A: Shell method around the x axis, $V = \int_0^r 2(2\pi)\text{(shell radius)(shell height)} \ dy$
So for this problem $$\int_0^1 4\pi\cdot y\sqrt{1-y^2} \ dy - \int_0^{0.5} 4\pi\cdot y\sqrt{0.25 - y^2} \ dy$$

A: You already know (it's in the question you linked) that the volume of a solid obtained by rotating a segment of a curve $y=f(x)$ around the $x$-axis is:
$$ \int_a^b \pi\, f(x)^2\,dx $$
where $(a,b)$ is the interval on which your segment of $f(x)$ is defined.
For example, consider $f(x)=\sqrt{r^2-x^2}$, its graph is half of a circumference of radius $r$ and centered in the origin. Rotating that around the $x$-axis gives you a sphere, whose volume is:
$$ \int_{-r}^r \pi (r^2-x^2)\, dx $$
Now, a spherical shell is just a bigger sphere "minus" a smaller one...


text:
Q: What Windows API function should I use to mark/unmark files/folders as protected operating system file? What Windows API function should I use to mark/unmark files/folders as protected operating system file?

A: You can use the SetFileAttributes() API with flags FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM.

A: PathMakeSystemFolder() is the documented way to mark a directory as a system folder


text:
Q: How to debug program that doesn't like Alt+Tab? I am trying to fix an obscure bug in an old game by running it with IDA. The trouble is, the game runs fullscreen in 800x600 resolution and REALLY doesn't like being minimized, which makes it more or less impossible to actually use IDA while the game is running.
How might I approach this problem?


text:
Q: How to have make fail on some warnings but not others I have a make file that includes:
%.dat: %.txt
   ... PREPROCESSING OF TEXT FILE
   tidy -o $*.html $<
   ... FURTHER PROCESSING

tidy produces lots of warnings that I can suppress with the flag --show-warnings false, but despite supressing the warnings, the exit status from tidy still 1 instead of 0, and so make fails part way through the recipe. How can I have make continue in the face of tidy giving exit status 1 while still allowing make to fail if any other recipe gives warnings?
I have looked at these two question (Have make fail if unit tests fail and gcc, make: how to disable fail on warning?) but neither seems to deal with this problem.
AFTER EDIT: In Make: how to continue after a command fails?, the question relates to how one gets make to continue after any non-zero exit status in executing a particular command, whereas in my case, I want an exit status of 2 from tidy indicating errors, to cause make to fail, but I want an exit status of 1 from tidy, indicating warningsto allowmake to continue`.

A: The simpliest solution:
tidy -o $*.html $< || true

So if tidy's exit code isn't zero the true produces zero exit code.
But check the tidy's exit codes:

Exit Status
0
All input files were processed successfully.
1
There were warnings.
2
There were errors.

Maybe you want skip only the error code 1. In this case:
tidy -o $*.html $< || [ $$? -eq 1 ] && true


text:
Q: What is the defintion of variation in a box plot? Variation is a term I have always been confused with. The first time I heard it, it was defined as "the different between the max and min values in a distribution". Lately, I've been hearing that variation is actually either the difference between the first and third quartiles or the average of the square of the deviations of each number.
The question that I'm trying to do gives us a set of box plots and asks us to locate the day with the highest variation.

If the first definition was correct, then Friday would be the clear winner (because of the outlier who got barely any sleep at all). If the second definition was correct, then Saturday would be the winner.
I'm not sure if I'm making a mistake or confusing different terms, so can somebody please point me in the right direction?

A: A boxplot invites you to characterize variation in many different ways, by comparing the quantities shown on the plot: extremes, extremes of the whiskers, quartiles, and median.  That gives 21 different measures of variation in each one!  On that basis I can identify (with some difficulty, because many of the boxplots are similar to one another) three possible correct answers (Sat, Sun, and Mon).
To illustrate, here are sample data similar to yours:

Each boxplot depicts at least seven quantities, as labeled in the Thursday boxplot (although some may coincide): eXtremes, Fences (the tips of the whiskers), Hinges (the borders of the boxes), and the Median.  The first three occur below the median ("-" subscripts) and above ("+" subscripts), for a total of seven statistics.

The absolute difference between any two distinct statistics measures some aspect of "dispersion" or "variation" in the underlying data.

For instance, $X_{+} - X_{-}$ is the range, $H_{+} - H_{-}$ is the interquartile range, and so on.  Each such difference, apart from the range, focuses on a part of the data distribution.  This gives you a flexible tool for choosing what aspect of the dataset you wish to characterize.
Here are plots of each of these 21 statistics for the sample data.

In each plot I have highlighted the largest of the seven values.  The highlighting color is determined by the day of the week.  It is evident that five of the seven weekdays can be considered, in some specific sense, to have the largest variation.  (Only Tues and Fri don't show up.)  For instance, the "X-,X+" chart in row 1, column 6 plots the ranges and indicates Thursday's range is the largest.

To answer your question, then, you must

*

*Select some measure of variation.

*Assess it in the graphic by systematically comparing the corresponding parts in each boxplot to estimate their vertical distances.

*Select the day (or days) where those distances are the largest.
For instance, it looks to me like the largest $M$ to $X_{+}$ variation (the distance from the upper tip to the midline), which measures the spread of above-average values in the data, occurs on Sunday in your data, because there is an outlying extreme value then.
Ordinarily, one uses the IQR as measured by the box height $H_{+}-H_{-}$ as the default measure of variation in a boxplot.  That is because it is relatively unaffected by extreme values, making it a robust indicator of variation, and it is symmetric in not emphasizing high or low values.  So, if you are given no further guidance in the question, in the textbooks, or in your classnotes, this would be the measure to choose.


text:
Q: JScrollPane problem high position I have a problem with a JScrollPane that I can not switch to high position, I tried everything:
setValue(0);
setCaretPosition(0);
getViewport().setViewPosition(new Point(0,0));

Finally all ...
One thing only works for putting up is the use of a showMessageDialog, but I would prefer to avoid ...
That's part of my code:
public class fenetre_departement {

    private static final long serialVersionUID = 1L;
    private JPanel container = new JPanel();

    private Vector<Component> sous_titreComp = new Vector<Component>();

    public JPanel getContainer() {
        return container;
    }

    public void setContainer(JPanel container) {
        this.container = container;
    }

    private ImageIcon icon;
    private ImageIcon icon2;
    private ImageIcon icon3;
    private JTextArea titre = new JTextArea("");
    private JTextArea texte = new JTextArea("");
    private JTextArea titre2 = new JTextArea("");
    private JTextArea texte2 = new JTextArea("");
    private JTextArea titre3 = new JTextArea("");
    private JTextArea texte3 = new JTextArea("");
    private JTextArea titre4 = new JTextArea("");
    private JTextArea texte4 = new JTextArea("");
    private JTextArea titre5 = new JTextArea("");
    private JTextArea texte5 = new JTextArea("");
    private JTextArea titre6 = new JTextArea(":");
    private JTextArea texte6 = new JTextArea("");
    private JTextArea titre7 = new JTextArea("");
    private JTextArea texte7 = new JTextArea("");

    private JScrollBar ascenceur;

    private JScrollPane dipScroll;

    public JScrollPane getDipScroll() {
        return dipScroll;
    }

    public void setDipScroll(JScrollPane dipScroll) {
        this.dipScroll = dipScroll;
    }

    private Color sous_titre;

    public fenetre_departement(){

    container.setLayout(new BorderLayout());

    //Construction du header
    JPanel top = new JPanel();
    icon = new ImageIcon(getClass().getResource("/images/header_small.jpg"),"Liste des étudiants");
    JLabel lbli2 = new JLabel(icon);
    top.add(lbli2);

    //construction du panneau central
    JPanel middle = new JPanel();
    middle.setLayout(new BoxLayout(middle,BoxLayout.PAGE_AXIS));
    titre.setOpaque(false);
    titre.setEditable(false);
    titre.setFont(new Font("Arial",Font.BOLD,16));
    //construction du panneau intermédiaire inclus dans le panneau central
    JPanel col1 = new JPanel();
    col1.setLayout(new BorderLayout());
    icon2 = new ImageIcon(getClass().getResource("/images/logo_dis.jpg"),"Liste des étudiants");
    JLabel lbli3 = new JLabel(icon2);
    texte.setOpaque(false);
    texte.setEditable(false);
    middle.add(titre);
    col1.add(lbli3, BorderLayout.WEST);
    col1.add(texte, BorderLayout.CENTER);
    middle.add(col1);
    //construction des paragraphes de fin de panneau central
    titre2.setOpaque(false);
    titre2.setEditable(false);
    middle.add(titre2);
    texte2.setOpaque(false);
    texte2.setEditable(false);
    middle.add(texte2);
    titre3.setOpaque(false);
    titre3.setEditable(false);
    middle.add(titre3);
    //construction du panneau intermédiaire inclus dans le panneau central
    JPanel col2 = new JPanel();
    col2.setLayout(new BorderLayout());
    icon3 = new ImageIcon(getClass().getResource("/images/photo.png"),"Liste des étudiants");
    JLabel lbli4 = new JLabel(icon3);
    texte3.setOpaque(false);
    texte3.setEditable(false);
    col2.add(lbli4, BorderLayout.EAST);
    col2.add(texte3, BorderLayout.WEST);
    middle.add(col2);
    titre4.setOpaque(false);
    titre4.setEditable(false);
    middle.add(titre4);
    texte4.setOpaque(false);
    texte4.setEditable(false);
    middle.add(texte4);
    titre5.setOpaque(false);
    titre5.setEditable(false);
    middle.add(titre5);
    texte5.setOpaque(false);
    texte5.setEditable(false);
    middle.add(texte5);
    titre6.setOpaque(false);
    titre6.setEditable(false);
    middle.add(titre6);
    texte6.setOpaque(false);
    texte6.setEditable(false);
    middle.add(texte6);
    titre7.setOpaque(false);
    titre7.setEditable(false);
    middle.add(titre7);
    texte7.setOpaque(false);
    texte7.setEditable(false);
    middle.add(texte7);

    sous_titre = new Color(104,150,255);
    sous_titreComp.add(titre2);
    sous_titreComp.add(titre3);
    sous_titreComp.add(titre4);
    sous_titreComp.add(titre5);
    sous_titreComp.add(titre6);
    sous_titreComp.add(titre7);

    dipScroll = new JScrollPane(middle);
    dipScroll.setBorder(null);
    container.add(top, BorderLayout.NORTH);
    container.add(dipScroll, BorderLayout.CENTER);

    top.setBackground(new Color(255,255,255));
    middle.setBackground(new Color(255,255,255));
    col1.setBackground(new Color(255,255,255));
    col2.setBackground(new Color(255,255,255));

    for(Component c : sous_titreComp){
        c.setFont(new Font("Arial",Font.BOLD,15));
        c.setForeground(sous_titre);
    }
    }

    public void setAscenceur(JScrollBar ascenceur) {
        this.ascenceur = ascenceur;
    }

    public JScrollBar getAscenceur() {
        return ascenceur;
    }
}

Knowing that I call this page with a menu to get it into the panel with another class
if(e.getSource()==(this.Departement))
            {

                fenetre3 = new fenetre_departement();
                bas.removeAll();
                container2.removeAll();
                container2 = fenetre3.getContainer();

                bas.add(container2, BorderLayout.NORTH);
                this.setContentPane(container);

            }

Thank you very much for your help ...

A: On the item in the scrollbar, call scrollRectToVisible().


text:
Q: WSO2 - Move Databases to new Instance, APIM cannot find reference I have a WSO2 API Manager 1.6.0 setup with SVN repository syncing. I recently had to move my databases off a SQL Server instance to another SQL Server instance. The databases moved effortlessly, however, the API's are not showing like they used to before you log into the store page. I am also receiving these errors:
TID: [0] [AM] [2014-10-15 09:38:54,517]  INFO {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil} -  'admin@carbon.super [-1234]' logged in at [2014-10-15 09:38:54,517-0500] {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil}
TID: [0] [AM] [2014-10-15 09:38:54,710]  INFO {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil} -  'admin@carbon.super [-1234]' logged in at [2014-10-15 09:38:54,710-0500] {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil}
TID: [0] [AM] [2014-10-15 09:38:55,740] ERROR {org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO} -  Unable to find the API: org.wso2.carbon.apimgt.api.model.APIIdentifier@3b581336 in the database {org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO}
TID: [0] [AM] [2014-10-15 09:38:55,744] ERROR {org.wso2.carbon.apimgt.hostobjects.APIStoreHostObject} -  Error from Registry API while getting Recently Added APIs Information {org.wso2.carbon.apimgt.hostobjects.APIStoreHostObject}
org.wso2.carbon.apimgt.api.APIManagementException: Unable to find the API: org.wso2.carbon.apimgt.api.model.APIIdentifier@3b581336 in the database
    at org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.getAPIID(ApiMgtDAO.java:4656)
    at org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.getAverageRating(ApiMgtDAO.java:3577)
    at org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.getAverageRating(ApiMgtDAO.java:3547)
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.getAverageRating(APIUtil.java:1730)
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.getAPI(APIUtil.java:141)
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.getAPIs(APIConsumerImpl.java:1614)
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.getRecentlyAddedAPIs(APIConsumerImpl.java:670)
    at org.wso2.carbon.apimgt.impl.UserAwareAPIConsumer.getRecentlyAddedAPIs(UserAwareAPIConsumer.java:34)
    at org.wso2.carbon.apimgt.hostobjects.APIStoreHostObject.jsFunction_getRecentlyAddedAPIs(APIStoreHostObject.java:538)
    at sun.reflect.GeneratedMethodAccessor79.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
    at org.mozilla.javascript.FunctionObject.call(FunctionObject.java:386)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.store.modules.api.c1._c_anonymous_1(/store/modules/api/recently-added.jag:8)
    at org.jaggeryjs.rhino.store.modules.api.c1.call(/store/modules/api/recently-added.jag)
    at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2430)
    at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:269)
    at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:97)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.store.modules.api.c0._c_anonymous_5(/store/modules/api/module.jag:19)
    at org.jaggeryjs.rhino.store.modules.api.c0.call(/store/modules/api/module.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.store.site.blocks.api.recently_added.c0._c_anonymous_2(/store/site/blocks/api/recently-added/block.jag:10)
    at org.jaggeryjs.rhino.store.site.blocks.api.recently_added.c0.call(/store/site/blocks/api/recently-added/block.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.store.jagg.c0._c_anonymous_26(/store/jagg/jagg.jag:198)
    at org.jaggeryjs.rhino.store.jagg.c0.call(/store/jagg/jagg.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.store.jagg.c0._c_anonymous_27(/store/jagg/jagg.jag:258)
    at org.jaggeryjs.rhino.store.jagg.c0.call(/store/jagg/jagg.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.store.jagg.c0._c_anonymous_26(/store/jagg/jagg.jag:210)
    at org.jaggeryjs.rhino.store.jagg.c0.call(/store/jagg/jagg.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.store.jagg.c0._c_anonymous_27(/store/jagg/jagg.jag:258)
    at org.jaggeryjs.rhino.store.jagg.c0.call(/store/jagg/jagg.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.store.jagg.c0._c_anonymous_26(/store/jagg/jagg.jag:193)
    at org.jaggeryjs.rhino.store.jagg.c0.call(/store/jagg/jagg.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.store.jagg.c0._c_anonymous_38(/store/jagg/jagg.jag:423)
    at org.jaggeryjs.rhino.store.jagg.c0.call(/store/jagg/jagg.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.store.site.pages.c0._c_anonymous_1(/store/site/pages/list-apis.jag:19)
    at org.jaggeryjs.rhino.store.site.pages.c0.call(/store/site/pages/list-apis.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:23)
    at org.jaggeryjs.rhino.store.site.pages.c0._c_script_0(/store/site/pages/list-apis.jag:10)
    at org.jaggeryjs.rhino.store.site.pages.c0.call(/store/site/pages/list-apis.jag)
    at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
    at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
    at org.jaggeryjs.rhino.store.site.pages.c0.call(/store/site/pages/list-apis.jag)
    at org.jaggeryjs.rhino.store.site.pages.c0.exec(/store/site/pages/list-apis.jag)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.execScript(RhinoEngine.java:570)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.exec(RhinoEngine.java:273)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.execute(WebAppManager.java:432)
    at org.jaggeryjs.jaggery.core.JaggeryServlet.doGet(JaggeryServlet.java:24)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:379)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at org.jaggeryjs.jaggery.core.JaggeryFilter.doFilter(JaggeryFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

I'm not exactly sure what its not finding, because when I look at the contents of the database, they are the same as what is in the synapse-config/api/ folder. What is the API Manager process missing?

A: WSO2 API Manager loads APIs in the Store from registry database and API manager database. According to the error message,your APIs are in the registry database, but not in the API manager database. To find out the problem, check what is the database you have pointed as the 'WSO2AM_DB' data source inside AM_HOME/repository/conf/datasources/master-datasource.xml. Then please double check that you have correctly moved data from that data source in to new database.


text:
Q: cts query to filter documents from a particular collection for the last 24 hours I have been trying to find the documents from a particular collection based on the field report_time.
I have been trying the below query. But, it doesn't work.
cts.andQuery(cts.collectionQuery('myCollection'),cts.jsonPropertyRangeQuery("report_time", ">", new Date(Date.now() - 86400 * 1000).toISOString()))

A: From that snippet, the one thing that needs adjustment is that the query criteria need to be in an array for the cts.andQuery() param:
cts.andQuery([
  cts.collectionQuery('myCollection'),
  cts.jsonPropertyRangeQuery("report_time", ">", new Date(Date.now() - 86400 * 1000).toISOString())
])

A: You don't have to do the math, you can use an "age query".  See the end of the page at https://docs.marklogic.com/guide/search-dev/rangequery


text:
Q: Unable to read pipe I don't know if I accidentally deleted or put in a typo somewhere but all of the sudden some of my code stopped working. For some reason no lines are ever read from $in.
use Win32::Job;
use IO::Handle;

STDOUT->autoflush;

pipe my $in, my $out;

my $job = Win32::Job->new;

sub flush_pipe{
    while (defined(my $line = <$in>)) {
       chomp($line);
       print($line);

    }
}
my $pid = $job->spawn("cmd", "cmd /C \"ipconfig\"",
    {
        stdout=>$out
    }
);
flush_pipe();

Edit:
Through trial and error I eventually found out I have to close the $out filehandle before flushing the pipe.

A: A pipe is unidirectional. Each of the processes it connects can either read or write.
After pipe you have two filehandles, and both the parent and the child see them both.  If the child is going to write and the parent to read, as in your code, then the child must first close the handle it won't use ($in) and the parent must close its unused one, $out. Otherwise you'll have deadlocks.
The spawn from the module starts a child process (or, rather, a Windows approximation of it) and redirects its STDOUT to the writing end of the pipe, $out.
Some very basic code that should cover this
use strict;
use warnings;
use feature 'say';

pipe my $in, my $out;

my $pid = fork // die "Can't fork: $!";

if ($pid == 0) { # child
    close $in;
    print $out "hi ";         # can't read this yet (no newline) ...
    sleep 1;
    say   $out "from child";  # now the other end can read it
    close $out;
    exit;
}

# parent
close $out;

say while <$in>;
close $in;

wait;

When you want prints to become available to the reader right away (up to buffering outside your code) send a newline. Close unused ends of the pipe in each process before doing anything else.
I can't write code on Windows now, but in your code parent must close $out (after spawn).
The term "flush" here can relate to the code in the writer or to Perl's clearing of IO buffers; the code in your flush_pipe() merely reads the pipe. So I'd change that name, to read_pipe or such.


text:
Q: Print text file with python Editing a kodi plugin at the moment and trying to solve to print out a specific txt-file with python.
There is a txt located on another folder containting: build021.7.0
I want to be able to print out the version number.
How can this be done?
Would really appreciate some help!
Thanks!
/Martin


text:
Q: Combining Javascript objects I am creating a food menu app using reactjs at the frontend and django backend. I unfortunately got stuck here mostly because of my little knowledge of Javascript.Here is my problem. I have this array of objects
const objectOfArray = [
    {
    "id":"1a2f2c7a-0e06-4784-a1fb-68e083a72aa5","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
    },
    {
    "id":"7bee12ac-7253-4e5a-a86f-2ea0a3765541","cat_id":"6968da9d-4475-4431-801d-e3eeda02145a","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
    },
    {
    "id":"42763c0d-84f1-4f07-97c8-aa914bfb92fa","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
    }
]

then another object const myObject = {"seat":"4","table":"10"}
I want each of the object in objectOfArray to have myObject so that the output now looks like this
[
    {
    "id":"1a2f2c7a-0e06-4784-a1fb-68e083a72aa5","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856","seat":"4","table":"10"
    },
    {
    "id":"7bee12ac-7253-4e5a-a86f-2ea0a3765541","cat_id":"6968da9d-4475-4431-801d-e3eeda02145a","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856","seat":"4","table":"10"
    },
    {
    "id":"42763c0d-84f1-4f07-97c8-aa914bfb92fa","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856","seat":"4","table":"10"
    }
]

A: As Lawrence suggested in a comment you can accomplish this using map with spread syntax:

const objectOfArray = [
    {
    "id":"1a2f2c7a-0e06-4784-a1fb-68e083a72aa5","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
    },
    {
    "id":"7bee12ac-7253-4e5a-a86f-2ea0a3765541","cat_id":"6968da9d-4475-4431-801d-e3eeda02145a","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
    },
    {
    "id":"42763c0d-84f1-4f07-97c8-aa914bfb92fa","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
    }
]

const myObject = {"seat":"4","table":"10"};

const result = objectOfArray.map(item => ({...item, ...myObject}));

console.log(result);

A: You can assign the properties in myObject to some other object with Object.assign().
You also need a way to iterate over the original array: .map will do that.
Combining these two, you get

const objectOfArray = [
        {
            "id":"1a2f2c7a-0e06-4784-a1fb-68e083a72aa5","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
        },
        {
            "id":"7bee12ac-7253-4e5a-a86f-2ea0a3765541","cat_id":"6968da9d-4475-4431-801d-e3eeda02145a","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
        },
        {
            "id":"42763c0d-84f1-4f07-97c8-aa914bfb92fa","cat_id":"812347b3-615f-4f4a-b201-64737ddf4718","event_id":"ead9898c-9606-49e0-aa2b-c7f34331a856"
        }
    ];

const myObject = {"seat":"4","table":"10"}

newArray = objectOfArray.map(e=>Object.assign(e,myObject));

console.log(newArray);


text:
Q: Solving recurrence equations Is there a method to determine the generating function for a mutually recursive recurrence equation?
As an example, consider the following set if equations
$$R_n = R_{n-1}+  3P_{n-1}; R_0 = 3$$
$$M_n = R_{n-1} +  2P_{n-1};M_0 = 2$$
$$P_n = 5M_{n-1} ;P_0 = 0$$
What I am interested here is to determine, given a value of n, I can find the nth value of R(n), M(n) and P(n) without determining all the values from 1 to n - 1

A: Hint
$$\begin{bmatrix}
R_{n}\\
M_{n}\\
P_{n}
\end{bmatrix}=
\begin{bmatrix}
1&0&3\\
1&0&2\\
0&5&0
\end{bmatrix}\cdot \begin{bmatrix}
R_{n-1}\\
M_{n-1}\\
P_{n-1}
\end{bmatrix}$$
let
$$A=\begin{bmatrix}
1&0&3\\
1&0&2\\
0&5&0
\end{bmatrix}$$
then we only find $A^n$ it is easy to find it ,because
$$A=Q^{-1}diag{(\lambda_{1},\lambda_{2},\lambda_{3})}Q$$
where $\lambda_{i}$ is eigenvalue of $A$,$Q$ is Orthogonal matrix
Solution 2:
since
$$M_{n-1}=\dfrac{P_{n}}{5}\Longrightarrow M_{n}=\dfrac{P_{n+1}}{5}$$
then we have
$$\dfrac{P_{n+1}}{5}=R_{n-1}+2P_{n-1}\Longrightarrow R_{n-1}=\dfrac{P_{n+1}}{5}-2P_{n-1}$$
so
$$\dfrac{P_{n+2}}{5}-2P_{n}=\dfrac{P_{n+1}}{5}-2P_{n-1}+3P_{n-1}$$
then
$$P_{n+2}=P_{n+1}+10P_{n}+5P_{n-1},P_{0}=0,P_{1}=10,P_{2}=15$$
then Characteristic equation is
$$x^3=x^2+10x+5$$ three roots is $x_{1},x_{2},x_{3}$
then
$$P_{n}=A(x_{1})^n+B(x_{2})^n+C(x_{3})^n$$
then It is easy to find it

A: It should be remarked that the characteristic polynomial of the matrix is $\lambda^3-\lambda^2-10\lambda-5$ just like the characteristic equation for the recurrence for the $P$ values. That is not a coincidence.
Also $M_{n+2}=M_{n+1}+10M_n+5M_{n-1}$ and $R_{n+2}=R_{n+1}+10R_n+5R_{n-1}$
The roots are nothing nice, roughly $r_1=3.896,r_2=-2.350,r_3=-0.546$ so you can get a formula $$P_n=c_1r_1^n+c_2r_2^n+c_3r_3^n$$ Where explicit (but not pretty) formulas (in terms of the various $r_i$) could be given for $c_1,c_2,c_3$ based on $P_0,P_1,P_2.$
We do see that the values grow rapidly (about as fast as $r_1^n$).
If you wanted the values of $P_n,R_n,M_n$ for $n=32$ then you could compute the matrices $A^2,A^4,A^8,A^{16},A^{32}$ by repeated squaring. So you didn't determine all the value from $n=1$ to $n=31,$   just $5$ of them. This multiply and square method can be adapted to deal with any $n.$


text:
Q: Laravel Multisite Setup with Sub Domains I want to build Laravel CMS with following requirements:

*

*Admin (manage all sites/database).

*Multi-sites (running on sub-domains, manage own database) each with API access.

*Same Codebase (can be replicated if needed).

*Same Database with different data for each site.

Can you please let me know how to setup this environment using Laravel 5.4.
Thanks.

A: This project has been finished now. So posting my own solution for the question.
Following are points to take care:

*

*I've used Laravel 5.4 (later upgraded to 5.5).

*For multi tenancy used Landlord extension for Laravel.

*Server is configured to listen for wild-card sub-domains.

*Each site is running on sub-domain.

*Using single database with site-id (tenant-id) under each DB table.

Whenever server gets request, sub-domain is matched with tenant id in the middleware & load all the records for that tenant only.
I've hope this might help someone else.

A: For build a Laravel CMS with following requirements you need use:
You can set an Admin Role with policies and gates or uses entrust
For Multi-sites, You can used something like https://github.com/hyn/multi-tenant, so If you use multitenant you can

*

*Multi-sites (running on sub-domains, manage own database) each with
API access. Same Codebase (can be replicated if needed). Same
Database with different data for each site.

For config subdomain you can read the official documentation https://laravel.com/docs/5.4/routing#route-group-sub-domain-routing


text:
Q: iOS7 - UITextView leave extra padding at top in Storyboard Tools Specification:

*

*OS X Yosemite 10.10

*Xcode 5.1.1

Today I found one weird issue (Or may be if i'm wrong with new specialisation or something else. Please make me correct if anything is wrong).
I created project using Xcode 5.1.1 for iOS 7.1 OS with Storyboard support. Everything here is default. Now just drag and drop UITextView into view of UIViewController (It is embedded in UINavigationController more precisely).
Here all properties of UITextView are default except background color (Change to highlight border of UITextView). I see that the default text in UITextView goes bottom when I change its height. Also left some space on top and than text is rendered. See the below image:

Run application to check this also in simulator. And it shows extra space on the top of UITextView.

I also did the same in Xcode 6.0.1 to double sure that this is not default behaviour. And it is perfect in Xcode 6.0.1, there were no extra space on top of content of UITextView.

Spotlight:
I never did face this issue before. I updated Mac OS Yosemite two days ago (If its relevant to the Mac OS).
Also one thing is to be note that if I remove embedded UINavigationController than it works normal.
So is it related to OS? OR Do I miss something, I mean Apple introduce or change any behaviour?
Note: There is no any constraints. Just drag and drop UITextView to view.

A: EDIT: Just updated to XCode6.1 and I am building onto iPad with iOS7.1 - THE SAME ISSUE PERSISTS!
I think it is a bug in XCode5.1.1, here is what I found, may be it will help you, it did help me.
EDIT: Hey, just discovered that UITableView does exactly the same, it appears scrolled down if it is 1st in a list in interface builder, same trick cures it.
Here I have my textview 1st in the list in interface builder:

and it is scrolled down when you run the app:

However, if I move my textview below the others:

It shows up in the app all right:

So, just make sure none of the textviews (or tableviews) are 1st in the list in interface builder! Seems like real bug to me, will log it in with Apple.

A: I think you can fix this by setting the property contentOffset as follows:
yourTextView.contentOffset = CGPointZero

This allow you to set the text at top of the UITextView's frame.


text:
Q: Origin of the term "understudy" I've recently seen a musical and, on the night I went, three roles were being played by understudies instead of the regular actors.
This term has always puzzled me, partly because I've never found a satisfactory translation for it in my native tongue. However, while I well understand its meaning and although I've researched various dictionaries, I haven't found clear indications of its origin. The Online Etymology Dictionary deals with the word in one line and the OALD, normally so generous with references to the origin of terms, doesn't even try.
Can anyone tell me how this word came into existence?

A: In English we regularly say that person A "studied under" person B, meaning that B was the teacher of A. "Study" should be plain enough: that's the common meaning of the word. To say that one person is "under" another means that he is subordinate or junior.
So an "understudy" is one who "studies under" another. In acting, the idea is that the junior actor is supposed to be learning from the senior actor, either by direct instruction or at least by example.


text:
Q: AWS Glacier inventory is either wrong or asynchronous? Using Boto3, I uploaded 12 files to Amazon's Glacier last night at 21:43 EST.
I received ArchiveID's for all 12 files, so I assume they uploaded correctly.
According the the AWS management console, the most recent inventory was run at 02:53 EST this morning. So about 5 hours after upload.
But the inventory does not show those 12 files.  There is only 1 file (that I uploaded 1 week ago).
I know I have to wait another day for the next AWS Inventory to run, but I thought I'd ask if this is expected behavior?
Does the time amazon calculated/reported time of the Inventory not really match when it was run? Is it possible the inventory actually ran before I uploaded those files?
If not, why would I get archiveID's (indicating successful upload) but they aren't listed in an intentory run AFTER they were uploaded?
Edit:
The files did show up on the next inventory.
But I'm still curious why the time of the 'Last Inventory' in AWS Console which was 5 hours after upload reported zero files. My only explanation is that the 'Last Inventory' time of the AWS Console is when the information was uploaded to the AWS Console. But that the ACTUAL inventory could have run hours earlier (hence it missed the recently uploaded files).

A:
When you initiate a job for a vault inventory, Amazon Glacier returns the last inventory it generated, which is a point-in-time snapshot and not real-time data.
http://docs.aws.amazon.com/amazonglacier/latest/dev/vault-inventory.html

Asking for an inventory apparently doesn't trigger the actual generation -- it just preps the last inventory for fetching.
Inventories are updated approximately once every 24 hours, so there's a good chance of those new files not appearing in the timetable you describe.
Unless you're interested in features only available through the Glacier API, like vault locks, you may find the S3/Glacier integration provides a more useful interface.  Files uploaded as S3 objects and then transitioned to the Glacier storage class by lifecycle policies are not visble through the Glacier API -- they continue to appear as S3 objects, making it more straightforward to iterate through them and their metadata, all of which is effectively in real time.


text:
Q: blueimp jquery file upload fails on images over 1mb I don't really know any where else to look or ask, on the support section in GitHub it suggested to start a question here. Is anyone here familiar enough with the framework to have a clue where to start?
Hoping I don't have to dive in blind. Thanks. If you really want to see a version of it you would have to sign up at http://merkd.com/signup then go to http://merkd.com/settings/icon to test it. I've tested it with a 978kb image and it works fine but I tried a 1.8mb, 2.2mb, and 3.7mb image and none of them work. The progress bar goes slow for a tiny bit, then it just speeds up as if it were a 50kb file.
I hope this is an easy fix. I was hoping to save time and use an already existing client-end upload framework.

A: Have you tried checking the documentation, setting max file size that can be uploaded?
Also try checking the FAQ's, found out that it could be the browser you are testing on


text:
Q: Configure firewalld for OpenVPN (server-bridge) in Fedora 20 I've installed an OpenVPN server (server-bridge) on Fedora 20, but I cannot get it to work. I'm almost sure that It's a firewall issue.
I'm trying to connect from an OSX client, but I can connect (just connect to VPN server, without access to anything) before the bridge is configured in server, however once I configure the bridge interface (using this script), then I cannot connect anymore. I've configured it as server-bridge, following these HOW-TOs from Fedora and OpenVPN Ethernet-Bridge.
The firewall config is explained using iptables:
iptables -A INPUT -i tap0 -j ACCEPT
iptables -A INPUT -i br0 -j ACCEPT
iptables -A FORWARD -i br0 -j ACCEPT

However, in Fedora 20, by default, It's installed firewalld, so, Can anyone tell me the equivalent commands using firewall-cmd ? I read the firewalld guide, but It's not clear to me how to achieve it (I'm a developer, no SysAdmin).
I know that I can install iptables, but I want it to work with firewalld.
UPDATE: After some reading on firewall-cmd man page, I tried to apply the previous commands using --passthroughoption, that is:
# firewall-cmd --permanent --direct --passthrough ipv4 -A FORWARD -i br0 -j ACCEPT
# firewall-cmd --permanent --direct --passthrough ipv4 -A INPUT -i br0 -j ACCEPT
# firewall-cmd --permanent --direct --passthrough ipv4 -A FORWARD -i br0 -j ACCEPT

The commands are successfully executed, but It doesn't work, I also tried to use eb instead of ipv4 with the same result.
The ifconfig output is something like:
br0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.40  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::c9:aff:fe02:d953  prefixlen 64  scopeid 0x20<link>
        ether 02:c9:09:02:d9:53  txqueuelen 0  (Ethernet)
        RX packets 11276  bytes 1374285 (1.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 899  bytes 240110 (234.4 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth0: flags=4419<UP,BROADCAST,RUNNING,PROMISC,MULTICAST>  mtu 1500
        inet6 fe80::c9:afa:fe02:d953  prefixlen 64  scopeid 0x20<link>
        ether 03:c9:0a:02:d9:53  txqueuelen 1000  (Ethernet)
        RX packets 13548  bytes 1942379 (1.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1162  bytes 269258 (262.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 117  base 0xc000

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 16436
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 0  (Local Loopback)
        RX packets 6883  bytes 2061608 (1.9 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6883  bytes 2061608 (1.9 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

p2p0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet6 fe80::9831:16ff:fe81:3658  prefixlen 64  scopeid 0x20<link>
        ether 9a:3b:16:84:36:58  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

tap0: flags=4355<UP,BROADCAST,PROMISC,MULTICAST>  mtu 1500
        ether d6:6c:20:12:f3:b6  txqueuelen 100  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.41  netmask 255.255.255.0  broadcast 0.0.0.0
        inet6 fe80::9a5b:16ff:fe81:3658  prefixlen 64  scopeid 0x20<link>
        ether 98:3b:11:81:36:58  txqueuelen 1000  (Ethernet)
        RX packets 2643  bytes 230523 (225.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5512  bytes 1726039 (1.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

A: firewalld has some services already pre-configured which can be seen with:
firewall-cmd --get-services

(Configuration file /usr/lib/firewalld/services/openvpn.xml)
If you see openvpn as already available service you can enable it with:
firewall-cmd --add-service openvpn

A: The answer to my original question is:
# firewall-cmd --permanent --direct --passthrough ipv4 -A FORWARD -i br0 -j ACCEPT
# firewall-cmd --permanent --direct --passthrough ipv4 -A INPUT -i br0 -j ACCEPT
# firewall-cmd --permanent --direct --passthrough ipv4 -A FORWARD -i br0 -j ACCEPT

Then, if you execute:
# firewall-cmd --permanent  --direct --get-all-passthroughs

You'll get this:
ipv4 -A INPUT -i tap0 -j ACCEPT
ipv4 -A INPUT -i br0 -j ACCEPT
ipv4 -A FORWARD -i br0 -j ACCEPT

However there is still something wrong, I cannot connect to the VPN server, so any idea/clue will be welcome.


text:
Q: get machine time in air/as3 Is there a way to get a reliable machine time that cannot be altered by changing the time/date on a mobile device or computer?
I'm looking to find a way to see time elapsed in an air app where you can...

*

*run the app

*change the system time (back an hour, or change the date forward by two weeks, etc.)

*run the app again with the correct time passed

any ideas how to implement this without relying on server connection?

A: I feel fairly confident saying it can't be done. Without a remote server to ping, all the app knows is what the OS tells it - and if the app isn't running, it can't be collecting its own data independently of the OS.
The closest you could get would be storing the system time at app shutdown, then comparing that to the system time on app startup to see if the OS' clock has been turned back - if the current time is before the previous time, you know something's up. Even then, the data about the last known system time has to be stored somewhere locally - which means the user is free to edit it if they want.
You could also mess with having the app running in the background constantly, or even as a service, though that moves out of the viability of using AIR - and even then, time would only pass while the system was on, and only if the user decides to let the background process continue running.

A: If your problem is measuring the elapsed time between two moments, getTimer should do the job.


text:
Q: Slideout from right to left on div with a variable width. i'm currently struggling to get a div with a variable width to slideout from right to left.
the problem is getting the button to animate along with the sliding div, see example below.
http://camoconnell.com/things/slideoutleft/
note -  width is dynamic, not static.
thanks in advance,

A: Here's a working example. It's not quite as simple as you'd think right off the bat.

A: With the way you have your html structured you will have to do a .animate() on the dynamic div's width and set the width property to negative of whatever length you are sliding your counter div to
.animate({width: -50})

Make this call right before or after your slider invocation.
Another suggestion is to put the button and the counter elements in a wrapper element (this would require a restructure of your html) and just slide out that wrapper element.

A: A simple solution would be to apply the animation to the wrapper div. So in your slideRightShow, you can have:
$('#caption').show();
$('#caption-wrap').show('slide', {direction: 'right'}, 1000);

A: This would be another solution:
HTML:

Hi there, Hide me

Show me

CSS:
.test {
    border: 1px solid black;
    background-color: yellow;
    padding: 10px;
    position: absolute;
    visibility: hidden;
}

JS
var variableWidth;

$(window).load(function() {

// gets complete element width (including margins), moves it out of the screen and sets visibility to its default
    variableWidth = $('#hithere').outerWidth(true);
    $('#hithere').css("left", variableWidth * -1);
    $('#hithere').css("visibility", "visible");
});

$("#show").click(function() {
    $('#hithere').animate({left: 0}, 400);
    });

$("#hide").click(function() {
        $('#hithere').animate({left: variableWidth * -1}, 400);
        });